Você está na página 1de 1688

HALCON Version 8.0.

MVTec Software GmbH

HALCON/COM
Reference Manual
This manual describes the operators of HALCON, version 8.0.2, in COM syntax. It was generated on May 13,
2008.

All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in
any form or by any means, electronic, mechanical, photocopying, recording, or otherwise, without prior written
permission of the publisher.

Copyright
c 1997-2008 by MVTec Software GmbH, München, Germany MVTec Software GmbH

More information about HALCON can be found at: http://www.mvtec.com


Contents

1 Classification 1
1.1 Gaussian-Mixture-Models . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
AddSampleClassGmm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
ClassifyClassGmm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
ClearAllClassGmm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
ClearClassGmm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
ClearSamplesClassGmm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
CreateClassGmm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
EvaluateClassGmm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
GetParamsClassGmm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
GetPrepInfoClassGmm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
GetSampleClassGmm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
GetSampleNumClassGmm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
ReadClassGmm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
ReadSamplesClassGmm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
TrainClassGmm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
WriteClassGmm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
WriteSamplesClassGmm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
1.2 Hyperboxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
ClearSampset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
CloseAllClassBox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
CloseClassBox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
CreateClassBox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
DescriptClassBox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
EnquireClassBox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
EnquireRejectClassBox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
GetClassBoxParam . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
LearnClassBox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
LearnSampsetBox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
ReadClassBox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
ReadSampset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
SetClassBoxParam . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
TestSampsetBox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
WriteClassBox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
1.3 Neural-Nets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
AddSampleClassMlp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
ClassifyClassMlp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27
ClearAllClassMlp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28
ClearClassMlp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
ClearSamplesClassMlp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29
CreateClassMlp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30
EvaluateClassMlp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
GetParamsClassMlp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
GetPrepInfoClassMlp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
GetSampleClassMlp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37
GetSampleNumClassMlp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38
ReadClassMlp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
ReadSamplesClassMlp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 39
TrainClassMlp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40
WriteClassMlp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
WriteSamplesClassMlp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
1.4 Support-Vector-Machines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
AddSampleClassSvm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43
ClassifyClassSvm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44
ClearAllClassSvm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
ClearClassSvm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
ClearSamplesClassSvm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
CreateClassSvm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46
GetParamsClassSvm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
GetPrepInfoClassSvm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
GetSampleClassSvm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
GetSampleNumClassSvm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
GetSupportVectorClassSvm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
GetSupportVectorNumClassSvm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55
ReadClassSvm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
ReadSamplesClassSvm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
ReduceClassSvm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57
TrainClassSvm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
WriteClassSvm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
WriteSamplesClassSvm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61

2 File 63
2.1 Images . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
ReadImage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
ReadSequence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
WriteImage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67
2.2 Misc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
DeleteFile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
FileExists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
ListFiles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
ReadWorldFile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
2.3 Region . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
ReadRegion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
WriteRegion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
2.4 Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
CloseAllFiles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
CloseFile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
FnewLine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
FreadChar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73
FreadLine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74
FreadString . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
FwriteString . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75
OpenFile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
2.5 Tuple . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
ReadTuple . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
WriteTuple . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
2.6 XLD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
ReadContourXldArcInfo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78
ReadContourXldDxf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79
ReadPolygonXldArcInfo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
ReadPolygonXldDxf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 81
WriteContourXldArcInfo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
WriteContourXldDxf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83
WritePolygonXldArcInfo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86
WritePolygonXldDxf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86

3 Filter 89
3.1 Arithmetic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
AbsImage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89
AddImage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
DivImage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91
InvertImage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92
MaxImage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93
MinImage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94
MultImage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95
ScaleImage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96
SqrtImage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97
SubImage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98
3.2 Bit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
BitAnd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99
BitLshift . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100
BitMask . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
BitNot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101
BitOr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102
BitRshift . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103
BitSlice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
BitXor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104
3.3 Color . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
CfaToRgb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
GenPrincipalCompTrans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106
LinearTransColor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
PrincipalComp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108
Rgb1ToGray . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
Rgb3ToGray . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
TransFromRgb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 110
TransToRgb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115
3.4 Edges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
CloseEdges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119
CloseEdgesLength . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
DerivateGauss . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121
DiffOfGauss . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
EdgesColor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
EdgesColorSubPix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 128
EdgesImage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
EdgesSubPix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133
FreiAmp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135
FreiDir . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
HighpassImage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 137
InfoEdges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
KirschAmp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140
KirschDir . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141
Laplace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
LaplaceOfGauss . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
PrewittAmp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
PrewittDir . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146
Roberts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
RobinsonAmp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148
RobinsonDir . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
SobelAmp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 150
SobelDir . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152
3.5 Enhancement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154
AdjustMosaicImages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154
CoherenceEnhancingDiff . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 156
Emphasize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 158
EquHistoImage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 159
Illuminate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 160
MeanCurvatureFlow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162
ScaleImageMax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
ShockFilter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 163
3.6 FFT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
ConvolFft . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 164
ConvolGabor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165
CorrelationFft . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166
EnergyGabor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167
FftGeneric . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168
FftImage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 169
FftImageInv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
GenBandfilter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 170
GenBandpass . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172
GenDerivativeFilter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173
GenFilterMask . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 174
GenGabor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
GenGaussFilter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 177
GenHighpass . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179
GenLowpass . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180
GenSinBandpass . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181
GenStdBandpass . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182
OptimizeFftSpeed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 183
OptimizeRftSpeed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184
PhaseDeg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
PhaseRad . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 185
PowerByte . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186
PowerLn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
PowerReal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
ReadFftOptimizationData . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188
RftGeneric . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
WriteFftOptimizationData . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190
3.7 Geometric-Transformations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190
AffineTransImage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 190
AffineTransImageSize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
GenBundleAdjustedMosaic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
GenCubeMapMosaic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196
GenProjectiveMosaic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198
GenSphericalMosaic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
MapImage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
MirrorImage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204
PolarTransImage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204
PolarTransImageExt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 206
PolarTransImageInv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208
ProjectiveTransImage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
ProjectiveTransImageSize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
RotateImage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 212
ZoomImageFactor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
ZoomImageSize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
3.8 Inpainting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
HarmonicInterpolation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 215
InpaintingAniso . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216
InpaintingCed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 218
InpaintingCt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 220
InpaintingMcf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222
InpaintingTexture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224
3.9 Lines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
BandpassImage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
LinesColor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226
LinesFacet . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228
LinesGauss . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230
3.10 Match . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
ExhaustiveMatch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232
ExhaustiveMatchMg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234
GenGaussPyramid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 235
Monotony . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236
3.11 Misc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
ConvolImage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
ExpandDomainGray . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 238
GrayInside . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
GraySkeleton . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240
LutTrans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241
Symmetry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 242
TopographicSketch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243
3.12 Noise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244
AddNoiseDistribution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244
AddNoiseWhite . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245
GaussDistribution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246
NoiseDistributionMean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246
SpDistribution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247
3.13 Optical-Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248
OpticalFlowMg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248
UnwarpImageVectorField . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 256
VectorFieldLength . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
3.14 Points . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
CornerResponse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257
DotsImage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259
PointsFoerstner . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 260
PointsHarris . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263
PointsSojka . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264
3.15 Smoothing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266
AnisotropeDiff . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 266
AnisotropicDiffusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267
BinomialFilter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 269
EliminateMinMax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270
EliminateSp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271
FillInterlace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273
GaussImage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273
InfoSmooth . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275
IsotropicDiffusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276
MeanImage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276
MeanN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278
MeanSp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 278
MedianImage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280
MedianSeparate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 281
MedianWeighted . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282
MidrangeImage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 283
RankImage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 284
SigmaImage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 286
SmoothImage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287
TrimmedMean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289
3.16 Texture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290
DeviationImage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 290
EntropyImage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291
TextureLaws . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 292
3.17 Wiener-Filter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294
GenPsfDefocus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294
GenPsfMotion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295
SimulateDefocus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296
SimulateMotion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 297
WienerFilter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 298
WienerFilterNi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300

4 Graphics 303
4.1 Drawing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303
DragRegion1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303
DragRegion2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304
DragRegion3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
DrawCircle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306
DrawCircleMod . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307
DrawEllipse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 308
DrawEllipseMod . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 309
DrawLine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310
DrawLineMod . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311
DrawNurbs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313
DrawNurbsInterp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315
DrawNurbsInterpMod . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317
DrawNurbsMod . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 319
DrawPoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321
DrawPointMod . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 322
DrawPolygon . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 323
DrawRectangle1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324
DrawRectangle1Mod . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325
DrawRectangle2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 326
DrawRectangle2Mod . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 327
DrawRegion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 328
DrawXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329
DrawXldMod . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 331
4.2 Gnuplot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332
GnuplotClose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 332
GnuplotOpenFile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333
GnuplotOpenPipe . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333
GnuplotPlotCtrl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334
GnuplotPlotFunct1D . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 334
GnuplotPlotImage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 335
4.3 LUT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336
DispLut . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 336
DrawLut . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 337
GetFixedLut . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 338
GetLut . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339
GetLutStyle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 339
QueryLut . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340
SetFixedLut . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 340
SetLut . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 341
SetLutStyle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 343
WriteLut . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 344
4.4 Mouse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345
GetMbutton . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 345
GetMposition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 346
GetMshape . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347
QueryMshape . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 347
SetMshape . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348
4.5 Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348
DispArc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348
DispArrow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 350
DispChannel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351
DispCircle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 352
DispColor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353
DispCross . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354
DispDistribution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 355
DispEllipse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 356
DispImage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 357
DispLine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 358
DispObj . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359
DispPolygon . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 360
DispRectangle1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361
DispRectangle2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362
DispRegion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 364
DispXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365
4.6 Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365
GetComprise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365
GetDraw . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366
GetFix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 366
GetHsi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367
GetIcon . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367
GetInsert . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368
GetLineApprox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 368
GetLineStyle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369
GetLineWidth . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 369
GetPaint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370
GetPart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 370
GetPartStyle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371
GetPixel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372
GetRgb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 372
GetShape . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373
QueryAllColors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374
QueryColor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 374
QueryColored . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 375
QueryGray . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376
QueryInsert . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 376
QueryLineWidth . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 377
QueryPaint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 378
QueryShape . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 378
SetColor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 379
SetColored . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 380
SetComprise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 380
SetDraw . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381
SetFix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 382
SetGray . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 382
SetHsi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 383
SetIcon . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 385
SetInsert . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 385
SetLineApprox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 386
SetLineStyle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 387
SetLineWidth . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 388
SetPaint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 388
SetPart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 392
SetPartStyle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 393
SetPixel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 394
SetRgb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 395
SetShape . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 396
4.7 Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397
GetFont . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397
GetStringExtents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 397
GetTposition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 398
GetTshape . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 399
NewLine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 399
QueryFont . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 400
QueryTshape . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 401
ReadChar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 401
ReadString . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 402
SetFont . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403
SetTposition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405
SetTshape . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 405
WriteString . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 406
4.8 Window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407
ClearRectangle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 407
ClearWindow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408
CloseWindow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 408
CopyRectangle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 409
DumpWindow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 411
DumpWindowImage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 412
GetOsWindowHandle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413
GetWindowAttr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 413
GetWindowExtents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 414
GetWindowPointer3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 415
GetWindowType . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 416
MoveRectangle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 416
NewExternWindow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 418
OpenTextwindow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 420
OpenWindow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 423
QueryWindowType . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427
SetWindowAttr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 427
SetWindowDc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 428
SetWindowExtents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 429
SetWindowType . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 430
SlideImage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 431

5 Image 433
5.1 Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 433
GetGrayval . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 433
GetImagePointer1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 434
GetImagePointer1Rect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 435
GetImagePointer3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 436
GetImageTime . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 437
5.2 Acquisition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 438
CloseAllFramegrabbers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 438
CloseFramegrabber . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 438
GetFramegrabberLut . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 439
GetFramegrabberParam . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 439
GrabData . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 440
GrabDataAsync . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 442
GrabImage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443
GrabImageAsync . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 444
GrabImageStart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 445
InfoFramegrabber . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 446
OpenFramegrabber . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 448
SetFramegrabberLut . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 450
SetFramegrabberParam . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 451
5.3 Channel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 452
AccessChannel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 452
AppendChannel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 452
ChannelsToImage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 453
Compose2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 453
Compose3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 454
Compose4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 455
Compose5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 455
Compose6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 456
Compose7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 457
CountChannels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 458
Decompose2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 459
Decompose3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 459
Decompose4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 460
Decompose5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 461
Decompose6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 462
Decompose7 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 463
ImageToChannels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 464
5.4 Creation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 464
CopyImage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 464
GenImage1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 465
GenImage1Extern . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 466
GenImage1Rect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 467
GenImage3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 468
GenImageConst . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 469
GenImageGrayRamp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 471
GenImageInterleaved . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 472
GenImageProto . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 474
GenImageSurfaceFirstOrder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 475
GenImageSurfaceSecondOrder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 477
RegionToBin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 478
RegionToLabel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 480
RegionToMean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481
5.5 Domain . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481
AddChannels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 481
ChangeDomain . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 482
FullDomain . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 483
GetDomain . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 483
Rectangle1Domain . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 484
ReduceDomain . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 485
5.6 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 485
AreaCenterGray . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 485
CoocFeatureImage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 486
CoocFeatureMatrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 487
EllipticAxisGray . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 488
EntropyGray . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 489
EstimateNoise . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 490
FitSurfaceFirstOrder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 493
FitSurfaceSecondOrder . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 494
FuzzyEntropy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 495
FuzzyPerimeter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 496
GenCoocMatrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 498
GrayHisto . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 499
GrayHistoAbs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 500
GrayProjections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 501
Histo2Dim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 502
Intensity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 503
MinMaxGray . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 504
MomentsGrayPlane . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 505
PlaneDeviation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 506
SelectGray . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 507
ShapeHistoAll . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 508
ShapeHistoPoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 510
5.7 Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 511
ChangeFormat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 511
CropDomain . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 511
CropDomainRel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 512
CropPart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 513
CropRectangle1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 514
TileChannels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 515
TileImages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 516
TileImagesOffset . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 517
5.8 Manipulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 519
OverpaintGray . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 519
OverpaintRegion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 520
PaintGray . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 521
PaintRegion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 522
PaintXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 524
SetGrayval . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 525
5.9 Type-Conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 526
ComplexToReal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 526
ConvertImageType . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 526
RealToComplex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 527
RealToVectorField . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 527
VectorFieldToReal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 528

6 Lines 529
6.1 Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 529
ApproxChain . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 529
ApproxChainSimple . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 532
6.2 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 533
LineOrientation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 533
LinePosition . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 534
PartitionLines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 535
SelectLines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 536
SelectLinesLongest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 538

7 Matching 541
7.1 Component-Based . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 541
ClearAllComponentModels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 541
ClearAllTrainingComponents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 541
ClearComponentModel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 542
ClearTrainingComponents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 542
ClusterModelComponents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 543
CreateComponentModel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 545
CreateTrainedComponentModel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 549
FindComponentModel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 552
GenInitialComponents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 556
GetComponentModelParams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 560
GetComponentModelTree . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 561
GetComponentRelations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 563
GetFoundComponentModel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 565
GetTrainingComponents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 567
InspectClusteredComponents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 569
ModifyComponentRelations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 570
ReadComponentModel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 572
ReadTrainingComponents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 572
TrainModelComponents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 573
WriteComponentModel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 577
WriteTrainingComponents . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 578
7.2 Correlation-Based . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 578
ClearAllNccModels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 578
ClearNccModel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 579
CreateNccModel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 579
FindNccModel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 581
GetNccModelOrigin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 585
GetNccModelParams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 585
ReadNccModel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 586
SetNccModelOrigin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 587
WriteNccModel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 587
7.3 Gray-Value-Based . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 588
AdaptTemplate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 588
BestMatch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 588
BestMatchMg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 590
BestMatchPreMg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 591
BestMatchRot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 592
BestMatchRotMg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 594
ClearAllTemplates . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 595
ClearTemplate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 595
CreateTemplate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 596
CreateTemplateRot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 598
FastMatch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 599
FastMatchMg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 600
ReadTemplate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 601
SetOffsetTemplate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 602
SetReferenceTemplate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 602
WriteTemplate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 603
7.4 Shape-Based . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 603
ClearAllShapeModels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 603
ClearShapeModel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 604
CreateAnisoShapeModel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 605
CreateScaledShapeModel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 609
CreateShapeModel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 614
DetermineShapeModelParams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 617
FindAnisoShapeModel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 620
FindAnisoShapeModels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 624
FindScaledShapeModel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 629
FindScaledShapeModels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 633
FindShapeModel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 637
FindShapeModels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 641
GetShapeModelContours . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 645
GetShapeModelOrigin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 645
GetShapeModelParams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 646
InspectShapeModel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 647
ReadShapeModel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 648
SetShapeModelOrigin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 649
WriteShapeModel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 649

8 Matching-3D 651
AffineTransObjectModel3D . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 651
ClearAllObjectModel3D . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 652
ClearAllShapeModel3D . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 652
ClearObjectModel3D . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 652
ClearShapeModel3D . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 653
ConvertPoint3DCartToSpher . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 653
ConvertPoint3DSpherToCart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 655
CreateCamPoseLookAtPoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 656
CreateShapeModel3D . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 658
FindShapeModel3D . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 663
GetObjectModel3DParams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 667
GetShapeModel3DContours . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 668
GetShapeModel3DParams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 669
ProjectObjectModel3D . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 670
ProjectShapeModel3D . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 671
ReadObjectModel3DDxf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 672
ReadShapeModel3D . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 674
TransPoseShapeModel3D . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 675
WriteShapeModel3D . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 676

9 Morphology 677
9.1 Gray-Values . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 677
DualRank . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 677
GenDiscSe . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 679
GrayBothat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 679
GrayClosing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 680
GrayClosingRect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 681
GrayClosingShape . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 682
GrayDilation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 683
GrayDilationRect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 684
GrayDilationShape . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 684
GrayErosion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 685
GrayErosionRect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 686
GrayErosionShape . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 687
GrayOpening . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 688
GrayOpeningRect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 689
GrayOpeningShape . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 690
GrayRangeRect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 691
GrayTophat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 692
ReadGraySe . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 692
9.2 Region . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 693
BottomHat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 693
Boundary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 694
Closing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 695
ClosingCircle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 696
ClosingGolay . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 697
ClosingRectangle1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 698
Dilation1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 699
Dilation2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 701
DilationCircle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 702
DilationGolay . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 703
DilationRectangle1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 704
DilationSeq . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 705
Erosion1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 707
Erosion2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 708
ErosionCircle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 709
ErosionGolay . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 710
ErosionRectangle1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 711
ErosionSeq . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 713
Fitting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 714
GenStructElements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 714
GolayElements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 715
HitOrMiss . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 719
HitOrMissGolay . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 720
HitOrMissSeq . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 721
MinkowskiAdd1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 722
MinkowskiAdd2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 723
MinkowskiSub1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 725
MinkowskiSub2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 726
MorphHat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 727
MorphSkeleton . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 728
MorphSkiz . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 729
Opening . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 730
OpeningCircle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 731
OpeningGolay . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 732
OpeningRectangle1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 734
OpeningSeg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 735
Pruning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 736
Thickening . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 737
ThickeningGolay . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 738
ThickeningSeq . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 739
Thinning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 740
ThinningGolay . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 741
ThinningSeq . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 742
TopHat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 744

10 OCR 745
10.1 Hyperboxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 745
CloseAllOcrs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 745
CloseOcr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 745
CreateOcrClassBox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 746
DoOcrMulti . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 748
DoOcrSingle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 749
InfoOcrClassBox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 750
OcrChangeChar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 751
OcrGetFeatures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 752
ReadOcr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 752
TestdOcrClassBox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 753
TraindOcrClassBox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 754
TrainfOcrClassBox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 754
WriteOcr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 755
10.2 Lexica . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 756
ClearAllLexica . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 756
ClearLexicon . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 756
CreateLexicon . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 757
ImportLexicon . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 757
InspectLexicon . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 758
LookupLexicon . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 758
SuggestLexicon . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 759
10.3 Neural-Nets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 759
ClearAllOcrClassMlp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 759
ClearOcrClassMlp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 760
CreateOcrClassMlp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 760
DoOcrMultiClassMlp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 764
DoOcrSingleClassMlp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 765
DoOcrWordMlp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 766
GetFeaturesOcrClassMlp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 767
GetParamsOcrClassMlp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 768
GetPrepInfoOcrClassMlp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 769
ReadOcrClassMlp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 770
TrainfOcrClassMlp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 771
WriteOcrClassMlp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 773
10.4 Support-Vector-Machines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 773
ClearAllOcrClassSvm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 773
ClearOcrClassSvm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 774
CreateOcrClassSvm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 774
DoOcrMultiClassSvm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 778
DoOcrSingleClassSvm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 778
DoOcrWordSvm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 779
GetFeaturesOcrClassSvm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 781
GetParamsOcrClassSvm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 781
GetPrepInfoOcrClassSvm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 782
GetSupportVectorNumOcrClassSvm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 784
GetSupportVectorOcrClassSvm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 785
ReadOcrClassSvm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 785
ReduceOcrClassSvm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 786
TrainfOcrClassSvm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 787
WriteOcrClassSvm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 788
10.5 Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 789
SegmentCharacters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 789
SelectCharacters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 791
TextLineOrientation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 794
TextLineSlant . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 795
10.6 Training-Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 796
AppendOcrTrainf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 796
ConcatOcrTrainf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 797
ReadOcrTrainf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 798
ReadOcrTrainfNames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 798
ReadOcrTrainfSelect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 799
WriteOcrTrainf . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 800
WriteOcrTrainfImage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 800

11 Object 803
11.1 Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 803
CountObj . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 803
GetChannelInfo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 803
GetObjClass . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 804
TestEqualObj . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 805
TestObjDef . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 806
11.2 Manipulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 806
ClearObj . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 806
ConcatObj . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 807
CopyObj . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 808
GenEmptyObj . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 809
IntegerToObj . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 809
ObjToInteger . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 810
SelectObj . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 811

12 Regions 813
12.1 Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 813
GetRegionChain . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 813
GetRegionContour . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 814
GetRegionConvex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 814
GetRegionPoints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 815
GetRegionPolygon . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 816
GetRegionRuns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 817
12.2 Creation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 818
GenCheckerRegion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 818
GenCircle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 819
GenEllipse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 820
GenEmptyRegion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 822
GenGridRegion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 822
GenRandomRegion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 824
GenRandomRegions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 825
GenRectangle1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 827
GenRectangle2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 828
GenRegionContourXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 829
GenRegionHisto . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 830
GenRegionHline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 831
GenRegionLine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 832
GenRegionPoints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 833
GenRegionPolygon . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 834
GenRegionPolygonFilled . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 835
GenRegionPolygonXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 835
GenRegionRuns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 836
LabelToRegion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 837
12.3 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 838
AreaCenter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 838
Circularity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 839
Compactness . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 840
ConnectAndHoles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 841
Contlength . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 841
Convexity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 842
DiameterRegion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 843
Eccentricity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 844
EllipticAxis . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 845
EulerNumber . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 846
FindNeighbors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 847
GetRegionIndex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 848
GetRegionThickness . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 849
HammingDistance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 849
HammingDistanceNorm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 850
InnerCircle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 851
InnerRectangle1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 853
MomentsRegion2Nd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 853
MomentsRegion2NdInvar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 855
MomentsRegion2NdRelInvar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 856
MomentsRegion3Rd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 856
MomentsRegion3RdInvar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 857
MomentsRegionCentral . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 858
MomentsRegionCentralInvar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 859
OrientationRegion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 860
Rectangularity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 861
Roundness . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 862
RunlengthDistribution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 863
RunlengthFeatures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 864
SelectRegionPoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 865
SelectRegionSpatial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 866
SelectShape . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 867
SelectShapeProto . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 870
SelectShapeStd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 872
SmallestCircle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 873
SmallestRectangle1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 874
SmallestRectangle2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 875
SpatialRelation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 876
12.4 Geometric-Transformations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 877
AffineTransRegion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 877
MirrorRegion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 879
MoveRegion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 880
PolarTransRegion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 881
PolarTransRegionInv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 883
ProjectiveTransRegion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 885
TransposeRegion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 885
ZoomRegion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 887
12.5 Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 887
Complement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 887
Difference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 888
Intersection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 889
SymmDifference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 890
Union1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 891
Union2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 891
12.6 Tests . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 892
TestEqualRegion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 892
TestRegionPoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 893
TestSubsetRegion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 894
12.7 Transformation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 894
BackgroundSeg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 894
ClipRegion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 895
ClipRegionRel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 896
Connection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 897
DistanceTransform . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 899
EliminateRuns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 900
ExpandRegion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 901
FillUp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 902
FillUpShape . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 903
HammingChangeRegion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 904
Interjacent . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 905
JunctionsSkeleton . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 906
MergeRegionsLineScan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 907
PartitionDynamic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 908
PartitionRectangle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 909
RankRegion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 910
RemoveNoiseRegion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 911
ShapeTrans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 912
Skeleton . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 913
SortRegion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 913
SplitSkeletonLines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 914
SplitSkeletonRegion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 916

13 Segmentation 917
13.1 Classification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 917
AddSamplesImageClassGmm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 917
AddSamplesImageClassMlp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 918
AddSamplesImageClassSvm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 919
Class2DimSup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 920
Class2DimUnsup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 921
ClassNdimBox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 922
ClassNdimNorm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 923
ClassifyImageClassGmm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 924
ClassifyImageClassMlp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 925
ClassifyImageClassSvm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 926
LearnNdimBox . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 928
LearnNdimNorm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 929
13.2 Edges . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 930
DetectEdgeSegments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 930
HysteresisThreshold . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 932
NonmaxSuppressionAmp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 933
NonmaxSuppressionDir . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 934
13.3 Regiongrowing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 935
ExpandGray . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 935
ExpandGrayRef . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 936
ExpandLine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 938
Regiongrowing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 939
RegiongrowingMean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 940
RegiongrowingN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 941
13.4 Threshold . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 946
AutoThreshold . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 946
BinThreshold . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 947
CharThreshold . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 947
CheckDifference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 949
DualThreshold . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 950
DynThreshold . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 952
FastThreshold . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 953
HistoToThresh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 955
Threshold . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 956
ThresholdSubPix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 957
VarThreshold . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 958
ZeroCrossing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 959
ZeroCrossingSubPix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 960
13.5 Topography . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 961
CriticalPointsSubPix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 961
LocalMax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 962
LocalMaxSubPix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 963
LocalMin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 964
LocalMinSubPix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 964
Lowlands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 965
LowlandsCenter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 966
Plateaus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 966
PlateausCenter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 967
Pouring . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 967
SaddlePointsSubPix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 969
Watersheds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 970
WatershedsThreshold . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 971

14 System 973
14.1 Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 973
CountRelation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 973
GetModules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 974
ResetObjDb . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 975
14.2 Error-Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 976
GetCheck . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 976
GetErrorText . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 976
GetSpy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 977
QuerySpy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 978
SetCheck . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 978
SetSpy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 979
14.3 Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 981
GetChapterInfo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 981
GetKeywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 982
GetOperatorInfo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 983
GetOperatorName . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 984
GetParamInfo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 985
GetParamNames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 986
GetParamNum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 987
GetParamTypes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 988
QueryOperatorInfo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 989
QueryParamInfo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 989
SearchOperator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 990
14.4 Operating-System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 990
CountSeconds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 990
SystemCall . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 991
WaitSeconds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 991
14.5 Parallelization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 992
CheckParHwPotential . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 992
LoadParKnowledge . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 993
StoreParKnowledge . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 994
14.6 Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 994
GetSystem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 994
SetSystem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 998
14.7 Serial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1004
ClearSerial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1004
CloseAllSerials . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1005
CloseSerial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1005
GetSerialParam . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1006
OpenSerial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1007
ReadSerial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1007
SetSerialParam . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1008
WriteSerial . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1009
14.8 Sockets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1010
CloseSocket . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1010
GetNextSocketDataType . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1010
GetSocketDescriptor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1011
GetSocketTimeout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1011
OpenSocketAccept . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1012
OpenSocketConnect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1013
ReceiveImage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1014
ReceiveRegion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1014
ReceiveTuple . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1015
ReceiveXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1015
SendImage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1016
SendRegion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1016
SendTuple . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1017
SendXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1017
SetSocketTimeout . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1018
SocketAcceptConnect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1019

15 Tools 1021
15.1 2D-Transformations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1021
AffineTransPixel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1021
AffineTransPoint2D . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1022
BundleAdjustMosaic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1023
HomMat2dCompose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1026
HomMat2dDeterminant . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1026
HomMat2dIdentity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1027
HomMat2dInvert . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1027
HomMat2dRotate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1028
HomMat2dRotateLocal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1029
HomMat2dScale . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1030
HomMat2dScaleLocal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1032
HomMat2dSlant . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1033
HomMat2dSlantLocal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1035
HomMat2dToAffinePar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1036
HomMat2dTranslate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1037
HomMat2dTranslateLocal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1038
HomMat2dTranspose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1039
HomMat3dProject . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1040
HomVectorToProjHomMat2d . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1041
ProjMatchPointsRansac . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1043
ProjectiveTransPixel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1045
ProjectiveTransPoint2D . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1046
VectorAngleToRigid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1047
VectorFieldToHomMat2d . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1049
VectorToHomMat2d . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1049
VectorToProjHomMat2d . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1050
VectorToRigid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1052
VectorToSimilarity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1053
15.2 3D-Transformations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1054
AffineTransPoint3D . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1054
ConvertPoseType . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1055
CreatePose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1056
GetPoseType . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1061
HomMat3dCompose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1061
HomMat3dIdentity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1062
HomMat3dInvert . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1063
HomMat3dRotate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1063
HomMat3dRotateLocal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1065
HomMat3dScale . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1066
HomMat3dScaleLocal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1068
HomMat3dToPose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1069
HomMat3dTranslate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1070
HomMat3dTranslateLocal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1071
PoseToHomMat3d . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1072
ReadPose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1073
SetOriginPose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1074
WritePose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1075
15.3 Background-Estimator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1077
CloseAllBgEsti . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1077
CloseBgEsti . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1077
CreateBgEsti . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1078
GetBgEstiParams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1081
GiveBgEsti . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1082
RunBgEsti . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1083
SetBgEstiParams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1084
UpdateBgEsti . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1086
15.4 Barcode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1087
ClearAllBarCodeModels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1087
ClearBarCodeModel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1088
CreateBarCodeModel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1088
FindBarCode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1089
GetBarCodeObject . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1091
GetBarCodeParam . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1092
GetBarCodeResult . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1093
SetBarCodeParam . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1094
15.5 Calibration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1097
CaltabPoints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1097
CamMatToCamPar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1098
CamParToCamMat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1099
CameraCalibration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1100
ChangeRadialDistortionCamPar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1107
ChangeRadialDistortionContoursXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1108
ChangeRadialDistortionImage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1109
ContourToWorldPlaneXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1110
CreateCaltab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1111
DispCaltab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1114
FindCaltab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1115
FindMarksAndPose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1116
GenCaltab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1118
GenImageToWorldPlaneMap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1122
GenRadialDistortionMap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1124
GetCirclePose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1125
GetLineOfSight . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1127
GetRectanglePose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1128
HandEyeCalibration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1131
ImagePointsToWorldPlane . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1139
ImageToWorldPlane . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1140
Project3DPoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1142
RadiometricSelfCalibration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1143
ReadCamPar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1146
SimCaltab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1149
StationaryCameraSelfCalibration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1151
WriteCamPar . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1156
15.6 Datacode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1159
ClearAllDataCode2DModels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1159
ClearDataCode2DModel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1159
CreateDataCode2DModel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1160
FindDataCode2D . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1163
GetDataCode2DObjects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1167
GetDataCode2DParam . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1169
GetDataCode2DResults . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1171
QueryDataCode2DParams . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1178
ReadDataCode2DModel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1179
SetDataCode2DParam . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1180
WriteDataCode2DModel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1185
15.7 Fourier-Descriptor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1186
AbsInvarFourierCoeff . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1186
Fourier1Dim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1187
Fourier1DimInv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1187
InvarFourierCoeff . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1188
MatchFourierCoeff . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1189
MoveContourOrig . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1190
PrepContourFourier . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1190
15.8 Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1191
AbsFunct1D . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1191
ComposeFunct1D . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1191
CreateFunct1DArray . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1192
CreateFunct1DPairs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1193
DerivateFunct1D . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1193
DistanceFunct1D . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1194
Funct1DToPairs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1194
GetPairFunct1D . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1195
GetYValueFunct1D . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1195
IntegrateFunct1D . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1196
InvertFunct1D . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1196
LocalMinMaxFunct1D . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1197
MatchFunct1DTrans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1198
NegateFunct1D . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1199
NumPointsFunct1D . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1199
ReadFunct1D . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1200
SampleFunct1D . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1200
ScaleYFunct1D . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1201
SmoothFunct1DGauss . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1201
SmoothFunct1DMean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1202
TransformFunct1D . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1203
WriteFunct1D . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1203
XRangeFunct1D . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1204
YRangeFunct1D . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1204
ZeroCrossingsFunct1D . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1205
15.9 Geometry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1205
AngleLl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1205
AngleLx . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1206
DistanceCc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1207
DistanceCcMin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1208
DistanceLc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1209
DistanceLr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1210
DistancePc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1211
DistancePl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1211
DistancePp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1213
DistancePr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1214
DistancePs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1215
DistanceRrMin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1216
DistanceRrMinDil . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1217
DistanceSc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1218
DistanceSl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1219
DistanceSr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1220
DistanceSs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1221
GetPointsEllipse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1222
IntersectionLl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1223
ProjectionPl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1225
15.10 Grid-Rectification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1226
ConnectGridPoints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1226
CreateRectificationGrid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1227
FindRectificationGrid . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1228
GenArbitraryDistortionMap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1229
GenGridRectificationMap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1230
15.11 Hough . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1231
HoughCircleTrans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1231
HoughCircles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1232
HoughLineTrans . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1233
HoughLineTransDir . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1234
HoughLines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1235
HoughLinesDir . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1236
SelectMatchingLines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1238
15.12 Image-Comparison . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1239
ClearAllVariationModels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1239
ClearTrainDataVariationModel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1239
ClearVariationModel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1240
CompareExtVariationModel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1240
CompareVariationModel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1242
CreateVariationModel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1243
GetThreshImagesVariationModel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1244
GetVariationModel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1245
PrepareDirectVariationModel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1246
PrepareVariationModel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1247
ReadVariationModel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1248
TrainVariationModel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1249
WriteVariationModel . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1250
15.13 Kalman-Filter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1251
FilterKalman . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1251
ReadKalman . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1255
SensorKalman . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1257
UpdateKalman . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1258
15.14 Measure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1261
CloseAllMeasures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1261
CloseMeasure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1261
FuzzyMeasurePairing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1262
FuzzyMeasurePairs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1264
FuzzyMeasurePos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1266
GenMeasureArc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1268
GenMeasureRectangle2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1271
MeasurePairs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1273
MeasurePos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1275
MeasureProjection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1277
MeasureThresh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1278
ResetFuzzyMeasure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1279
SetFuzzyMeasure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1280
SetFuzzyMeasureNormPair . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1281
TranslateMeasure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1283
15.15 OCV . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1284
CloseAllOcvs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1284
CloseOcv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1284
CreateOcvProj . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1285
DoOcvSimple . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1286
ReadOcv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1287
TraindOcvProj . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1287
WriteOcv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1288
15.16 Shape-from . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1289
DepthFromFocus . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1289
EstimateAlAm . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1290
EstimateSlAlLr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1290
EstimateSlAlZc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1291
EstimateTiltLr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1291
EstimateTiltZc . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1292
PhotStereo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1292
SelectGrayvaluesFromChannels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1293
SfsModLr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1294
SfsOrigLr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1295
SfsPentland . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1296
ShadeHeightField . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1298
15.17 Stereo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1299
BinocularCalibration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1299
BinocularDisparity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1302
BinocularDistance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1305
DisparityToDistance . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1309
DisparityToPoint3D . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1310
DistanceToDisparity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1311
EssentialToFundamentalMatrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1311
GenBinocularProjRectification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1313
GenBinocularRectificationMap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1315
IntersectLinesOfSight . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1317
MatchEssentialMatrixRansac . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1319
MatchFundamentalMatrixRansac . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1323
MatchRelPoseRansac . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1326
Reconst3dFromFundamentalMatrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1330
RelPoseToFundamentalMatrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1331
VectorToEssentialMatrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1332
VectorToFundamentalMatrix . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1335
VectorToRelPose . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1337
15.18 Tools-Legacy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1340
Decode1DBarCode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1340
Decode2DBarCode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1341
Discrete1DBarCode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1342
Find1DBarCode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1343
Find1DBarCodeRegion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1347
Find1DBarCodeScanline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1348
Find2DBarCode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1349
Gen1DBarCodeDescr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1353
Gen1DBarCodeDescrGen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1354
Gen2DBarCodeDescr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1355
Get1DBarCode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1357
Get1DBarCodeScanline . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1358
Get2DBarCode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1359
Get2DBarCodePos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1363

16 Tuple 1365
16.1 Arithmetic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1365
TupleAbs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1365
TupleAcos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1365
TupleAdd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1366
TupleAsin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1366
TupleAtan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1367
TupleAtan2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1367
TupleCeil . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1368
TupleCos . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1368
TupleCosh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1368
TupleCumul . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1369
TupleDeg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1369
TupleDiv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1370
TupleExp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1370
TupleFabs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1370
TupleFloor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1371
TupleFmod . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1371
TupleLdexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1372
TupleLog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1372
TupleLog10 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1373
TupleMax2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1373
TupleMin2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1374
TupleMod . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1374
TupleMult . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1375
TupleNeg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1375
TuplePow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1375
TupleRad . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1376
TupleSgn . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1376
TupleSin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1377
TupleSinh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1377
TupleSqrt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1377
TupleSub . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1378
TupleTan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1378
TupleTanh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1379
16.2 Bit-Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1379
TupleBand . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1379
TupleBnot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1379
TupleBor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1380
TupleBxor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1380
TupleLsh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1381
TupleRsh . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1381
16.3 Comparison . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1382
TupleEqual . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1382
TupleGreater . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1382
TupleGreaterEqual . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1383
TupleLess . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1384
TupleLessEqual . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1384
TupleNotEqual . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1385
16.4 Conversion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1385
TupleChr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1385
TupleChrt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1386
TupleInt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1386
TupleIsNumber . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1387
TupleNumber . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1387
TupleOrd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1387
TupleOrds . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1388
TupleReal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1388
TupleRound . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1389
TupleString . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1389
16.5 Creation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1391
TupleConcat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1391
TupleGenConst . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1391
TupleRand . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1392
16.6 Element-Order . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1392
TupleInverse . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1392
TupleSort . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1392
TupleSortIndex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1393
16.7 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1393
TupleDeviation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1393
TupleLength . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1394
TupleMax . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1394
TupleMean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1395
TupleMedian . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1395
TupleMin . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1395
TupleSum . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1396
16.8 Logical-Operations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1396
TupleAnd . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1396
TupleNot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1397
TupleOr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1397
TupleXor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1398
16.9 Selection . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1398
TupleFind . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1398
TupleFirstN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1399
TupleLastN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1399
TupleRemove . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1400
TupleSelect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1400
TupleSelectRange . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1401
TupleSelectRank . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1402
TupleStrBitSelect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1402
TupleUniq . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1403
16.10 String-Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1403
TupleEnvironment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1403
TupleRegexpMatch . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1404
TupleRegexpReplace . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1405
TupleRegexpSelect . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1406
TupleRegexpTest . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1407
TupleSplit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1408
TupleStrFirstN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1408
TupleStrLastN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1409
TupleStrchr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1409
TupleStrlen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1410
TupleStrrchr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1410
TupleStrrstr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1411
TupleStrstr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1412

17 XLD 1413
17.1 Access . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1413
GetContourXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1413
GetLinesXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1413
GetParallelsXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1414
GetPolygonXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1415
17.2 Creation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1416
GenContourNurbsXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1416
GenContourPolygonRoundedXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1418
GenContourPolygonXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1418
GenContourRegionXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1419
GenContoursSkeletonXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1420
GenCrossContourXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1421
GenEllipseContourXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1422
GenParallelsXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1423
GenPolygonsXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1424
GenRectangle2ContourXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1425
ModParallelsXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1426
17.3 Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1427
AreaCenterPointsXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1427
AreaCenterXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1428
CircularityXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1429
CompactnessXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1430
ContourPointNumXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1430
ConvexityXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1431
DiameterXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1432
DistEllipseContourPointsXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1433
DistEllipseContourXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1434
DistRectangle2ContourPointsXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1436
EccentricityPointsXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1437
EccentricityXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1437
EllipticAxisPointsXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1438
EllipticAxisXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1440
FitCircleContourXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1441
FitEllipseContourXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1443
FitLineContourXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1446
FitRectangle2ContourXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1448
GetContourAngleXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1450
GetContourAttribXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1451
GetContourGlobalAttribXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1452
GetRegressParamsXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1452
InfoParallelsXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1453
LengthXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1454
LocalMaxContoursXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1455
MaxParallelsXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1456
MomentsAnyPointsXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1456
MomentsAnyXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1458
MomentsPointsXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1459
MomentsXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1460
OrientationPointsXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1461
OrientationXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1462
QueryContourAttribsXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1463
QueryContourGlobalAttribsXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1463
SelectContoursXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1464
SelectShapeXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1465
SelectXldPoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1467
SmallestCircleXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1468
SmallestRectangle1Xld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1469
SmallestRectangle2Xld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1469
TestSelfIntersectionXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1470
TestXldPoint . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1471
17.4 Geometric-Transformations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1472
AffineTransContourXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1472
AffineTransPolygonXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1473
GenParallelContourXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1474
PolarTransContourXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1475
PolarTransContourXldInv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1477
ProjectiveTransContourXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1479
17.5 Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1479
DifferenceClosedContoursXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1479
DifferenceClosedPolygonsXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1480
IntersectionClosedContoursXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1481
IntersectionClosedPolygonsXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1482
SymmDifferenceClosedContoursXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1483
SymmDifferenceClosedPolygonsXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1484
Union2ClosedContoursXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1485
Union2ClosedPolygonsXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1486
17.6 Transformation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1487
AddNoiseWhiteContourXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1487
ClipContoursXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1488
CloseContoursXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1489
CombineRoadsXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1490
CropContoursXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1491
MergeContLineScanXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1492
RegressContoursXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1493
SegmentContoursXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1494
ShapeTransXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1496
SmoothContoursXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1497
SortContoursXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1497
SplitContoursXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1498
UnionAdjacentContoursXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1499
UnionCocircularContoursXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1500
UnionCollinearContoursExtXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1502
UnionCollinearContoursXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1504
UnionStraightContoursHistoXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1506
UnionStraightContoursXld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1507

18 Class Hierarchy 1509


18.1 HBarCodeX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1509
18.2 HBarCode1DX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1509
18.3 HBarCode2DX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1510
18.4 HBgEstiX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1511
18.5 HClassBoxX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1511
18.6 HClassGmmX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1512
18.7 HClassMlpX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1513
18.8 HClassSvmX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1514
18.9 HComponentModelX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1515
18.10 HComponentTrainingX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1516
18.11 HDataCode2DX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1516
18.12 HFeatureSetX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1517
18.13 HFileX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1517
18.14 HFramegrabberX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1518
18.15 HFunction1dX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1520
18.16 HGnuplotX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1521
18.17 HHistogramX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1521
18.18 HHomMat2dX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1522
18.19 HHomMat3dX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1524
18.20 HImageX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1525
18.21 HInfoX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1541
18.22 HLexiconX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1542
18.23 HMeasureX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1543
18.24 HMiscX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1544
18.25 HNccModelX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1547
18.26 HObjectX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1548
18.27 HObjectModel3DX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1548
18.28 HOcrBoxX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1549
18.29 HOcrMlpX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1550
18.30 HOcrSvmX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1550
18.31 HOcvX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1551
18.32 HOperatorSetX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1552
18.33 HPoseX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1604
18.34 HRegionX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1605
18.35 HSerialX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1614
18.36 HShapeModelX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1615
18.37 HShapeModel3DX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1616
18.38 HSocketX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1616
18.39 HSystemX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1617
18.40 HTemplateX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1618
18.41 HTupleX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1619
18.42 HUntypedObjectX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1623
18.43 HVariationModelX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1624
18.44 HWindowX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1624
18.45 HXLDX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1631
18.46 HXLDContX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1633
18.47 HXLDExtParaX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1636
18.48 HXLDModParaX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1636
18.49 HXLDParaX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1637
18.50 HXLDPolyX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1637

Index 1639
Chapter 1

Classification

1.1 Gaussian-Mixture-Models
void HClassGmmX.AddSampleClassGmm ([in] VARIANT Features,
[in] long ClassID, [in] double Randomize )
void HOperatorSetX.AddSampleClassGmm ([in] VARIANT GMMHandle,
[in] VARIANT Features, [in] VARIANT ClassID, [in] VARIANT Randomize )

Add a training sample to the training data of a Gaussian Mixture Model.


AddSampleClassGmm adds a training sample to the Gaussian Mixture Model (GMM) given by GMMHandle.
The training sample is given by Features and ClassID. Features is the feature vector of the sample, and
consequently must be a real vector of length NumDim, as specified in CreateClassGmm. ClassID is the class
of the sample, an integer between 0 and NumClasses-1 (set in CreateClassGmm).
In the special case where the feature vectors are of integer type, they are lying in the feature space in a grid with
step width 1.0. For example, the RGB feature vectors typically used for color classification are triples having
integer values between 0 and 255 for each of their components. In fact, there might be even several feature vectors
representing the same point. When training a GMM with such data, the training algorithm may tend to align the
modelled Gaussians along linearly dependent lines or planes of data that are parallel to the grid dimensions. If
the number of Centers returned by TrainClassGmm is unusually high, this indicates such a behavior of the
algorithm. The parameter Randomize can be used to handle such undesired effects. If Randomize > 0.0,
random Gaussian noise with mean 0 and standard deviation Randomize is added to each component of the
training data vectors, and the transformed training data is stored in the GMM. For values of Randomize ≤ 1.0,
the randomized data will look like small clouds around the grid points, which does not improve the properties of
the data cloud. For values of Randomize  2.0, the randomization might have a too strong influence on the
resulting GMM. For integer feature vectors, a value of Randomize between 1.5 and 2.0 is recommended, which
transfoms the integer data into homogeneous clouds, without modifying its general form in the feature space. If
the data has been created from integer data by scaling, the same problem may occur. Here, Randomize must be
scaled with the same scale factor that was used to scale the original data.
Before the GMM can be trained with TrainClassGmm, all training samples must be added to the GMM with
AddSampleClassGmm.
The number of currently stored training samples can be queried with GetSampleNumClassGmm. Stored train-
ing samples can be read out again with GetSampleClassGmm.
Normally, it is useful to save the training samples in a file with WriteSamplesClassGmm to facilitate reusing
the samples, and to facilitate that, if necessary, new training samples can be added to the data set, and hence to
facilitate that a newly created GMM can be trained anew with the extended data set.
Parameter

. GMMHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_gmm ; HClassGmmX / VARIANT


GMM handle.
. Features (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Feature vector of the training sample to be stored.

1
2 CHAPTER 1. CLASSIFICATION

. ClassID (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; long / VARIANT


Class of the training sample to be stored.
. Randomize (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Standard deviation of the Gaussian noise added to the training data.
Default Value : 0.0
Suggested values : Randomize ∈ {0.0, 1.5, 2.0}
Restriction : (Randomize ≥ 0.0)
Result
If the parameters are valid, the operator AddSampleClassGmm returns the value TRUE. If necessary an excep-
tion handling is raised.
Parallelization Information
AddSampleClassGmm is processed completely exclusively without parallelization.
Possible Predecessors
CreateClassGmm
Possible Successors
TrainClassGmm, WriteSamplesClassGmm
See also
ClearSamplesClassGmm, GetSampleNumClassGmm, GetSampleClassGmm
Alternatives
ReadSamplesClassGmm, AddSamplesImageClassGmm
Module
Foundation

[out] VARIANT ClassID HClassGmmX.ClassifyClassGmm


([in] VARIANT Features, [in] long Num, [out] VARIANT ClassProb,
[out] VARIANT Density, [out] VARIANT KSigmaProb )
void HOperatorSetX.ClassifyClassGmm ([in] VARIANT GMMHandle,
[in] VARIANT Features, [in] VARIANT Num, [out] VARIANT ClassID,
[out] VARIANT ClassProb, [out] VARIANT Density, [out] VARIANT KSigmaProb )

Calculate the class of a feature vector by a Gaussian Mixture Model.


ClassifyClassGmm computes the best Num classes of the feature vector Features with the Gaussian Mixture
Model (GMM) GMMHandle and returns the classes in ClassID and the corresponding probabilities of the classes
in ClassProb. Before calling ClassifyClassGmm, the GMM must be trained with TrainClassGmm.
ClassifyClassGmm corresponds to a call to EvaluateClassGmm and an additional step that extracts
the best Num classes. As described with EvaluateClassGmm, the output values of the GMM can be in-
terpreted as probabilities of the occurrence of the respective classes. However, here the posterior probability
ClassProb is further normalized as ClassProb = p(i|x)/p(x), where p(i|x) and p(x) are specified with
EvaluateClassGmm. In most cases it should be sufficient to use Num = 1 in order to decide whether the prob-
ability of the best class is high enough. In some applications it may be interesting to also take the second best class
into account (Num = 2), particularly if it can be expected that the classes show a significant degree of overlap.
Density and KSigmaProb are explained with EvaluateClassGmm.
Parameter
. GMMHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_gmm ; HClassGmmX / VARIANT
GMM handle.
. Features (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Feature vector.
. Num (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of best classes to determine.
Default Value : 1
Suggested values : Num ∈ {1, 2, 3, 4, 5}
. ClassID (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Result of classifying the feature vector with the GMM.

HALCON/COM Reference Manual, 2008-5-13


1.1. GAUSSIAN-MIXTURE-MODELS 3

. ClassProb (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )


A-posteriori probability of the classes.
. Density (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Probability density of the feature vector.
. KSigmaProb (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Normalized k-sigma-probability for the feature vector.
Result
If the parameters are valid, the operator ClassifyClassGmm returns the value TRUE. If necessary an exception
handling is raised.
Parallelization Information
ClassifyClassGmm is reentrant and processed without parallelization.
Possible Predecessors
TrainClassGmm, ReadClassGmm
See also
CreateClassGmm
Alternatives
EvaluateClassGmm
References
Christopher M. Bishop: “Neural Networks for Pattern Recognition”; Oxford University Press, Oxford; 1995.
Mario A.T. Figueiredo: “Unsupervised Learning of Finite Mixture Models”; IEEE Transactions on Pattern Analy-
sis and Machine Intelligence, Vol. 24, No. 3; March 2002.
Module
Foundation

void HMiscX.ClearAllClassGmm ( )
void HOperatorSetX.ClearAllClassGmm ( )

Clear all Gaussian Mixture Models.


ClearAllClassGmm clears all Gaussian Mixture Models (GMM) and frees all memory required for the GMMs.
After calling ClearAllClassGmm, no GMM can be used any longer.
Attention
ClearAllClassGmm exists solely for the purpose of implementing the “reset program” functionality in HDe-
velop. ClearAllClassGmm must not be used in any application.
Result
ClearAllClassGmm always returns TRUE.
Parallelization Information
ClearAllClassGmm is processed completely exclusively without parallelization.
Possible Predecessors
ClassifyClassGmm, EvaluateClassGmm
See also
CreateClassGmm, ReadClassGmm, WriteClassGmm, TrainClassGmm
Alternatives
ClearClassGmm
Module
Foundation

void HOperatorSetX.ClearClassGmm ([in] VARIANT GMMHandle )

Clear a Gaussian Mixture Model.

HALCON 8.0.2
4 CHAPTER 1. CLASSIFICATION

ClearClassGmm clears the Gaussian Mixture Model (GMM) given by GMMHandle and frees all memory re-
quired for the GMM. After calling ClearClassGmm, the GMM can no longer be used. The handle GMMHandle
becomes invalid.
Parameter

. GMMHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_gmm ; HClassGmmX / VARIANT


GMM handle.
Result
If the parameters are valid, the operator ClearClassGmm returns the value TRUE. If necessary an exception
handling is raised.
Parallelization Information
ClearClassGmm is processed completely exclusively without parallelization.
Possible Predecessors
ClassifyClassGmm, EvaluateClassGmm
See also
CreateClassGmm, ReadClassGmm, WriteClassGmm, TrainClassGmm
Module
Foundation

void HClassGmmX.ClearSamplesClassGmm ( )
void HOperatorSetX.ClearSamplesClassGmm ([in] VARIANT GMMHandle )

Clear the training data of a Gaussian Mixture Model.


ClearSamplesClassGmm clears all training samples that have been stored in the Gaussian Mixture
Model (GMM) GMMHandle. ClearSamplesClassGmm should only be used if the GMM is trained
in the same process that uses the GMM for evaluation with EvaluateClassGmm or for classification
with ClassifyClassGmm. In this case, the memory required for the training samples can be freed
with ClearSamplesClassGmm, and hence memory can be saved. In the normal usage, in which the
GMM is trained offline and written to a file with WriteClassGmm, it is typically unnecessary to call
ClearSamplesClassGmm because WriteClassGmm does not save the training samples, and hence the on-
line process, which reads the GMM with ReadClassGmm, requires no memory for the training samples.
Parameter

. GMMHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_gmm ; HClassGmmX / VARIANT


GMM handle.
Result
If the parameters are valid, the operator ClearSamplesClassGmm returns the value TRUE. If necessary an
exception handling is raised.
Parallelization Information
ClearSamplesClassGmm is processed completely exclusively without parallelization.
Possible Predecessors
TrainClassGmm, WriteSamplesClassGmm
See also
CreateClassGmm, ClearClassGmm, AddSampleClassGmm, ReadSamplesClassGmm
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


1.1. GAUSSIAN-MIXTURE-MODELS 5

void HClassGmmX.CreateClassGmm ([in] long NumDim, [in] long NumClasses,


[in] VARIANT NumCenters, [in] String CovarType, [in] String Preprocessing,
[in] long NumComponents, [in] long RandSeed )
void HOperatorSetX.CreateClassGmm ([in] VARIANT NumDim,
[in] VARIANT NumClasses, [in] VARIANT NumCenters, [in] VARIANT CovarType,
[in] VARIANT Preprocessing, [in] VARIANT NumComponents,
[in] VARIANT RandSeed, [out] VARIANT GMMHandle )

Create a Gaussian Mixture Model for classification


CreateClassGmm creates a Gaussian Mixture Model (GMM) for classification. NumDim specifies the num-
ber of dimensions of the feature space, NumClasses specifies the number of classes. A GMM consists of
NumCenters Gaussian centers per class. NumCenters can not only be the exact number of centers to be used,
but, depending on the number of parameters, can specify upper and lower bounds for the number of centers:

exactly one parameter: The parameter determines the exact number of centers to be used for all classes.
exactly two parameters: The first parameter determines the mimimum number of centers, the second determines
the maximum number of centers for all classes.
exactly 2 · N umClasses parameters: Alternatingly every first parameter determines the minimum number of
centers per class and every second parameters determines the maximum number of centers per class.

When upper and lower bounds are specified, the optimum number of centers will be determined with the help of
the Mimimum Message Length Criterion (MML). In general, we recommend to start the training with (too) many
centers as maximum and the expected number of centers as minimum.
Each center is described by the parameters center mj , covariance matrix Cj , and mixing coefficient Pj . These pa-
rameters are calculated from the training data by means of the Expectation Maximization (EM) algorithm. A GMM
can approximate an arbitrary probability density, provided that enough centers are being used. The covariance ma-
trices Cj have the dimensions NumDim · NumDim (NumComponents · NumComponents if preprocessing is
used) and are symmetric. Further constraints can be given by CovarType:
For CovarType = ’spherical’, Cj is a scalar multiple of the identity matrix Cj = s2j I. The center density
function p(x|j) is

2
1 kx − mj k
p(x|j) = exp(− )
2
(2πsj )d/2 2s2j

For CovarType = ’diag’, Cj is a diagonal matrix Cj = diag(s2j,1 , ..., s2j,d ). The center density function p(x|j)
is

d
1 X (xi − mj,i )2
p(x|j) = exp(− )
d 2s2j,i
s2j,i )d/2
Q
(2π i=1
i=1

For CovarType = ’full’, Cj is a positive definite matrix. The center density function p(x|j) is

1 1
p(x|j) = 1 exp(− (x − mj )T C−1 (x − mj ))
(2π)d/2 |Cj | 2 2

The complexity of the calculations increases from CovarType = ’spherical’ over CovarType = ’diag’ to
CovarType = ’full’. At the same time the flexibility of the centers increases. In general, ’spherical’ therefore
needs higher values for NumCenters than ’full’.
The procedure to use GMM is as follows: First, a GMM is created by CreateClassGmm. Then, training vectors
are added by AddSampleClassGmm, afterwards they can be written to disk with WriteSamplesClassGmm.
With TrainClassGmm the classifier center parameters (defined above) are determined. Furthermore, they can
be saved with WriteClassGmm for later classifications.
From the mixing probabilities Pj and the center density function p(x|j), the probability density function p(x) can
be calculated by:

HALCON 8.0.2
6 CHAPTER 1. CLASSIFICATION

ncomp
X
p(x) = P (j)p(x|j)
j=1

The probability density function p(x) can be evaluated with EvaluateClassGmm for a feature vector x.
ClassifyClassGmm sorts the p(x) and therefore discovers the most probable class of the feature vector.
The parameters Preprocessing and NumComponents can be used to preprocess the training data and reduce
its dimensions. These parameteters are explained in the description of the operator CreateClassMlp.
CreateClassGmm initializes the coordinates of the centers with random numbers. To ensure that the results of
training the classifier with TrainClassGmm are reproducible, the seed value of the random number generator is
passed in RandSeed.
Parameter

. NumDim (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT


Number of dimensions of the feature space.
Default Value : 3
Suggested values : NumDim ∈ {1, 2, 3, 4, 5, 8, 10, 15, 20, 30, 40, 50, 60, 70, 80, 90, 100}
Restriction : (N umDim ≥ 1)
. NumClasses (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of classes of the GMM.
Default Value : 5
Suggested values : NumClasses ∈ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Restriction : (N umClasses ≥ 1)
. NumCenters (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Number of centers per class.
Default Value : 1
Suggested values : NumCenters ∈ {1, 2, 3, 4, 5, 8, 10, 15, 20, 30}
Restriction : (N umClasses ≥ 1)
. CovarType (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Type of the covariance matrices.
Default Value : ’spherical’
List of values : CovarType ∈ {’spherical’, ’diag’, ’full’}
. Preprocessing (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Type of preprocessing used to transform the feature vectors.
Default Value : ’normalization’
List of values : Preprocessing ∈ {’none’, ’normalization’, ’principal_components’,
’canonical_variates’}
. NumComponents (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Preprocessing parameter: Number of transformed features (ignored for Preprocessing = ’none’ and
Preprocessing = ’normalization’).
Default Value : 10
Suggested values : NumComponents ∈ {1, 2, 3, 4, 5, 8, 10, 15, 20, 30, 40, 50, 60, 70, 80, 90, 100}
Restriction : (N umComponents ≥ 1)
. RandSeed (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Seed value of the random number generator that is used to initialize the GMM with random values.
Default Value : 42
. GMMHandle (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_gmm ; HClassGmmX / VARIANT
GMM handle.
Example

* Classification with Gaussian Mixture Models


create_class_gmm (NumDim, NumClasses, [1,5], ’full’, 42, GMMHandle)
* Add the training data
for J := 0 to NData-1 by 1
Features := [...]

HALCON/COM Reference Manual, 2008-5-13


1.1. GAUSSIAN-MIXTURE-MODELS 7

Class := [...]
add_sample_class_gmm (GMMHandle, Features, Class)
endfor
* Train the GMM
train_class_gmm (GMMHandle, 100, 0.001, 0, Centers, Iter)
* Classify unknown data in ’Features’
classify_class_gmm (GMMHandle, Features, 1, ClassProb, Density, KSigmaProb)
clear_class_gmm (GMMHandle)

Result
If the parameters are valid, the operator CreateClassGmm returns the value TRUE. If necessary an exception
handling is raised.
Parallelization Information
CreateClassGmm is processed completely exclusively without parallelization.
Possible Successors
AddSampleClassGmm, AddSamplesImageClassGmm
See also
ClearClassGmm, TrainClassGmm, ClassifyClassGmm, EvaluateClassGmm,
ClassifyImageClassGmm
Alternatives
CreateClassMlp, CreateClassSvm, CreateClassBox
References
Christopher M. Bishop: “Neural Networks for Pattern Recognition”; Oxford University Press, Oxford; 1995.
Mario A.T. Figueiredo: “Unsupervised Learning of Finite Mixture Models”; IEEE Transactions on Pattern Analy-
sis and Machine Intelligence, Vol. 24, No. 3; March 2002.
Module
Foundation

[out] VARIANT ClassProb HClassGmmX.EvaluateClassGmm


([in] VARIANT Features, [out] double Density, [out] double KSigmaProb )
void HOperatorSetX.EvaluateClassGmm ([in] VARIANT GMMHandle,
[in] VARIANT Features, [out] VARIANT ClassProb, [out] VARIANT Density,
[out] VARIANT KSigmaProb )

Evaluate a feature vector by a Gaussian Mixture Model.


EvaluateClassGmm computes three different probability values for a feature vector Features with the Gaus-
sian Mixture Model (GMM) GMMHandle.
The a-posteriori probablity of class i for the sample Features is computed as

ncomp
X
p(i|x) = P (j)p(x|j)
j=1

and returned for each class in ClassProb. The formulas for the calculation of the center density function p(x|j)
are described with CreateClassGmm.
The probablity density of the feature vector is computed as a sum of the posterior class probabilities

nclasses
X
p(x) = P r(i)p(i|x)
i=1

and is returned in Density. Here, P r(i) are the prior classes probabilities as computed by TrainClassGmm.
Density can be used for novelty detection, i.e., to reject feature vectors that do not belong to any of the trained

HALCON 8.0.2
8 CHAPTER 1. CLASSIFICATION

classes. However, since Density depends on the scaling of the feature vectors and since Density is a probabil-
ity density, and consequently does not need to lie between 0 and 1, the novelty detection can typically be performed
more easily with KSigmaProb (see below).
A k-sigma error ellipsoid is defined as a locus of points for which

(x − µ)T C −1 (x − µ) = k 2

In the one dimensional case this is the interval [µ − kσ, µ + kσ]. For any 1D Gaussian distribution, it is true
that approximately 65% of the occurrences of the random variable are within this range for k = 1, approximately
95% for k = 2, approximately 99% for k = 3, etc. Hence, the probability that a Gaussian distribution will
generate a random variable outside this range is approximately 35%, 5%, and 1%, respectively. This probability is
called k-sigma probability and is denoted by P [k]. P [k] can be computed numerically for univariate as well as for
multivariate Gaussian distributions, where it should be noted that for the same values of k, P (N ) [k] > P (N +1) [k]
(here N and (N+1) denote dimensions). For Gaussian mixture models the k-sigma probability is computed as:

ncomp
X
PGM M [x] = P (j)Pj [kj ], where kj2 = (x − µj )T Cj−1 (x − µj )
j=1

They then are weighted with the class priors, normalized, and returned for each class in KSigmaProb, such that

P r(i)
KSigmaProb[i] = PGM M [x]
P rmax

KSigmaProb can be used for novelty detection. Typically, feature vectors having values below 0.0001
should be rejected. The parameter RejectionThreshold in ClassifyImageClassGmm is based on the
KSigmaProb values of the features.
Before calling EvaluateClassGmm, the GMM must be trained with TrainClassGmm.
The position of the maximum value of ClassProb is usally interpreted as the class of the feature vector and the
corresponding value as the probability of the class. In this case, ClassifyClassGmm should be used instead of
EvaluateClassGmm, because ClassifyClassGmm directly returns the class and corresponding probability.
Parameter
. GMMHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_gmm ; HClassGmmX / VARIANT
GMM handle.
. Features (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Feature vector.
. ClassProb (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
A-posteriori probability of the classes.
. Density (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Probability density of the feature vector.
. KSigmaProb (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Normalized k-sigma-probability for the feature vector.
Result
If the parameters are valid, the operator EvaluateClassGmm returns the value TRUE. If necessary an exception
handling is raised.
Parallelization Information
EvaluateClassGmm is reentrant and processed without parallelization.
Possible Predecessors
TrainClassGmm, ReadClassGmm
See also
CreateClassGmm
Alternatives
ClassifyClassGmm
References
Christopher M. Bishop: “Neural Networks for Pattern Recognition”; Oxford University Press, Oxford; 1995.

HALCON/COM Reference Manual, 2008-5-13


1.1. GAUSSIAN-MIXTURE-MODELS 9

Mario A.T. Figueiredo: “Unsupervised Learning of Finite Mixture Models”; IEEE Transactions on Pattern Analy-
sis and Machine Intelligence, Vol. 24, No. 3; March 2002.
Module
Foundation

[out] long NumDim HClassGmmX.GetParamsClassGmm ([out] long NumClasses,


[out] VARIANT MinCenters, [out] VARIANT MaxCenters, [out] String CovarType )
void HOperatorSetX.GetParamsClassGmm ([in] VARIANT GMMHandle,
[out] VARIANT NumDim, [out] VARIANT NumClasses, [out] VARIANT MinCenters,
[out] VARIANT MaxCenters, [out] VARIANT CovarType )

Return the parameters of a Gaussian Mixture Model.


GetParamsClassGmm returns the parameters of a Gaussian Mixture Model (GMM) that were specified when
the GMM was created with CreateClassGmm. This is particularly useful if the GMM was read with
ReadClassGmm. The output of GetParamsClassGmm can, for example, be used to check whether the feature
vectors and/or the target data to be used have appropriate dimensions to be used with GMM. For a description of
the parameters, see CreateClassGmm.
Parameter
. GMMHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_gmm ; HClassGmmX / VARIANT
GMM handle.
. NumDim (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of dimensions of the feature space.
. NumClasses (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of classes of the GMM.
. MinCenters (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Minimum number of centers per GMM class.
. MaxCenters (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Maximum number of centers per GMM class.
. CovarType (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Type of the covariance matrices.
Result
If the parameters are valid, the operator GetParamsClassGmm returns the value TRUE. If necessary an excep-
tion handling is raised.
Parallelization Information
GetParamsClassGmm is reentrant and processed without parallelization.
Possible Predecessors
CreateClassGmm, ReadClassGmm
Possible Successors
AddSampleClassGmm, TrainClassGmm
See also
EvaluateClassGmm, ClassifyClassGmm
Module
Foundation

[out] VARIANT InformationCont HClassGmmX.GetPrepInfoClassGmm


([in] String Preprocessing, [out] VARIANT CumInformationCont )
void HOperatorSetX.GetPrepInfoClassGmm ([in] VARIANT GMMHandle,
[in] VARIANT Preprocessing, [out] VARIANT InformationCont,
[out] VARIANT CumInformationCont )

Compute the information content of the preprocessed feature vectors of a GMM.

HALCON 8.0.2
10 CHAPTER 1. CLASSIFICATION

GetPrepInfoClassGmm computes the information content of the training vectors that have been transformed
with the preprocessing given by Preprocessing. Preprocessing can be set to ’principal_components’
or ’canonical_variates’. The preprocessing methods are described with CreateClassMlp. The information
content is derived from the variations of the transformed components of the feature vector, i.e., it is computed
solely based on the training data, independent of any error rate on the training data. The information con-
tent is computed for all relevant components of the transformed feature vectors (NumComponents for ’prin-
cipal_components’ and ’canonical_variates’, see CreateClassGmm), and is returned in InformationCont
as a number between 0 and 1. To convert the information content into a percentage, it simply needs to be mul-
tiplied by 100. The cumulative information content of the first n components is returned in the n-th compo-
nent of CumInformationCont, i.e., CumInformationCont contains the sums of the first n elements of
InformationCont. To use GetPrepInfoClassGmm, a sufficient number of samples must be added to the
GMM given by GMMHandle by using AddSampleClassGmm or ReadSamplesClassGmm.
InformationCont and CumInformationCont can be used to decide how many components of the
transformed feature vectors contain relevant information. An often used criterion is to require that the trans-
formed data must represent x% (e.g., 90%) of the data. This can be decided easily from the first value
of CumInformationCont that lies above x%. The number thus obtained can be used as the value for
NumComponents in a new call to CreateClassGmm. The call to GetPrepInfoClassGmm already re-
quires the creation of a GMM, and hence the setting of NumComponents in CreateClassGmm to an ini-
tial value. However, if GetPrepInfoClassGmm is called, it is typically not known how many components
are relevant, and hence how to set NumComponents in this call. Therefore, the following two-step approach
should typically be used to select NumComponents: In a first step, a GMM with the maximum number for
NumComponents is created (NumComponents for ’principal_components’ and ’canonical_variates’). Then,
the training samples are added to the GMM and are saved in a file using WriteSamplesClassGmm. Subse-
quently, GetPrepInfoClassGmm is used to determine the information content of the components, and with this
NumComponents. After this, a new GMM with the desired number of components is created, and the training
samples are read with ReadSamplesClassGmm. Finally, the GMM is trained with TrainClassGmm.
Parameter
. GMMHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_gmm ; HClassGmmX / VARIANT
GMM handle.
. Preprocessing (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Type of preprocessing used to transform the feature vectors.
Default Value : ’principal_components’
List of values : Preprocessing ∈ {’principal_components’, ’canonical_variates’}
. InformationCont (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Relative information content of the transformed feature vectors.
. CumInformationCont (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Cumulative information content of the transformed feature vectors.
Example

* Create the initial GMM


create_class_gmm (NDim, NClasses, ’full’, ’principal_components’,
NDim, 42, GMMHandle)
* Generate and add the training data
for J := 0 to NData-1 by 1
* Generate training features and classes
* Data = [...]
* Class = [...]
add_sample_class_gmm (GMMHandle, Data, Class)
endfor
write_samples_class_gmm (GMMHandle, ’samples.gtf’)
* Compute the information content of the transformed features
get_prep_info_class_gmm (GMMHandle, ’principal_components’,
InformationCont, CumInformationCont)
* Determine NComp by inspecting InformationCont and CumInformationCont
* NComp = [...]
clear_class_gmm (GMMHandle)
* Create the actual GMM

HALCON/COM Reference Manual, 2008-5-13


1.1. GAUSSIAN-MIXTURE-MODELS 11

create_class_gmm (NIn, NClasses, ’full’, ’principal_components’,


NComp, 42, GMMHandle)
* Train the GMM
read_samples_class_gmm (GMMHandle, ’samples.gtf’)
train_class_gmm (GMMHandle, 200, 0.0001, 0.0001, Centers,Iter)
write_class_gmm (GMMHandle, ’classifier.gmm’)
clear_class_gmm (GMMHandle)

Result
If the parameters are valid, the operator GetPrepInfoClassGmm returns the value TRUE. If necessary an
exception handling is raised.
GetPrepInfoClassGmm may return the error 9211 (Matrix is not positive definite) if Preprocessing =
’canonical_variates’ is used. This typically indicates that not enough training samples have been stored for each
class.
Parallelization Information
GetPrepInfoClassGmm is reentrant and processed without parallelization.
Possible Predecessors
AddSampleClassGmm, ReadSamplesClassGmm
Possible Successors
ClearClassGmm, CreateClassGmm
References
Christopher M. Bishop: “Neural Networks for Pattern Recognition”; Oxford University Press, Oxford; 1995.
Andrew Webb: “Statistical Pattern Recognition”; Arnold, London; 1999.
Module
Foundation

[out] VARIANT Features HClassGmmX.GetSampleClassGmm


([in] VARIANT NumSample, [out] long ClassID )
void HOperatorSetX.GetSampleClassGmm ([in] VARIANT GMMHandle,
[in] VARIANT NumSample, [out] VARIANT Features, [out] VARIANT ClassID )

Return a training sample from the training data of a Gaussian Mixture Models (GMM).
GetSampleClassGmm reads out a training sample from the Gaussian Mixture Model (GMM) given by
GMMHandle that was stored with AddSampleClassGmm or AddSamplesImageClassGmm. The index
of the sample is specified with NumSample. The index is counted from 0, i.e., NumSample must be a number
between 0 and NumSamples − 1, where NumSamples can be determined with GetSampleNumClassGmm.
The training sample is returned in Features and ClassID. Features is a feature vector of length NumDim,
while ClassID is its class (see AddSampleClassGmm and CreateClassGmm).
GetSampleClassGmm can, for example, be used to reclassify the training data with ClassifyClassGmm in
order to determine which training samples, if any, are classified incorrectly.
Parameter

. GMMHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_gmm ; HClassGmmX / VARIANT


GMM handle.
. NumSample (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Index of the stored training sample.
. Features (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Feature vector of the training sample.
. ClassID (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; long / VARIANT
Class of the training sample.
Example

HALCON 8.0.2
12 CHAPTER 1. CLASSIFICATION

create_class_gmm (2, 2, [1,10], ’spherical’, ’none’, 2, 42, GMMHandle)


read_samples_class_gmm (GMMHandle, ’samples.gsf’)
train_class_gmm (GMMHandle, 100, 1e-4, ’training’, 1e-4, Centers, Iter)
* Reclassify the training samples
get_sample_num_class_gmm (GMMHandle, NumSamples)
for I := 0 to NumSamples-1 by 1
get_sample_class_gmm (GMMHandle, I, Features, Class)
classify_class_gmm (GMMHandle, Features, 2, ClassProb, Density,
KSigmaProb)
if (not (Class=ClassProb[0]))
* classified incorrectly
endif
endfor
clear_class_gmm (GMMHandle)

Result
If the parameters are valid, the operator GetSampleClassGmm returns the value TRUE. If necessary an excep-
tion handling is raised.
Parallelization Information
GetSampleClassGmm is reentrant and processed without parallelization.
Possible Predecessors
AddSampleClassGmm, AddSamplesImageClassGmm, ReadSamplesClassGmm,
GetSampleNumClassGmm
Possible Successors
ClassifyClassGmm, EvaluateClassGmm
See also
CreateClassGmm
Module
Foundation

[out] long NumSamples HClassGmmX.GetSampleNumClassGmm ( )


void HOperatorSetX.GetSampleNumClassGmm ([in] VARIANT GMMHandle,
[out] VARIANT NumSamples )

Return the number of training samples stored in the training data of a Gaussian Mixture Model (GMM).
GetSampleNumClassGmm returns in NumSamples the number of training samples that are stored in the Gaus-
sian Mixture Model (GMM) given by GMMHandle. GetSampleNumClassGmm should be called before the
individual training samples are read out with GetSampleClassGmm, e.g., for the purpose of reclassifying the
training data (see GetSampleClassGmm).
Parameter

. GMMHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_gmm ; HClassGmmX / VARIANT


GMM handle.
. NumSamples (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of stored training samples.
Result
If the parameters are valid, the operator GetSampleNumClassGmm returns the value TRUE. If necessary an
exception handling is raised.
Parallelization Information
GetSampleNumClassGmm is reentrant and processed without parallelization.
Possible Predecessors
AddSampleClassGmm, AddSamplesImageClassGmm, ReadSamplesClassGmm

HALCON/COM Reference Manual, 2008-5-13


1.1. GAUSSIAN-MIXTURE-MODELS 13

Possible Successors
GetSampleClassGmm
See also
CreateClassGmm
Module
Foundation

void HClassGmmX.ReadClassGmm ([in] String FileName )


void HOperatorSetX.ReadClassGmm ([in] VARIANT FileName,
[out] VARIANT GMMHandle )

Read a Gaussian Mixture Model from a file.


ReadClassGmm reads a Gaussian Mixture Model (GMM) that has been stored with WriteClassGmm. Since
the training of an GMM can consume a relatively long time, the GMM is typically trained in an offline process
and written to a file with WriteClassGmm. In the online process the GMM is read with ReadClassGmm and
subsequently used for evaluation with EvaluateClassGmm or for classification with ClassifyClassGmm.
Parameter
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.read ; String / VARIANT
File name.
. GMMHandle (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_gmm ; HClassGmmX / VARIANT
GMM handle.
Result
If the parameters are valid, the operator ReadClassGmm returns the value TRUE. If necessary an exception
handling is raised.
Parallelization Information
ReadClassGmm is processed completely exclusively without parallelization.
Possible Successors
ClassifyClassGmm, EvaluateClassGmm
See also
CreateClassGmm, WriteClassGmm
Module
Foundation

void HClassGmmX.ReadSamplesClassGmm ([in] String FileName )


void HOperatorSetX.ReadSamplesClassGmm ([in] VARIANT GMMHandle,
[in] VARIANT FileName )

Read the training data of a Gaussian Mixture Model from a file.


ReadSamplesClassGmm reads training samples from the file given by FileName and adds them to the train-
ing samples that have already been stored in the Gaussian Mixture Model (GMM) given by GMMHandle. The
GMM must be created with CreateClassGmm before calling ReadSamplesClassGmm. As described with
TrainClassGmm and WriteSamplesClassGmm, ReadSamplesClassGmm, AddSampleClassGmm,
and WriteSamplesClassGmm can be used to build up a database of training samples, and hence to improve
the performance of the GMM by retraining the GMM with extended data sets.
It should be noted that the training samples must have the correct dimensionality. The feature vectors stored in
FileName must have the lengths NumDim that was specified with CreateClassGmm, and enough classes
must have been created in CreateClassGmm. If this is not the case, an error message is returned.
It is possible to read files of samples that were written with WriteSamplesClassSvm or
WriteSamplesClassMlp.

HALCON 8.0.2
14 CHAPTER 1. CLASSIFICATION

Parameter
. GMMHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_gmm ; HClassGmmX / VARIANT
GMM handle.
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.read ; String / VARIANT
File name.
Result
If the parameters are valid, the operator ReadSamplesClassGmm returns the value TRUE. If necessary an
exception handling is raised.
Parallelization Information
ReadSamplesClassGmm is processed completely exclusively without parallelization.
Possible Predecessors
CreateClassGmm
Possible Successors
TrainClassGmm
See also
WriteSamplesClassGmm, WriteSamplesClassMlp, ClearSamplesClassGmm
Alternatives
AddSampleClassGmm
Module
Foundation

[out] VARIANT Centers HClassGmmX.TrainClassGmm ([in] long MaxIter,


[in] double Threshold, [in] String ClassPriors, [in] double Regularize,
[out] VARIANT Iter )
void HOperatorSetX.TrainClassGmm ([in] VARIANT GMMHandle,
[in] VARIANT MaxIter, [in] VARIANT Threshold, [in] VARIANT ClassPriors,
[in] VARIANT Regularize, [out] VARIANT Centers, [out] VARIANT Iter )

Train a Gaussian Mixture Model.


TrainClassGmm trains the Gaussian Mixture Model (GMM) referenced by GMMHandle. Before the
GMM can be trained, all training samples to be used for the training must be stored in the GMM using
AddSampleClassGmm, AddSamplesImageClassGmm, or ReadSamplesClassGmm. After the train-
ing, new training samples can be added to the GMM and the GMM can be trained again. Only the classes with
newly added training vectors will be calculated again.
During the training, the error that results from the GMM applied to the training vectors will be minimized with the
expectation maximization (EM) algorithm.
MaxIter specifies the maximum number of iterations per class for the EM algorithm. In practice, values between
20 and 200 should be sufficient for most problems. Threshold specifies a threshold for the relative changes
of the error. If the relative change in error exceeds the threshold after MaxIter iterations, the algorithm will be
canceled for this class. Because the algorithm starts with the maximum specified number of centers (parameter
NumCenters in CreateClassGmm), in case of a premature termination the number of centers and the error
for this class will not be optimal. In this case, a new training with different parameters (e.g. another value for
RandSeed in CreateClassGmm) can be tried.
ClassPriors specifies the method of calculation of the class priors in GMM. If ’training’ is specified, the
priors of the classes are taken from the proportion of the corresponding sample data during training. If ’uniform’
is specified, the priors are set equal to 1/NumClasses for all classes.
Regularize is used to regularize (nearly) singular covariance matrices during the training. A covariance matrix
might collapse to singularity if it is trained with linearly dependent data. To avoid this, a small value specified by
Regularize is added to each main diagonal element of the covariance matrix, which prevents this element from
becoming smaller than Regularize. A recommended value for Regularize is 0.0001. If Regularize is
set to 0.0, no regularization is performed.
The centers are initially randomly distributed. In individual cases, relatively high errors will result from the algo-
rithm because the initial random values determined by RandSeed in CreateClassGmm lead to local minima.

HALCON/COM Reference Manual, 2008-5-13


1.1. GAUSSIAN-MIXTURE-MODELS 15

In this case, a new GMM with a different value for RandSeed should be generated to test whether a significantly
smaller error can be obtained.
It should be noted that, depending on the number of centers, the type of covariance matrix, and the number of
training samples, the training can take from a few seconds to several hours.
On output, TrainClassGmm returns in Centers the number of centers per class that have been found to be
optimal by the EM algorithm. This values can be used as a reference in NumCenters (in CreateClassGmm)
for future GMMs. If the number of centers found by training a new GMM on integer training data is unexpectedly
high, this might be corrected by adding a Randomize noise to the training data in AddSampleClassGmm.
Iter contains the number of performed iterations per class. If a value in Iter equals MaxIter, the training
algorithm has been terminated prematurely (see above).
Parameter
. GMMHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_gmm ; HClassGmmX / VARIANT
GMM handle.
. MaxIter (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Maximum number of iterations of the expectation maximization algorithm
Default Value : 100
Suggested values : MaxIter ∈ {10, 20, 30, 50, 100, 200}
. Threshold (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Threshold for relative change of the error for the expectation maximization algorithm to terminate.
Default Value : 0.001
Suggested values : Threshold ∈ {0.001, 0.0001}
Restriction : ((T hreshold ≥ 0.0) ∧ (T hreshold ≤ 1.0))
. ClassPriors (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Mode to determine the a-priori probabilities of the classes
Default Value : ’training’
List of values : ClassPriors ∈ {’training’, ’uniform’}
. Regularize (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Regularization value for preventing covariance matrix singularity.
Default Value : 0.0001
Restriction : ((Regularize ≥ 0.0) ∧ (Regularize < 1.0))
. Centers (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Number of found centerss per class
. Iter (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Number of executed iterations per class
Example

create_class_gmm (NumDim, NumClasses, [1,5], ’full’, ’none’, 0, 42,


GMMHandle)
* Add the training data
read_samples_class_gmm (GMMHandle, ’samples.gsf’)
* Train the GMM
train_class_gmm (GMMHandle, 100, 1e-4, ’training’, 1e-4, Centers, Iter)
* Write the Gaussian Mixture Model to file
write_class_gmm (GMMHandle, ’gmmclassifier.gmm’)
clear_class_gmm (GMMHandle)

Result
If the parameters are valid, the operator TrainClassGmm returns the value TRUE. If necessary an exception
handling is raised.
Parallelization Information
TrainClassGmm is processed completely exclusively without parallelization.
Possible Predecessors
AddSampleClassGmm, ReadSamplesClassGmm
Possible Successors
EvaluateClassGmm, ClassifyClassGmm, WriteClassGmm

HALCON 8.0.2
16 CHAPTER 1. CLASSIFICATION

See also
CreateClassGmm
Alternatives
ReadClassGmm
References
Christopher M. Bishop: “Neural Networks for Pattern Recognition”; Oxford University Press, Oxford; 1995.
Mario A.T. Figueiredo: “Unsupervised Learning of Finite Mixture Models”; IEEE Transactions on Pattern Analy-
sis and Machine Intelligence, Vol. 24, No. 3; March 2002.
Module
Foundation

void HClassGmmX.WriteClassGmm ([in] String FileName )


void HOperatorSetX.WriteClassGmm ([in] VARIANT GMMHandle,
[in] VARIANT FileName )

Write a Gaussian Mixture Model to a file.


WriteClassGmm writes the Gaussian Mixture Model (GMM) GMMHandle to the file given by FileName.
WriteClassGmm is typically called after the GMM has been trained with TrainClassGmm. The GMM can
be read with ReadClassGmm. WriteClassGmm does not write any training samples that possibly have been
stored in the GMM. For this purpose, WriteSamplesClassGmm should be used.
Parameter
. GMMHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_gmm ; HClassGmmX / VARIANT
GMM handle.
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.write ; String / VARIANT
File name.
Result
If the parameters are valid, the operator WriteClassGmm returns the value TRUE. If necessary an exception
handling is raised.
Parallelization Information
WriteClassGmm is reentrant and processed without parallelization.
Possible Predecessors
TrainClassGmm
Possible Successors
ClearClassGmm
See also
CreateClassGmm, ReadClassGmm, WriteSamplesClassGmm
Module
Foundation

void HClassGmmX.WriteSamplesClassGmm ([in] String FileName )


void HOperatorSetX.WriteSamplesClassGmm ([in] VARIANT GMMHandle,
[in] VARIANT FileName )

Write the training data of a Gaussian Mixture Model to a file.


WriteSamplesClassGmm writes the training samples stored in the Gaussian Mixture Model (GMM)
GMMHandle to the file given by FileName. WriteSamplesClassGmm can be used to build up a database
of training samples, and hence to improve the performance of the GMM by training it with an extended data set
(see TrainClassGmm).
The file FileName is overwritten by WriteSamplesClassGmm. Nevertheless, extending the database of
training samples is easy because ReadSamplesClassGmm and AddSampleClassGmm add the training
samples to the training samples that are already stored in memory with the GMM.

HALCON/COM Reference Manual, 2008-5-13


1.2. HYPERBOXES 17

The created file can be read with ReadSamplesClassMlp if the classificator of a multilayer perceptron (MLP)
should be used. The class of a training sample in the GMM corresponds to a component of the target vector in the
MLP being 1.0.
Parameter

. GMMHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_gmm ; HClassGmmX / VARIANT


GMM handle.
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.write ; String / VARIANT
File name.
Result
If the parameters are valid, the operator WriteSamplesClassGmm returns the value TRUE. If necessary an
exception handling is raised.
Parallelization Information
WriteSamplesClassGmm is reentrant and processed without parallelization.
Possible Predecessors
AddSampleClassGmm
Possible Successors
ClearSamplesClassGmm
See also
CreateClassGmm, ReadSamplesClassGmm, ReadSamplesClassMlp, WriteSamplesClassMlp
Module
Foundation

1.2 Hyperboxes

void HOperatorSetX.ClearSampset ([in] VARIANT SampKey )

Free memory of a data set.


ClearSampset frees the memory which was used for training data set having read by ReadSampset. This
memory is only reusable in combination with ReadSampset.
Parameter

. SampKey (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . feature_set ; HFeatureSetX / VARIANT


Number of the data set.
Result
ClearSampset returns TRUE. An exception handling is raised if the key SampKey does not exist.
Parallelization Information
ClearSampset is local and processed completely exclusively without parallelization.
Possible Predecessors
CreateClassBox, EnquireClassBox, LearnClassBox, WriteClassBox
See also
TestSampsetBox, LearnSampsetBox, ReadSampset
Module
Foundation

void HMiscX.CloseAllClassBox ( )
void HOperatorSetX.CloseAllClassBox ( )

Destroy all classificators.


CloseAllClassBox deletes all classificators and frees the used memory space. All the trained data will be lost.

HALCON 8.0.2
18 CHAPTER 1. CLASSIFICATION

Attention
CloseAllClassBox exists solely for the purpose of implementing the “reset program” functionality in HDe-
velop. CloseAllClassBox must not be used in any application.
Result
If it is possible to close the classificators the operator CloseAllClassBox returns the value TRUE. Otherwise
an exception handling is raised.
Parallelization Information
CloseAllClassBox is local and processed completely exclusively without parallelization.
Alternatives
CloseClassBox
Module
Foundation

void HOperatorSetX.CloseClassBox ([in] VARIANT ClassifHandle )

Destroy the classificator.


CloseClassBox deletes the classificator and frees the used memory space. All the trained data will be lost. For
saving this trained data you should use WriteClassBox before.
Parameter
. ClassifHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_box ; HClassBoxX / VARIANT
Classificator’s handle number.
Result
CloseClassBox returns TRUE.
Parallelization Information
CloseClassBox is local and processed completely exclusively without parallelization.
Possible Predecessors
CreateClassBox, EnquireClassBox, LearnClassBox, WriteClassBox
See also
CreateClassBox, EnquireClassBox, LearnClassBox
Module
Foundation

void HClassBoxX.CreateClassBox ( )
void HOperatorSetX.CreateClassBox ([out] VARIANT ClassifHandle )

Create a new classificator.


CreateClassBox creates a new adaptive classificator. All procedures which are explained in chapter classi-
fication refer to such a initialized classificator (of type 2). See LearnClassBox for more details about the
functionality of the classificator.
Parameter
. ClassifHandle (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_box ; HClassBoxX / VARIANT
Classificator’s handle number.
Result
CreateClassBox returns TRUE if the parameter is correct. An exception handling is raised if a classificator
with this name already exists or there is not enough memory.
Parallelization Information
CreateClassBox is local and processed completely exclusively without parallelization.
Possible Successors
LearnClassBox, EnquireClassBox, WriteClassBox, CloseClassBox, ClearSampset

HALCON/COM Reference Manual, 2008-5-13


1.2. HYPERBOXES 19

See also
LearnClassBox, EnquireClassBox, CloseClassBox
Module
Foundation

void HClassBoxX.DescriptClassBox ([in] long Dimensions )


void HOperatorSetX.DescriptClassBox ([in] VARIANT ClassifHandle,
[in] VARIANT Dimensions )

Description of the classificator.


A classificator uses a set of hyper cuboids for every class. With these hyper cuboids it is attempted to get the
array attributes inside the class. DescriptClassBox returns for every class the expansion of every appropriate
cuboid from dimension 1 up to Dimensions (to ’standard_output’).
Parameter
. ClassifHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_box ; HClassBoxX / VARIANT
Classificator’s handle number.
. Dimensions (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Highest dimension for output.
Default Value : 3
Result
DescriptClassBox returns TRUE.
Parallelization Information
DescriptClassBox is local and processed completely exclusively without parallelization.
Possible Predecessors
CreateClassBox, LearnClassBox, SetClassBoxParam
Possible Successors
EnquireClassBox, LearnClassBox, WriteClassBox, CloseClassBox
See also
CreateClassBox, EnquireClassBox, LearnClassBox, ReadClassBox, WriteClassBox
Module
Foundation

HClassBoxX.EnquireClassBox ([in] VARIANT FeatureList )


[out] long Class
void HOperatorSetX.EnquireClassBox ([in] VARIANT ClassifHandle,
[in] VARIANT FeatureList, [out] VARIANT Class )

Classify a tuple of attributes.


FeatureList is a tuple of any floating point- or integer numbers (attributes) which has to be assigned to a
class with assistance of a previous trained ( LearnClassBox) classificator. It is possible to specify attributes as
unknown by indicating the symbol ’∗’ instead of a number. If you specify n values, then all following values, i.e.
the attributes n+1 until ’max’, are automatically supposed to be undefined.
See LearnClassBox for more details about the functionality of the classificator.
You may call the procedures LearnClassBox and EnquireClassBox alternately, so that it is possible to
classify already in the phase of learning. This means you could see when a satisfying behavior had been reached.
Parameter
. ClassifHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_box ; HClassBoxX / VARIANT
Classificator’s handle number.
. FeatureList (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( integer, real, string )
Array of attributes which has to be classified.
Default Value : 1.0

HALCON 8.0.2
20 CHAPTER 1. CLASSIFICATION

. Class (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT


Number of the class to which the array of attributes had been assigned.
Result
EnquireClassBox returns TRUE.
Parallelization Information
EnquireClassBox is local and processed completely exclusively without parallelization.
Possible Predecessors
CreateClassBox, LearnClassBox, SetClassBoxParam
Possible Successors
LearnClassBox, WriteClassBox, CloseClassBox
See also
TestSampsetBox, LearnClassBox, LearnSampsetBox
Alternatives
EnquireRejectClassBox
Module
Foundation

[out] long Class HClassBoxX.EnquireRejectClassBox


([in] VARIANT FeatureList )
void HOperatorSetX.EnquireRejectClassBox
([in] VARIANT ClassifHandle, [in] VARIANT FeatureList, [out] VARIANT Class )

Classify a tuple of attributes with rejection class.


FeatureList is a tuple of any floating point- or integer numbers (attributes) which has to be assigned to a
class with assistance of a previous trained ( LearnClassBox) classificator. It is possible to specify attributes as
unknown by indicating the symbol ’∗’ instead of a number. If you specify n values, then all following values, i.e.
the attributes n+1 until ’max’, are automatically supposed to be undefined.
If the array of attributes cannot be assigned to a class, i.e. the array does not reside inside of one of the hyper
boxes, then in contrary to EnquireClassBox not the next class is going to be returned, but the rejection class
-1 as a result is going to be passed.
See LearnClassBox for more details about the functionality of the classificator.
You may call the procedures LearnClassBox and EnquireClassBox alternately, so that it is possible to
classify already in the phase of learning. By this means you could see when a satisfying behavior had been reached.
Parameter
. ClassifHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_box ; HClassBoxX / VARIANT
Classificator’s handle number.
. FeatureList (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( integer, real, string )
Array of attributes which has to be classified.
Default Value : 1.0
. Class (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of the class, to which the array of attributes had been assigned or -1 for the rejection class.
Result
EnquireRejectClassBox returns TRUE.
Parallelization Information
EnquireRejectClassBox is local and processed completely exclusively without parallelization.
Possible Predecessors
CreateClassBox, LearnClassBox, SetClassBoxParam
Possible Successors
LearnClassBox, WriteClassBox, CloseClassBox
See also
TestSampsetBox, LearnClassBox, LearnSampsetBox

HALCON/COM Reference Manual, 2008-5-13


1.2. HYPERBOXES 21

Alternatives
EnquireClassBox
Module
Foundation

HClassBoxX.GetClassBoxParam ([in] String Flag )


[out] VARIANT Value
void HOperatorSetX.GetClassBoxParam ([in] VARIANT ClassifHandle,
[in] VARIANT Flag, [out] VARIANT Value )

Get information about the current parameter.


GetClassBoxParam gets the parameter of the classificator. The meaning of the parameter is explained in
SetClassBoxParam.
Default values:
’min_samples_for_split’ = 80,
’split_error’ = 0.1,
’prop_constant’ = 0.25
Parameter

. ClassifHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_box ; HClassBoxX / VARIANT


Classificator’s handle number.
. Flag (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Name of the system parameter.
Default Value : ’split_error’
List of values : Flag ∈ {’split_error’, ’prop_constant’, ’used_memory’, ’min_samples_for_split’}
. Value (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Value of the system parameter.
Result
GetClassBoxParam returns TRUE. An exception handling is raised if Flag has been set with wrong values.
Parallelization Information
GetClassBoxParam is local and processed completely exclusively without parallelization.
Possible Predecessors
CreateClassBox, EnquireClassBox, LearnClassBox, WriteClassBox
Possible Successors
SetClassBoxParam, LearnClassBox, EnquireClassBox, WriteClassBox, CloseClassBox,
ClearSampset
See also
CreateClassBox, SetClassBoxParam
Module
Foundation

void HClassBoxX.LearnClassBox ([in] VARIANT Features, [in] long Class )


void HOperatorSetX.LearnClassBox ([in] VARIANT ClassifHandle,
[in] VARIANT Features, [in] VARIANT Class )

Train the classificator.


Features is a tuple of any floating point numbers or integers (attributes) which has to be assigned to the class
Class. This class is specified by an integer. You may use procedure EnquireClassBox later to find the
most probable class for any array (=tupel). The algorithm tries to describe the set of arrays of one class by hyper
cuboids in the feature space. On demand you may even create several cuboids per class. Hence it is possible to
learn disjunct concepts, too. I.e such concepts which split in several "‘cluster"’ of points in the feature space. The
data structure is hidden to the user and only accessible with such procedures which are described in this chapter.

HALCON 8.0.2
22 CHAPTER 1. CLASSIFICATION

It is possible to specify attributes as unknown by indicating the symbol ’∗’ instead of a number. If you specify n
values, then all following values, i.e. the attributes n+1 until ’max’, are automatically supposed to be undefined.
You may call the procedures LearnClassBox and EnquireClassBox alternately, so that it is possible to
classify already in the phase of learning. By this means you could see when a satisfying behavior had been reached.
The classificator is going to be bigger using further training. This means, that it is not advisable to continue training
after reaching a satisfactory behavior.
Parameter
. ClassifHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_box ; HClassBoxX / VARIANT
Classificator’s handle number.
. Features (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real, string )
Array of attributes to learn.
Default Value : [1.0,1.5,2.0]
. Class (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Class to which the array has to be assigned.
Default Value : 1
Result
LearnClassBox returns TRUE for a normal case. An exception handling is raised if there are memory allocation
problems. The number of classes is constrained. If this limit is passed, an exception handling is raised, too.
Parallelization Information
LearnClassBox is local and processed completely exclusively without parallelization.
Possible Predecessors
CreateClassBox, EnquireClassBox
Possible Successors
TestSampsetBox, LearnClassBox, EnquireClassBox, WriteClassBox, CloseClassBox,
ClearSampset
See also
TestSampsetBox, CloseClassBox, CreateClassBox, EnquireClassBox, LearnSampsetBox
Module
Foundation

void HClassBoxX.LearnSampsetBox ([in] HFeatureSetX SampKey,


[in] String Outfile, [in] long NSamples, [in] double StopError,
[in] long ErrorN )
void HFeatureSetX.LearnSampsetBox ([in] HClassBoxX ClassifHandle,
[in] String Outfile, [in] long NSamples, [in] double StopError,
[in] long ErrorN )
void HOperatorSetX.LearnSampsetBox ([in] VARIANT ClassifHandle,
[in] VARIANT SampKey, [in] VARIANT Outfile, [in] VARIANT NSamples,
[in] VARIANT StopError, [in] VARIANT ErrorN )

Train the classificator with one data set.


LearnSampsetBox trains the classificator with data for the key SampKey (see ReadSampset). The training
sequence is terminated at least after NSamples examples. If NSamples is bigger than the number of examples
in SampKey, then a cyclic start at the beginning occurs. If the error underpasses the value StopError, then
the training sequence is prematurely terminated. StopError is calculated with N / ErrorN. Whereby N signifi-
cates the number of examples which were wrong classified during the last ErrorN training examples. Typically
ErrorN is the number of examples in SampKey and NSamples is a multiple of it. If you want a data set with
100 examples to run 5 times at most and if you want it to terminate with an error lower than 5%, then the cor-
responding values are NSamples = 500, ErrorN = 100 and StopError = 0.05. A protocol of the training
activity is going to be written in file Outfile.

HALCON/COM Reference Manual, 2008-5-13


1.2. HYPERBOXES 23

Parameter

. ClassifHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_box ; HClassBoxX / VARIANT


Classificator’s handle number.
. SampKey (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . feature_set ; HFeatureSetX / VARIANT
Number of the data set to train.
. Outfile (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.write ; String / VARIANT
Name of the protocol file.
Default Value : ’training_prot’
. NSamples (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of arrays of attributes to learn.
Default Value : 500
. StopError (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Classification error for termination.
Default Value : 0.05
. ErrorN (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Error during the assignment.
Default Value : 100
Result
LearnSampsetBox returns TRUE. An exception handling is raised if key SampKey does not exist or there are
problems while opening the file.
Parallelization Information
LearnSampsetBox is local and processed completely exclusively without parallelization.
Possible Predecessors
CreateClassBox
Possible Successors
TestSampsetBox, EnquireClassBox, WriteClassBox, CloseClassBox, ClearSampset
See also
TestSampsetBox, EnquireClassBox, LearnClassBox, ReadSampset
Module
Foundation

void HClassBoxX.ReadClassBox ([in] String FileName )


void HOperatorSetX.ReadClassBox ([in] VARIANT ClassifHandle,
[in] VARIANT FileName )

Read the classificator from a file.


ReadClassBox reads the saved classificator from the file FileName (see WriteClassBox). The values of
the current classificator are overwritten.
Attention
All values of the classificator are going to be overwritten.
Parameter

. ClassifHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_box ; HClassBoxX / VARIANT


Classificator’s handle number.
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.read ; String / VARIANT
Filename of the classificators.
Default Value : ’klassifikator1’
Result
ReadClassBox returns TRUE. An exception handling is raised if it was not possible to open file FileName or
the file has the wrong format.
Parallelization Information
ReadClassBox is local and processed completely exclusively without parallelization.

HALCON 8.0.2
24 CHAPTER 1. CLASSIFICATION

Possible Predecessors
CreateClassBox
Possible Successors
TestSampsetBox, EnquireClassBox, WriteClassBox, CloseClassBox, ClearSampset
See also
CreateClassBox, WriteClassBox
Module
Foundation

void HFeatureSetX.ReadSampset ([in] String FileName )


void HOperatorSetX.ReadSampset ([in] VARIANT FileName,
[out] VARIANT SampKey )

Read a training data set from a file.


The training examples are accessible with the key SampKey by calling procedures ClearSampset and
LearnSampsetBox. You may edit the file using an editor. Every row contains an array of attributes with
corresponding class. An example for a format might be:
(1.0, 25.3, *, 17 | 3)
This row specifies an array of attributes which belong to class 3. In this array the third attribute is unknown.
Attributes upwards 5 are supposed to be unknown, too. You may insert comments like /* .. */ in any place.
Parameter
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.read ; String / VARIANT
Filename of the data set to train.
Default Value : ’sampset1’
. SampKey (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . feature_set ; HFeatureSetX / VARIANT
Identification of the data set to train.
Result
ReadSampset returns TRUE. An exception handling is raised if it is not possible to open the file or it contains
syntax errors or there is not enough memory.
Parallelization Information
ReadSampset is local and processed completely exclusively without parallelization.
Possible Predecessors
CreateClassBox
Possible Successors
TestSampsetBox, EnquireClassBox, WriteClassBox, CloseClassBox, ClearSampset
See also
TestSampsetBox, ClearSampset, LearnSampsetBox
Module
Foundation

void HClassBoxX.SetClassBoxParam ([in] String Flag,


[in] VARIANT Value )
void HOperatorSetX.SetClassBoxParam ([in] VARIANT ClassifHandle,
[in] VARIANT Flag, [in] VARIANT Value )

Set system parameters for classification.


SetClassBoxParam modifies parameter which manipulate the training sequence while calling
LearnClassBox. Only parameters of the classificator are modified, all other classificators remain un-
modified. ’min_samples_for_split’ is the number of examples at least which have to train in one cuboid of this
classificator, before the cuboid is allowed to divide itself. ’split_error’ indicates the critical error. By its exceeding

HALCON/COM Reference Manual, 2008-5-13


1.2. HYPERBOXES 25

the cuboid divides itself, if there are more than ’min_samples_for_split’ examples to train. ’prop_constant’
manipulates the extension of the cuboids. It is proportional to the average distance of the training examples in this
cuboid to the center of the cuboid. More detailed:
extension × prop = average distance of the expectation value.
This relation is valid in every dimension. Hence inside a cuboid the dimensions of the feature space are supposed
to be independent.
The parameters are set with problem independent default values, which must not modified without any rea-
son. Parameters are only important during a learning sequence. They do not influence on the behavior of
EnquireClassBox.
Default setting:
’min_samples_for_split’ = 80,
’split_error’ = 0.1,
’prop_constant’ = 0.25
Parameter
. ClassifHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_box ; HClassBoxX / VARIANT
Classificator’s handle number.
. Flag (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Name of the wanted parameter.
Default Value : ’split_error’
Suggested values : Flag ∈ {’min_samples_for_split’, ’split_error’, ’prop_constant’}
. Value (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Value of the parameter.
Default Value : 0.1
Result
ReadSampset returns TRUE.
Parallelization Information
SetClassBoxParam is local and processed completely exclusively without parallelization.
Possible Predecessors
CreateClassBox, EnquireClassBox
Possible Successors
LearnClassBox, TestSampsetBox, WriteClassBox, CloseClassBox, ClearSampset
See also
EnquireClassBox, GetClassBoxParam, LearnClassBox
Module
Foundation

[out] double Error HClassBoxX.TestSampsetBox


([in] HFeatureSetX SampKey )
[out] double Error HFeatureSetX.TestSampsetBox
([in] HClassBoxX ClassifHandle )
void HOperatorSetX.TestSampsetBox ([in] VARIANT ClassifHandle,
[in] VARIANT SampKey, [out] VARIANT Error )

Classify a set of arrays.


In contrast to LearnSampsetBox there is not a learning here. Typically you use TestSampsetBox to
classify independent test data. Error gives you information about the applicability of the learned training set on
new examples.
Parameter
. ClassifHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_box ; HClassBoxX / VARIANT
Classificator’s handle number.
. SampKey (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . feature_set ; HFeatureSetX / VARIANT
Key of the test data.

HALCON 8.0.2
26 CHAPTER 1. CLASSIFICATION

. Error (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT


Error during the assignment.
Result
TestSampsetBox returns TRUE. An exception handling is raised, if if key SampKey does not exist or problems
occur while opening the file.
Parallelization Information
TestSampsetBox is local and processed completely exclusively without parallelization.
Possible Predecessors
CreateClassBox, LearnClassBox, SetClassBoxParam
Possible Successors
EnquireClassBox, LearnClassBox, WriteClassBox, CloseClassBox, ClearSampset
See also
EnquireClassBox, LearnClassBox, LearnSampsetBox, ReadSampset
Module
Foundation

void HClassBoxX.WriteClassBox ([in] String FileName )


void HOperatorSetX.WriteClassBox ([in] VARIANT ClassifHandle,
[in] VARIANT FileName )

Save the classificator in a file.


WriteClassBox saves the classificator in a file. You may read the data by calling ReadClassBox.
Attention
If a file with this name exists, it is overwritten without a warning. The file can not be edited.
Parameter
. ClassifHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_box ; HClassBoxX / VARIANT
Classificator’s handle number.
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.write ; String / VARIANT
Name of the file which contains the written data.
Default Value : ’klassifikator1’
Result
WriteClassBox returns TRUE. An exception handling is raised if it was not possible to open file FileName.
Parallelization Information
WriteClassBox is local and processed completely exclusively without parallelization.
Possible Predecessors
CreateClassBox, EnquireClassBox, LearnClassBox, TestSampsetBox, WriteClassBox
Possible Successors
CloseClassBox, ClearSampset
See also
CreateClassBox, ReadClassBox
Module
Foundation

1.3 Neural-Nets
void HClassMlpX.AddSampleClassMlp ([in] VARIANT Features,
[in] VARIANT Target )
void HOperatorSetX.AddSampleClassMlp ([in] VARIANT MLPHandle,
[in] VARIANT Features, [in] VARIANT Target )

Add a training sample to the training data of a multilayer perceptron.

HALCON/COM Reference Manual, 2008-5-13


1.3. NEURAL-NETS 27

AddSampleClassMlp adds a training sample to the multilayer perceptron (MLP) given by MLPHandle. The
training sample is given by Features and Target. Features is the feature vector of the sample, and conse-
quently must be a real vector of length NumInput, as specified in CreateClassMlp. Target is the target
vector of the sample, which must have the length NumOutput (see CreateClassMlp) for all three types of
activation functions of the MLP (exception: see below). If the MLP is used for regression (function approxima-
tion), i.e., if OutputFunction = ’linear’, Target is the value of the function at the coordinate Features.
In this case, Target can contain arbitrary real numbers. For OutputFunction = ’logistic’, Target can only
contain the values 0.0 and 1.0. A value of 1.0 specifies that the attribute in question is present, while a value of
0.0 specifies that the attribute is absent. Because in this case the attributes are independent, arbitrary combinations
of 0.0 and 1.0 can be passed. For OutputFunction = ’softmax’, Target also can only contain the values 0.0
and 1.0. In contrast to OutputFunction = ’logistic’, the value 1.0 must be present for exactly one element of
the tuple Target. The location in the tuple designates the class of the sample. For ease of use, a single integer
value may be passed if OutputFunction = ’softmax’. This value directly designates the class of the sample,
which is counted from 0, i.e., the class must be an integer between 0 and NumOutput − 1. The class is converted
to a target vector of length NumOutput internally.
Before the MLP can be trained with TrainClassMlp, all training samples must be added to the MLP with
AddSampleClassMlp.
The number of currently stored training samples can be queried with GetSampleNumClassMlp. Stored train-
ing samples can be read out again with GetSampleClassMlp.
Normally, it is useful to save the training samples in a file with WriteSamplesClassMlp to facilitate reusing
the samples, and to facilitate that, if necessary, new training samples can be added to the data set, and hence to
facilitate that a newly created MLP can be trained anew with the extended data set.
Parameter

. MLPHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_mlp ; HClassMlpX / VARIANT


MLP handle.
. Features (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Feature vector of the training sample to be stored.
. Target (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( integer, real )
Class or target vector of the training sample to be stored.
Result
If the parameters are valid, the operator AddSampleClassMlp returns the value TRUE. If necessary an excep-
tion handling is raised.
Parallelization Information
AddSampleClassMlp is processed completely exclusively without parallelization.
Possible Predecessors
CreateClassMlp
Possible Successors
TrainClassMlp, WriteSamplesClassMlp
See also
ClearSamplesClassMlp, GetSampleNumClassMlp, GetSampleClassMlp
Alternatives
ReadSamplesClassMlp
Module
Foundation

[out] VARIANT Class HClassMlpX.ClassifyClassMlp ([in] VARIANT Features,


[in] VARIANT Num, [out] VARIANT Confidence )
void HOperatorSetX.ClassifyClassMlp ([in] VARIANT MLPHandle,
[in] VARIANT Features, [in] VARIANT Num, [out] VARIANT Class,
[out] VARIANT Confidence )

Calculate the class of a feature vector by a multilayer perceptron.

HALCON 8.0.2
28 CHAPTER 1. CLASSIFICATION

ClassifyClassMlp computes the best Num classes of the feature vector Features with the multilayer per-
ceptron (MLP) MLPHandle and returns the classes in Class and the corresponding confidences (probabili-
ties) of the classes in Confidence. Before calling ClassifyClassMlp, the MLP must be trained with
TrainClassMlp.
ClassifyClassMlp can only be called if the MLP is used as a classifier with OutputFunction = ’softmax’
(see CreateClassMlp). Otherwise, an error message is returned. ClassifyClassMlp corresponds to a
call to EvaluateClassMlp and an additional step that extracts the best Num classes. As described with
EvaluateClassMlp, the output values of the MLP can be interpreted as probabilities of the occurrence of the
respective classes. However, here the posterior probability ClassProb is further normalized as ClassProb =
p(i|x)/p(x), where p(i|x) and p(x) are defined as in EvaluateClassGmm. In most cases it should be sufficient
to use Num = 1 in order to decide whether the probability of the best class is high enough. In some applications it
may be interesting to also take the second best class into account (Num = 2), particularly if it can be expected that
the classes show a significant degree of overlap.
Parameter

. MLPHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_mlp ; HClassMlpX / VARIANT


MLP handle.
. Features (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Feature vector.
. Num (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Number of best classes to determine.
Default Value : 1
Suggested values : Num ∈ {1, 2, 3, 4, 5}
. Class (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Result of classifying the feature vector with the MLP.
. Confidence (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Confidence(s) of the class(es) of the feature vector.
Result
If the parameters are valid, the operator ClassifyClassMlp returns the value TRUE. If necessary an exception
handling is raised.
Parallelization Information
ClassifyClassMlp is reentrant and processed without parallelization.
Possible Predecessors
TrainClassMlp, ReadClassMlp
See also
CreateClassMlp
Alternatives
EvaluateClassMlp
References
Christopher M. Bishop: “Neural Networks for Pattern Recognition”; Oxford University Press, Oxford; 1995.
Andrew Webb: “Statistical Pattern Recognition”; Arnold, London; 1999.
Module
Foundation

void HMiscX.ClearAllClassMlp ( )
void HOperatorSetX.ClearAllClassMlp ( )

Clear all multilayer perceptrons.


ClearAllClassMlp clears all multilayer perceptrons (MLP) and frees all memory required for the MLPs.
After calling ClearAllClassMlp, no MLP can be used any longer.
Attention
ClearAllClassMlp exists solely for the purpose of implementing the “reset program” functionality in HDe-
velop. ClearAllClassMlp must not be used in any application.

HALCON/COM Reference Manual, 2008-5-13


1.3. NEURAL-NETS 29

Result
ClearAllClassMlp always returns TRUE.
Parallelization Information
ClearAllClassMlp is processed completely exclusively without parallelization.
Possible Predecessors
ClassifyClassMlp, EvaluateClassMlp
See also
CreateClassMlp, ReadClassMlp, WriteClassMlp, TrainClassMlp
Alternatives
ClearClassMlp
Module
Foundation

void HOperatorSetX.ClearClassMlp ([in] VARIANT MLPHandle )

Clear a multilayer perceptron.


ClearClassMlp clears the multilayer perceptron (MLP) given by MLPHandle and frees all memory required
for the MLP. After calling ClearClassMlp, the MLP can no longer be used. The handle MLPHandle becomes
invalid.
Parameter

. MLPHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_mlp ; HClassMlpX / VARIANT


MLP handle.
Result
If MLPHandle is valid, the operator ClearClassMlp returns the value TRUE. If necessary an exception
handling is raised.
Parallelization Information
ClearClassMlp is processed completely exclusively without parallelization.
Possible Predecessors
ClassifyClassMlp, EvaluateClassMlp
See also
CreateClassMlp, ReadClassMlp, WriteClassMlp, TrainClassMlp
Module
Foundation

void HClassMlpX.ClearSamplesClassMlp ( )
void HOperatorSetX.ClearSamplesClassMlp ([in] VARIANT MLPHandle )

Clear the training data of a multilayer perceptron.


ClearSamplesClassMlp clears all training samples that have been added to the multilayer perceptron (MLP)
MLPHandle with AddSampleClassMlp or ReadSamplesClassMlp. ClearSamplesClassMlp
should only be used if the MLP is trained in the same process that uses the MLP for evaluation with
EvaluateClassMlp or for classification with ClassifyClassMlp. In this case, the memory required
for the training samples can be freed with ClearSamplesClassMlp, and hence memory can be saved. In
the normal usage, in which the MLP is trained offline and written to a file with WriteClassMlp, it is typically
unnecessary to call ClearSamplesClassMlp because WriteClassMlp does not save the training samples,
and hence the online process, which reads the MLP with ReadClassMlp, requires no memory for the training
samples.

HALCON 8.0.2
30 CHAPTER 1. CLASSIFICATION

Parameter
. MLPHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_mlp ; HClassMlpX / VARIANT
MLP handle.
Result
If the parameters are valid, the operator ClearSamplesClassMlp returns the value TRUE. If necessary an
exception handling is raised.
Parallelization Information
ClearSamplesClassMlp is processed completely exclusively without parallelization.
Possible Predecessors
TrainClassMlp, WriteSamplesClassMlp
See also
CreateClassMlp, ClearClassMlp, AddSampleClassMlp, ReadSamplesClassMlp
Module
Foundation

void HClassMlpX.CreateClassMlp ([in] long NumInput,


[in] long NumHidden, [in] long NumOutput, [in] String OutputFunction,
[in] String Preprocessing, [in] long NumComponents, [in] long RandSeed )
void HOperatorSetX.CreateClassMlp ([in] VARIANT NumInput,
[in] VARIANT NumHidden, [in] VARIANT NumOutput, [in] VARIANT OutputFunction,
[in] VARIANT Preprocessing, [in] VARIANT NumComponents,
[in] VARIANT RandSeed, [out] VARIANT MLPHandle )

Create a multilayer perceptron for classification or regression.


CreateClassMlp creates a neural net in the form of a multilayer perceptron (MLP), which can be used for
classification or regression (function approximation), depending on how OutputFunction is set. The MLP
consists of three layers: an input layer with NumInput input variables (units, neurons), a hidden layer with
NumHidden units, and an output layer with NumOutput output variables. The MLP performs the following
steps to calculate the activations zj of the hidden units from the input data xi (the so-called feature vector):

ni
(1) (1) (1)
X
aj = wji xi + bj , j = 1, . . . , nh
i=1
(1) 
zj = tanh aj , j = 1, . . . , nh

(1) (1)
Here, the matrix wji and the vector bj are the weights of the input layer (first layer) of the MLP. In the hidden
layer (second layer), the activations zj are transformed in a first step by using linear combinations of the variables
in an analogous manner as above:

nh
(2) (2) (2)
X
ak = wkj zj + bk , k = 1, . . . , no
j=1

(2) (2)
Here, the matrix wkj and the vector bk are the weights of the second layer of the MLP.
The activation function used in the output layer can be determined by setting OutputFunction. For
OutputFunction = ’linear’, the data are simply copied:

(2)
yk = ak , k = 1, . . . , no

This type of activation function should be used for regression problems (function approximation). This activation
function is not suited for classification problems.

HALCON/COM Reference Manual, 2008-5-13


1.3. NEURAL-NETS 31

For OutputFunction = ’logistic’, the activations are computed as follows:

1
yk = (2) 
, k = 1, . . . , no
1 + exp − ak

This type of activation function should be used for classification problems with multiple (NumOutput) indepen-
dent logical attributes as output. This kind of classification problem is relatively rare in practice.
For OutputFunction = ’softmax’, the activations are computed as follows:

(2) 
exp ak
yk = Pno (2) , k = 1, . . . , no
l=1 al

This type of activation function should be used for common classification problems with multiple (NumOutput)
mutually exclusive classes as output. In particular, OutputFunction = ’softmax’ must be used for the classifi-
cation of pixel data with ClassifyImageClassMlp.
The parameters Preprocessing and NumComponents can be used to specify a preprocessing of the feature
vectors. For Preprocessing = ’none’, the feature vectors are passed unaltered to the MLP. NumComponents
is ignored in this case.
For all other values of Preprocessing, the training data set is used to compute a transformation of the feature
vectors during the training as well as later in the classification or evaluation.
For Preprocessing = ’normalization’, the feature vectors are normalized by subtracting the mean of the
training vectors and dividing the result by the standard deviation of the individual components of the training
vectors. Hence, the transformed feature vectors have a mean of 0 and a standard deviation of 1. The normalization
does not change the length of the feature vector. NumComponents is ignored in this case. This transformation
can be used if the mean and standard deviation of the feature vectors differs substantially from 0 and 1, respectively,
or for data in which the components of the feature vectors are measured in different units (e.g., if some of the data
are gray value features and some are region features, or if region features are mixed, e.g., ’circularity’ (unit: scalar)
and ’area’ (unit: pixel squared)). In these cases, the training of the net will typically require fewer iterations than
without normalization.
For Preprocessing = ’principal_components’, a principal component analysis is performed. First, the feature
vectors are normalized (see above). Then, an orthogonal transformation (a rotation in the feature space) that decor-
relates the training vectors is computed. After the transformation, the mean of the training vectors is 0 and the co-
variance matrix of the training vectors is a diagonal matrix. The transformation is chosen such that the transformed
features that contain the most variation is contained in the first components of the transformed feature vector. With
this, it is possible to omit the transformed features in the last components of the feature vector, which typically are
mainly influenced by noise, without losing a large amount of information. The parameter NumComponents can
be used to detemine how many of the transformed feature vector components should be used. Up to NumInput
components can be selected. The operator GetPrepInfoClassMlp can be used to determine how much in-
formation each transformed component contains. Hence, it aids the selection of NumComponents. Like data
normalization, this transformation can be used if the mean and standard deviation of the feature vectors differs
substantially from 0 and 1, respectively, or for feature vectors in which the components of the data are measured in
different units. In addition, this transformation is useful if it can be expected that the features are highly correlated.
In contrast to the above three transformations, which can be used for all MLP types, the transformation spec-
ified by Preprocessing = ’canonical_variates’ can only be used if the MLP is used as a classifier with
OutputFunction = ’softmax’). The computation of the canonical variates is also called linear discriminant
analysis. In this case, a transformation that first normalizes the training vectors and then decorrelates the training
vectors on average over all classes is computed. At the same time, the transformation maximally separates the mean
values of the individual classes. As for Preprocessing = ’principal_components’, the transformed compo-
nents are sorted by information content, and hence transformed components with little information content can be
omitted. For canonical variates, up to min(NumOutput−1, NumInput) components can be selected. Also in this
case, the information content of the transformed components can be determined with GetPrepInfoClassMlp.
Like principal component analysis, canonical variates can be used to reduce the amount of data without losing a
large amount of information, while additionally optimizing the separability of the classes after the data reduction.
For the last two types of transformations (’principal_components’ and ’canonical_variates’), the actual number of
input units of the MLP is determined by NumComponents, whereas NumInput determines the dimensionality

HALCON 8.0.2
32 CHAPTER 1. CLASSIFICATION

of the input data (i.e., the length of the untransformed feature vector). Hence, by using one of these two transfor-
mations, the number of input variables, and thus usually also the number of hidden units can be reduced. With this,
the time needed to train the MLP and to evaluate and classify a feature vector is typically reduced.
Usually, NumHidden should be selected in the order of magnitude of NumInput and NumOutput. In many
cases, much smaller values of NumHidden already lead to very good classification results. If NumHidden is
chosen too large, the MLP may overfit the training data, which typically leads to bad generalization properties, i.e.,
the MLP learns the training data very well, but does not return very good results on unknown data.
CreateClassMlp initializes the above described weights with random numbers. To ensure that the results of
training the classifier with TrainClassMlp are reproducible, the seed value of the random number generator is
passed in RandSeed. If the training results in a relatively large error, it sometimes may be possible to achieve a
smaller error by selecting a different value for RandSeed and retraining an MLP.
After the MLP has been created, typically training samples are added to the MLP by repeatedly calling
AddSampleClassMlp or ReadSamplesClassMlp. After this, the MLP is typically trained using
TrainClassMlp. Hereafter, the MLP can be saved using WriteClassMlp. Alternatively, the MLP can
be used immediately after training to evaluate data using EvaluateClassMlp or, if the MLP is used as a
classifier (i.e., for OutputFunction = ’softmax’), to classify data using ClassifyClassMlp.
A comparison of the MLP and the support vector machine (SVM) (see CreateClassSvm) typically shows
that SVMs are generally faster at training, especially for huge training sets, and achieve slightly better recognition
rates than MLPs. The MLP is faster at classification and should therefore be prefered in time critical applications.
Please note that this guideline assumes optimal tuning of the parameters.
Parameter
. NumInput (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of input variables (features) of the MLP.
Default Value : 20
Suggested values : NumInput ∈ {1, 2, 3, 4, 5, 8, 10, 15, 20, 30, 40, 50, 60, 70, 80, 90, 100}
Restriction : (N umInput ≥ 1)
. NumHidden (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of hidden units of the MLP.
Default Value : 10
Suggested values : NumHidden ∈ {1, 2, 3, 4, 5, 8, 10, 15, 20, 30, 40, 50, 60, 70, 80, 90, 100, 120, 150}
Restriction : (N umHidden ≥ 1)
. NumOutput (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of output variables (classes) of the MLP.
Default Value : 5
Suggested values : NumOutput ∈ {1, 2, 3, 4, 5, 8, 10, 15, 20, 30, 40, 50, 60, 70, 80, 90, 100, 120, 150}
Restriction : (N umOutput ≥ 1)
. OutputFunction (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Type of the activation function in the output layer of the MLP.
Default Value : ’softmax’
List of values : OutputFunction ∈ {’linear’, ’logistic’, ’softmax’}
. Preprocessing (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Type of preprocessing used to transform the feature vectors.
Default Value : ’normalization’
List of values : Preprocessing ∈ {’none’, ’normalization’, ’principal_components’,
’canonical_variates’}
. NumComponents (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Preprocessing parameter: Number of transformed features (ignored for Preprocessing = ’none’ and
Preprocessing = ’normalization’).
Default Value : 10
Suggested values : NumComponents ∈ {1, 2, 3, 4, 5, 8, 10, 15, 20, 30, 40, 50, 60, 70, 80, 90, 100}
Restriction : (N umComponents ≥ 1)
. RandSeed (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Seed value of the random number generator that is used to initialize the MLP with random values.
Default Value : 42
. MLPHandle (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_mlp ; HClassMlpX / VARIANT
MLP handle.

HALCON/COM Reference Manual, 2008-5-13


1.3. NEURAL-NETS 33

Example

* Use the MLP for regression (function approximation)


create_class_mlp (1, NHidden, 1, ’linear’, ’none’, 1, 42, MLPHandle)
* Generate the training data
* D = [...]
* T = [...]
* Add the training data
for J := 0 to NData-1 by 1
add_sample_class_mlp (MLPHandle, D[J], T[J])
endfor
* Train the MLP
train_class_mlp (MLPHandle, 200, 0.001, 0.001, Error, ErrorLog)
* Generate test data
* X = [...]
* Compute the output of the MLP on the test data
for J := 0 to N-1 by 1
evaluate_class_mlp (MLPHandle, X[J], Y)
endfor
clear_class_mlp (MLPHandle)

* Use the MLP for classification


create_class_mlp (NIn, NHidden, NOut, ’softmax’, ’normalization’, NIn,
42, MLPHandle)
* Generate and add the training data
for J := 0 to NData-1 by 1
* Generate training features and classes
* Data = [...]
* Class = [...]
add_sample_class_mlp (MLPHandle, Data, Class)
endfor
* Train the MLP
train_class_mlp (MLPHandle, 100, 1, 0.01, Error, ErrorLog)
* Use the MLP to classify unknown data
for J := 0 to N-1 by 1
* Extract features
* Features = [...]
classify_class_mlp (MLPHandle, Features, 1, Class, Confidence)
endfor
clear_class_mlp (MLPHandle)

Result
If the parameters are valid, the operator CreateClassMlp returns the value TRUE. If necessary an exception
handling is raised.
Parallelization Information
CreateClassMlp is processed completely exclusively without parallelization.
Possible Successors
AddSampleClassMlp
See also
ClearClassMlp, TrainClassMlp, ClassifyClassMlp, EvaluateClassMlp
Alternatives
CreateClassSvm, CreateClassGmm, CreateClassBox
References
Christopher M. Bishop: “Neural Networks for Pattern Recognition”; Oxford University Press, Oxford; 1995.
Andrew Webb: “Statistical Pattern Recognition”; Arnold, London; 1999.

HALCON 8.0.2
34 CHAPTER 1. CLASSIFICATION

Module
Foundation

[out] VARIANT Result HClassMlpX.EvaluateClassMlp


([in] VARIANT Features )
void HOperatorSetX.EvaluateClassMlp ([in] VARIANT MLPHandle,
[in] VARIANT Features, [out] VARIANT Result )

Calculate the evaluation of a feature vector by a multilayer perceptron.


EvaluateClassMlp computes the result Result of evaluating the feature vector Features with the
multilayer perceptron (MLP) MLPHandle. The formulas used for the evaluation are described with
CreateClassMlp. Before calling EvaluateClassMlp, the MLP must be trained with TrainClassMlp.
If the MLP is used for regression (function approximation), i.e., if (OutputFunction = ’linear’), Result is
the value of the function at the coordinate Features. For OutputFunction = ’logistic’ and ’softmax’, the
values in Result can be interpreted as probabilities. Hence, for OutputFunction = ’logistic’ the elements of
Result represent the probabilities of the presence of the respective independent attributes. Typically, a threshold
of 0.5 is used to decide whether the attribute is present or not. Depending on the application, other thresholds may
be used as well. For OutputFunction = ’softmax’ usually the position of the maximum value of Result is
interpreted as the class of the feature vector, and the corresponding value as the probability of the class. In this
case, ClassifyClassMlp should be used instead of EvaluateClassMlp because ClassifyClassMlp
directly returns the class and corresponding probability.
Parameter

. MLPHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_mlp ; HClassMlpX / VARIANT


MLP handle.
. Features (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Feature vector.
. Result (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Result of evaluating the feature vector with the MLP.
Result
If the parameters are valid, the operator EvaluateClassMlp returns the value TRUE. If necessary an exception
handling is raised.
Parallelization Information
EvaluateClassMlp is reentrant and processed without parallelization.
Possible Predecessors
TrainClassMlp, ReadClassMlp
See also
CreateClassMlp
Alternatives
ClassifyClassMlp
References
Christopher M. Bishop: “Neural Networks for Pattern Recognition”; Oxford University Press, Oxford; 1995.
Andrew Webb: “Statistical Pattern Recognition”; Arnold, London; 1999.
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


1.3. NEURAL-NETS 35

[out] long NumInput HClassMlpX.GetParamsClassMlp


([out] long NumHidden, [out] long NumOutput, [out] String OutputFunction,
[out] String Preprocessing, [out] long NumComponents )
void HOperatorSetX.GetParamsClassMlp ([in] VARIANT MLPHandle,
[out] VARIANT NumInput, [out] VARIANT NumHidden, [out] VARIANT NumOutput,
[out] VARIANT OutputFunction, [out] VARIANT Preprocessing,
[out] VARIANT NumComponents )

Return the parameters of a multilayer perceptron.


GetParamsClassMlp returns the parameters of a multilayer perceptron (MLP) that were specified when the
MLP was created with CreateClassMlp. This is particularly useful if the MLP was read from a file with
ReadClassMlp. The output of GetParamsClassMlp can, for example, be used to check whether the feature
vectors and, if necessary, the target data to be used with the MLP have the correct lengths. For a description of the
parameters, see CreateClassMlp.
Parameter
. MLPHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_mlp ; HClassMlpX / VARIANT
MLP handle.
. NumInput (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of input variables (features) of the MLP.
. NumHidden (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of hidden units of the MLP.
. NumOutput (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of output variables (classes) of the MLP.
. OutputFunction (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Type of the activation function in the output layer of the MLP.
. Preprocessing (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Type of preprocessing used to transform the feature vectors.
. NumComponents (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Preprocessing parameter: Number of transformed features.
Result
If the parameters are valid, the operator GetParamsClassMlp returns the value TRUE. If necessary an excep-
tion handling is raised.
Parallelization Information
GetParamsClassMlp is reentrant and processed without parallelization.
Possible Predecessors
CreateClassMlp, ReadClassMlp
Possible Successors
AddSampleClassMlp, TrainClassMlp
See also
EvaluateClassMlp, ClassifyClassMlp
Module
Foundation

[out] VARIANT InformationCont HClassMlpX.GetPrepInfoClassMlp


([in] String Preprocessing, [out] VARIANT CumInformationCont )
void HOperatorSetX.GetPrepInfoClassMlp ([in] VARIANT MLPHandle,
[in] VARIANT Preprocessing, [out] VARIANT InformationCont,
[out] VARIANT CumInformationCont )

Compute the information content of the preprocessed feature vectors of a multilayer perceptron.
GetPrepInfoClassMlp computes the information content of the training vectors that have been transformed
with the preprocessing given by Preprocessing. Preprocessing can be set to ’principal_components’

HALCON 8.0.2
36 CHAPTER 1. CLASSIFICATION

or ’canonical_variates’. The preprocessing methods are described with CreateClassMlp. The information
content is derived from the variations of the transformed components of the feature vector, i.e., it is computed
solely based on the training data, independent of any error rate on the training data. The information content is
computed for all relevant components of the transformed feature vectors (NumInput for ’principal_components’
and min(NumOutput − 1, NumInput) for ’canonical_variates’, see CreateClassMlp), and is returned in
InformationCont as a number between 0 and 1. To convert the information content into a percentage, it
simply needs to be multiplied by 100. The cumulative information content of the first n components is returned
in the n-th component of CumInformationCont, i.e., CumInformationCont contains the sums of the
first n elements of InformationCont. To use GetPrepInfoClassMlp, a sufficient number of samples
must be added to the multilayer perceptron (MLP) given by MLPHandle by using AddSampleClassMlp or
ReadSamplesClassMlp.
InformationCont and CumInformationCont can be used to decide how many components of the
transformed feature vectors contain relevant information. An often used criterion is to require that the trans-
formed data must represent x% (e.g., 90%) of the data. This can be decided easily from the first value
of CumInformationCont that lies above x%. The number thus obtained can be used as the value for
NumComponents in a new call to CreateClassMlp. The call to GetPrepInfoClassMlp already re-
quires the creation of an MLP, and hence the setting of NumComponents in CreateClassMlp to an ini-
tial value. However, if GetPrepInfoClassMlp is called it is typically not known how many components
are relevant, and hence how to set NumComponents in this call. Therefore, the following two-step approach
should typically be used to select NumComponents: In a first step, an MLP with the maximum number for
NumComponents is created (NumInput for ’principal_components’ and min(NumOutput − 1, NumInput)
for ’canonical_variates’). Then, the training samples are added to the MLP and are saved in a file using
WriteSamplesClassMlp. Subsequently, GetPrepInfoClassMlp is used to determine the information
content of the components, and with this NumComponents. After this, a new MLP with the desired number of
components is created, and the training samples are read with ReadSamplesClassMlp. Finally, the MLP is
trained with TrainClassMlp.
Parameter
. MLPHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_mlp ; HClassMlpX / VARIANT
MLP handle.
. Preprocessing (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Type of preprocessing used to transform the feature vectors.
Default Value : ’principal_components’
List of values : Preprocessing ∈ {’principal_components’, ’canonical_variates’}
. InformationCont (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Relative information content of the transformed feature vectors.
. CumInformationCont (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Cumulative information content of the transformed feature vectors.
Example

* Create the initial MLP


create_class_mlp (NIn, NHidden, NOut, ’softmax’, ’principal_components’,
NIn, 42, MLPHandle)
* Generate and add the training data
for J := 0 to NData-1 by 1
* Generate training features and classes
* Data = [...]
* Class = [...]
add_sample_class_mlp (MLPHandle, Data, Class)
endfor
write_samples_class_mlp (MLPHandle, ’samples.mtf’)
* Compute the information content of the transformed features
get_prep_info_class_mlp (MLPHandle, ’principal_components’,
InformationCont, CumInformationCont)
* Determine NComp by inspecting InformationCont and CumInformationCont
* NComp = [...]
clear_class_mlp (MLPHandle)
* Create the actual MLP

HALCON/COM Reference Manual, 2008-5-13


1.3. NEURAL-NETS 37

create_class_mlp (NIn, NHidden, NOut, ’softmax’, ’principal_components’,


NComp, 42, MLPHandle)
* Train the MLP
read_samples_class_mlp (MLPHandle, ’samples.mtf’)
train_class_mlp (MLPHandle, 100, 1, 0.01, Error, ErrorLog)
write_class_mlp (MLPHandle, ’classifier.mlp’)
clear_class_mlp (MLPHandle)

Result
If the parameters are valid, the operator GetPrepInfoClassMlp returns the value TRUE. If necessary an
exception handling is raised.
GetPrepInfoClassMlp may return the error 9211 (Matrix is not positive definite) if Preprocessing =
’canonical_variates’ is used. This typically indicates that not enough training samples have been stored for each
class.
Parallelization Information
GetPrepInfoClassMlp is reentrant and processed without parallelization.
Possible Predecessors
AddSampleClassMlp, ReadSamplesClassMlp
Possible Successors
ClearClassMlp, CreateClassMlp
References
Christopher M. Bishop: “Neural Networks for Pattern Recognition”; Oxford University Press, Oxford; 1995.
Andrew Webb: “Statistical Pattern Recognition”; Arnold, London; 1999.
Module
Foundation

[out] VARIANT Features HClassMlpX.GetSampleClassMlp


([in] VARIANT IndexSample, [out] VARIANT Target )
void HOperatorSetX.GetSampleClassMlp ([in] VARIANT MLPHandle,
[in] VARIANT IndexSample, [out] VARIANT Features, [out] VARIANT Target )

Return a training sample from the training data of a multilayer perceptron.


GetSampleClassMlp reads out a training sample from the multilayer perceptron (MLP) given by MLPHandle
that was added with AddSampleClassMlp or ReadSamplesClassMlp. The index of the sample is spec-
ified with IndexSample. The index is counted from 0, i.e., IndexSample must be a number between 0 and
IndexSamples − 1, where IndexSamples can be determined with GetSampleNumClassMlp. The train-
ing sample is returned in Features and Target. Features is a feature vector of length NumInput, while
Target is a target vector of length NumOutput (see AddSampleClassMlp and CreateClassMlp).
GetSampleClassMlp can, for example, be used to reclassify the training data with ClassifyClassMlp in
order to determine which training samples, if any, are classified incorrectly.
Parameter

. MLPHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_mlp ; HClassMlpX / VARIANT


MLP handle.
. IndexSample (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Number of stored training sample.
. Features (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Feature vector of the training sample.
. Target (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Target vector of the training sample.
Example

HALCON 8.0.2
38 CHAPTER 1. CLASSIFICATION

* Train an MLP
create_class_mlp (NIn, NHidden, NOut, ’softmax’, ’canonical_variates’,
NComp, 42, MLPHandle)
read_samples_class_mlp (MLPHandle, ’samples.mtf’)
train_class_mlp (MLPHandle, 100, 1, 0.01, Error, ErrorLog)
* Reclassify the training samples
get_sample_num_class_mlp (MLPHandle, NumSamples)
for I := 0 to NumSamples-1 by 1
get_sample_class_mlp (MLPHandle, I, Data, Target)
classify_class_mlp (MLPHandle, Data, 1, Class, Confidence)
Result := gen_tuple_const(NOut,0)
Result[Class] := 1
Diffs := Target-Result
if (sum(fabs(Diffs)) > 0)
* Sample has been classified incorrectly
endif
endfor
clear_class_mlp (MLPHandle)

Result
If the parameters are valid, the operator GetSampleClassMlp returns the value TRUE. If necessary an excep-
tion handling is raised.
Parallelization Information
GetSampleClassMlp is reentrant and processed without parallelization.
Possible Predecessors
AddSampleClassMlp, ReadSamplesClassMlp, GetSampleNumClassMlp
Possible Successors
ClassifyClassMlp, EvaluateClassMlp
See also
CreateClassMlp
Module
Foundation

HClassMlpX.GetSampleNumClassMlp ( )
[out] long NumSamples
void HOperatorSetX.GetSampleNumClassMlp ([in] VARIANT MLPHandle,
[out] VARIANT NumSamples )

Return the number of training samples stored in the training data of a multilayer perceptron.
GetSampleNumClassMlp returns in NumSamples the number of training samples that are stored in the mul-
tilayer perceptron (MLP) given by MLPHandle. GetSampleNumClassMlp should be called before the
individual training samples are accessed with GetSampleClassMlp, e.g., for the purpose of reclassifying the
training data (see GetSampleClassMlp).
Parameter

. MLPHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_mlp ; HClassMlpX / VARIANT


MLP handle.
. NumSamples (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of stored training samples.
Result
If MLPHandle is valid, the operator GetSampleNumClassMlp returns the value TRUE. If necessary an
exception handling is raised.
Parallelization Information
GetSampleNumClassMlp is reentrant and processed without parallelization.

HALCON/COM Reference Manual, 2008-5-13


1.3. NEURAL-NETS 39

Possible Predecessors
AddSampleClassMlp, ReadSamplesClassMlp
Possible Successors
GetSampleClassMlp
See also
CreateClassMlp
Module
Foundation

void HClassMlpX.ReadClassMlp ([in] String FileName )


void HOperatorSetX.ReadClassMlp ([in] VARIANT FileName,
[out] VARIANT MLPHandle )

Read a multilayer perceptron from a file.


ReadClassMlp reads a multilayer perceptron (MLP) that has been stored with WriteClassMlp. Since the
training of an MLP can consume a relatively long time, the MLP is typically trained in an offline process and
written to a file with WriteClassMlp. In the online process the MLP is read with ReadClassMlp and
subsequently used for evaluation with EvaluateClassMlp or for classification with ClassifyClassMlp.
Parameter
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.read ; String / VARIANT
File name.
. MLPHandle (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_mlp ; HClassMlpX / VARIANT
MLP handle.
Result
If the parameters are valid, the operator ReadClassMlp returns the value TRUE. If necessary an exception
handling is raised.
Parallelization Information
ReadClassMlp is processed completely exclusively without parallelization.
Possible Successors
ClassifyClassMlp, EvaluateClassMlp
See also
CreateClassMlp, WriteClassMlp
Module
Foundation

void HClassMlpX.ReadSamplesClassMlp ([in] String FileName )


void HOperatorSetX.ReadSamplesClassMlp ([in] VARIANT MLPHandle,
[in] VARIANT FileName )

Read the training data of a multilayer perceptron from a file.


ReadSamplesClassMlp reads training samples from the file given by FileName and adds them to the
training samples that have already been added to the multilayer perceptron (MLP) given by MLPHandle.
The MLP must be created with CreateClassMlp before calling ReadSamplesClassMlp. As de-
scribed with TrainClassMlp and WriteSamplesClassMlp, the operators ReadSamplesClassMlp,
AddSampleClassMlp, and WriteSamplesClassMlp can be used to build up a extensive set of training
samples, and hence to improve the performance of the MLP by retraining the MLP with extended data sets.
It should be noted that the training samples must have the correct dimensionality. The feature vectors and tar-
get vectors stored in FileName must have the lengths NumInput and NumOutput that were specified with
CreateClassMlp. If this is not the case an error message is returned.

HALCON 8.0.2
40 CHAPTER 1. CLASSIFICATION

Parameter

. MLPHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_mlp ; HClassMlpX / VARIANT


MLP handle.
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.read ; String / VARIANT
File name.
Result
If the parameters are valid, the operator ReadSamplesClassMlp returns the value TRUE. If necessary an
exception handling is raised.
Parallelization Information
ReadSamplesClassMlp is processed completely exclusively without parallelization.
Possible Predecessors
CreateClassMlp
Possible Successors
TrainClassMlp
See also
WriteSamplesClassMlp, ClearSamplesClassMlp
Alternatives
AddSampleClassMlp
Module
Foundation

[out] double Error HClassMlpX.TrainClassMlp ([in] long MaxIterations,


[in] double WeightTolerance, [in] double ErrorTolerance,
[out] VARIANT ErrorLog )
void HOperatorSetX.TrainClassMlp ([in] VARIANT MLPHandle,
[in] VARIANT MaxIterations, [in] VARIANT WeightTolerance,
[in] VARIANT ErrorTolerance, [out] VARIANT Error, [out] VARIANT ErrorLog )

Train a multilayer perceptron.


TrainClassMlp trains the multilayer perceptron (MLP) given in MLPHandle. Before the MLP can be trained,
all training samples to be used for the training must be stored in the MLP using AddSampleClassMlp or
ReadSamplesClassMlp. If after the training new additional training samples should be used a new MLP
must be created with CreateClassMlp, in which again all training samples to be used (i.e., the original
ones and the additional ones) must be stored. In these cases, it is useful to save and read the training data with
WriteSamplesClassMlp and ReadSamplesClassMlp, respectively. A second training with additional
training samples is not explicitly forbidden by TrainClassMlp. However, this typically does not lead to good
results because the training of an MLP is a complex nonlinear optimization problem, and consequently the second
training with new data will very likely lead to the fact that the optimization gets stuck in a local minimum.
During the training, the error the MLP achieves on the stored training samples is minimized by using a non-
linear optimization algorithm. With this, the MLP weights described in CreateClassMlp are determined.
CreateClassMlp initializes the weights with random values to make it very likely that the optimization con-
verges to the global minimum of the error function. Nevertheless, in rare cases it may happen that the random
values determined with RandSeed in CreateClassMlp result in a relatively large optimum error, i.e., that
the optimization gets stuck in a local minimum. If it can be conjectured that this has happened the MLP should be
created anew with a different value for RandSeed in order to check whether a significantly smaller error can be
achieved.
The parameters MaxIterations, WeightTolerance, and ErrorTolerance control the nonlinear opti-
mization algorithm. MaxIterations specifies the maximum number of iterations of the optimization algorithm.
In practice, values between 100 and 200 should be sufficient for most problems. WeightTolerance specifies
a threshold for the change of the weights per iteration. Here, the absolute value of the change of the weights
between two iterations is summed. Hence, this value depends on the number of weights as well as the size of
the weights, which in turn depend on the scaling of the training data. Typically, values between 0.00001 and 1
should be used. ErrorTolerance specifies a threshold for the change of the error value per iteration. This

HALCON/COM Reference Manual, 2008-5-13


1.3. NEURAL-NETS 41

value depends on the number of training samples as well as the number of output variables of the MLP. Also here,
values between 0.00001 and 1 should typically be used. The optimization is terminated if the weight change is
smaller than WeightTolerance and the change of the error value is smaller than ErrorTolerance. In any
case, the optimization is terminated after at most MaxIterations iterations. It should be noted that, depending
on the size of the MLP and the number of training samples, the training can take from a few seconds to several
hours.
On output, TrainClassMlp returns the error of the MLP with the optimal weights on the training samples
in Error. Furthermore, ErrorLog contains the error value as a function of the number of iterations. With
this, it is possible to decide whether a second training of the MLP with the same training data without creating
the MLP anew makes sense. If ErrorLog is regarded as a function, it should drop off steeply initially, while
leveling out very flatly at the end. If ErrorLog is still relatively steep at the end, it usually makes sense to
call TrainClassMlp again. It should be noted, however, that this mechanism should not be used to train the
MLP successively with MaxIterations = 1 (or other small values for MaxIterations) because this will
substantially increase the number of iterations required to train the MLP.
Parameter
. MLPHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_mlp ; HClassMlpX / VARIANT
MLP handle.
. MaxIterations (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Maximum number of iterations of the optimization algorithm.
Default Value : 200
Suggested values : MaxIterations ∈ {20, 40, 60, 80, 100, 120, 140, 160, 180, 200, 220, 240, 260, 280,
300}
. WeightTolerance (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Threshold for the difference of the weights of the MLP between two iterations of the optimization algorithm.
Default Value : 1.0
Suggested values : WeightTolerance ∈ {1.0, 0.1, 0.01, 0.001, 0.0001, 0.00001}
Restriction : (W eightT olerance ≥ 1.0e − 8)
. ErrorTolerance (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Threshold for the difference of the mean error of the MLP on the training data between two iterations of the
optimization algorithm.
Default Value : 0.01
Suggested values : ErrorTolerance ∈ {1.0, 0.1, 0.01, 0.001, 0.0001, 0.00001}
Restriction : (ErrorT olerance ≥ 1.0e − 8)
. Error (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Mean error of the MLP on the training data.
. ErrorLog (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Mean error of the MLP on the training data as a function of the number of iterations of the optimization
algorithm.
Example

* Train an MLP
create_class_mlp (NIn, NHidden, NOut, ’softmax’, ’normalization’, 1,
42, MLPHandle)
read_samples_class_mlp (MLPHandle, ’samples.mtf’)
train_class_mlp (MLPHandle, 100, 1, 0.01, Error, ErrorLog)
write_class_mlp (MLPHandle, ’classifier.mlp’)
clear_class_mlp (MLPHandle)

Result
If the parameters are valid, the operator TrainClassMlp returns the value TRUE. If necessary an exception
handling is raised.
TrainClassMlp may return the error 9211 (Matrix is not positive definite) if Preprocessing = ’canoni-
cal_variates’ is used. This typically indicates that not enough training samples have been stored for each class.
Parallelization Information
TrainClassMlp is processed completely exclusively without parallelization.

HALCON 8.0.2
42 CHAPTER 1. CLASSIFICATION

Possible Predecessors
AddSampleClassMlp, ReadSamplesClassMlp
Possible Successors
EvaluateClassMlp, ClassifyClassMlp, WriteClassMlp
See also
CreateClassMlp
Alternatives
ReadClassMlp
References
Christopher M. Bishop: “Neural Networks for Pattern Recognition”; Oxford University Press, Oxford; 1995.
Andrew Webb: “Statistical Pattern Recognition”; Arnold, London; 1999.
Module
Foundation

void HClassMlpX.WriteClassMlp ([in] String FileName )


void HOperatorSetX.WriteClassMlp ([in] VARIANT MLPHandle,
[in] VARIANT FileName )

Write a multilayer perceptron to a file.


WriteClassMlp writes the multilayer perceptron (MLP) MLPHandle to the file given by FileName.
WriteClassMlp is typically called after the MLP has been trained with TrainClassMlp. The MLP can
be read with ReadClassMlp. WriteClassMlp does not write any training samples that possibly have been
stored in the MLP. For this purpose, WriteSamplesClassMlp should be used.
Parameter
. MLPHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_mlp ; HClassMlpX / VARIANT
MLP handle.
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.write ; String / VARIANT
File name.
Result
If the parameters are valid, the operator WriteClassMlp returns the value TRUE. If necessary an exception
handling is raised.
Parallelization Information
WriteClassMlp is reentrant and processed without parallelization.
Possible Predecessors
TrainClassMlp
Possible Successors
ClearClassMlp
See also
CreateClassMlp, ReadClassMlp, WriteSamplesClassMlp
Module
Foundation

void HClassMlpX.WriteSamplesClassMlp ([in] String FileName )


void HOperatorSetX.WriteSamplesClassMlp ([in] VARIANT MLPHandle,
[in] VARIANT FileName )

Write the training data of a multilayer perceptron to a file.


WriteSamplesClassMlp writes the training samples stored in the multilayer perceptron (MLP) MLPHandle
to the file given by FileName. WriteSamplesClassMlp can be used to build up a database of train-
ing samples, and hence to improve the performance of the MLP by training it with an extended data set (see
TrainClassMlp). For other possible uses of WriteSamplesClassMlp see GetPrepInfoClassMlp.

HALCON/COM Reference Manual, 2008-5-13


1.4. SUPPORT-VECTOR-MACHINES 43

The file FileName is overwritten by WriteSamplesClassMlp. Nevertheless, extending the database of


training samples is easy to do because ReadSamplesClassMlp and AddSampleClassMlp add the training
samples to the training samples that are already stored in memory with the MLP.
Parameter
. MLPHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_mlp ; HClassMlpX / VARIANT
MLP handle.
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.write ; String / VARIANT
File name.
Result
If the parameters are valid, the operator WriteSamplesClassMlp returns the value TRUE. If necessary an
exception handling is raised.
Parallelization Information
WriteSamplesClassMlp is reentrant and processed without parallelization.
Possible Predecessors
AddSampleClassMlp
Possible Successors
ClearSamplesClassMlp
See also
CreateClassMlp, GetPrepInfoClassMlp, ReadSamplesClassMlp
Module
Foundation

1.4 Support-Vector-Machines

void HClassSvmX.AddSampleClassSvm ([in] VARIANT Features,


[in] VARIANT Class )
void HOperatorSetX.AddSampleClassSvm ([in] VARIANT SVMHandle,
[in] VARIANT Features, [in] VARIANT Class )

Add a training sample to the training data of a support vector machine.


AddSampleClassSvm adds a training sample to the support vector machine (SVM) given by SVMHandle.
The training sample is given by Features and Class. Features is the feature vector of the sample, and
consequently must be a real vector of length NumFeatures, as specified in CreateClassSvm. Class
is the target of the sample, which must be in the range of 0 to NumClasses-1 (see CreateClassSvm).
Before the SVM can be trained with TrainClassSvm, training samples must be added to the SVM with
AddSampleClassSvm. The usage of support vectors of an already trained SVM as training samples is de-
scribed in TrainClassSvm.
The number of currently stored training samples can be queried with GetSampleNumClassSvm. Stored train-
ing samples can be read out again with GetSampleClassSvm.
Normally, it is useful to save the training samples in a file with WriteSamplesClassSvm to facilitate reusing
the samples and to facilitate that, if necessary, new training samples can be added to the data set, and hence to
facilitate that a newly created SVM can be trained with the extended data set.
Parameter
. SVMHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_svm ; HClassSvmX / VARIANT
SVM handle.
. Features (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Feature vector of the training sample to be stored.
. Class (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Class of the training sample to be stored.
Result
If the parameters are valid the operator AddSampleClassSvm returns the value TRUE. If necessary, an excep-
tion handling is raised.

HALCON 8.0.2
44 CHAPTER 1. CLASSIFICATION

Parallelization Information
AddSampleClassSvm is processed completely exclusively without parallelization.
Possible Predecessors
CreateClassSvm
Possible Successors
TrainClassSvm, WriteSamplesClassSvm, GetSampleNumClassSvm, GetSampleClassSvm
See also
ClearSamplesClassSvm, GetSupportVectorClassSvm
Alternatives
ReadSamplesClassSvm
Module
Foundation

[out] VARIANT Class HClassSvmX.ClassifyClassSvm ([in] VARIANT Features,


[in] VARIANT Num )
void HOperatorSetX.ClassifyClassSvm ([in] VARIANT SVMHandle,
[in] VARIANT Features, [in] VARIANT Num, [out] VARIANT Class )

Classify a feature vector by a support vector machine.


ClassifyClassSvm computes the best Num classes of the feature vector Features with the SVM
SVMHandle and returns them in Class. If the classifier was created in the Mode = ’one-versus-one’, the
classes are ordered by the number of votes of the sub-classifiers. If Mode = ’one-versus-all’ was used, the classes
are ordered by the value of each sub-classifier (see CreateClassSvm for more details). If the classifier was
created in the Mode = ’novelty-detection’, it determines whether the feature vector belongs to the same class as
the training data (Class = 1) or is regarded as outlier (Class = 0). In this case Num must be set to 1 as the
classifier only determines membership.
Before calling ClassifyClassSvm, the SVM must be trained with TrainClassSvm.
Parameter

. SVMHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_svm ; HClassSvmX / VARIANT


SVM handle.
. Features (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Feature vector.
. Num (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Number of best classes to determine.
Default Value : 1
Suggested values : Num ∈ {1, 2, 3, 4, 5}
. Class (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Result of classifying the feature vector with the SVM.
Result
If the parameters are valid the operator ClassifyClassSvm returns the value TRUE. If necessary, an exception
handling is raised.
Parallelization Information
ClassifyClassSvm is reentrant and processed without parallelization.
Possible Predecessors
TrainClassSvm, ReadClassSvm
See also
CreateClassSvm
References
John Shawe-Taylor, Nello Cristianini: “Kernel Methods for Pattern Analysis”; Cambridge University Press, Cam-
bridge; 2004.
Bernhard Schölkopf, Alexander J.Smola: “Lerning with Kernels”; MIT Press, London; 1999.

HALCON/COM Reference Manual, 2008-5-13


1.4. SUPPORT-VECTOR-MACHINES 45

Module
Foundation

void HMiscX.ClearAllClassSvm ( )
void HOperatorSetX.ClearAllClassSvm ( )

Clear all support vector machines.


ClearAllClassSvm clears all support vector machines (SVM) and frees all memory required for the SVMs.
After calling ClearAllClassSvm, no SVM can be used any longer.
Attention
ClearAllClassSvm exists solely for the purpose of implementing the “reset program” functionality in HDe-
velop. ClearAllClassSvm must not be used in any application.
Result
ClearAllClassSvm always returns TRUE.
Parallelization Information
ClearAllClassSvm is processed completely exclusively without parallelization.
Possible Predecessors
ClassifyClassSvm
See also
CreateClassSvm, ReadClassSvm, WriteClassSvm, TrainClassSvm
Alternatives
ClearClassSvm
Module
Foundation

void HOperatorSetX.ClearClassSvm ([in] VARIANT SVMHandle )

Clear a support vector machine.


ClearClassSvm clears the support vector machine (SVM) given by SVMHandle and frees all memory required
for the SVM. After calling ClearClassSvm, the SVM can no longer be used. The handle SVMHandle becomes
invalid.
Parameter

. SVMHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_svm ; HClassSvmX / VARIANT


SVM handle.
Result
If SVMHandle is valid the operator ClearClassSvm returns the value TRUE. If necessary, an exception
handling is raised.
Parallelization Information
ClearClassSvm is processed completely exclusively without parallelization.
Possible Predecessors
ClassifyClassSvm
See also
CreateClassSvm, ReadClassSvm, WriteClassSvm, TrainClassSvm
Module
Foundation

HALCON 8.0.2
46 CHAPTER 1. CLASSIFICATION

void HClassSvmX.ClearSamplesClassSvm ( )
void HOperatorSetX.ClearSamplesClassSvm ([in] VARIANT SVMHandle )

Clear the training data of a support vector machine.


ClearSamplesClassSvm clears all training samples that have been added to the support vec-
tor machine (SVM) SVMHandle with AddSampleClassSvm or ReadSamplesClassSvm.
ClearSamplesClassSvm should only be used if the SVM is trained in the same process that uses the
SVM for classification with ClassifyClassSvm. In this case, the memory required for the training samples
can be freed with ClearSamplesClassSvm, and hence memory can be saved. In the normal usage, in
which the SVM is trained offline and written to a file with WriteClassSvm, it is typically unnecessary to
call ClearSamplesClassSvm because WriteClassSvm does not save the training samples, and hence the
online process, which reads the SVM with ReadClassSvm, requires no memory for the training samples.
Parameter
. SVMHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_svm ; HClassSvmX / VARIANT
SVM handle.
Result
If the parameters are valid the operator ClearSamplesClassSvm returns the value TRUE. If necessary, an
exception handling is raised.
Parallelization Information
ClearSamplesClassSvm is processed completely exclusively without parallelization.
Possible Predecessors
TrainClassSvm, WriteSamplesClassSvm
See also
CreateClassSvm, ClearClassSvm, AddSampleClassSvm, ReadSamplesClassSvm
Module
Foundation

void HClassSvmX.CreateClassSvm ([in] long NumFeatures,


[in] String KernelType, [in] double KernelParam, [in] double Nu,
[in] long NumClasses, [in] String Mode, [in] String Preprocessing,
[in] long NumComponents )
void HOperatorSetX.CreateClassSvm ([in] VARIANT NumFeatures,
[in] VARIANT KernelType, [in] VARIANT KernelParam, [in] VARIANT Nu,
[in] VARIANT NumClasses, [in] VARIANT Mode, [in] VARIANT Preprocessing,
[in] VARIANT NumComponents, [out] VARIANT SVMHandle )

Create a support vector machine for pattern classification.


CreateClassSvm creates a support vector machine that can be used for pattern classification. The dimension
of the patterns to be classified is specified in NumFeatures, the number of different classes in NumClasses.
For a binary classification problem in which the classes are linearly separable the SVM algorithm selects data
vectors from the training set that are utilized to construct the optimal separating hyperplane between different
classes. This hyperplane is optimal in the sense that the margin between the convex hulls of the different classes
is maximized. The training patterns that are located at the margin define the hyperplane and are called support
vectors (SV).
Classification of a feature vector z is performed with the following formula:

nsv
!
X
f (z) = sign αi yi < xi , z > +b
i=1

Here, xi are the support vectors, yi encodes their class membership (±1) and αi the weight coefficients. The
distance of the hyperplane to the origin is b. The α and b are determined during training with TrainClassSvm.

HALCON/COM Reference Manual, 2008-5-13


1.4. SUPPORT-VECTOR-MACHINES 47

Note that only a subset of the original training set (nsv : number of support vectors) is necessary for the definition
of the decision boundary and therefore data vectors that are not support vectors are discarded. The classification
speed depends on the evaluation of the dot product between support vectors and the feature vector to be classified,
and hence depends on the length of the feature vector and the number nsv of support vectors.
For classification problems in which the classes are not linearly separable the algorithm is extended in two ways.
First, during training a certain amount of errors (overlaps) is compensated with the use of slack variables. This
means that the α are upper bounded by a regularization constant. To enable an intuitive control of the amount of
training errors, the Nu-SVM version of the training algorithm is used. Here, the regularization parameter Nu is an
asymptotic upper bound on the number of training errors and an asymptotic lower bound on the number of support
vectors. As a rule of thumb, the parameter Nu should be set to the prior expectation of the application’s specific
error ratio, e.g., 0.01 (corresponding to a maximum training error of 1%). Please note that a too big value for Nu
might lead to an infeasible training problem, i.e., the SVM cannot be trained correctly (see TrainClassSvm
for more details). Since this can only be determined during training, an exception can only be raised there. In this
case, a new SVM with Nu chosen smaller must be created.
Second, because the above SVM exclusively calculates dot products between the feature vectors, it is possible to
incorporate a kernel function into the training and testing algorithm. This means that the dot products are substi-
tuted by a kernel function, which implicitly performs the dot product in a higher dimensional feature space. Given
the appropriate kernel transformation, an originally not linearly separable classification task becomes linearly sep-
arable in the higher dimensional feature space.
Different kernel functions can be selected with the parameter KernelType. For KernelType = ’linear’ the
dot product, as specified in the above formula is calculated. This kernel should solely be used for linearly or nearly
linearly separable classification tasks. The parameter KernelParam is ignored here.
The radial basis function (RBF) KernelType = ’rbf’ is the best choice for a kernel function because it achieves
good results for many classification tasks. It is defined as:

2
= e−γ·
x−z
K(x, z)

Here, the parameter KernelParam is used to select γ. The intuitive meaning of γ is the amount of influence of
a support vector upon its surroundings. A big value of γ (small influence on the surroundings) means that each
training vector becomes a support vector. The training algorithm learns the training data “by heart”, but lacks any
generalization ability (over-fitting). Additionally, the training/classification times grow significantly. A too small
value for γ (big influence on the surroundings) leads to few support vectors defining the separating hyperplane
(under-fitting). One typical strategy is to select a small γ-Nu pair and consecutively increase the values as long as
the recognition rate increases.
With KernelType = ’polynomial_homogeneous’ or ’polynomial_inhomogeneous’, polynomial kernels can be
selected. They are defined in the following way:

K(x, z) = (< x, z >)d


K(x, z) = (< x, z > +1)d

The degree of the polynomial kernel must be set with KernelParam. Please note that a too high degree polyno-
mial (d > 10) might result in numerical problems.
As a rule of thumb, the RBF kernel provides a good choice for most of the classification problems and should
therefore be used in almost all cases. Nevertheless, the linear and polynomial kernels might be better suited
for certain applications and can be tested for comparison. Please note that the novelty-detection Mode and the
ReduceClassSvm operator are provided only for the RBF kernel.
Mode specifies the general classification task, which is either how to break down a multi-class decision problem to
binary sub-cases or whether to use a special classifier mode called ’novelty-detection’. Mode = ’one-versus-all’
creates a classifier where each class is compared to the rest of the training data. During testing the class with the
largest output (see the classification formula without sign) is chosen. Mode = ’one-versus-one’ creates a binary
classifier between each single class. During testing a vote is cast and the class with the majority of the votes
is selected. The optimal Mode for multi-class classification depends on the number of classes. Given n classes
’one-versus-all’ creates n classifiers, whereas ’one-versus-one’ creates n(n − 1)/2. Note that for a binary decision
task ’one-versus-one’ would create exactly one, whereas ’one-versus-all’ unnecessarily creates two symmetric

HALCON 8.0.2
48 CHAPTER 1. CLASSIFICATION

classifiers. For few classes (3-10) ’one-versus-one’ is faster for training and testing, because the sub-classifier all
consist of fewer training data and result in overall fewer support vectors. In case of many classes ’one-versus-all’
is preferable, because ’one-versus-one’ generates a prohibitively large amount of sub-classifiers, as their number
grows quadratically with the number of classes.
A special case of classification is Mode = 0 novelty − detection 0 , where the test data is classified with regard to
membership to the training data. The separating hyperplane lies around the training data and thereby implicitly
divides the training data from the rejection class. The advantage is that the rejection class is not defined explicitly,
which is difficult to do in certain applications like texture classification. The resulting support vectors are all lying
at the border. With the parameter Nu, the ratio of outliers in the training data set is specified.
The parameters Preprocessing and NumComponents can be used to specify a preprocessing of the feature
vectors. For Preprocessing = ’none’, the feature vectors are passed unaltered to the SVM. NumComponents
is ignored in this case.
For all other values of Preprocessing, the training data set is used to compute a transformation of the feature
vectors during the training as well as later in the classification.
For Preprocessing = ’normalization’, the feature vectors are normalized. In case of a polynomial kernel, the
minimum and maximum value of the training data set is transformed to -1 and +1. In case of the RBF kernel, the
data is normalized by subtracting the mean of the training vectors and dividing the result by the standard deviation
of the individual components of the training vectors. Hence, the transformed feature vectors have a mean of 0 and
a standard deviation of 1. The normalization does not change the length of the feature vector. NumComponents
is ignored in this case. This transformation can be used if the mean and standard deviation of the feature vectors
differs substantially from 0 and 1, respectively, or for data in which the components of the feature vectors are
measured in different units (e.g., if some of the data are gray value features and some are region features, or if
region features are mixed, e.g., ’circularity’ (unit: scalar) and ’area’ (unit: pixel squared)). The normalization
transformation should be performed in general, because it increases the numerical stability during training/testing.
For Preprocessing = ’principal_components’, a principal component analysis (PCA) is performed. First, the
feature vectors are normalized (see above). Then, an orthogonal transformation (a rotation in the feature space)
that decorrelates the training vectors is computed. After the transformation, the mean of the training vectors is
0 and the covariance matrix of the training vectors is a diagonal matrix. The transformation is chosen such that
the transformed features that contain the most variation is contained in the first components of the transformed
feature vector. With this, it is possible to omit the transformed features in the last components of the feature vector,
which typically are mainly influenced by noise, without losing a large amount of information. The parameter
NumComponents can be used to determine how many of the transformed feature vector components should
be used. Up to NumFeatures components can be selected. The operator GetPrepInfoClassSvm can be
used to determine how much information each transformed component contains. Hence, it aids the selection of
NumComponents. Like data normalization, this transformation can be used if the mean and standard deviation of
the feature vectors differs substantially from 0 and 1, respectively, or for feature vectors in which the components
of the data are measured in different units. In addition, this transformation is useful if it can be expected that the
features are highly correlated. Please note that the RBF kernel is very robust against the dimensionality reduction
performed by PCA and should therefore be the first choice when speeding up the classification time.
The transformation specified by Preprocessing = ’canonical_variates’ first normalizes the training vectors
and then decorrelates the training vectors on average over all classes. At the same time, the transformation maxi-
mally separates the mean values of the individual classes. As for Preprocessing = ’principal_components’,
the transformed components are sorted by information content, and hence transformed components with little in-
formation content can be omitted. For canonical variates, up to min(NumClasses − 1, NumFeatures) compo-
nents can be selected. Also in this case, the information content of the transformed components can be determined
with GetPrepInfoClassSvm. Like principal component analysis, canonical variates can be used to reduce
the amount of data without losing a large amount of information, while additionally optimizing the separability of
the classes after the data reduction. The computation of the canonical variates is also called linear discriminant
analysis.
For the last two types of transformations (’principal_components’ and ’canonical_variates’), the length of input
data of the SVM is determined by NumComponents, whereas NumFeatures determines the dimensionality of
the input data (i.e., the length of the untransformed feature vector). Hence, by using one of these two transforma-
tions, the size of the SVM with respect to data length is reduced, leading to shorter training/classification times by
the SVM.
After the SVM has been created with CreateClassSvm, typically training samples are added to the SVM by
repeatedly calling AddSampleClassSvm or ReadSamplesClassSvm. After this, the SVM is typically

HALCON/COM Reference Manual, 2008-5-13


1.4. SUPPORT-VECTOR-MACHINES 49

trained using TrainClassSvm. Hereafter, the SVM can be saved using WriteClassSvm. Alternatively, the
SVM can be used immediately after training to classify data using ClassifyClassSvm.
A comparison of the SVM and the multi-layer perceptron (MLP) (see CreateClassMlp) typically shows that
SVMs are generally faster at training, especially for huge training sets, and achieve slightly better recognition rates
than MLPs. The MLP is faster at classification and should therefore be prefered in time critical applications. Please
note that this guideline assumes optimal tuning of the parameters.
Parameter
. NumFeatures (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of input variables (features) of the SVM.
Default Value : 10
Suggested values : NumFeatures ∈ {1, 2, 3, 4, 5, 8, 10, 15, 20, 30, 40, 50, 60, 70, 80, 90, 100}
Restriction : (N umF eatures ≥ 1)
. KernelType (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
The kernel type.
Default Value : ’rbf’
List of values : KernelType ∈ {’linear’, ’rbf’, ’polynomial_inhomogeneous’, ’polynomial_homogeneous’}
. KernelParam (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Additional parameter for the kernel function. In case of RBF kernel the value for γ. For polynomial kernel the
degree
Default Value : 0.02
Suggested values : KernelParam ∈ {0.01, 0.02, 0.05, 0.1, 0.5}
. Nu (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Regularisation constant of the SVM.
Default Value : 0.05
Suggested values : Nu ∈ {0.0001, 0.001, 0.01, 0.05, 0.1, 0.2, 0.3}
Restriction : ((N u > 0.0) ∧ (N u < 1.0))
. NumClasses (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of classes.
Default Value : 5
Suggested values : NumClasses ∈ {2, 3, 4, 5, 6, 7, 8, 9, 10}
Restriction : (N umClasses ≥ 1)
. Mode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
The mode of the SVM.
Default Value : ’one-versus-one’
List of values : Mode ∈ {’novelty-detection’, ’one-versus-all’, ’one-versus-one’}
. Preprocessing (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Type of preprocessing used to transform the feature vectors.
Default Value : ’normalization’
List of values : Preprocessing ∈ {’none’, ’normalization’, ’principal_components’,
’canonical_variates’}
. NumComponents (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Preprocessing parameter: Number of transformed features (ignored for Preprocessing = ’none’ and
Preprocessing = ’normalization’).
Default Value : 10
Suggested values : NumComponents ∈ {1, 2, 3, 4, 5, 8, 10, 15, 20, 30, 40, 50, 60, 70, 80, 90, 100}
Restriction : (N umComponents ≥ 1)
. SVMHandle (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_svm ; HClassSvmX / VARIANT
SVM handle.
Example

create_class_svm (NumFeatures, ’rbf’, 0.01, 0.01, NumClasses,


’one-versus-all’, ’normalization’, NumFeatures,
SVMHandle)
* Generate and add the training data
for J := 0 to NData-1 by 1
* Generate training features and classes

HALCON 8.0.2
50 CHAPTER 1. CLASSIFICATION

* Data = [...]
* Class = ...
add_sample_class_svm (SVMHandle, Data, Class)
endfor
* Train the SVM
train_class_svm (SVMHandle, 0.001, ’default’)
* Use the SVM to classify unknown data
for J := 0 to N-1 by 1
* Extract features
* Features = [...]
classify_class_svm (SVMHandle, Features, 1, Class)
endfor
clear_class_svm (SVMHandle)

Result
If the parameters are valid the operator CreateClassSvm returns the value TRUE. If necessary, an exception
handling is raised.
Parallelization Information
CreateClassSvm is processed completely exclusively without parallelization.
Possible Successors
AddSampleClassSvm
See also
ClearClassSvm, TrainClassSvm, ClassifyClassSvm
Alternatives
CreateClassMlp, CreateClassGmm, CreateClassBox
References
Bernhard Schölkopf, Alexander J.Smola: “Learning with Kernels”; MIT Press, London; 1999.
John Shawe-Taylor, Nello Cristianini: “Kernel Methods for Pattern Analysis”; Cambridge University Press, Cam-
bridge; 2004.
Module
Foundation

[out] long NumFeatures HClassSvmX.GetParamsClassSvm


([out] String KernelType, [out] double KernelParam, [out] double Nu,
[out] long NumClasses, [out] String Mode, [out] String Preprocessing,
[out] long NumComponents )
void HOperatorSetX.GetParamsClassSvm ([in] VARIANT SVMHandle,
[out] VARIANT NumFeatures, [out] VARIANT KernelType,
[out] VARIANT KernelParam, [out] VARIANT Nu, [out] VARIANT NumClasses,
[out] VARIANT Mode, [out] VARIANT Preprocessing,
[out] VARIANT NumComponents )

Return the parameters of a support vector machine.


GetParamsClassSvm returns the parameters of a support vector machine (SVM) that were specified when the
SVM was created with CreateClassSvm. This is particularly useful if the SVM was read from a file with
ReadClassSvm. The output of GetParamsClassSvm can, for example, be used to check whether the feature
vectors and, if necessary, the target data to be used with the SVM have the correct lengths. For a description of the
parameters, see CreateClassSvm.
Parameter
. SVMHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_svm ; HClassSvmX / VARIANT
SVM handle.
. NumFeatures (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of input variables (features) of the SVM.

HALCON/COM Reference Manual, 2008-5-13


1.4. SUPPORT-VECTOR-MACHINES 51

. KernelType (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT


The kernel type.
. KernelParam (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Additional parameter for the kernel.
. Nu (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Regularization constant of the SVM.
. NumClasses (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of classes of the test data.
. Mode (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
The mode of the SVM.
. Preprocessing (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Type of preprocessing used to transform the feature vectors.
. NumComponents (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Preprocessing parameter: Number of transformed features (ignored for Preprocessing = ’none’ and
Preprocessing = ’normalization’).
Result
If the parameters are valid the operator GetParamsClassSvm returns the value TRUE. If necessary, an excep-
tion handling is raised.
Parallelization Information
GetParamsClassSvm is reentrant and processed without parallelization.
Possible Predecessors
CreateClassSvm, ReadClassSvm
Possible Successors
AddSampleClassSvm, TrainClassSvm
See also
ClassifyClassSvm
Module
Foundation

[out] VARIANT InformationCont HClassSvmX.GetPrepInfoClassSvm


([in] String Preprocessing, [out] VARIANT CumInformationCont )
void HOperatorSetX.GetPrepInfoClassSvm ([in] VARIANT SVMHandle,
[in] VARIANT Preprocessing, [out] VARIANT InformationCont,
[out] VARIANT CumInformationCont )

Compute the information content of the preprocessed feature vectors of a support vector machine
GetPrepInfoClassSvm computes the information content of the training vectors that have been transformed
with the preprocessing given by Preprocessing. Preprocessing can be set to ’principal_components’
or ’canonical_variates’. The preprocessing methods are described with CreateClassSvm. The information
content is derived from the variations of the transformed components of the feature vector, i.e., it is computed solely
based on the training data, independent of any error rate on the training data. The information content is computed
for all relevant components of the transformed feature vectors (NumFeatures for ’principal_components’ and
min(NumClasses − 1, NumFeatures) for ’canonical_variates’, see CreateClassSvm), and is returned
in InformationCont as a number between 0 and 1. To convert the information content into a percentage, it
simply needs to be multiplied by 100. The cumulative information content of the first n components is returned
in the n-th component of CumInformationCont, i.e., CumInformationCont contains the sums of the
first n elements of InformationCont. To use GetPrepInfoClassSvm, a sufficient number of samples
must be added to the support vector machine (SVM) given by SVMHandle by using AddSampleClassSvm or
ReadSamplesClassSvm.
InformationCont and CumInformationCont can be used to decide how many components of the
transformed feature vectors contain relevant information. An often used criterion is to require that the trans-
formed data must represent x% (e.g., 90%) of the data. This can be decided easily from the first value
of CumInformationCont that lies above x%. The number thus obtained can be used as the value for
NumComponents in a new call to CreateClassSvm. The call to GetPrepInfoClassSvm already

HALCON 8.0.2
52 CHAPTER 1. CLASSIFICATION

requires the creation of an SVM, and hence the setting of NumComponents in CreateClassSvm to an
initial value. However, when GetPrepInfoClassSvm is called, it is typically not known how many com-
ponents are relevant, and hence how to set NumComponents in this call. Therefore, the following two-step
approach should typically be used to select NumComponents: In a first step, an SVM with the maximum num-
ber for NumComponents is created (NumFeatures for ’principal_components’ and min(NumClasses −
1, NumFeatures) for ’canonical_variates’). Then, the training samples are added to the SVM and are saved in
a file using WriteSamplesClassSvm. Subsequently, GetPrepInfoClassSvm is used to determine the
information content of the components, and with this NumComponents. After this, a new SVM with the desired
number of components is created, and the training samples are read with ReadSamplesClassSvm. Finally,
the SVM is trained with TrainClassSvm.
Parameter
. SVMHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_svm ; HClassSvmX / VARIANT
SVM handle.
. Preprocessing (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Type of preprocessing used to transform the feature vectors.
Default Value : ’principal_components’
List of values : Preprocessing ∈ {’principal_components’, ’canonical_variates’}
. InformationCont (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Relative information content of the transformed feature vectors.
. CumInformationCont (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Cumulative information content of the transformed feature vectors.
Example

* Create the initial SVM


create_class_svm (NumFeatures, ’rbf’, 0.01, 0.01, NumClasses,
’one-versus-all’, ’normalization’, NumFeatures,
SVMHandle)
* Generate and add the training data
for J := 0 to NData-1 by 1
* Generate training features and classes
* Data = [...]
* Class = ...
add_sample_class_svm (SVMHandle, Data, Class)
endfor
write_samples_class_svm (SVMHandle, ’samples.mtf’)
* Compute the information content of the transformed features
get_prep_info_class_svm (SVMHandle, ’principal_components’,
InformationCont, CumInformationCont)
* Determine NComp by inspecting InformationCont and CumInformationCont
* NComp = [...]
clear_class_svm (SVMHandle)
* Create the actual SVM
create_class_svm (NumFeatures, ’rbf’, 0.01, 0.01, NumClasses,
’one-versus-all’, ’principal_components’, NComp, SVMHandle)
* Train the SVM
read_samples_class_svm (SVMHandle, ’samples.mtf’)
train_class_svm (SVMHandle, 0.001, ’default’)
write_class_svm (SVMHandle, ’classifier.svm’)
clear_class_svm (SVMHandle)

Result
If the parameters are valid the operator GetPrepInfoClassSvm returns the value TRUE. If necessary, an
exception handling is raised.
GetPrepInfoClassSvm may return the error 9211 (Matrix is not positive definite) if Preprocessing =
’canonical_variates’ is used. This typically indicates that not enough training samples have been stored for each
class.

HALCON/COM Reference Manual, 2008-5-13


1.4. SUPPORT-VECTOR-MACHINES 53

Parallelization Information
GetPrepInfoClassSvm is reentrant and processed without parallelization.
Possible Predecessors
AddSampleClassSvm, ReadSamplesClassSvm
Possible Successors
ClearClassSvm, CreateClassSvm
References
Christopher M. Bishop: “Neural Networks for Pattern Recognition”; Oxford University Press, Oxford; 1995.
Andrew Webb: “Statistical Pattern Recognition”; Arnold, London; 1999.
Module
Foundation

[out] VARIANT Features HClassSvmX.GetSampleClassSvm


([in] VARIANT IndexSample, [out] long Target )
void HOperatorSetX.GetSampleClassSvm ([in] VARIANT SVMHandle,
[in] VARIANT IndexSample, [out] VARIANT Features, [out] VARIANT Target )

Return a training sample from the training data of a support vector machine.
GetSampleClassSvm reads out a training sample from the support vector machine (SVM) given by
SVMHandle that was added with AddSampleClassSvm or ReadSamplesClassSvm. The index
of the sample is specified with IndexSample. The index is counted from 0, i.e., IndexSample
must be a number between 0 and IndexSamples − 1, where IndexSamples can be determined with
GetSampleNumClassSvm. The training sample is returned in Features and Target. Features is a
feature vector of length NumFeatures (see CreateClassSvm), while Target is the index of the class,
ranging between 0 and NumClasses-1 (see AddSampleClassSvm).
GetSampleClassSvm can, for example, be used to reclassify the training data with ClassifyClassSvm in
order to determine which training samples, if any, are classified incorrectly.
Parameter
. SVMHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_svm ; HClassSvmX / VARIANT
SVM handle.
. IndexSample (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Number of the stored training sample.
. Features (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Feature vector of the training sample.
. Target (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Target vector of the training sample.
Example

* Train an SVM
create_class_svm (NumFeatures, ’rbf’, 0.01, 0.01, NumClasses,
’one-versus-all’, ’normalization’, NumFeatures,
SVMHandle)
read_samples_class_svm (SVMHandle, ’samples.mtf’)
train_class_svm (SVMHandle, 0.001, ’default’)
* Reclassify the training samples
get_sample_num_class_svm (SVMHandle, NumSamples)
for I := 0 to NumSamples-1 by 1
get_sample_class_svm (SVMHandle, I, Data, Target)
classify_class_svm (SVMHandle, Data, 1, Class)
if (Class # Target)
* Sample has been classified incorrectly
endif
endfor

HALCON 8.0.2
54 CHAPTER 1. CLASSIFICATION

clear_class_svm (SVMHandle)

Result
If the parameters are valid the operator GetSampleClassSvm returns the value TRUE. If necessary, an excep-
tion handling is raised.
Parallelization Information
GetSampleClassSvm is reentrant and processed without parallelization.
Possible Predecessors
AddSampleClassSvm, ReadSamplesClassSvm, GetSampleNumClassSvm,
GetSupportVectorClassSvm
Possible Successors
ClassifyClassSvm
See also
CreateClassSvm
Module
Foundation

HClassSvmX.GetSampleNumClassSvm ( )
[out] long NumSamples
void HOperatorSetX.GetSampleNumClassSvm ([in] VARIANT SVMHandle,
[out] VARIANT NumSamples )

Return the number of training samples stored in the training data of a support vector machine.
GetSampleNumClassSvm returns in NumSamples the number of training samples that are stored in the sup-
port vector machine (SVM) given by SVMHandle. GetSampleNumClassSvm should be called before the
individual training samples are accessed with GetSampleClassSvm, e.g., for the purpose of reclassifying the
training data (see GetSampleClassSvm).
Parameter
. SVMHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_svm ; HClassSvmX / VARIANT
SVM handle.
. NumSamples (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of stored training samples.
Result
If SVMHandle is valid the operator GetSampleNumClassSvm returns the value TRUE. If necessary, an
exception handling is raised.
Parallelization Information
GetSampleNumClassSvm is reentrant and processed without parallelization.
Possible Predecessors
AddSampleClassSvm, ReadSamplesClassSvm
Possible Successors
GetSampleClassSvm
See also
CreateClassSvm
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


1.4. SUPPORT-VECTOR-MACHINES 55

[out] double Index HClassSvmX.GetSupportVectorClassSvm


([in] VARIANT IndexSupportVector )
void HOperatorSetX.GetSupportVectorClassSvm
([in] VARIANT SVMHandle, [in] VARIANT IndexSupportVector,
[out] VARIANT Index )

Return the index of a support vector from a trained support vector machine.
The operator GetSupportVectorClassSvm maps support vectors of a trained SVM (given in SVMHandle)
to the original training data set. The index of the SV is specified with IndexSupportVector. The index is
counted from 0, i.e., IndexSupportVector must be a number between 0 and IndexSupportVectors
− 1, where IndexSupportVectors can be determined with GetSupportVectorNumClassSvm. The
index of this SV in the training data is returned in Index. This Index can be used for a query with
GetSampleClassSvm to obtain the feature vectors that become support vectors. GetSampleClassSvm
can, for example, be used to visualize the support vectors.
Note that when using TrainClassSvm with a mode different from ’default’ or reducing the SVM with
ReduceClassSvm, the returned Index will always be -1, i.e., it will be invalid. The reason for this is that
a consistent mapping between SV and training data becomes impossible.
Parameter
. SVMHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_svm ; HClassSvmX / VARIANT
SVM handle.
. IndexSupportVector (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Number of stored support vectors.
. Index (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Index of the support vector in the training set.
Result
If the parameters are valid the operator GetSampleClassSvm returns the value TRUE. If necessary, an excep-
tion handling is raised.
Parallelization Information
GetSupportVectorClassSvm is reentrant and processed without parallelization.
Possible Predecessors
TrainClassSvm, GetSupportVectorNumClassSvm
Possible Successors
GetSampleClassSvm
See also
CreateClassSvm
Module
Foundation

[out] long NumSupportVectors HClassSvmX.GetSupportVectorNumClassSvm


([out] VARIANT NumSVPerSVM )
void HOperatorSetX.GetSupportVectorNumClassSvm
([in] VARIANT SVMHandle, [out] VARIANT NumSupportVectors,
[out] VARIANT NumSVPerSVM )

Return the number of support vectors of a support vector machine.


GetSupportVectorNumClassSvm returns in NumSupportVectors the number of sup-
port vectors that are stored in the support vector machine (SVM) given by SVMHandle.
GetSupportVectorNumClassSvm should be called before the labels of individual support vectors are
read out with GetSupportVectorClassSvm, e.g., for visualizing which the training data become a SV
(see GetSupportVectorClassSvm). The number of SVs in each classifier is listed in NumSVPerSVM.
The reason that its sum differs from the Number obtained in NumSupportVectors is that SV evaluations are
reused throughout different sub-classifiers. NumSVPerSVM provides the possibility for controlling the process of
speeding up SVM classification time with the operator ReduceClassSvm.

HALCON 8.0.2
56 CHAPTER 1. CLASSIFICATION

Parameter

. SVMHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_svm ; HClassSvmX / VARIANT


SVM handle.
. NumSupportVectors (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Total number of support vectors.
. NumSVPerSVM (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Number of SV of each sub-SVM.
Result
If SVMHandle is valid the operator GetSampleNumClassSvm returns the value TRUE. If necessary, an
exception handling is raised.
Parallelization Information
GetSupportVectorNumClassSvm is reentrant and processed without parallelization.
Possible Predecessors
TrainClassSvm
Possible Successors
GetSampleClassSvm
See also
CreateClassSvm
Module
Foundation

void HClassSvmX.ReadClassSvm ([in] String FileName )


void HOperatorSetX.ReadClassSvm ([in] VARIANT FileName,
[out] VARIANT SVMHandle )

Read a support vector machine from a file.


ReadClassSvm reads a support vector machine (SVM) that has been stored with WriteClassSvm. Since
the training of an SVM can consume a relatively long time, the SVM is typically trained in an offline process
and written to a file with WriteClassSvm. In the online process the SVM is read with ReadClassSvm and
subsequently used for classification with ClassifyClassSvm.
Parameter

. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.read ; String / VARIANT


File name.
. SVMHandle (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_svm ; HClassSvmX / VARIANT
SVM handle.
Result
If the parameters are valid the operator ReadClassSvm returns the value TRUE. If necessary, an exception
handling is raised.
Parallelization Information
ReadClassSvm is processed completely exclusively without parallelization.
Possible Successors
ClassifyClassSvm
See also
CreateClassSvm, WriteClassSvm
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


1.4. SUPPORT-VECTOR-MACHINES 57

void HClassSvmX.ReadSamplesClassSvm ([in] String FileName )


void HOperatorSetX.ReadSamplesClassSvm ([in] VARIANT SVMHandle,
[in] VARIANT FileName )

Read the training data of a support vector machine from a file.


ReadSamplesClassSvm reads training samples from the file given by FileName and adds them to the
training samples that have already been added to the support vector machine (SVM) given by SVMHandle.
The SVM must be created with CreateClassSvm before calling ReadSamplesClassSvm. As de-
scribed with TrainClassSvm and WriteSamplesClassSvm, the operators ReadSamplesClassSvm,
AddSampleClassSvm, and WriteSamplesClassSvm can be used to build up a extensive set of training
samples, and hence to improve the performance of the SVM by retraining the SVM with extended data sets.
It should be noted that the training samples must have the correct dimensionality. The feature vectors and tar-
get vectors stored in FileName must have the lengths NumFeatures and NumClasses that were speci-
fied with CreateClassSvm. The target is stored in vector form for compability reason with the MLP (see
ReadSamplesClassMlp). If the dimensions are incorrect an error message is returned.
Parameter

. SVMHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_svm ; HClassSvmX / VARIANT


SVM handle.
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.read ; String / VARIANT
File name.
Result
If the parameters are valid the operator ReadSamplesClassSvm returns the value TRUE. If necessary, an
exception handling is raised.
Parallelization Information
ReadSamplesClassSvm is processed completely exclusively without parallelization.
Possible Predecessors
CreateClassSvm
Possible Successors
TrainClassSvm
See also
WriteSamplesClassSvm, ClearSamplesClassSvm
Alternatives
AddSampleClassSvm
Module
Foundation

[out] HClassSvmX SVMHandleReduced HClassSvmX.ReduceClassSvm


([in] String Method, [in] long MinRemainingSV, [in] double MaxError )
void HOperatorSetX.ReduceClassSvm ([in] VARIANT SVMHandle,
[in] VARIANT Method, [in] VARIANT MinRemainingSV, [in] VARIANT MaxError,
[out] VARIANT SVMHandleReduced )

Approximate a trained support vector machine by a reduced support vector machine for faster classification.
As described in CreateClassSvm, the classification time of a SVM depends on the number of kernel evalu-
ations between the support vectors and the feature vectors. While the length of the data vectors can be reduced
in a preprocessing step like ’pricipal_components’ or ’canonical_variates’ (see CreateClassSvm for details),
the number of resulting SV depends on the complexity of the classification problem. The number of SVs is deter-
mined during training. To further reduce classification time, the number of SVs can be reduced by approximating
the original separating hyperplane with fewer SVs than originally required. For this purpose, a copy of the orig-
inal SVM provided by SVMHandle is created and returned in SVMHandleReduced. This new SVM has the
same parametrization as the original SVM, but a different SV expansion. The training samples that are included in
SVMHandle are not copied. The original SVM is not modified by ReduceClassSvm.

HALCON 8.0.2
58 CHAPTER 1. CLASSIFICATION

The reduction method is selected with Method. Currently, only a bottom up approch is supported, which itera-
tively merges SVs. The algorithm stops if either the minimum number of SVs is reached (MinRemainingSV)
or if the accumulated maximum error exceeds the threshold MaxError. Note that the approximation reduces the
complexity of the hyperplane and thereby leads to a deteriorated classification rate. A common approch is there-
fore to start from a small MaxError e.g., 0.001, and to increase its value step by step. To control the reduction
ratio, at each step the number of remaining SVs is determined with GetSupportVectorNumClassSvm and
the classification rate is checked on a separate test data set with ClassifyClassSvm.
Parameter

. SVMHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_svm ; HClassSvmX / VARIANT


Original SVM handle.
. Method (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Type of postprocessing to reduce number of SV.
Default Value : ’bottom_up’
List of values : Method ∈ {’bottom_up’}
. MinRemainingSV (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Minimum number of remaining SVs.
Default Value : 2
Suggested values : MinRemainingSV ∈ {2, 3, 4, 5, 7, 10, 15, 20, 30, 50}
Restriction : (M inRemainingSV ≥ 2)
. MaxError (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Maximum allowed error of reduction.
Default Value : 0.001
Suggested values : MaxError ∈ {0.0001, 0.0002, 0.0005, 0.001, 0.002, 0.005, 0.01, 0.02, 0.05}
Restriction : (M axError > 0.0)
. SVMHandleReduced (output control) . . . . . . . . . . . . . . . . . . . . . . . . . class_svm ; HClassSvmX / VARIANT
SVMHandle of reduced SVM.
Example

* Train an SVM
create_class_svm (NumFeatures, ’rbf’, 0.01, 0.01, NumClasses,
’one-versus-all’, ’normalization’, NumFeatures,
SVMHandle)
read_samples_class_svm (SVMHandle, ’samples.mtf’)
train_class_svm (SVMHandle, 0.001, ’default’)
* Create a reduced SVM
reduce_class_svm (SVMHandle, ’bottom_up’, 2, 0.01, SVMHandleReduced)
write_class_svm (SVMHandleReduced, ’classifier.svm)
clear_class_svm (SVMHandleReduced)
clear_class_svm (SVMHandle)

Result
If the parameters are valid the operator TrainClassSvm returns the value TRUE. If necessary, an exception
handling is raised.
Parallelization Information
ReduceClassSvm is processed completely exclusively without parallelization.
Possible Predecessors
TrainClassSvm, GetSupportVectorNumClassSvm
Possible Successors
ClassifyClassSvm, WriteClassSvm, GetSupportVectorNumClassSvm
See also
TrainClassSvm
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


1.4. SUPPORT-VECTOR-MACHINES 59

void HClassSvmX.TrainClassSvm ([in] double Epsilon,


[in] VARIANT TrainMode )
void HOperatorSetX.TrainClassSvm ([in] VARIANT SVMHandle,
[in] VARIANT Epsilon, [in] VARIANT TrainMode )

Train a support vector machine.


TrainClassSvm trains the support vector machine (SVM) given in SVMHandle. Before the SVM can be
trained, the training samples to be used for the training must be added to the SVM using AddSampleClassSvm
or ReadSamplesClassSvm.
Technically, training an SVM means solving a convex quadratic optimization problem. This implies that it can
be assured that training terminates after finite steps at the global optimum. In order to recognize termination,
the gradient of the function that is optimized intenally must fall below a threshold, which is set in Epsilon.
By default, a value of 0.001 should be used for Epsilon since this yields the best results in practice. A too
big value leads to a too early termination and might result in suboptimal solutions. With a too small value the
optimization requires a longer time, often without changing the recognition rate significantly. Nevertheless, if
longer training times are possible, a smaller value than 0.001 might be chosen. There are two common reasons
for changing Epsilon: First, if you specified a very small value for Nu when calling ( CreateClassSvm),
e.g., Nu = 0.001, a smaller Epsilon might significantly improve the recognition rate. A second case is the
determination of the optimal kernel function and its parameterization (e.g., the KernelParam-Nu pair for the
RBF kernel) with the computationally intensive n-fold cross validation. Here, choosing a bigger Epsilon reduces
the computational time without changing the parameters of the optimal kernel that would be obtained when using
the default Epsilon. After the optimal KernelParam-Nu pair is obtained, the final training is conducted with
a small Epsilon.
The duration of the training depends on the training data, in particular on the number of resulting support vectors
(SVs), and Epsilon. It can lie between seconds and several hours. It is therefore recommended to choose the
SVM parameter Nu in CreateClassSvm so that as few SVs as possible are generated without decreasing the
recognition rate. Special care must be taken with the parameter Nu in CreateClassSvm so that the optimization
starts from a feasible region. If too many training errors are chosen with a too big Nu, an exception handling is
raised. In this case, an SVM with the same training data, but with smaller Nu must be trained.
With the parameter TrainMode you can choose between different training modes. Normally, you train an SVM
without additional information and TrainMode is set to ’default’. If multiple SVMs for the same data set but
with different kernels are trained, subsequent training runs can reuse optimization results and thus speedup the
overall training time of all runs. For this mode, in TrainMode a SVM handle of a previously trained SVM is
passed. Note that the SVM handle passed in SVMHandle and the SVMHandle passed in TrainMode must have
the same training data, the same mode and the same number of classes (see CreateClassSvm). The application
for this training mode is the evaluation of different kernel functions given the same training set. In the literature
this is referred to as alpha seeding.
With TrainMode = ’add_sv_to_train_set’ it is possible to append the support vectors that were generated by
a previous call of TrainClassSvm to the currently saved training set. This mode has two typical application
areas: First, it is possible to gradually train a SVM. For this, the complete training set is divided into disjunctive
chunks. The first chunk is trained normally using TrainMode = ’default’. Afterwards, the previous training
set is removed with ClearSamplesClassSvm, the next chunk is added with AddSampleClassSvm and
trained with TrainMode = ’add_sv_to_train_set’. This is repeated until all chunks are trained. This approach has
the advantage that even huge training data sets can be trained efficiently with respect to memory consumption. A
second application area for this mode is that a general purpose classifier can be specialized by adding characteristic
training samples and then retraining it. Please note that the preprocessing (as described in CreateClassSvm)
is not changed when training with TrainMode = ’add_sv_to_train_set’.
Parameter
. SVMHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_svm ; HClassSvmX / VARIANT
SVM handle.
. Epsilon (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Stop parameter for training.
Default Value : 0.001
Suggested values : Epsilon ∈ {0.00001, 0.0001, 0.001, 0.01, 0.1}
. TrainMode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( string, integer )
Mode of training. For normal operation: ’default’. If SVs already included in the SVM should be used for

HALCON 8.0.2
60 CHAPTER 1. CLASSIFICATION

training: ’add_sv_to_train_set’. For alpha seeding: the respective SVM handle.


Default Value : ’default’
List of values : TrainMode ∈ {’default’, ’add_sv_to_train_set’}
Example

* Train an SVM
create_class_svm (NumFeatures, ’rbf’, 0.01, 0.01, NumClasses,
’one-versus-all’, ’normalization’, NumFeatures,
SVMHandle)
read_samples_class_svm (SVMHandle, ’samples.mtf’)
train_class_svm (SVMHandle, 0.001, ’default’)
write_class_svm (SVMHandle, ’classifier.svm)
clear_class_svm (SVMHandle)

Result
If the parameters are valid the operator TrainClassSvm returns the value TRUE. If necessary, an exception
handling is raised.
Parallelization Information
TrainClassSvm is processed completely exclusively without parallelization.
Possible Predecessors
AddSampleClassSvm, ReadSamplesClassSvm
Possible Successors
ClassifyClassSvm, WriteClassSvm
See also
CreateClassSvm
Alternatives
ReadClassSvm
References
John Shawe-Taylor, Nello Cristianini: “Kernel Methods for Pattern Analysis”; Cambridge University Press, Cam-
bridge; 2004.
Bernhard Schölkopf, Alexander J.Smola: “Lerning with Kernels”; MIT Press, London; 1999.
Module
Foundation

void HClassSvmX.WriteClassSvm ([in] String FileName )


void HOperatorSetX.WriteClassSvm ([in] VARIANT SVMHandle,
[in] VARIANT FileName )

Write a support vector machine to a file.


WriteClassSvm writes the support vector machine (SVM) SVMHandle to the file given by FileName.
WriteClassSvm is typically called after the SVM has been trained with TrainClassSvm. The SVM can
be read with ReadClassSvm. WriteClassSvm does not write any training samples that possibly have been
stored in the SVM. For this purpose, WriteSamplesClassSvm should be used.
Parameter
. SVMHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_svm ; HClassSvmX / VARIANT
SVM handle.
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.write ; String / VARIANT
File name.
Result
If the parameters are valid the operator WriteClassSvm returns the value TRUE. If necessary, an exception
handling is raised.

HALCON/COM Reference Manual, 2008-5-13


1.4. SUPPORT-VECTOR-MACHINES 61

Parallelization Information
WriteClassSvm is reentrant and processed without parallelization.
Possible Predecessors
TrainClassSvm
Possible Successors
ClearClassSvm
See also
CreateClassSvm, ReadClassSvm, WriteSamplesClassSvm
Module
Foundation

void HClassSvmX.WriteSamplesClassSvm ([in] String FileName )


void HOperatorSetX.WriteSamplesClassSvm ([in] VARIANT SVMHandle,
[in] VARIANT FileName )

Write the training data of a support vector machine to a file.


WriteSamplesClassSvm writes the training samples currently stored in the support vector machine (SVM)
SVMHandle to the file given by FileName. WriteSamplesClassSvm can be used to build up a database
of training samples, and hence to improve the performance of the SVM by training it with an extended data
set (see TrainClassSvm). The file FileName is overwritten by WriteSamplesClassSvm. Nev-
ertheless, extending the database of training samples is easy to do because ReadSamplesClassSvm and
AddSampleClassSvm add the training samples to the training samples that are already stored in memory with
the SVM.
Parameter

. SVMHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_svm ; HClassSvmX / VARIANT


SVM handle.
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.write ; String / VARIANT
File name.
Result
If the parameters are valid the operator WriteSamplesClassSvm returns the value TRUE. If necessary, an
exception handling is raised.
Parallelization Information
WriteSamplesClassSvm is reentrant and processed without parallelization.
Possible Predecessors
AddSampleClassSvm
Possible Successors
ClearSamplesClassSvm
See also
CreateClassSvm, GetPrepInfoClassSvm, ReadSamplesClassSvm
Module
Foundation

HALCON 8.0.2
62 CHAPTER 1. CLASSIFICATION

HALCON/COM Reference Manual, 2008-5-13


Chapter 2

File

2.1 Images

void HImageX.ReadImage ([in] VARIANT FileName )


void HOperatorSetX.ReadImage ([out] HUntypedObjectX Image,
[in] VARIANT FileName )

Read an image with different file formats.


The operator ReadImage reads the indicated image files from the background storage and generates the image.
One or more file names can be passed in FileName. If more than one file name is passed, an image object tuple
with the corresponding number of image objects is returned.
For the image formats PNG and JPEG-2000, binary alpha channels are interpreted as regions. Otherwise the region
of the generated image object (= all pixels of the matrix) is chosen maximal.
All images files written by the operator WriteImage (format ’ima’) have the extension ’.ima’. A description
file can be available for every image in HALCON format (same file name with extension ’.exp’). The type of the
pixel data (byte, int4, real) can also be taken from the description file. If this information is not available the type
byte is used as presetting.
Besides the HALCON format TIFF, GIF, BMP, JPEG, JPEG-2000, PNG, PCX, SUN-Raster, PGM, PPM, PBM
and XWD files can also be read. The gray values of PBM images are set at the values 0 and 255. The file formats
are either recognized by the extension (if indicated) or because of the internal structure of the files. If the extension
is indicated the image can be found faster. If no extension is indicated, files with extension are preferred to files
without extension. In case of PGM, PPM and PBM the corresponding extension (e.g. ’pgm’) or the general value
’pnm’ can be used. In case of TIFF ’tiff’ and ’tif’ are accepted. In case of JPEG-2000 only ’jp2’ is accepted. In
case of colored images an image with three color channels (matrices) is created, the red channel being stored in
the first, the blue channel in the second and the green channel in the third component (channel number).
Image files are searched in the current directory (determined by the environment variable) and in the image direc-
tory of HALCON . The image directory of HALCON is preset at ’.’ and ’/usr/local/halcon/images’ in a UNIX
environment and can be set via the operator SetSystem. More than one image directory can be indicated. This
is done by separating the individual directories by a colon.
Furthermore the search path can be set via the environment variable HALCONIMAGES (same structure as ’im-
age_dir’). Example:

setenv HALCONIMAGES "/usr/images:/usr/local/halcon/images"\\*

HALCON also searches images in the subdirectory "‘images"’ (Images for the program examples). The environ-
ment variable HALCONROOT is used for the HALCON directory.
Attention
If CMYK or YCCK JPEG files are read, HALCON assumes that these files follow the Adobe Photoshop convention
that the CMYK channels are stored inverted, i.e., 0 represents 100% ink coverage, rather than 0% ink as one would
expect. The images are converted to RGB images using this convention. If the JPEG file does not follow this

63
64 CHAPTER 2. FILE

convention, but stores the CMYK channels in the usual fashion, InvertImage must be called after reading the
image.
If PNG images that contain an alpha channel are read, the alpha channel is returned as the second or fourth channel
of the output image, unless the alpha channel contains exactly two different gray values, in which case a one or
three channel image with a reduced domain is returned, in which the points in the domain correspond to the points
with the higher gray value in the alpha channel.
Parameter

. Image (output iconic) . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, direction, cyclic, int1,
int2, uint2, int4, real )
Read image.
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.read(-array) ; VARIANT ( string )
Name of the image to be read.
Default Value : ’fabrik’
Suggested values : FileName ∈ {’monkey’, ’fabrik’, ’mreut’}
Example

/* Reading an image: */
read_image(Image,’monkey’).

/* Reading 3 images into an image array: */


read_image(Images,[’ic_0’,’ic_1’,’ic_2’]).

/* Setting of search path for images on ’/mnt/images’ and ’/home/images’:


*/
set_system(’image_dir’,’/mnt/images:/home/images’).

Result
If the parameters are correct the operator ReadImage returns the value TRUE. Otherwise an exception handling
is raised.
Parallelization Information
ReadImage is reentrant and processed without parallelization.
Possible Successors
DispImage, Threshold, Regiongrowing, CountChannels, Decompose3, ClassNdimNorm,
GaussImage, FillInterlace, ZoomImageSize, ZoomImageFactor, CropPart, WriteImage,
Rgb1ToGray
See also
SetSystem, WriteImage
Alternatives
ReadSequence
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


2.1. IMAGES 65

void HImageX.ReadSequence ([in] long HeaderSize, [in] long SourceWidth,


[in] long SourceHeight, [in] long StartRow, [in] long StartColumn,
[in] long DestWidth, [in] long DestHeight, [in] String PixelType,
[in] String BitOrder, [in] String ByteOrder, [in] String Pad, [in] long Index,
[in] String FileName )
void HOperatorSetX.ReadSequence ([out] HUntypedObjectX Image,
[in] VARIANT HeaderSize, [in] VARIANT SourceWidth, [in] VARIANT SourceHeight,
[in] VARIANT StartRow, [in] VARIANT StartColumn, [in] VARIANT DestWidth,
[in] VARIANT DestHeight, [in] VARIANT PixelType, [in] VARIANT BitOrder,
[in] VARIANT ByteOrder, [in] VARIANT Pad, [in] VARIANT Index,
[in] VARIANT FileName )

Read images.
The operator ReadSequence reads unformatted image data, from a file and returns a “suitable” image. The
image data must be filled consecutively pixel by pixel and line by line.
Any file headers (with the length HeaderSize bytes) are skipped. The parameters SourceWidth and
SourceHeight indicate the size of the filled image. DestWidth and DestHeight indicate the size of the
image. In the simplest case these parameters are the same. However, areas can also be read. The upper left corner
of the required image area can be determined via StartRow and StartColumn.
The pixel types ’bit’, ’byte’, ’short’ (16 bits, unsigned), ’signed_short’ (16 bits, signed), ’long’ (32 bits, signed),
’swapped_long’ (32 bits, with swapped segments), and ’real’ (32 bit floating point numbers) are supported. Fur-
thermore, the operator ReadSequence enables the extraction of components of a RBG image, if a triple of three
bytes (in the sequence “red”, “green”, “blue”) was filed in the image file. For the red component the pixel type
’r_byte’ must be chosen, and correspondingly for the green and blue components ’g_byte’ or ’b_byte’, respectively.
’MSBFirst’ (most significant bit first) or the inversion thereof (’LSBFirst’) can be chosen for the bit order
(BitOrder). The byte orders (ByteOrder) ’MSBFirst’ (most significant byte first) or ’LSBFirst’, respectively,
are processed analogously. Finally an alignment (Pad) can be set at the end of the line: ’byte’, ’short’ or ’long’. If
a whole image sequence is stored in the file a single image (beginning at Index 1) can be chosen via the parameter
Index.
Image files are searched in the current directory (determined by the environment variable) and in the image direc-
tory of HALCON . The image directory of HALCON is preset at ’.’ and ’/usr/local/halcon/images’ in a UNIX
environment and can be set via the operator SetSystem. More than one image directory can be indicated. This
is done by separating the individual directories by a colon.
Furthermore the search path can be set via the environment variable HALCONIMAGES (same structure as ’im-
age_dir’). Example:

setenv HALCONIMAGES "/usr/images:/usr/local/halcon/images"\\*

HALCON also searches images in the subdirectory "‘images"’ (Images for the program examples). The environ-
ment variable HALCONROOT is used for the HALCON directory.
Attention
If files of pixel type ’real’ are read and the byte order is chosen incorrectly (i.e., differently from the byte order in
which the data is stored in the file) program error and even crashes because of floating point exceptions may result.
Parameter
. Image (output iconic) . . . . . . . . . . . . . . . . . . . image ; HImageX / HUntypedObjectX ( byte, int2, uint2, int4 )
Image read.
. HeaderSize (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of bytes for file header.
Default Value : 0
. SourceWidth (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; long / VARIANT
Number of image columns of the filed image.
Default Value : 512
. SourceHeight (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; long / VARIANT
Number of image lines of the filed image.
Default Value : 512

HALCON 8.0.2
66 CHAPTER 2. FILE

. StartRow (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; long / VARIANT


Starting point of image area (line).
Default Value : 0
Restriction : (StartRow < SourceHeight)
. StartColumn (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; long / VARIANT
Starting point of image area (column).
Default Value : 0
Restriction : (StartColumn < SourceW idth)
. DestWidth (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; long / VARIANT
Number of image columns of output image.
Default Value : 512
Restriction : (DestW idth ≤ SourceW idth)
. DestHeight (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; long / VARIANT
Number of image lines of output image.
Default Value : 512
Restriction : (DestHeight ≤ SourceHeight)
. PixelType (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Type of pixel values.
Default Value : ’byte’
List of values : PixelType ∈ {’bit’, ’byte’, ’r_byte’, ’g_byte’, ’b_byte’, ’short’, ’signed_short’, ’long’,
’swapped_long’, ’real’}
. BitOrder (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Sequence of bits within one byte.
Default Value : ’MSBFirst’
List of values : BitOrder ∈ {’MSBFirst’, ’LSBFirst’}
. ByteOrder (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Sequence of bytes within one ’short’ unit.
Default Value : ’MSBFirst’
List of values : ByteOrder ∈ {’MSBFirst’, ’LSBFirst’}
. Pad (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Data units within one image line (alignment).
Default Value : ’byte’
List of values : Pad ∈ {’byte’, ’short’, ’long’}
. Index (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of images in the file.
Default Value : 1
(lin)
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.read ; String / VARIANT
Name of input file.
Result
If the parameter values are correct the operator ReadSequence returns the value TRUE. Otherwise an exception
handling is raised.
Parallelization Information
ReadSequence is reentrant and processed without parallelization.
Possible Successors
DispImage, CountChannels, Decompose3, WriteImage, Rgb1ToGray
See also
ReadImage
Alternatives
ReadImage
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


2.1. IMAGES 67

void HImageX.WriteImage ([in] String Format, [in] long FillColor,


[in] VARIANT FileName )
void HOperatorSetX.WriteImage ([in] IHObjectX Image,
[in] VARIANT Format, [in] VARIANT FillColor, [in] VARIANT FileName )

Write images in graphic formats.


The operator WriteImage returns the indicated image (Image) in different image formats in files. Pixels
outside the region receive the color defined by FillColor. For gray value images a value between 0 (black)
and 255 (white) must be passed, with RGB color images the RGB values can be passed directly as a hexadecimal
value: e.g., 0xffff00 for a yellow background (red=255, green=255, blue=0).
The following formats are currently supported:

’tiff’ TIFF format, 3-channel-images (RGB): 3 samples per pixel; other images (grayvalue images): 1 sample per
pixel, 8 bits per sample, uncompressed,72 dpi; file extension: *.tif
’bmp’ Windows-BMP format, 3-channel-images (RGB): 3 bytes per pixel; other images (gray value image): 1
byte per pixel; file extension: *.bmp
’jpeg’ JPEG format, with lost of information; together with the format string the quality value determining the
compression rate can be provided: e.g., ’jpeg 30’. Attention: images stored for being processed later should
not be compressed with the jpeg format according to the lost of information.
’jp2’ : JPEG-2000 format (lossless and lossy compression); together with the format string the quality value
determing the compression rate can be provided (e.g., ’jp2 40’). This value corresponds to the ratio of the
size of the compressed image and the size of the uncompressed image (in percent). Since lossless JPEG-
2000 compression already reduces the file size significantly, only smaller values (typically smaller than 50)
influence the file size. If no value is provided for the compression (and only then), the image is compressed
lossless. The image can contain an arbitrary number of channels. Possible types are byte, cyclic, direction,
int1, uint2, int2, and int4. In the case of int4 it is only possible to store images with less or equal to 24
bits precision (otherwise an exception handling is raised). If an image with a reduced domain is written, the
region is stored as 1 bit alpha channel.
’png’ PNG format (lossless compression); together with the format string, a compresion level between 0 and 9 can
be specified, where 0 corresponds to no compression and 9 to the best possible compression. Alternatively,
the compression can be selected with the following strings: ’best’, ’fastest’, and ’none’. Hence, examples for
correct parameters are ’png’, ’png 7’, and ’png none’. Images of type byte and uint2 can be stored in PNG
files. If an image with a reduced domain is written, the region is stored as the alpha channel, where the points
within the domain are stored as the maximum gray value of the image type and the points outside the domain
are stored as the gray value 0. If an image with a full domain is written, no alpha channel is stored.
’ima’ The data is written binary line by line (without header or carriage return). The size of the image and the
pixel type are stored in the description file "’FileName.exp"’. All HALCON pixel types except complex
and vector_field can be written. Only the first channel of the image is stored in the file. The file extension
is: ’.ima’

Attention

Parameter

. Image (input iconic) . . . . . . image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2,
uint2, int4, real )
Output image(s).
. Format (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Graphic format.
Default Value : ’tiff’
List of values : Format ∈ {’tiff’, ’bmp’, ’jpeg’, ’ima’, ’jpeg 100’, ’jpeg 80’, ’jpeg 60’, ’jpeg 40’, ’jpeg 20’,
’jp2’, ’jp2 50’, ’jp2 40’, ’jp2 30’, ’jp2 20’, ’png’, ’png best’, ’png fastest’, ’png none’}
. FillColor (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Fill gray value for pixels not belonging to the image region.
Default Value : 0
Suggested values : FillColor ∈ {-1, 0, 255, 0xff0000, 0xff00}

HALCON 8.0.2
68 CHAPTER 2. FILE

. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.write(-array) ; VARIANT ( string )


Name of graphic file.
Result
If the parameter values are correct the operator WriteImage returns the value TRUE. Otherwise an exception
handling is raised.
Parallelization Information
WriteImage is reentrant and processed without parallelization.
Possible Predecessors
OpenWindow, ReadImage
Module
Foundation

2.2 Misc
void HMiscX.DeleteFile ([in] String FileName )
void HOperatorSetX.DeleteFile ([in] VARIANT FileName )

Delete a file.
DeleteFile deletes the file given by FileName.
Parameter

. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename ; String / VARIANT


Name of file to be checked.
Result
DeleteFile returns the value TRUE if the file exists and could be deleted. Otherwise, an exception is raised.
Parallelization Information
DeleteFile is reentrant and processed without parallelization.
Module
Foundation

HMiscX.FileExists ([in] String FileName )


[out] long FileExists
void HOperatorSetX.FileExists ([in] VARIANT FileName,
[out] VARIANT FileExists )

Check whether file exists.


The operator FileExists checks whether the indicated file already exists. If this is the case, the parameter
FileExists is set to TRUE, otherwise to FALSE.
Attention

Parameter

. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename ; String / VARIANT


Name of file to be checked.
Default Value : /bin/cc
. FileExists (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
boolean number.
Result
If the parameters are correct the operator FileExists returns the value TRUE. Otherwise, an exception is
raised.
Parallelization Information
FileExists is reentrant and processed without parallelization.

HALCON/COM Reference Manual, 2008-5-13


2.2. MISC 69

Possible Successors
OpenFile
Alternatives
OpenFile
Module
Foundation

[out] VARIANT Files HMiscX.ListFiles ([in] String Directory,


[in] VARIANT Options )
void HOperatorSetX.ListFiles ([in] VARIANT Directory,
[in] VARIANT Options, [out] VARIANT Files )

List all files in a directory.


ListFiles returns all files in the directory given by Directory in the parameters Files. The current direc-
tory can be specified with ” or ’.’. The parameter Options can be used to specify different processing options by
passing a tuple of values. If Options contains ’files’ only the files present in Directory are returned. If ’direc-
tories’ is passed, only the directories present in Directory are returned. Directories are marked by a trailing ’\’
(Windows) or a trailing ’/’ (Unix). If files as well as directories should be returned, [’files’,’directories’] must be
passed. If neither ’files’ nor ’directories’ is passed, ListFiles returns an empty tuple. By passing ’recursive’,
it can be specified that the directory tree should be searched recursively by examining all sub-directories. On Unix
systems, ’follow_links’ can be used to specify that symbolic links to files or directories should be followed. In
the default setting, symbolic links are not dereferenced, and hence are not searched if they point to directories,
and not returned if they point to files. For the recursive search, a maximum search depth can be specified with
’max_depth <d>’, where ’<d>’ is a number that specifies the maximum depth. Hence, ’max_depth 2’ specifies
that Directory and all immediate sub-directories should be searched. If symbolic links should be followed it
might happen that the search does not terminate if the symbolic links lead to a cycle in the directory structure.
Because of this, at most 1000000 files (and directories) are returned in Files. By specifying a different number
with ’max_files <d>’, this value can be reduced.
Parameter
. Directory (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.dir ; String / VARIANT
Name of directory to be listed.
. Options (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Processing options.
Default Value : ’files’
Suggested values : Options ∈ {’files’, ’directories’, ’recursive’, ’follow_links’, ’max_depth 5’, ’max_files
1000’}
. Files (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( string )
Found files (and directories).
Result
ListFiles returns the value TRUE if the directory exists and could be read. Otherwise, an exception is raised.
Parallelization Information
ListFiles is reentrant and processed without parallelization.
Possible Successors
TupleRegexpSelect
Module
Foundation

void HHomMat2dX.ReadWorldFile ([in] String FileName )


void HOperatorSetX.ReadWorldFile ([in] VARIANT FileName,
[out] VARIANT WorldTransformation )

Read the geo coding from an ARC/INFO world file.

HALCON 8.0.2
70 CHAPTER 2. FILE

ReadWorldFile reads a geocoding from an ARC/INFO world file with the file name FileName and returns
it as a homogeneous 2D transformation matrix in WorldTransformation. To find the file FileName, all
directories contained in the HALCON system variable ’image_dir’ (usually this is the content of the environment
variable HALCONIMAGES) are searched (see ReadImage). This transformation matrix can be used to trans-
form XLD contours to the world coordinate system before writing them with WriteContourXldArcInfo.
If the matrix WorldTransformation is inverted by calling HomMat2dInvert, the resulting matrix can
be used to transform contours that have been read with ReadContourXldArcInfo to the image coordinate
system.
Parameter
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.read ; String / VARIANT
Name of the ARC/INFO world file.
. WorldTransformation (output control) . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )
Transformation matrix from image to world coordinates.
Result
If the parameters are correct and the world file could be read, the operator ReadWorldFile returns the value
TRUE. Otherwise an exception is raised.
Parallelization Information
ReadWorldFile is reentrant and processed without parallelization.
Possible Successors
HomMat2dInvert, AffineTransContourXld, AffineTransPolygonXld
See also
WriteContourXldArcInfo, ReadContourXldArcInfo, WritePolygonXldArcInfo,
ReadPolygonXldArcInfo
Module
Foundation

2.3 Region

void HRegionX.ReadRegion ([in] String FileName )


void HOperatorSetX.ReadRegion ([out] HUntypedObjectX Region,
[in] VARIANT FileName )

Read binary images or HALCON regions.


The operator ReadRegion reads regions from a binary file. The data is stored in packed form.
Tiff: Binary Tiff images with extension ’tiff’ or ’tif’. The result is always one region. The color black is used as
foreground.
BMP: Binary Windows bitmap images with extension ’bmp’. The result is always one region. The color black is
used as foreground.
HALCON regions: File format of HALCON for regions. Several images can be stored (in one file) or read
simultaneously via the operators WriteRegion and ReadRegion. All region files have the extension
’.reg’, which is not indicated when reading or writing the file.
A search path (’image_dir’) can be defined analogous to the operator ReadImage.
Attention
The clipping based on the current image format is set via the operator SetSystem
(’clipRegion’,<’true’/’false’>). Consequently, if no image of suffcient size has been cre-
ated before the call to ReadRegion, SetSystem(’clipRegion’,’false’) should be called before
calling ReadRegion to ensure that the region is not being clipped.
Parameter
. Region (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Read region.
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.read ; String / VARIANT
Name of the region to be read.

HALCON/COM Reference Manual, 2008-5-13


2.3. REGION 71

Example

/* Reading of regions and giving them gray values. */


read_image(Img,’bild_test5’)
read_region(Regs,’reg_test5’)
reduce_domain(Img,Regs,Res)

Result
If the parameter values are correct the operator ReadRegion returns the value TRUE. Otherwise an exception
handling is raised.
Parallelization Information
ReadRegion is reentrant and processed without parallelization.
Possible Predecessors
ReadImage
Possible Successors
ReduceDomain, DispRegion
See also
WriteRegion, ReadImage
Module
Foundation

void HRegionX.WriteRegion ([in] String FileName )


void HOperatorSetX.WriteRegion ([in] IHObjectX Region,
[in] VARIANT FileName )

Write regions on file.


The operator WriteRegion writes the regions of the input images (in runlength coding) to a binary file. The
data is stored in packed form. The output data can be read via the operator ReadRegion. If no extension has
been specified in FileName, the extension ’.reg’ is appended to FileName.
Attention

Parameter

. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Region of the images which are returned.
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.write ; String / VARIANT
Name of region file.
Default Value : ’region.reg’
Example

regiongrowing(Img,Segmente,3,3,5,10)
write_region(Segmente,’result1’).

Result
If the parameter values are correct the operator WriteRegion returns the value TRUE. Otherwise an exception
handling is raised.
Parallelization Information
WriteRegion is reentrant and processed without parallelization.
Possible Predecessors
OpenWindow, ReadImage, ReadRegion, Threshold, Regiongrowing

HALCON 8.0.2
72 CHAPTER 2. FILE

See also
ReadRegion
Module
Foundation

2.4 Text
void HMiscX.CloseAllFiles ( )
void HOperatorSetX.CloseAllFiles ( )

Close all open files.


CloseAllFiles closes all open files.
Attention
CloseAllFiles exists solely for the purpose of implementing the “reset program” functionality in HDevelop.
CloseAllFiles must not be used in any application.
Result
If it is possible to close the files the operator CloseAllFiles returns the value TRUE. Otherwise an exception
handling is raised.
Parallelization Information
CloseAllFiles is processed completely exclusively without parallelization.
Alternatives
CloseFile
Module
Foundation

void HOperatorSetX.CloseFile ([in] VARIANT FileHandle )

Closing a text file.


The operator CloseFile closes a file which was opened via the operator OpenFile.
Parameter

. FileHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . file ; HFileX / VARIANT


File handle.
Example

open_file(’/tmp/data.txt’,’input’,FileHandle)
// ....
close_file(FileHandle).

Result
If the file handle is correct CloseFile returns the value TRUE. Otherwise an exception handling is raised.
Parallelization Information
CloseFile is processed completely exclusively without parallelization.
Possible Predecessors
OpenFile
See also
OpenFile
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


2.4. TEXT 73

void HFileX.FnewLine ( )
void HOperatorSetX.FnewLine ([in] VARIANT FileHandle )

Create a line feed.


The operator FnewLine puts out a line feed into the output file. At the same time the output buffer is cleaned.
Attention

Parameter
. FileHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . file ; HFileX / VARIANT
File handle.
Example

fwrite_string(FileHandle,’Good Morning’)
fnew_line(FileHandle)

Result
If an output file is open and it can be written to the file the operator FnewLine returns the value TRUE. Otherwise
an exception handling is raised.
Parallelization Information
FnewLine is reentrant and processed without parallelization.
Possible Predecessors
FwriteString
See also
FwriteString
Module
Foundation

[out] String Char HFileX.FreadChar ( )


void HOperatorSetX.FreadChar ([in] VARIANT FileHandle,
[out] VARIANT Char )

Read a character from a text file.


The operator FreadChar reads a character from the current input file. If no character can be read because the
end of the file is reached, FreadChar returns the character sequence ’eof’. At the end of a line the value ’nl’ is
returned.
Attention

Parameter
. FileHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . file ; HFileX / VARIANT
File handle.
. Char (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Read character or control string (’nl’,’eof’).
Example

repeat >
fread_char(FileHandle:Char)
(if(Char = ’nl’) > fnew_line(FileHandle)) |
(if(Char != ’nl’) > fwrite_string(FileHandle,Char))
until(Char = ’eof’).

HALCON 8.0.2
74 CHAPTER 2. FILE

Result
If an input file is open the operator fread_char returns TRUE. Otherwise an exception handling is raised.
Parallelization Information
FreadChar is reentrant and processed without parallelization.
Possible Predecessors
OpenFile
Possible Successors
CloseFile
See also
OpenFile, CloseFile, FreadString, FreadLine
Alternatives
FreadString, ReadString, FreadLine
Module
Foundation

HFileX.FreadLine ([out] long IsEOF )


[out] String OutLine
void HOperatorSetX.FreadLine ([in] VARIANT FileHandle,
[out] VARIANT OutLine, [out] VARIANT IsEOF )

Read a line from a text file.


The operator FreadLine reads a line from the current input file (including the line skip). If the end of the file is
reached IsEOF returns the value 1, otherwise 0.
Attention
The maximum string length is 1024 character (including the end of string character).
Parameter

. FileHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . file ; HFileX / VARIANT


File handle.
. OutLine (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Read line.
. IsEOF (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Reached end of file.
Result
If the file is open and a suitable line is read FreadLine returns the value TRUE. Otherwise an exception handling
is raised.
Parallelization Information
FreadLine is reentrant and processed without parallelization.
Possible Predecessors
OpenFile
Possible Successors
CloseFile
See also
OpenFile, CloseFile, FreadChar, FreadString
Alternatives
FreadChar, FreadString
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


2.4. TEXT 75

HFileX.FreadString ([out] long IsEOF )


[out] String OutString
void HOperatorSetX.FreadString ([in] VARIANT FileHandle,
[out] VARIANT OutString, [out] VARIANT IsEOF )

Read strings from a text file.


The operator FreadString reads a string from the current input file. A string begins with the first representable
character: letters, numbers, additional characters (except blanks). A string ends when a blank or a line skip is
reached. Several successive line skips are ignored. If the end of the file is reached IsEOF return the value 1,
otherwise 0.
Attention

Parameter

. FileHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . file ; HFileX / VARIANT


File handle.
. OutString (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Read character sequence.
. IsEOF (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Reached end of file.
Example

fwrite_string(FileHandle,’Please enter text and return: ..’)


fread_string(FileHandle,String,IsEOF) >
fwrite_string(FileHandle,[’here it is again: ’,String])
fnew_line(FileHandle).

Result
If a file is open and a suitable string is read FreadString returns the value TRUE. Otherwise an exception
handling is raised.
Parallelization Information
FreadString is reentrant and processed without parallelization.
Possible Predecessors
OpenFile
Possible Successors
CloseFile
See also
OpenFile, CloseFile, FreadChar, FreadLine
Alternatives
FreadChar, ReadString, FreadLine
Module
Foundation

void HFileX.FwriteString ([in] VARIANT String )


void HOperatorSetX.FwriteString ([in] VARIANT FileHandle,
[in] VARIANT String )

Write values in a text file.


The operator FwriteString puts out a string or numbers on the output file. The operator OpenFile opens a
file. The call SetSystem(::’flushFile’, <boolean-value>:) determines whether the output char-
acters are put out directly on the output medium. If the value ’flush_file’ is set to ’false’ the characters (especially
in case of screen output) show up only after the operator FnewLine is called.

HALCON 8.0.2
76 CHAPTER 2. FILE

Strings as well as whole numbers and floating point numbers can be used as arguments. If more than one value
serves as input the values are put out consecutively without blanks.
Attention
The maximum string length is 1024 character (including the end of string character).
Parameter
. FileHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . file ; HFileX / VARIANT
File handle.
. String (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( integer, real, string )
Values to be put out on the text file.
Default Value : ’hallo’
Example

fwrite_string(FileHandle,[’text with numbers:’,5,’ and ’,1.0]).


/* results in the following output: */
/* ’text with numbers:5 and 1.00000’ */

Result
If the writing procedure was carried out successfully the operator FwriteString returns the value TRUE.
Otherwise an exception handling is raised.
Parallelization Information
FwriteString is reentrant and processed without parallelization.
Possible Predecessors
OpenFile
Possible Successors
CloseFile
See also
OpenFile, CloseFile, SetSystem
Alternatives
WriteString
Module
Foundation

void HFileX.OpenFile ([in] String FileName, [in] String FileType )


void HOperatorSetX.OpenFile ([in] VARIANT FileName,
[in] VARIANT FileType, [out] VARIANT FileHandle )

Open text file.


The operator OpenFile opens a file. FileType determines whether this file is an input (’input’) or output file
(’output’ or ’append’). OpenFile creates files which can be accessed either by reading (’input’) or by writing
(’output’ or ’append’) are created. For terminal input and output the file names ’standard’ (’input’ and ’output’)
and ’error’ (only ’output’) are reserved.
Attention

Parameter
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename ; String / VARIANT
Name of file to be opened.
Default Value : ’standard’
Suggested values : FileName ∈ {’standard’, ’error’, ’/tmp/dat.dat’}
. FileType (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Type of file.
Default Value : ’output’
List of values : FileType ∈ {’input’, ’output’, ’append’}

HALCON/COM Reference Manual, 2008-5-13


2.5. TUPLE 77

. FileHandle (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . file ; HFileX / VARIANT


File handle.
Example

/* Creating of an outputfile with the name ’/tmp/log.txt’ and writing */


/* of one string: */
open_file(’/tmp/log.txt’,’output’,FileHandle)
fwrite_string(FileHandle,’these are the first and last lines’)
fnew_line(FileHandle)
close_file(FileHandle).

Result
If the parameters are correct the operator OpenFile returns the value TRUE. Otherwise an exception handling
is raised.
Parallelization Information
OpenFile is processed completely exclusively without parallelization.
Possible Successors
FwriteString, FreadChar, FreadString, FreadLine, CloseFile
See also
CloseFile, FwriteString, FreadChar, FreadString, FreadLine
Module
Foundation

2.5 Tuple

[out] VARIANT Tuple HMiscX.ReadTuple ([in] String FileName )


[out] VARIANT Tuple HTupleX.ReadTuple ([in] String FileName )
void HOperatorSetX.ReadTuple ([in] VARIANT FileName,
[out] VARIANT Tuple )

Read a tuple from a file.


The operator ReadTuple reads the contents of FileName and converts it into Tuple. The file has to be
generated by WriteTuple.
Parameter

. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.read ; String / VARIANT


Name of the file to be read.
. Tuple (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( real, integer, string )
Tuple with any kind of data.
Result
If the parameters are correct the operator ReadTuple returns the value TRUE. Otherwise an exception handling
is raised.
Parallelization Information
ReadTuple is reentrant and processed without parallelization.
See also
WriteTuple, GnuplotPlotCtrl, WriteImage, WriteRegion, OpenFile
Alternatives
FwriteString
Module
Foundation

HALCON 8.0.2
78 CHAPTER 2. FILE

void HMiscX.WriteTuple ([in] VARIANT Tuple, [in] String FileName )


void HTupleX.WriteTuple ([in] VARIANT Tuple, [in] String FileName )
void HOperatorSetX.WriteTuple ([in] VARIANT Tuple,
[in] VARIANT FileName )

Write a tuple to a file.


The operator WriteTuple writes the contents of Tuple to a file. The data is written in an ASCII format.
Therefore, the file can be exchanged between different architectures. There is no specific extension for this kind of
file.
Parameter
. Tuple (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( real, integer, string )
Tuple with any kind of data.
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.write ; String / VARIANT
Name of the file to be written.
Result
If the parameters are correct the operator WriteTuple returns the value TRUE. Otherwise an exception handling
is raised.
Parallelization Information
WriteTuple is reentrant and processed without parallelization.
See also
ReadTuple, WriteImage, WriteRegion, OpenFile
Alternatives
FwriteString
Module
Foundation

2.6 XLD
void HXLDContX.ReadContourXldArcInfo ([in] String FileName )
void HOperatorSetX.ReadContourXldArcInfo
([out] HUntypedObjectX Contours, [in] VARIANT FileName )

Read XLD contours to a file in ARC/INFO generate format.


ReadContourXldArcInfo reads the lines stored in ARC/INFO generate format in the file FileName, and
returns them as XLD contours in Contours. To find the file FileName, all directories contained in the HAL-
CON system variable ’image_dir’ (usually this is the content of the environment variable HALCONIMAGES) are
searched (see ReadImage). The returned contours are in world coordinates. They can be transformed to the
image coordinate system with the operator AffineTransContourXld. The necessary transformation matrix
can be generated by using ReadWorldFile to read the transformation matrix from image to world coordinates,
and inverting this matrix by calling HomMat2dInvert.
Parameter
. Contours (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . xld_cont(-array) ; HXLDContX / HUntypedObjectX
Read XLD contours.
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.read ; String / VARIANT
Name of the ARC/INFO file.
Example

/* Read the transformation and invert it */


read_world_file (’image.tfw’, WorldTransformation)
hom_mat2d_invert (WorldTransformation, ImageTransformation)
/* Read the image */

HALCON/COM Reference Manual, 2008-5-13


2.6. XLD 79

read_image (Image, ’image.tif’)


/* Read the line data */
read_contour_xld_arc_info (LinesWorld, ’lines.gen’)
/* Transform the line data to image coordinates */
affine_trans_contour_xld (LinesWorld, Lines, ImageTransformation)

Result
If the parameters are correct and the file could be read, the operator ReadContourXldArcInfo returns the
value TRUE. Otherwise an exception is raised.
Parallelization Information
ReadContourXldArcInfo is reentrant and processed without parallelization.
Possible Successors
HomMat2dInvert, AffineTransContourXld
See also
ReadWorldFile, WriteContourXldArcInfo, ReadPolygonXldArcInfo
Module
Foundation

void HXLDContX.ReadContourXldDxf ([in] String FileName,


[in] VARIANT GenParamNames, [in] VARIANT GenParamValues,
[out] VARIANT DxfStatus )
void HOperatorSetX.ReadContourXldDxf ([out] HUntypedObjectX Contours,
[in] VARIANT FileName, [in] VARIANT GenParamNames,
[in] VARIANT GenParamValues, [out] VARIANT DxfStatus )

Read XLD contours from a DXF file.


ReadContourXldDxf reads the contents of the DXF file FileName (DXF version AC1009, AutoCAD Re-
lease 12) and converts them to the XLD contours Contours. If no absolute path is given in FileName the DXF
file is searched in the current directory of the HALCON process.
The output parameter DxfStatus contains information about the number of contours that were read and, if
necessary, warnings that parts of the DXF file could not be interpreted.
The operator ReadContourXldDxf supports the following DXF entities:

• POLYLINE
– 2D curves made up of line segments
– Closed 2D curves made up of line segments
• LWPOLYLINE
• LINE
• POINT
• CIRCLE
• ARC
• ELLIPSE
• SPLINE
• BLOCK
• INSERT

The x and y coordinates of the DXF entities are stored in the column and row coordinates, respectively, of the XLD
contours Contours.
If the file has been created with the operator WriteContourXldDxf, all attributes and global attributes that
were originally defined for the XLD contours are read. This means that ReadContourXldDxf supports all the

HALCON 8.0.2
80 CHAPTER 2. FILE

extended data written by the operator WriteContourXldDxf. The reading of these attributes can be switched
off by setting the generic parameter ’read_attributes’ to ’false’. Generic parameters are set by specifying the
parameter name(s) in GenParamNames and the corresponding value(s) in GenParamValues.
DXF entities of the type CIRCLE, ARC, ELLIPSE, and SPLINE are approximated by XLD contours. The
accuracy of this approximation can be controlled with the two generic parameters ’min_num_points’ and
’max_approx_error’ (for SPLINE only ’max_approx_error’). The parameter ’min_num_points’ defines the mini-
mum number of sampling points that are used for the approximation. Note that the parameter ’min_num_points’
always refers to the full circle or ellipse, respectively, even for ARCs or elliptical arcs, i.e., if ’min_num_points’ is
set to 50 and a DXF entity of the type ARC is read that represents a semi-circle, this semi-circle is approximated
by at least 25 sampling points. The parameter ’max_approx_error’ defines the maximum deviation of the XLD
contour from the ideal circle or ellipse, respectively (unit: pixel). For the determination of the accuracy of the
approximation both criteria are evaluated. Then, the criterion that leads to the more accurate approximation is
used.
Internally, the following default values are used for the generic parameters:

’read_attributes’ = ’true’
’min_num_points’ = 20
’max_approx_error’ = 0.25

To achieve a more accurate approximation, either the value for ’min_num_points’ must be increased or the value
for ’max_approx_error’ must be decreased.
Parameter
. Contours (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . xld_cont(-array) ; HXLDContX / HUntypedObjectX
Read XLD contours.
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.read ; String / VARIANT
Name of the DXF file.
. GenParamNames (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . attribute.name(-array) ; VARIANT ( string )
Names of the generic parameters that can be adjusted for the DXF input.
Default Value : []
List of values : GenParamNames ∈ {’read_attributes’, ’min_num_points’, ’max_approx_error’}
. GenParamValues (input control) . . . . . . . . . . . . attribute.value(-array) ; VARIANT ( integer, string, real )
Values of the generic parameters that can be adjusted for the DXF input.
Default Value : []
Suggested values : GenParamValues ∈ {’true’, ’false’, 0.1, 0.25, 0.5, 1, 2, 5, 10, 20}
. DxfStatus (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Status information.
Result
If the parameters are correct and the file could be read the operator ReadContourXldDxf returns the value
TRUE. Otherwise, an exception is raised.
Parallelization Information
ReadContourXldDxf is reentrant and processed without parallelization.
Possible Predecessors
WriteContourXldDxf
See also
WriteContourXldDxf, ReadPolygonXldDxf, QueryContourAttribsXld,
QueryContourGlobalAttribsXld, GetContourAttribXld, GetContourGlobalAttribXld
Module
Foundation

void HXLDPolyX.ReadPolygonXldArcInfo ([in] String FileName )


void HOperatorSetX.ReadPolygonXldArcInfo
([out] HUntypedObjectX Polygons, [in] VARIANT FileName )

Read XLD polygons from a file in ARC/INFO generate format.

HALCON/COM Reference Manual, 2008-5-13


2.6. XLD 81

ReadPolygonXldArcInfo reads the lines stored in ARC/INFO generate format in the file FileName, and
returns them as XLD polygons in Polygons. To find the file FileName, all directories contained in the HAL-
CON system variable ’image_dir’ (usually this is the content of the environment variable HALCONIMAGES) are
searched (see ReadImage). The returned polygons are in world coordinates. They can be transformed to the
image coordinate system with the operator AffineTransPolygonXld. The necessary transformation matrix
can be generated by using ReadWorldFile to read the transformation matrix from image to world coordinates,
and inverting this matrix by calling HomMat2dInvert.
Parameter
. Polygons (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . xld_poly(-array) ; HXLDPolyX / HUntypedObjectX
Read XLD polygons.
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.read ; String / VARIANT
Name of the ARC/INFO file.
Example

/* Read the transformation and invert it */


read_world_file (’image.tfw’, WorldTransformation)
hom_mat2d_invert (WorldTransformation, ImageTransformation)
/* Read the image */
read_image (Image, ’image.tif’)
/* Read the line data */
read_polygon_xld_arc_info (LinesWorld, ’lines.gen’)
/* Transform the line data to image coordinates */
affine_trans_polygon_xld (LinesWorld, Lines, ImageTransformation)

Result
If the parameters are correct and the file could be read, the operator ReadPolygonXldArcInfo returns the
value TRUE. Otherwise an exception is raised.
Parallelization Information
ReadPolygonXldArcInfo is reentrant and processed without parallelization.
Possible Successors
HomMat2dInvert, AffineTransPolygonXld
See also
ReadWorldFile, WritePolygonXldArcInfo, ReadContourXldArcInfo
Module
Foundation

void HXLDPolyX.ReadPolygonXldDxf ([in] String FileName,


[in] VARIANT GenParamNames, [in] VARIANT GenParamValues,
[out] VARIANT DxfStatus )
void HOperatorSetX.ReadPolygonXldDxf ([out] HUntypedObjectX Polygons,
[in] VARIANT FileName, [in] VARIANT GenParamNames,
[in] VARIANT GenParamValues, [out] VARIANT DxfStatus )

Read XLD polygons from a DXF file.


ReadPolygonXldDxf reads the contents of the DXF file FileName (DXF version AC1009, AutoCAD Re-
lease 12) and converts them to the XLD polygons Polygons. If no absolute path is given in FileName the DXF
file is searched in the current directory of the HALCON process.
The output parameter DxfStatus contains information about the number of polygons that were read and, if
necessary, warnings that parts of the DXF file could not be interpreted.
The operator ReadPolygonXldDxf supports the following DXF entities:

• POLYLINE

HALCON 8.0.2
82 CHAPTER 2. FILE

– 2D curves made up of line segments


– Closed 2D curves made up of line segments
• LWPOLYLINE
• LINE
• POINT
• CIRCLE
• ARC
• ELLIPSE
• SPLINE
• BLOCK
• INSERT

The x and y coordinates of the DXF entities are stored in the column and row coordinates, respectively, of the XLD
polygons Polygons.
DXF entities of the type CIRCLE, ARC, ELLIPSE, and SPLINE are approximated by XLD polygons. The
accuracy of this approximation can be controlled with the two generic parameters ’min_num_points’ and
’max_approx_error’ (for SPLINE only ’max_approx_error’). Generic parameters are set by specifying the pa-
rameter name(s) in GenParamNames and the corresponding value(s) in GenParamValues. The parameter
’min_num_points’ defines the minimum number of sampling points that are used for the approximation. Note that
the parameter ’min_num_points’ always refers to the full circle or ellipse, respectively, even for ARCs or elliptical
arcs, i.e., if ’min_num_points’ is set to 50 and a DXF entity of the type ARC is read that represents a semi-circle,
this semi-circle is approximated by at least 25 sampling points. The parameter ’max_approx_error’ defines the
maximum deviation of the XLD polygon from the ideal circle or ellipse, respectively (unit: pixel). For the deter-
mination of the accuracy of the approximation both criteria are evaluated. Then, the criterion that leads to the more
accurate approximation is used.
Internally, the following default values are used for the generic parameters:

’min_num_points’ = 20
’max_approx_error’ = 0.25

To achieve a more accurate approximation, either the value for ’min_num_points’ must be increased or the value
for ’max_approx_error’ must be decreased.
Note that reading a DXF file with ReadPolygonXldDxf results in exactly the same geometric information as
reading the file with ReadContourXldDxf. However, the resulting data structure is different.
Parameter
. Polygons (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . xld_poly(-array) ; HXLDPolyX / HUntypedObjectX
Read XLD polygons.
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.read ; String / VARIANT
Name of the DXF file.
. GenParamNames (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . attribute.name(-array) ; VARIANT ( string )
Names of the generic parameters that can be adjusted for the DXF input.
Default Value : []
List of values : GenParamNames ∈ {’min_num_points’, ’max_approx_error’}
. GenParamValues (input control) . . . . . . . . . . . . attribute.value(-array) ; VARIANT ( integer, string, real )
Values of the generic parameters that can be adjusted for the DXF input.
Default Value : []
Suggested values : GenParamValues ∈ {0.1, 0.25, 0.5, 1, 2, 5, 10, 20}
. DxfStatus (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Status information.
Result
If the parameters are correct and the file could be read the operator ReadPolygonXldDxf returns the value
TRUE. Otherwise, an exception is raised.
Parallelization Information
ReadPolygonXldDxf is reentrant and processed without parallelization.

HALCON/COM Reference Manual, 2008-5-13


2.6. XLD 83

Possible Predecessors
WritePolygonXldDxf
See also
WritePolygonXldDxf, ReadContourXldDxf
Module
Foundation

void HXLDContX.WriteContourXldArcInfo ([in] String FileName )


void HOperatorSetX.WriteContourXldArcInfo ([in] IHObjectX Contours,
[in] VARIANT FileName )

Write XLD contours to a file in ARC/INFO generate format.


WriteContourXldArcInfo writes the XLD contours Contours to an ARC/INFO generate format file with
name FileName. If no absolute path is given in FileName, the output file is created in the current direc-
tory of the HALCON process. The contours must have been transformed to the world coordinate system with
AffineTransContourXld beforehand. The necessary transformation can be read from an ARC/INFO world
file with ReadWorldFile.
Parameter
. Contours (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xld_cont(-array) ; HXLDContX / IHObjectX
XLD contours to be written.
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.write ; String / VARIANT
Name of the ARC/INFO file.
Example

/* Read transformation and image */


read_world_file (’image.tfw’, WorldTransformation)
read_image (Image, ’image.tif’)
/* Segment image */
...
/* Write result */
affine_trans_contour_xld (Contours, ContoursWorld, WorldTransformation)
write_contour_xld_arc_info (ContoursWorld, ’result.gen’)

Result
If the parameters are correct and the file could be written, the operator WriteContourXldArcInfo returns
the value TRUE. Otherwise an exception is raised.
Parallelization Information
WriteContourXldArcInfo is reentrant and processed without parallelization.
Possible Predecessors
AffineTransContourXld
See also
ReadWorldFile, ReadContourXldArcInfo, WritePolygonXldArcInfo
Module
Foundation

void HXLDContX.WriteContourXldDxf ([in] String FileName )


void HOperatorSetX.WriteContourXldDxf ([in] IHObjectX Contours,
[in] VARIANT FileName )

Write XLD contours to a file in DXF format.

HALCON 8.0.2
84 CHAPTER 2. FILE

WriteContourXldDxf writes the XLD contours Contours to the file FileName in DXF format. If no
absolute path is given in FileName the output file is created in the current directory of the HALCON process.
Besides the geometry of the Contours, all attributes and global attributes that are defined for the Contours are
written to the file.
WriteContourXldDxf writes the file according to the DXF version AC1009 (AutoCAD Release 12). Each
contour is stored as a POLYLINE. The attribute values are stored as extended data of each VERTEX of the POLY-
LINE. The global attribute values are stored as extended data of the POLYLINE. All attribute names are also stored
as extended data of the POLYLINE.
The operator ReadContourXldDxf can be used to read the XLD contours together with their attributes.
Other applications that are able to read DXF files only import the contour geometry, but they ignore the attribute
information.
Description of the format of the extended data
Each block of extended data starts with the following DXF group:
1001
HALCON
The attributes are written in the following format as extended data of each VERTEX:

DXF Explanation
1000 Meaning
contour attributes
1002 Beginning of the value list
{
1070 Number of attributes (here: 3)
3
1040 Value of the first attribute
5.00434303
1040 Value of the second attribute
126.8638916
1040 Value of the third attribute
4.99164152
1002 End of the value list
}

The global attributes are written in the following format as extended data of each POLYLINE:

DXF Explanation
1000 Meaning
global contour attributes
1002 Beginning of the value list
{
1070 Number of global attributes (here: 5)
5
1040 Value of the first global attribute
0.77951831
1040 Value of the second global attribute
0.62637949
1040 Value of the third global attribute
103.94314575
1040 Value of the fourth global attribute
0.21434096
1040 Value of the fifth global attribute
0.21921949
1002 End of the value list
}

The names of the attributes are written in the following format as extended data of each POLYLINE:

HALCON/COM Reference Manual, 2008-5-13


2.6. XLD 85

DXF Explanation
1000 Meaning
names of contour attributes
1002 Beginning of the value list
{
1070 Number of attribute names (here: 3)
3
1000 Name of the first attribute
angle
1000 Name of the second attribute
response
1000 Name of the third attribute
edge_direction
1002 End of the value list
}

The names of the global attributes are written in the following format as extended data of each POLYLINE:

DXF Explanation
1000 Meaning
names of global contour attributes
1002 Beginning of the value list
{
1070 Number of global attribute names (here: 5)
5
1000 Name of the first global attribute
regr_norm_row
1000 Name of the second global attribute
regr_norm_col
1000 Name of the third global attribute
regr_dist
1000 Name of the fourth global attribute
regr_mean_dist
1000 Name of the fifth global attribute
regr_dev_dist
1002 End of the value list
}

Parameter

. Contours (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xld_cont(-array) ; HXLDContX / IHObjectX


XLD contours to be written.
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.write ; String / VARIANT
Name of the DXF file.
Result
If the parameters are correct and the file could be written the operator WriteContourXldDxf returns the value
TRUE. Otherwise, an exception is raised.
Parallelization Information
WriteContourXldDxf is reentrant and processed without parallelization.
Possible Predecessors
EdgesSubPix
See also
ReadContourXldDxf, WritePolygonXldDxf, QueryContourAttribsXld,
QueryContourGlobalAttribsXld, GetContourAttribXld, GetContourGlobalAttribXld
Module
Foundation

HALCON 8.0.2
86 CHAPTER 2. FILE

void HXLDPolyX.WritePolygonXldArcInfo ([in] String FileName )


void HOperatorSetX.WritePolygonXldArcInfo ([in] IHObjectX Polygons,
[in] VARIANT FileName )

Write XLD polygons to a file in ARC/INFO generate format.


WritePolygonXldArcInfo writes the XLD polygons Polygons to an ARC/INFO generate format file with
name FileName. If no absolute path is given in FileName, the output file is created in the current direc-
tory of the HALCON process. The polygons must have been transformed to the world coordinate system with
AffineTransPolygonXld beforehand. The necessary transformation can be read from an ARC/INFO world
file with ReadWorldFile.
Attention
The XLD contours that are possibly referenced by Polygons are not stored in the ARC/INFO file, since this
is not possible with the ARC/INFO generate file format. Therefore, when the polygons are read again using
ReadPolygonXldArcInfo, this information is lost, and no references to contours are generated for the poly-
gons. Hence, operators that access the contours associated with a polygon, e.g., SplitContoursXld will not
work correctly.
Parameter
. Polygons (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xld_poly(-array) ; HXLDPolyX / IHObjectX
XLD polygons to be written.
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.write ; String / VARIANT
Name of the ARC/INFO file.
Example

/* Read transformation and image */


read_world_file (’image.tfw’, WorldTransformation)
read_image (Image, ’image.tif’)
/* Segment image */
...
/* Write result */
affine_trans_polygon_xld (Polygons, PolygonsWorld, WorldTransformation)
write_polygon_xld_arc_info (PolygonsWorld, ’result.gen’)

Result
If the parameters are correct and the file could be written, the operator WritePolygonXldArcInfo returns
the value TRUE. Otherwise an exception is raised.
Parallelization Information
WritePolygonXldArcInfo is reentrant and processed without parallelization.
Possible Predecessors
AffineTransPolygonXld
See also
ReadWorldFile, ReadPolygonXldArcInfo, WriteContourXldArcInfo
Module
Foundation

void HXLDPolyX.WritePolygonXldDxf ([in] String FileName )


void HOperatorSetX.WritePolygonXldDxf ([in] IHObjectX Polygons,
[in] VARIANT FileName )

Write XLD polygons to a file in DXF format.


WritePolygonXldDxf writes the XLD polygons Polygons to the file FileName in DXF format. If no
absolute path is given in FileName the output file is created in the current directory of the HALCON process.

HALCON/COM Reference Manual, 2008-5-13


2.6. XLD 87

WritePolygonXldDxf writes the file according to the DXF version AC1009 (AutoCAD Release 12). Each
polygon is stored as a POLYLINE.
The operator ReadPolygonXldDxf can be used to read the XLD polygon.
Attention
The XLD contours that are possibly referenced by Polygons are not stored in the DXF file. Therefore, when
the polygons are read again using ReadPolygonXldDxf, this information is lost, and no references to con-
tours are generated for the polygons. Hence, operators that access the contours associated with a polygon, e.g.,
SplitContoursXld will not work correctly.
Parameter

. Polygons (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xld_poly(-array) ; HXLDPolyX / IHObjectX


XLD polygons to be written.
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.write ; String / VARIANT
Name of the DXF file.
Result
If the parameters are correct and the file could be written the operator WritePolygonXldDxf returns the value
TRUE. Otherwise, an exception is raised.
Parallelization Information
WritePolygonXldDxf is reentrant and processed without parallelization.
Possible Predecessors
GenPolygonsXld
See also
ReadPolygonXldDxf, WriteContourXldDxf
Module
Foundation

HALCON 8.0.2
88 CHAPTER 2. FILE

HALCON/COM Reference Manual, 2008-5-13


Chapter 3

Filter

3.1 Arithmetic
HImageX.AbsImage ( )
[out] HImageX ImageAbs
void HOperatorSetX.AbsImage ([in] IHObjectX Image,
[out] HUntypedObjectX ImageAbs )

Calculate the absolute value (modulus) of an image.


The operator AbsImage calculates the absolute gray values of images of any type and stores the result in
ImageAbs. The power spectrum of complex images is calculated as a ’real’ image. The operator AbsImage
generates a logical copy of unsigned images.
Parameter

. Image (input iconic) . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( int1, int2, int4, real,
complex )
Image(s) for which the absolute gray values are to be calculated.
. ImageAbs (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX ( int1,
int2, int4, real )
Result image(s).
Example

convert_image_type (Image, ImageInt2, ’int2’)


texture_laws (ImageInt2, ImageTexture, ’el’, 2, 5)
abs_image (ImageTexture, ImageTexture)

Result
The operator AbsImage returns the value TRUE. The behavior in case of empty input (no input images available)
is set via the operator SetSystem(::’noObjectResult’,<Result>:)
Parallelization Information
AbsImage is reentrant and automatically parallelized (on tuple level, channel level, domain level).
See also
ConvertImageType, PowerByte
Module
Foundation

89
90 CHAPTER 3. FILTER

[out] HImageX ImageResult HImageX.AddImage ([in] HImageX Image2,


[in] VARIANT Mult, [in] VARIANT Add )
void HOperatorSetX.AddImage ([in] IHObjectX Image1,
[in] IHObjectX Image2, [out] HUntypedObjectX ImageResult, [in] VARIANT Mult,
[in] VARIANT Add )

Add two images.


The operator AddImage adds two images. The gray values (g1, g2) of the input images (Image1 and Image2)
are transformed as follows:

g 0 := (g1 + g2) ∗ Mult + Add

If an overflow or an underflow occurs the values are clipped. This is not the case with int2 images if Mult is equal
to 1 and Add is equal to 0. To reduce the runtime the underflow and overflow check is skipped. The resulting
image is stored in ImageResult.
It is possible to add byte images with int2, uint2 or int4 images and to add int4 to int2 or uint2 images. In this case
the result will be of type int2 or int4 respectively.
Several images can be processed in one call. In this case both input parameters contain the same number of images
which are then processed in pairs. An output image is generated for every pair.

Please note that the runtime of the operator varies with different control parameters. For frequently used combina-
tions special optimizations are used. Additionally, for byte, int2, uint2, and int4 images special optimizations are
implemented that use SIMD technology. The actual application of these special optimizations is controlled by the
system parameter ’mmx_enable’ (see SetSystem). If ’mmx_enable’ is set to ’true’ (and the SIMD instruction
set is available), the internal calculations are performed using SIMD technology.
Attention
Note that SIMD technology performs best on large, compact input regions. Depending on the input region and
the capabilities of the hardware the execution of AddImage might even take significantly more time with
SIMD technology than without. In this case, the use of SIMD technology can be avoided by SetSystem(:
:’mmxEnable’,’false’:).
Parameter

. Image1 (input iconic) . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, int1, int2,


uint2, int4, real, direction, cyclic, complex )
Image(s) 1.
. Image2 (input iconic) . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, int1, int2,
uint2, int4, real, direction, cyclic, complex )
Image(s) 2.
. ImageResult (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX (
byte, int1, int2, uint2, int4, real, di-
rection, cyclic, complex )
Result image(s) by the addition.
. Mult (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Factor for gray value adaption.
Default Value : 0.5
Suggested values : Mult ∈ {0.2, 0.4, 0.6, 0.8, 1.0, 1.5, 2.0, 3.0, 5.0}
Typical range of values : -255.0 ≤ Mult ≤ -255.0
Minimum Increment : 0.001
Recommended Increment : 0.1
. Add (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Value for gray value range adaption.
Default Value : 0
Suggested values : Add ∈ {0, 64, 128, 255, 512}
Typical range of values : -512.0 ≤ Add ≤ -512.0
Minimum Increment : 0.01
Recommended Increment : 1.0

HALCON/COM Reference Manual, 2008-5-13


3.1. ARITHMETIC 91

Example

read_image(Image0,"fabrik")
disp_image(Image0,WindowHandle)
read_image(Image1,"Affe")
disp_image(Image1,WindowHandle)
add_image(Image0,Image1,Result,2.0,10.0)
disp_image(Result,WindowHandle)

Result
The operator AddImage returns the value TRUE if the parameters are correct. The behavior in case of empty
input (no input images available) is set via the operator SetSystem(::’noObjectResult’,<Result>:
) If necessary an exception handling is raised.
Parallelization Information
AddImage is reentrant and automatically parallelized (on tuple level, channel level, domain level).
See also
SubImage, MultImage
Alternatives
SubImage, MultImage
Module
Foundation

[out] HImageX ImageResult HImageX.DivImage ([in] HImageX Image2,


[in] VARIANT Mult, [in] VARIANT Add )
void HOperatorSetX.DivImage ([in] IHObjectX Image1,
[in] IHObjectX Image2, [out] HUntypedObjectX ImageResult, [in] VARIANT Mult,
[in] VARIANT Add )

Divide two images.


The operator DivImage divides two images. The gray values (g1, g2) of the input images (Image1) are trans-
formed as follows:

g 0 := g1/g2 ∗ Mult + Add

If an overflow or an underflow occurs the values are clipped.


Several images can be processed in one call. In this case both input parameters contain the same number of images
which are then processed in pairs. An output image is generated for every pair.
Parameter

. Image1 (input iconic) . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, int1, int2,


uint2, int4, real, complex )
Image(s) 1.
. Image2 (input iconic) . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, int1, int2,
uint2, int4, real, complex )
Image(s) 2.
. ImageResult (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX (
byte, int1, int2, uint2, int4, real,
complex )
Result image(s) by the division.

HALCON 8.0.2
92 CHAPTER 3. FILTER

. Mult (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )


Factor for gray range adaption.
Default Value : 255
Suggested values : Mult ∈ {0.1, 0.2, 0.5, 1.0, 2.0, 3.0, 10, 100, 500, 1000}
Typical range of values : -1000 ≤ Mult ≤ -1000
Minimum Increment : 0.001
Recommended Increment : 1
. Add (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Value for gray range adaption.
Default Value : 0
Suggested values : Add ∈ {0.0, 128.0, 256.0, 1025}
Typical range of values : -1000 ≤ Add ≤ -1000
Minimum Increment : 0.01
Recommended Increment : 1.0
Example

read_image(Image0,"fabrik")
disp_image(Image0,WindowHandle)
read_image(Image1,"Affe")
disp_image(Image1,WindowHandle)
div_image(Image0,Image1,Result,2.0,10.0)
disp_image(Result,WindowHandle)

Result
The operator DivImage returns the value TRUE if the parameters are correct. The behavior in case of empty
input (no input images available) is set via the operator SetSystem(::’noObjectResult’,<Result>:
) If necessary an exception handling is raised.
Parallelization Information
DivImage is reentrant and automatically parallelized (on tuple level, channel level, domain level).
See also
AddImage, SubImage, MultImage
Alternatives
AddImage, SubImage, MultImage
Module
Foundation

HImageX.InvertImage ( )
[out] HImageX ImageInvert
void HOperatorSetX.InvertImage ([in] IHObjectX Image,
[out] HUntypedObjectX ImageInvert )

Invert an image.
The operator InvertImage inverts the gray values of an image. For images of the ’byte’ and ’cyclic’ type the
result is calculated as:

g 0 = 255 − g

Images of the ’direction’ type are transformed by

g 0 = (g + 90) modulo 180

In the case of signed types the values are negated. The resulting image has the same pixel type as the input image.
Several images can be processed in one call. An output image is generated for every input image.

HALCON/COM Reference Manual, 2008-5-13


3.1. ARITHMETIC 93

Parameter

. Image (input iconic) . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic,


int1, int2, uint2, int4, real )
Input image(s).
. ImageInvert (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX (
byte, direction, cyclic, int1, int2,
uint2, int4, real )
Image(s) with inverted gray values.
Example

read_image(Orig,"fabrik")
invert_image(Orig,Invert)
disp_image(Invert,WindowHandle).

Parallelization Information
InvertImage is reentrant and automatically parallelized (on tuple level, channel level, domain level).
Possible Successors
Watersheds
See also
ScaleImage, AddImage, SubImage
Alternatives
ScaleImage
Module
Foundation

HImageX.MaxImage ([in] HImageX Image2 )


[out] HImageX ImageMax
void HOperatorSetX.MaxImage ([in] IHObjectX Image1,
[in] IHObjectX Image2, [out] HUntypedObjectX ImageMax )

Calculate the maximum of two images pixel by pixel.


MaxImage calculates the maximum of the images Image1 and Image2 (pixel by pixel). The result is stored in
the image ImageMax. The resulting image has the same pixel type as the input image. If several (pairs of) images
are processed in one call, every i-th image from Image1 is compared to the i-th image from Image2. Thus the
number of images in both input parameters must be the same. An output image is generated for every input pair.
Attention
The two input images must be of the same type and size.
Parameter

. Image1 (input iconic) . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, int1, int2,


uint2, int4, real, direction, cyclic )
Image(s) 1.
. Image2 (input iconic) . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, int1, int2,
uint2, int4, real, direction, cyclic )
Image(s) 2.
. ImageMax (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX ( byte,
int1, int2, uint2, int4, real, direction,
cyclic )
Result image(s) by the maximization.
Example

read_image(Bild1,"affe")

HALCON 8.0.2
94 CHAPTER 3. FILTER

read_image(Bild2,"fabrik")
max_image(Bild1,Bild2,Max)
disp_image(Max,WindowHandle)

Result
If the parameter values are correct the operator MaxImage returns the value TRUE. The behavior in case of empty
input (no input images available) is set via the operator SetSystem(::’noObjectResult’,<Result>:
). If necessary an exception handling is raised.
Parallelization Information
MaxImage is reentrant and automatically parallelized (on tuple level, channel level, domain level).
See also
MinImage
Alternatives
MaxImage
Module
Foundation

[out] HImageX ImageMin HImageX.MinImage ([in] HImageX Image2 )


void HOperatorSetX.MinImage ([in] IHObjectX Image1,
[in] IHObjectX Image2, [out] HUntypedObjectX ImageMin )

Calculate the minimum of two images pixel by pixel.


The operator MinImage determines the minimum (pixel by pixel) of the images Image1 and Image2. The
result is stored in the image ImageMin. The resulting image has the same pixel type as the input image. If several
(pairs of) images are processed in one call, every i-th image from Image1 is compared to the i-th image from
Image2. Thus the number of images in both input parameters must be the same. An output image is generated
for every input pair.
Parameter

. Image1 (input iconic) . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, int1, int2,


uint2, int4, real, direction, cyclic )
Image(s) 1.
. Image2 (input iconic) . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, int1, int2,
uint2, int4, real, direction, cyclic )
Image(s) 2.
. ImageMin (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX ( byte,
int1, int2, uint2, int4, real, direction,
cyclic )
Result image(s) by the minimization.
Result
If the parameter values are correct the operator MinImage returns the value TRUE. The behavior in case of empty
input (no input images available) is set via the operator SetSystem(::’noObjectResult’,<Result>:
) If necessary an exception handling is raised.
Parallelization Information
MinImage is reentrant and automatically parallelized (on tuple level, channel level, domain level).
See also
MaxImage, MinImage
Alternatives
GrayErosion
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


3.1. ARITHMETIC 95

[out] HImageX ImageResult HImageX.MultImage ([in] HImageX Image2,


[in] VARIANT Mult, [in] VARIANT Add )
void HOperatorSetX.MultImage ([in] IHObjectX Image1,
[in] IHObjectX Image2, [out] HUntypedObjectX ImageResult, [in] VARIANT Mult,
[in] VARIANT Add )

Multiply two images.


MultImage multiplies two images. The gray values (g1, g2) of the input images (Image1) are transformed as
follows:

g 0 := g1 ∗ g2 ∗ Mult + Add

If an overflow or an underflow occurs the values are clipped.


Several images can be processed in one call. In this case both input parameters contain the same number of images
which are then processed in pairs. An output image is generated for every pair.
Parameter
. Image1 (input iconic) . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, int1, int2,
uint2, int4, real, direction, cyclic, complex )
Image(s) 1.
. Image2 (input iconic) . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, int1, int2,
uint2, int4, real, direction, cyclic, complex )
Image(s) 2.
. ImageResult (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX (
byte, int1, int2, uint2, int4, real, di-
rection, cyclic, complex )
Result image(s) by the product.
. Mult (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Factor for gray range adaption.
Default Value : 0.005
Suggested values : Mult ∈ {0.001, 0.01, 0.5, 1.0, 2.0, 3.0, 5.0, 10.0}
Typical range of values : -255.0 ≤ Mult ≤ -255.0
Minimum Increment : 0.001
Recommended Increment : 0.1
. Add (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Value for gray range adaption.
Default Value : 0
Suggested values : Add ∈ {0.0, 128.0, 256.0}
Typical range of values : -512.0 ≤ Add ≤ -512.0
Minimum Increment : 0.01
Recommended Increment : 1.0
Example

read_image(Image0,"fabrik")
disp_image(Image0,WindowHandle)
read_image(Image1,"Affe")
disp_image(Image1,WindowHandle)
mult_image(Image0,Image1,Result,2.0,10.0)
disp_image(Result,WindowHandle)

Result
The operator MultImage returns the value TRUE if the parameters are correct. The behavior in case of empty
input (no input images available) is set via the operator SetSystem(::’noObjectResult’,<Result>:
) If necessary an exception handling is raised.
Parallelization Information
MultImage is reentrant and automatically parallelized (on tuple level, channel level, domain level).

HALCON 8.0.2
96 CHAPTER 3. FILTER

See also
AddImage, SubImage, DivImage
Alternatives
AddImage, SubImage, DivImage
Module
Foundation

[out] HImageX ImageScaled HImageX.ScaleImage ([in] VARIANT Mult,


[in] VARIANT Add )
void HOperatorSetX.ScaleImage ([in] IHObjectX Image,
[out] HUntypedObjectX ImageScaled, [in] VARIANT Mult, [in] VARIANT Add )

Scale the gray values of an image.


The operator ScaleImage scales the input images (Image) by the following transformation:

g 0 := g ∗ Mult + Add

If an overflow or an underflow occurs the values are clipped.


This operator can be applied, e.g., to map the gray values of an image, i.e., the interval [GMin,GMax], to the
maximum range [0:255]. For this, the parameters are chosen as follows:

255
Mult = Add = −Mult ∗ GMin
GMax − GMin
The values for GMin and GMax can be determined, e.g., with the operator MinMaxGray.
Please note that the runtime of the operator varies with different control parameters. For frequently used combi-
nations special optimizations are used. Additionally, special optimizations are implemented that use fixed point
arithmetic (for int2 and uint2 images), and further optimizations that use SIMD technology (for byte, int2, and uint2
images). The actual application of these special optimizations is controlled by the system parameters ’int_zooming’
and ’mmx_enable’ (see SetSystem). If ’int_zooming’ is set to ’true’, the internal calculation is performed us-
ing fixed point arithmetic, leading to much shorter execution times. However, the accuracy of the transformed
gray values is slightly lower in this mode. The difference to the more accurate calculation (using ’int_zooming’
= ’false’) is typically less than two gray levels. If ’mmx_enable’ is set to ’true’(and the SIMD instruction set is
available), the internal calculations are performed using fixed point arithmetic and SIMD technology. In this case
the setting of ’int_zooming’ is ignored.
Attention
Note that SIMD technology performs best on large, compact input regions. Depending on the input region and
the capabilities of the hardware the execution of ScaleImage might even take significantly more time with
SIMD technology than without. In this case, the use of SIMD technology can be avoided by SetSystem(::
’mmxEnable’,’false’:).
Parameter

. Image (input iconic) . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, int1, int2, uint2,
int4, real, direction, cyclic, complex )
Image(s) whose gray values are to be scaled.
. ImageScaled (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX (
byte, int1, int2, uint2, int4, real, di-
rection, cyclic, complex )
Result image(s) by the scale.
. Mult (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Scale factor.
Default Value : 0.01
Suggested values : Mult ∈ {0.001, 0.003, 0.005, 0.008, 0.01, 0.02, 0.03, 0.05, 0.08, 0.1, 0.5, 1.0}
Minimum Increment : 0.001
Recommended Increment : 0.1

HALCON/COM Reference Manual, 2008-5-13


3.1. ARITHMETIC 97

. Add (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )


Offset.
Default Value : 0
Suggested values : Add ∈ {0, 10, 50, 100, 200, 500}
Minimum Increment : 0.01
Recommended Increment : 1.0
Example

/* Complement of the gray values: */


scale_image(Bild,Invert,-1.0,255.0,)

Result
The operator ScaleImage returns the value TRUE if the parameters are correct. The behavior in case of empty
input (no input images available) is set via the operator SetSystem(::’noObjectResult’,<Result>:
) Otherwise an exception treatment is carried out.
Parallelization Information
ScaleImage is reentrant and automatically parallelized (on tuple level, channel level, domain level).
Possible Predecessors
MinMaxGray
See also
MinMaxGray
Alternatives
MultImage, AddImage, SubImage
Module
Foundation

HImageX.SqrtImage ( )
[out] HImageX SqrtImage
void HOperatorSetX.SqrtImage ([in] IHObjectX Image,
[out] HUntypedObjectX SqrtImage )

Calculate the square root of an image.


SqrtImage calculates the square root of an input image Image and stores the result in the image SqrtImage
of the same pixel type. In case the picture Image is of a signed pixel type, negative pixel values will be mapped
to zero in SqrtImage.
Parameter

. Image (input iconic) . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, int1, int2, uint2,
int4, real )
Input image
. SqrtImage (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX ( byte,
int1, int2, uint2, int4, real )
Output image
Parallelization Information
SqrtImage is reentrant and automatically parallelized (on tuple level, channel level, domain level).
Module
Foundation

HALCON 8.0.2
98 CHAPTER 3. FILTER

[out] HImageX ImageSub HImageX.SubImage ([in] HImageX ImageSubtrahend,


[in] VARIANT Mult, [in] VARIANT Add )
void HOperatorSetX.SubImage ([in] IHObjectX ImageMinuend,
[in] IHObjectX ImageSubtrahend, [out] HUntypedObjectX ImageSub,
[in] VARIANT Mult, [in] VARIANT Add )

Subtract two images.


The operator SubImage subtracts two images. The gray values (g1, g2) of the input images (ImageMinuend
and ImageSubtrahend) are transformed as follows:

g 0 := (g1 − g2) ∗ Mult + Add

If an overflow or an underflow occurs the values are clipped.


Several images can be processed in one call. In this case both input parameters contain the same number of images
which are then processed in pairs. An output image is generated for every pair.
Please note that the runtime of the operator varies with different control parameters. For frequently used com-
binations special optimizations are used. Additionally, for byte, int2, and uint2 images special optimizations are
implemented that use SIMD technology. The actual application of these special optimizations is controlled by the
system parameter ’mmx_enable’ (see SetSystem). If ’mmx_enable’ is set to ’true’ (and the SIMD instruction
set is available), the internal calculations are performed using SIMD technology.
Attention
Note that SIMD technology performs best on large, compact input regions. Depending on the input region and
the capabilities of the hardware the execution of SubImage might even take significantly more time with
SIMD technology than without. In this case, the use of SIMD technology can be avoided by SetSystem(:
:’mmxEnable’,’false’:).
Parameter
. ImageMinuend (input iconic) . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, int1,
int2, uint2, int4, real, direction,
cyclic, complex )
Minuend(s).
. ImageSubtrahend (input iconic) . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte,
int1, int2, uint2, int4, real, di-
rection, cyclic, complex )
Subtrahend(s).
. ImageSub (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX ( byte,
int1, int2, uint2, int4, real, direction,
cyclic, complex )
Result image(s) by the subtraction.
. Mult (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Correction factor.
Default Value : 1.0
Suggested values : Mult ∈ {0.0, 1.0, 2.0, 3.0, 4.0}
Typical range of values : -255.0 ≤ Mult ≤ -255.0
Minimum Increment : 0.001
Recommended Increment : 0.1
. Add (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Correction value.
Default Value : 128.0
Suggested values : Add ∈ {0.0, 128.0, 256.0}
Typical range of values : -512.0 ≤ Add ≤ -512.0
Minimum Increment : 0.01
Recommended Increment : 1.0
Example

read_image(Image0,"fabrik")

HALCON/COM Reference Manual, 2008-5-13


3.2. BIT 99

disp_image(Image0,WindowHandle)
read_image(Image1,"Affe")
disp_image(Image1,WindowHandle)
sub_image(Image0,Image1,Result,2.0,10.0)
disp_image(Result,WindowHandle)

Result
The operator SubImage returns the value TRUE if the parameters are correct. The behavior in case of empty
input (no input images available) is set via the operator SetSystem(::’noObjectResult’,<Result>:
) If necessary an exception handling is raised.
Parallelization Information
SubImage is reentrant and automatically parallelized (on tuple level, channel level, domain level).
Possible Successors
DualThreshold
See also
AddImage, MultImage, DynThreshold, CheckDifference
Alternatives
MultImage, AddImage, SubImage
Module
Foundation

3.2 Bit
HImageX.BitAnd ([in] HImageX Image2 )
[out] HImageX ImageAnd
void HOperatorSetX.BitAnd ([in] IHObjectX Image1, [in] IHObjectX Image2,
[out] HUntypedObjectX ImageAnd )

Bit-by-bit AND of all pixels of the input images.


The operator BitAnd calculates the “and” of all pixels of the input images bit by bit. The semantics of the
“and” operation corresponds to that of C for the respective types (signed char, unsigned char, short, unsigned short,
int/long). The images must have the same size and pixel type. The pixels within the definition range of the image
in the first parameter are processed.
Several images can be processed in one call. In this case both input parameters contain the same number of images
which are then processed in pairs. An output image is generated for every pair.
Parameter
. Image1 (input iconic) . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, direction,
cyclic, int1, int2, uint2, int4 )
Input image(s) 1.
. Image2 (input iconic) . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, direction,
cyclic, int1, int2, uint2, int4 )
Input image(s) 2.
. ImageAnd (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX ( byte, di-
rection, cyclic, int1, int2, uint2, int4 )
Result image(s) by AND-operation.
Example

read_image(Image0,’affe’)
disp_image(Image0,WindowHandle)
read_image(Image1,’fabrik’)
disp_image(Image1,WindowHandle)
bit_and(Image0,Image1,ImageBitA)
disp_image(ImageBitA,WindowHandle).

HALCON 8.0.2
100 CHAPTER 3. FILTER

Result
If the images are correct (type and number) the operator BitAnd returns the value TRUE. The be-
havior in case of empty input (no input images available) is set via the operator SetSystem(::
’noObjectResult’,<Result>:) If necessary an exception handling is raised.
Parallelization Information
BitAnd is reentrant and automatically parallelized (on tuple level, channel level, domain level).
See also
BitMask, AddImage, MaxImage
Alternatives
BitMask, AddImage, MaxImage
Module
Foundation

HImageX.BitLshift ([in] long Shift )


[out] HImageX ImageLShift
void HOperatorSetX.BitLshift ([in] IHObjectX Image,
[out] HUntypedObjectX ImageLShift, [in] VARIANT Shift )

Left shift of all pixels of the image.


The operator BitLshift calculates a “left shift” of all pixels of the input image bit by bit. The semantics of
the “left shift” operation corresponds to that of C (“«“) for the respective types (signed char, unsigned char, short,
unsigned short, int/long). If an overflow occurs the result is limited to the maximum value of the respective pixel
type. Only the pixels within the definition range of the image are processed.
Several images can be processed in one call. An output image is generated for every input image.
Parameter
. Image (input iconic) . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic,
int1, int2, uint2, int4 )
Input image(s).
. ImageLShift (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX (
byte, direction, cyclic, int1, int2,
uint2, int4 )
Result image(s) by shift operation.
. Shift (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Shift value.
Default Value : 3
Suggested values : Shift ∈ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 20, 24, 30, 31}
Typical range of values : 0 ≤ Shift ≤ 0
Minimum Increment : 1
Recommended Increment : 1
Restriction : ((Shif t ≥ 1) ∧ (Shif t ≤ 31))
Result
If the images are correct (type) and if Shift has a valid value the operator BitLshift returns the value
TRUE. The behavior in case of empty input (no input images available) is set via the operator SetSystem(::
’noObjectResult’,<Result>:) If necessary an exception handling is raised.
Parallelization Information
BitLshift is reentrant and automatically parallelized (on tuple level, channel level, domain level).
See also
BitRshift
Alternatives
ScaleImage
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


3.2. BIT 101

HImageX.BitMask ([in] long BitMask )


[out] HImageX ImageMask
void HOperatorSetX.BitMask ([in] IHObjectX Image,
[out] HUntypedObjectX ImageMask, [in] VARIANT BitMask )

Logical “AND” of each pixel using a bit mask.


The operator BitMask carries out an “and” operation of each pixel with a fixed mask. The semantics of the
“and” operation corresponds to that of C for the respective types (signed char, unsigned char, unsigned short, short,
int/long). Only the pixels within the definition range of the image are processed.
Several images can be processed in one call. An output image is generated for every input image.
Parameter

. Image (input iconic) . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic,


int1, int2, uint2, int4 )
Input image(s).
. ImageMask (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX ( byte,
direction, cyclic, int1, int2, uint2, int4
)
Result image(s) by combination with mask.
. BitMask (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Bit field
Default Value : 128
Suggested values : BitMask ∈ {1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096}
List of values : BitMask ∈ {1, 2, 4, 8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096}
Result
If the images are correct (type) the operator BitMask returns the value TRUE. The behavior in case of empty
input (no input images available) is set via the operator SetSystem(::’noObjectResult’,<Result>:
) If necessary an exception handling is raised.
Parallelization Information
BitMask is reentrant and automatically parallelized (on tuple level, channel level, domain level).
Possible Successors
Threshold, BitOr
See also
BitAnd, BitLshift
Alternatives
BitSlice
Module
Foundation

HImageX.BitNot ( )
[out] HImageX ImageNot
void HOperatorSetX.BitNot ([in] IHObjectX Image,
[out] HUntypedObjectX ImageNot )

Complement all bits of the pixels.


The operator BitNot calculates the “complement” of all pixels of the input image bit by bit. The semantics of
the “complement” operation corresponds to that of C (“∼”) for the respective types (signed char, unsigned char,
short, unsigned short, int/long). Only the pixels within the definition range of the image are processed.
Several images can be processed in one call. An output image is generated for every input image.
Parameter

. Image (input iconic) . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic,


int1, int2, uint2, int4 )
Input image(s).

HALCON 8.0.2
102 CHAPTER 3. FILTER

. ImageNot (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX ( byte, di-


rection, cyclic, int1, int2, uint2, int4 )
Result image(s) by complement operation.
Example

read_image(Image0,’affe’)
disp_image(Image0,WindowHandle)
bit_not(Image0,ImageBitN)
disp_image(ImageBitN,WindowHandle).

Result
If the images are correct (type) the operator BitNot returns the value TRUE. The behavior in case of empty
input (no input images available) is set via the operator SetSystem(::’noObjectResult’,<Result>:
) If necessary an exception handling is raised.
Parallelization Information
BitNot is reentrant and automatically parallelized (on tuple level, channel level, domain level).
See also
BitSlice, BitMask
Alternatives
BitOr, BitAnd, AddImage
Module
Foundation

HImageX.BitOr ([in] HImageX Image2 )


[out] HImageX ImageOr
void HOperatorSetX.BitOr ([in] IHObjectX Image1, [in] IHObjectX Image2,
[out] HUntypedObjectX ImageOr )

Bit-by-bit OR of all pixels of the input images.


The operator BitOr calculates the “or” of all pixels of the input images bit by bit. The semantics of the
“or”operation corresponds to that of C for the respective types (signed char, unsigned char, short, unsigned short,
int/long). The images must have the same size and pixel type. The pixels within the definition range of the image
in the first parameter are processed.
Several images can be processed in one call. In this case both input parameters contain the same number of images
which are then processed in pairs. An output image is generated for every pair.
Parameter

. Image1 (input iconic) . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, direction,


cyclic, int1, int2, uint2, int4 )
Input image(s) 1.
. Image2 (input iconic) . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, direction,
cyclic, int1, int2, uint2, int4 )
Input image(s) 2.
. ImageOr (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX ( byte, di-
rection, cyclic, int1, int2, uint2, int4 )
Result image(s) by OR-operation.
Example

read_image(Image0,’affe’)
disp_image(Image0,WindowHandle)
read_image(Image1,’fabrik’)
disp_image(Image1,WindowHandle)
bit_or(Image0,Image1,ImageBitO)
disp_image(ImageBitO,WindowHandle).

HALCON/COM Reference Manual, 2008-5-13


3.2. BIT 103

Result
If the images are correct (type and number) the operator BitOr returns the value TRUE. The be-
havior in case of empty input (no input images available) is set via the operator SetSystem(::
’noObjectResult’,<Result>:) If necessary an exception handling is raised.
Parallelization Information
BitOr is reentrant and automatically parallelized (on tuple level, channel level, domain level).
See also
BitXor, BitAnd
Alternatives
BitAnd, AddImage
Module
Foundation

HImageX.BitRshift ([in] long Shift )


[out] HImageX ImageRShift
void HOperatorSetX.BitRshift ([in] IHObjectX Image,
[out] HUntypedObjectX ImageRShift, [in] VARIANT Shift )

Right shift of all pixels of the image.


The operator BitRshift calculates a “right shift” of all pixels of the input image bit by bit. The semantics of
the “right shift” operation corresponds to that of C (“»”) for the respective types (signed char, unsigned char, short,
unsigned short, int/long). Only the pixels within the definition range of the image are processed.
Several images can be processed in one call. An output image is generated for every input image.
Parameter

. Image (input iconic) . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic,


int1, int2, uint2, int4 )
Input image(s).
. ImageRShift (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX (
byte, direction, cyclic, int1, int2,
uint2, int4 )
Result image(s) by shift operation.
. Shift (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
shift value
Default Value : 3
Suggested values : Shift ∈ {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 20, 24, 30, 31}
Typical range of values : 0 ≤ Shift ≤ 0
Minimum Increment : 1
Recommended Increment : 1
Restriction : ((Shif t ≥ 1) ∧ (Shif t ≤ 31))
Result
If the images are correct (type) and Shift has a valid value the operator BitRshift returns the value
TRUE. The behavior in case of empty input (no input images available) is set via the operator SetSystem
(::’noObjectResult’,<Result>:) If necessary an exception handling is raised.
Parallelization Information
BitRshift is reentrant and automatically parallelized (on tuple level, channel level, domain level).
See also
BitLshift
Alternatives
ScaleImage
Module
Foundation

HALCON 8.0.2
104 CHAPTER 3. FILTER

HImageX.BitSlice ([in] long Bit )


[out] HImageX ImageSlice
void HOperatorSetX.BitSlice ([in] IHObjectX Image,
[out] HUntypedObjectX ImageSlice, [in] VARIANT Bit )

Extract a bit from the pixels.


The operator BitSlice extracts a bit level from the input image. The semantics of the “and” operation corre-
sponds to that of C for the respective types (signed char, unsigned char, short, unsigned short, int/long). Only the
pixels within the definition range of the image are processed.
Several images can be processed in one call. An output image is generated for every input image.
Parameter
. Image (input iconic) . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic,
int1, int2, uint2, int4 )
Input image(s).
. ImageSlice (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX ( byte,
direction, cyclic, int1, int2, uint2, int4
)
Result image(s) by extraction.
. Bit (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Bit to be selected.
Default Value : 8
Suggested values : Bit ∈ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 20, 24, 30, 32}
Typical range of values : 1 ≤ Bit ≤ 1
Minimum Increment : 1
Recommended Increment : 1
Restriction : ((Bit ≥ 1) ∧ (Bit ≤ 32))
Result
If the images are correct (type) and Bit has a valid value, the operator BitSlice returns the value TRUE.
The behavior in case of empty input (no input images available) is set via the operator SetSystem(::
’noObjectResult’,<Result>:) If necessary an exception handling is raised.
Parallelization Information
BitSlice is reentrant and automatically parallelized (on tuple level, channel level, domain level).
Possible Successors
Threshold, BitOr
See also
BitAnd, BitLshift
Alternatives
BitMask
Module
Foundation

HImageX.BitXor ([in] HImageX Image2 )


[out] HImageX ImageXor
void HOperatorSetX.BitXor ([in] IHObjectX Image1, [in] IHObjectX Image2,
[out] HUntypedObjectX ImageXor )

Bit-by-bit XOR of all pixels of the input images.


The operator BitXor calculates the “xor” of all pixels of the input images bit by bit. The semantics of the
“xor” operation corresponds to that of C for the respective types (signed char, unsigned char, short, unsigned short,
int/long). The images must have the same size and pixel type. The pixels within the definition range of the image
in the first parameter are processed.
Several images can be processed in one call. In this case both input parameters contain the same number of images
which are then processed in pairs. An output image is generated for every pair.

HALCON/COM Reference Manual, 2008-5-13


3.3. COLOR 105

Parameter

. Image1 (input iconic) . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, direction,


cyclic, int1, int2, uint2, int4 )
Input image(s) 1.
. Image2 (input iconic) . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, direction,
cyclic, int1, int2, uint2, int4 )
Input image(s) 2.
. ImageXor (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX ( byte, di-
rection, cyclic, int1, int2, uint2, int4 )
Result image(s) by XOR-operation.
Example

read_image(Image0,’affe’)
disp_image(Image0,WindowHandle)
read_image(Image1,’fabrik’)
disp_image(Image1,WindowHandle)
bit_xor(Image0,Image1,ImageBitX)
disp_image(ImageBitX,WindowHandle).

Result
If the parameter values are correct the operator BitXor returns the value TRUE. The behavior in
case of empty input (no input images available) can be determined by the operator SetSystem(::
’noObjectResult’,<Result>:) If necessary an exception handling is raised.
Parallelization Information
BitXor is reentrant and automatically parallelized (on tuple level, channel level, domain level).
See also
BitOr, BitAnd
Alternatives
BitOr, BitAnd, AddImage
Module
Foundation

3.3 Color
[out] HImageX RGBImage HImageX.CfaToRgb ([in] String CFAType,
[in] String Interpolation )
void HOperatorSetX.CfaToRgb ([in] IHObjectX CFAImage,
[out] HUntypedObjectX RGBImage, [in] VARIANT CFAType,
[in] VARIANT Interpolation )

Convert a single-channel color filter array image into an RGB image.


CfaToRgb converts a single-channel color filter array image CFAImage into an RGB image RGBImage. Color
filter array images are typically generated by single-chip CCD cameras. The conversion from color filter array
image to RGB image is typically done on the camera itself or is performed by the device driver of the frame grabber
that is used to grab the image. In some cases, however, the device driver simply passes the color filter array image
through unchanged. In this case, the corresponding HALCON frame grabber interface typically converts the image
into an RGB image. Hence, the operator CfaToRgb is normally used if the images are not being grabbed using
the HALCON frame grabber interface ( GrabImage or GrabImageAsync), but are grabbed using function
calls from the frame grabber SDK, and are passed to HALCON using GenImage1 or GenImage1Extern.
In single-chip CCD cameras, a color filter array in front of the sensor provides (subsampled) color information.
The most frequently used filter is the so called Bayer filter. The color filter array has the following layout in this
case:

HALCON 8.0.2
106 CHAPTER 3. FILTER

G B G B G B ···

R G R G R G ···

G B G B G B ···

R G R G R G ···
.. .. .. .. .. .. ..
. . . . . . .

Each gray value of the input image CFAImage corresponds to the brightness of the pixel behind the corresponding
color filter. Hence, in the above layout, the pixel (0,0) corresponds to a green color value, while the pixel (0,1)
corresponds to a blue color value. The layout of the Bayer filter is completely determined by the first two elements
of the first row of the image, and can be chosen with the parameter CFAType. In particular, this enables the correct
conversion of color filter array images that have been cropped out of a larger image (e.g., using CropPart or
CropRectangle1). The algorithm that is used to interpolate the RGB values is determined by the parameter
Interpolation. Currently, the only possible choice is ’bilinear’.
Parameter
. CFAImage (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, uint2 )
Input image.
. RGBImage (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / HUntypedObjectX ( byte, uint2 )
Output image.
. CFAType (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Color filter array type.
Default Value : ’bayer_gb’
List of values : CFAType ∈ {’bayer_gb’, ’bayer_gr’, ’bayer_bg’, ’bayer_rg’}
. Interpolation (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Interpolation type.
Default Value : ’bilinear’
List of values : Interpolation ∈ {’bilinear’}
Result
CfaToRgb returns TRUE if all parameters are correct. If the input is empty the behavior can be set via
SetSystem(::’noObjectResult’,<Result>:). If necessary, an exception handling is raised.
Parallelization Information
CfaToRgb is reentrant and automatically parallelized (on tuple level, domain level).
Possible Predecessors
GenImage1Extern, GenImage1, GrabImage
Possible Successors
Decompose3
See also
TransFromRgb
Module
Foundation

[out] VARIANT Trans HImageX.GenPrincipalCompTrans


([out] VARIANT TransInv, [out] VARIANT Mean, [out] VARIANT Cov,
[out] VARIANT InfoPerComp )
void HOperatorSetX.GenPrincipalCompTrans
([in] IHObjectX MultichannelImage, [out] VARIANT Trans,
[out] VARIANT TransInv, [out] VARIANT Mean, [out] VARIANT Cov,
[out] VARIANT InfoPerComp )

Compute the transformation matrix of the principal component analysis of multichannel images.
GenPrincipalCompTrans computes the transformation matrix of a principal components analysis of mul-
tichannel images. This is useful for images obtained, e.g., with the thematic mapper of the Landsat satellite.

HALCON/COM Reference Manual, 2008-5-13


3.3. COLOR 107

Because the spectral bands are highly correlated, it is desirable to transform them to uncorrelated images. This can
be used to save storage, since the bands containing little information can be discarded, and with respect to a later
classification step.
The operator GenPrincipalCompTrans takes one or more multichannel images MultichannelImage
and computes the transformation matrix Trans for the principal components analysis, as well as its inverse
TransInv. All input images must have the same number of channels. The principal components analysis is
performed based on the collection of data of all images. Hence, GenPrincipalCompTrans facilitates using
the statistics of multiple images.
If n is the number of channels, Trans and TransInv are matrices of dimension n × (n + 1), which describe an
affine transformation of the multichannel gray values. They can be used to transform a multichannel image with
LinearTransColor. For information purposes, the mean gray value of the channels and the n × n covariance
matrix of the channels are returned in Mean and Cov, respectively. The parameter InfoPerComp contains the
relative information content of each output channel.
Parameter

. MultichannelImage (input iconic) . . . . . . multichannel-image-array ; HImageX / IHObjectX ( byte,


direction, cyclic, int1, int2,
uint2, int4, real )
Multichannel input image.
. Trans (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Transformation matrix for the computation of the PCA.
. TransInv (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Transformation matrix for the computation of the inverse PCA.
. Mean (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Mean gray value of the channels.
. Cov (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Covariance matrix of the channels.
. InfoPerComp (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Information content of the transformed channels.
Result
The operator GenPrincipalCompTrans returns the value TRUE if the parameters are correct. Otherwise an
exception is raised.
Parallelization Information
GenPrincipalCompTrans is reentrant and processed without parallelization.
Possible Successors
LinearTransColor
Alternatives
PrincipalComp
Module
Foundation

[out] HImageX ImageTrans HImageX.LinearTransColor


([in] VARIANT TransMat )
void HOperatorSetX.LinearTransColor ([in] IHObjectX Image,
[out] HUntypedObjectX ImageTrans, [in] VARIANT TransMat )

Compute an affine transformation of the color values of a multichannel image.


LinearTransColor performs an affine transformation of the color values of the multichannel image Image
and returns the result in ImageTrans. The affine transformation of the color values is described by the transfor-
mation matrix TransMat. If n is the number of channels in Image, TransMat is a homogeneous n × (n + 1)
that is stored row by row. Homogeneous means that the left n × n submatrix of TransMat describes a linear
transformation of the color values, while the last column of TransMat describes a constant offset of the color
values. The transformation matrix is typically computed with GenPrincipalCompTrans. It can, however,

HALCON 8.0.2
108 CHAPTER 3. FILTER

also be specified directly. For example, a transformation from RGB to YIQ, which is described by the following
transformation
      
Y 0.299 0.587 0.144 R 0
 I  =  0.595 −0.276 −0.333   G  +  128 
Q 0.209 −0.522 0.287 B 128

can be achieved by setting TransMat to

[0.299, 0.587, 0.144, 0.0, 0.595, −0.276, −0.333, 128.0, 0.209, −0.522, 0.287, 128.0]

Here, it should be noted that the above transformation is unnormalized, i.e., the resulting color values can lie
outside the range [0, 255]. The transformation ’yiq’ in TransFromRgb additionally scales the rows of the matrix
(except for the constant offset) appropriately.
To avoid a loss of information, LinearTransColor returns an image of type real. If a different image type is
desired, the image can be transformed with ConvertImageType.
Parameter
. Image (input iconic) . . . . . . multichannel-image-array ; HImageX / IHObjectX ( byte, direction, cyclic,
int1, int2, uint2, int4, real )
Multichannel input image.
. ImageTrans (output iconic) . . . . . . . . . . multichannel-image-array ; HImageX / HUntypedObjectX ( real )
Multichannel output image.
. TransMat (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Transformation matrix for the color values.
Result
The operator LinearTransColor returns the value TRUE if the parameters are correct. Otherwise an excep-
tion is raised.
Parallelization Information
LinearTransColor is reentrant and automatically parallelized (on tuple level, domain level).
Possible Predecessors
GenPrincipalCompTrans
Possible Successors
ConvertImageType
Alternatives
PrincipalComp, TransFromRgb, TransToRgb
Module
Foundation

[out] HImageX PCAImage HImageX.PrincipalComp


([out] VARIANT InfoPerComp )
void HOperatorSetX.PrincipalComp ([in] IHObjectX MultichannelImage,
[out] HUntypedObjectX PCAImage, [out] VARIANT InfoPerComp )

Compute the principal components of multichannel images.


PrincipalComp does a principal components analysis of multichannel images. This is useful for images ob-
tained, e.g., with the thematic mapper of the Landsat satellite. Because the spectral bands are highly correlated, it
is desirable to transform them to uncorrelated images. This can be used to save storage, since the bands containing
little information can be discarded, and with respect to a later classification step.
The operator PrincipalComp takes a (multichannel) image MultichannelImage and transforms it to the
output image PCAImage, which contains the same number of channels, using the principal components analysis.
The parameter InfoPerComp contains the relative information content of each output channel.

HALCON/COM Reference Manual, 2008-5-13


3.3. COLOR 109

Parameter
. MultichannelImage (input iconic) . . . . . . multichannel-image-array ; HImageX / IHObjectX ( byte,
direction, cyclic, int1, int2,
uint2, int4, real )
Multichannel input image.
. PCAImage (output iconic) . . . . . . . . . . . . multichannel-image-array ; HImageX / HUntypedObjectX ( real )
Multichannel output image.
. InfoPerComp (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Information content of each output channel.
Result
The operator PrincipalComp returns the value TRUE if the parameters are correct. Otherwise an exception is
raised.
Parallelization Information
PrincipalComp is reentrant and processed without parallelization.
See also
LinearTransColor
Alternatives
GenPrincipalCompTrans
Module
Foundation

[out] HImageX GrayImage HImageX.Rgb1ToGray ( )


void HOperatorSetX.Rgb1ToGray ([in] IHObjectX RGBImage,
[out] HUntypedObjectX GrayImage )

Transform an RGB image into a gray scale image.


Rgb1ToGray transforms an RGB image into a gray scale image. The three channels of the RGB image are passed
as the first three channels of the input image. The image is transformed according to the following formula:

k = 0.299r + 0.587g + 0.114b .

Parameter
. RGBImage (input iconic) . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte, int2, uint2 )
Three-channel RBG image.
. GrayImage (output iconic) . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, int2, uint2 )
Gray scale image.
Example

/* Tranformation from rgb to gray */


read_image(Image,’patras’)
disp_color(Image,WindowHandle)
rgb1_to_gray(Image,GrayImage)
disp_image(GrayImage,WindowHandle).

Parallelization Information
Rgb1ToGray is reentrant and automatically parallelized (on tuple level, domain level).
Possible Predecessors
Compose3
Alternatives
TransFromRgb, Rgb3ToGray
Module
Foundation

HALCON 8.0.2
110 CHAPTER 3. FILTER

[out] HImageX ImageGray HImageX.Rgb3ToGray ([in] HImageX ImageGreen,


[in] HImageX ImageBlue )
void HOperatorSetX.Rgb3ToGray ([in] IHObjectX ImageRed,
[in] IHObjectX ImageGreen, [in] IHObjectX ImageBlue,
[out] HUntypedObjectX ImageGray )

Transform an RGB image to a gray scale image.


Rgb3ToGray transforms an RGB image into a gray scale image. The three channels of the RGB image are passed
as three separate images. The image is transformed according to the following formula:

k = 0.299r + 0.587g + 0.114b .

Parameter

. ImageRed (input iconic) . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte, int2, uint2 )


Input image (red channel).
. ImageGreen (input iconic) . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte, int2, uint2 )
Input image (green channel).
. ImageBlue (input iconic) . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte, int2, uint2 )
Input image (blue channel).
. ImageGray (output iconic) . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, int2, uint2 )
Gray scale image.
Example

/* Tranformation from rgb to gray */


read_image(Image,’patras’)
disp_color(Image,WindowHandle)
decompose3(Image,Rimage,Gimage,Bimage)
rgb3_to_gray(Rimage,Gimage,Bimage,GrayImage)
disp_image(GrayImage,WindowHandle).

Parallelization Information
Rgb3ToGray is reentrant and automatically parallelized (on tuple level, domain level).
Possible Predecessors
Decompose3
Alternatives
Rgb1ToGray, TransFromRgb
Module
Foundation

[out] HImageX ImageResult1 HImageX.TransFromRgb


([in] HImageX ImageGreen, [in] HImageX ImageBlue, [out] HImageX ImageResult2,
[out] HImageX ImageResult3, [in] String ColorSpace )
void HOperatorSetX.TransFromRgb ([in] IHObjectX ImageRed,
[in] IHObjectX ImageGreen, [in] IHObjectX ImageBlue,
[out] HUntypedObjectX ImageResult1, [out] HUntypedObjectX ImageResult2,
[out] HUntypedObjectX ImageResult3, [in] VARIANT ColorSpace )

Transform an image from the RGB color space to an arbitrary color space.
TransFromRgb transforms an image from the RGB color space to an arbitrary color space (ColorSpace).
The three channels of the image are passed as three separate images on input and output.

HALCON/COM Reference Manual, 2008-5-13


3.3. COLOR 111

The operator TransFromRgb supports the image types byte, uint2, int4, and real. In the case of int4 images, the
images should not contain negative values. In the case of real images, all values should lay within 0 and 1. If not,
the results of the transformation may not be reasonable.
Certain scalings are performed accordingly to the image type:

• Considering byte and uint2 images, the domain of color space values is generally mapped to the full domain
of [0..255] resp. [0..65535]. Because of this, the origin of signed values (e.g., CIELab or YIQ) may not be at
the center of the domain.
• Hue values are represented by angles of [0..2π] and are coded for the particular image types differently:
– byte-images map the angle domain on [0..255].
– uint2/int4-images are coded in angle minutes [0..21600].
– real-images are coded in radians [0..2π] .
• Saturation values are represented by percentages of [0..100] and are coded for the particular image type
differently:
– byte-images map the saturation values to [0..255].
– uint2/int4-images map the the saturation values to [0..10000].
– real-images map the saturation values to [0..1].

The following transformations are supported:


(All range of values are based on RGB values scaled to [0;1]. To obtain the range of values for a certain image
type, they must be multiplied with the maximum of the image type, e.g., 255 in the case of a byte image)
’yiq’
    
Y 0.299 0.587 0.144 R
 I  =  0.595 −0.276 −0.333   G 
Q 0.209 −0.522 0.287 B

Range of values:
Y ∈ [0; 1.03], I ∈ [−0.609; 0.595], Q ∈ [−0.522; 0.496]

Point of origin for image type byte:


I0 = 128.89, Q0 = 130.71
’yuv’
    
Y 0.299 0.587 0.114 R
 U  =  −0.147 −0.289 0.436   G 
V 0.615 −0.515 0.100 B

Range of values:
Y ∈ [0; 1], U ∈ [−0.436; 0.436], V ∈ [−0.615; 0.496]

’argyb’
    
A 0.30 0.59 0.11 R
 Rg  =  0.50 −0.50 0.00   G 
Yb 0.25 0.25 −0.50 B

Range of values:
A ∈ [0; 1], Rg ∈ [−0.5; 0.5], Y b ∈ [−0.5; 0.5]

’ciexyz’
    
X 0.412453 0.357580 0.180423 R
 Y  =  0.212671 0.715160 0.072169   G 
Z 0.019334 0.119193 0.950227 B

The primary colors used correspond to sRGB respectively CIE Rec. 709. D65 is used as white point.

HALCON 8.0.2
112 CHAPTER 3. FILTER

Used primary
 colors (x, y, z):      
0.6400 0.3000 0.1500 0.3127
red:= , green:= , blue:= , white65 :=
0.3300 0.6000 0.0600 0.3290
Range of values:
X ∈ [0; 0.950456], Y ∈ [0; 1], Z ∈ [0; 1.088754]
’hls’ min = min(R,G,B)
max = max(R,G,B)
L = (min + max) / 2
if (max == min)
H = 0
S = 0
else
if (L > 0.5)
S = (max - min) / (2 - max - min)
else
S = (max - min) / (max + min)
fi
if (R == max)
H = ((G - B) / (max - min)) * 60
elif (G == max)
H = (2 + (B - R) / (max - min)) * 60
elif (B == max)
H = (4 + (R - G) / (max - min)) * 60
fi
fi
Range of values:
H ∈ [0; 2π], L ∈ [0; 1], S ∈ [0; 1]

’hsi’
  √2 −1 −1

√ √
 
M1 6 6 6 R
√1 −1
 M2  = 
 0 2

2

 G 
I1 √1 √1 √1 B
3 3 3
   M2 
H √arctan M 1
 S  =  M 12 + M 22 
I1
I √
3

Range of values: q
2
H ∈ [0; 2π], S ∈ [0; 3 ], I ∈ [0; 1]

’hsv’ min = min(R,G,B)


max = max(R,G,B)
V = max
if (max == min)
S = 0
H = 0
else
S = (max - min) / max
if (R == max)
H = ((G - B) / (max - min)) * 60
elif (G == max)
H = (2 + (B - R) / (max - min)) * 60
elif (B == max)
H = (4 + (R - G) / (max - min)) * 60
fi
fi

HALCON/COM Reference Manual, 2008-5-13


3.3. COLOR 113

Range of values:
H ∈ [0; 2π], S ∈ [0; 1], V ∈ [0; 1]

’ihs’ min = min(R,G,B)


max = max(R,G,B)
I = (R + G + B) / 3
if (I == 0)
H = 0
S = 1
else
S = 1 - min / I
if (S == 0)
H = 0
else
A = (R + R - G - B) / 2
B = (R - G) * (R - G) + (R - B) * (G - B)
C = sqrt(B)
if (C == 0)
H = 0
else
H = acos(A / C)
fi
if (B > G)
H = 2 * pi - H
fi
fi
fi
Range of values:
I ∈ [0; 1], H ∈ [0; 2π], S ∈ [0; 1]

’cielab’
    
X 0.412453 0.357580 0.180423 R
 Y  =  0.212671 0.715160 0.072169   G 
Z 0.019334 0.119193 0.950227 B

Y
L = 116 ∗ f ( ) − 16
Yw
X Y
a = 500 ∗ (f ( ) − f ( ))
Xw Yw
Y Z
b = 200 ∗ (f ( ) − f ( ))
Yw Zw
where 1 24 3
f (t) = t 3 , t > ( 116 )
841 16
f (t) = 108 ∗ t + 116 , otherwise
Black point B:
(Rb , Gb , Bb ) = (0, 0, 0)
White point W = (Rw , Gw , Bw ), according to image type:
Wbyte = (255, 255, 255), Wuint2 = (216 − 1, 216 − 1, 216 − 1),
Wint4 = (231 − 1, 231 − 1, 231 − 1), Wreal = (1.0, 1.0, 1.0)
Range of values:
L ∈ [0; 100], a ∈ [−86.1813; 98.2352], b ∈ [−107.8617; 94.4758]
(Scaled to the maximum gray value in the case of byte and uint2. In the case of int4 L and a are scaled
to the maximum gray value, b is scaled to the minimum gray value, such that the origin stays at 0.)
’i1i2i3’
    
I1 0.333 0.333 0.333 R
 I2  =  1.0 0.0 −1.0   G 
I3 −0.5 1.0 −0.5 B

HALCON 8.0.2
114 CHAPTER 3. FILTER

Range of values:
I1 ∈ [0; 1], I2 ∈ [−1; 1], I3 ∈ [−1; 1]

’ciexyz2’
    
X 0.620 0.170 0.180 R
 Y  =  0.310 0.590 0.110   G 
Z 0.000 0.066 1.020 B

Range of values:
X ∈ [0; 0.970], Y ∈ [0; 1.010], Z ∈ [0; 1.086]

’ciexyz3’
    
X 0.618 0.177 0.205 R
 Y  =  0.299 0.587 0.114   G 
Z 0.000 0.056 0.944 B

Range of values:
X ∈ [0; 1], Y ∈ [0; 1], Z ∈ [0; 1]

’ciexyz4’
    
X 0.476 0.299 0.175 R
 Y  =  0.262 0.656 0.082   G 
Z 0.020 0.161 0.909 B

 colors(x, y, z):
Used primary      
0.628 0.268 0.150 0.313
red:=  0.346  , green:=  0.588  , blue:=  0.070  , white65 :=  0.329 
0.026 0.144 0.780 0.358
Range of values:
X ∈ [0; 0.951], Y ∈ [0; 1], Z ∈ [0; 1.088]

Parameter
. ImageRed (input iconic) . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte, uint2, int4, real )
Input image (red channel).
. ImageGreen (input iconic) . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte, uint2, int4, real )
Input image (green channel).
. ImageBlue (input iconic) . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte, uint2, int4, real )
Input image (blue channel).
. ImageResult1 (output iconic) . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, uint2, int4,
real )
Color-transformed output image (channel 1).
. ImageResult2 (output iconic) . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, uint2, int4,
real )
Color-transformed output image (channel 1).
. ImageResult3 (output iconic) . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, uint2, int4,
real )
Color-transformed output image (channel 1).
. ColorSpace (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Color space of the output image.
Default Value : ’hsv’
List of values : ColorSpace ∈ {’cielab’, ’hsv’, ’hsi’, ’yiq’, ’yuv’, ’argyb’, ’ciexyz’, ’ciexyz2’, ’ciexyz3’,
’ciexyz4’, ’hls’, ’ihs’, ’i1i2i3’}
Example

/* Tranformation from rgb to hsv and conversely */


read_image(Image,’patras’)

HALCON/COM Reference Manual, 2008-5-13


3.3. COLOR 115

disp_color(Image,WindowHandle)
decompose3(Image,Rimage,Gimage,Bimage)
trans_from_rgb(Rimage,Gimage,Bimage,Image1,Image2,Image3,’hsv’)
trans_to_rgb(Image1,Image2,Image3,ImageRed,ImageGreen,ImageBlue,’hsv’)
compose3(ImageRed,ImageGreen,ImageBlue,Multichannel)
disp_color(Multichannel,WindowHandle).

Result
TransFromRgb returns TRUE if all parameters are correct. If the input is empty the behaviour can be set via
SetSystem(::’noObjectResult’,<Result>:). If necessary, an exception handling is raised.
Parallelization Information
TransFromRgb is reentrant and automatically parallelized (on tuple level, domain level).
Possible Predecessors
Decompose3
Possible Successors
Compose3
See also
TransToRgb
Alternatives
Rgb1ToGray, Rgb3ToGray
Module
Foundation

[out] HImageX ImageRed HImageX.TransToRgb ([in] HImageX ImageInput2,


[in] HImageX ImageInput3, [out] HImageX ImageGreen, [out] HImageX ImageBlue,
[in] String ColorSpace )
void HOperatorSetX.TransToRgb ([in] IHObjectX ImageInput1,
[in] IHObjectX ImageInput2, [in] IHObjectX ImageInput3,
[out] HUntypedObjectX ImageRed, [out] HUntypedObjectX ImageGreen,
[out] HUntypedObjectX ImageBlue, [in] VARIANT ColorSpace )

Transform an image from an arbitrary color space to the RGB color space.
TransToRgb transforms an image from an arbitrary color space (ColorSpace) to the RGB color space. The
three channels of the image are passed as three separate images on input and output.
The operator TransToRgb supports the image types byte, uint2, int4, and real. The domain of the input images
must match the domain provided by a corresponding transformation with TransFromRgb. If not, the results of
the transformation may not be reasonable.
This includes some scalings in the case of certain image types and transformations:

• Considering byte and uint2 images, the domain of color space values is expected to be spread to the full
domain of [0..255] resp. [0..65535]. This includes a shift in the case of signed values, such that the origin of
signed values (e.g. CIELab or YIQ) may not be at the center of the domain.
• Hue values are represented by angles of [0..2π] and are coded for the particular image types differently:
– byte-images map the angle domain on [0..255].
– uint2/int4-images are coded in angle minutes [0..21600].
– real-images are coded in radians [0..2π] .
• Saturation values are represented by percentages of [0..100] and are coded for the particular image type
differently:
– byte-images map the saturation values to [0..255].
– uint2/int4-images map the the saturation values to [0..10000].
– real-images map the saturation values to [0..1].

HALCON 8.0.2
116 CHAPTER 3. FILTER

The following transformations are supported:


(All domains are based on RGB values scaled to [0;1]. To obtain the domains for a certain image type, they must
be multiplied with the maximum of the image type, e.g. 255 in the case of a byte image)
’yiq’
    
R 0.999 0.962 0.615 Y
 G  =  0.949 −0.220 −0.732   I 
B 0.999 −1.101 1.706 Q
Domain:
Y ∈ [0; 1.03], I ∈ [−0.609; 0.595], Q ∈ [−0.522; 0.496]

Point of origin for image type byte:


I0 = 128.89, Q0 = 130.71
’yuv’
    
R 1.0 0.0 1.140 Y
 G  =  1.0 −0.394 −0.581   U 
B 1.0 2.032 0.0 V
Domain:
Y ∈ [0; 1], U ∈ [−0.436; 0.436], V ∈ [−0.615; 0.496]

’argyb’
    
R 1.00 1.29 0.22 A
 G  =  1.00 −0.71 0.22   Rg 
B 1.00 0.29 −1.78 Yb
Domain:
A ∈ [0; 1], Rg ∈ [−0.5; 0.5], Y b ∈ [−0.5; 0.5]

’ciexyz’
    
R 3.240479 −1.53715 −0.498535 X
 G  =  −0.969256 1.875991 0.041556   Y 
B 0.055648 −0.204043 1.057311 Z
The primary colors used correspond to sRGB respectively CIE Rec. 709. D65 is used as white point.
Used primary
 colors (x, y, z):      
0.6400 0.3000 0.1500 0.3127
red:= , green:= , blue:= , white65 :=
0.3300 0.6000 0.0600 0.3290
Domain:
X ∈ [0; 0.950456], Y ∈ [0; 1], Z ∈ [0; 1.088754]
’cielab’
fy = (L + 16)/116
fx = a/500 + fy
fz = b/200 − fy

24
X = Xw ∗ fx3 , fx > 116
16 108
X = (fx − 116 ) ∗ Xw ∗ 841 , otherwise

24
Y = Yw ∗ fy3 , fy > 116
16 108
Y = (fy − 116 ) ∗ Yw ∗ 841 , otherwise

24
Z = Zw ∗ fz3 , fz > 116
16 108
Z = (fz − 116 ) ∗ Zw ∗ 841 , otherwise
    
R 3.240479 −1.53715 −0.498535 X
 G  =  −0.969256 1.875991 0.041556   Y 
B 0.055648 −0.204043 1.057311 Z

HALCON/COM Reference Manual, 2008-5-13


3.3. COLOR 117

Black point B:
(Rb , Gb , Bb ) = (0, 0, 0)
White point W = (Rw , Gw , Bw ), according to image type:
Wbyte = (255, 255, 255), Wuint2 = (216 − 1, 216 − 1, 216 − 1),
Wint4 = (231 − 1, 231 − 1, 231 − 1), Wreal = (1.0, 1.0, 1.0)
Domain:
L ∈ [0; 100], a ∈ [−94.3383; 90.4746], b ∈ [−101.3636; 84.4473]
(Scaled to the maximum gray value in the case of byte and uint2. In the case of int4 L and a are scaled
to the maximum gray value, b is scaled to the minimum gray value, such that the origin stays at 0.)
’hls’ Hi = integer(H * 6)
Hf = fraction(H * 6)
if (L <= 0.5)
max = L * (S + 1)
else
max = L + S - (L * S)
fi
min = 2 * L - max
if (S == 0)
R = L
G = L
B = L
else
if (Hi == 0)
R = max
G = min + Hf * (max - min)
B = min
elif (Hi == 1)
R = min + (1 - Hf) * (max - min)
G = max
B = min
elif (Hi == 2)
R = min
G = max
B = min + Hf * (max - min)
elif (Hi == 3)
R = min
G = min + (1 - Hf) * (max - min)
B = max
elif (Hi == 4)
R = min + Hf * (max - min)
G = min
B = max
elif (Hi == 5)
R = max
G = min
B = min + (1 - Hf) * (max - min)
fi
fi
Domain:
H ∈ [0; 2π], L ∈ [0; 1], S ∈ [0; 1]

’hsi’

M 1 = S ∗ sin H

M 2 = S ∗ cos H
I
I1 = √
3

HALCON 8.0.2
118 CHAPTER 3. FILTER

√2 √1
  
0
 
R 6 3 M1
 G = −1
√ √1 √1 M2 

 6 2 3 
B −1
√ −1
√ √1 I1
6 2 3

’hsv’ Domain: q
H ∈ [0; 2π], S ∈ [0; 23 ], I ∈ [0; 1]

if (S == 0)
R = V
G = V
B = V
else
Hi = integer(H)
Hf = fraction(H)
if (Hi == 0)
R = V
G = V * (1 - (S * (1 - Hf)))
B = V * (1 - S)
elif (Hi == 1)
R = V * (1 - (S * Hf))
G = V
B = V * (1 - S)
elif (Hi == 2)
R = V * (1 - S)
G = V
B = V * (1 - (S * (1 - Hf)))
elif (Hi == 3)
R = V * (1 - S)
G = V * (1 - (S * Hf))
B = V
elif (Hi == 4)
R = V * (1 - (S * (1 - Hf)))
G = V * (1 - S)
B = V
elif (Hi == 5)
R = V
G = V * (1 - S)
B = V * (1 - (S * Hf))
fi
fi
Domain:
H ∈ [0; 2π], S ∈ [0; 1], V ∈ [0; 1]

’ciexyz4’
    
R 2.750 −1.149 −0.426 X
 G  =  −1.118 2.026 0.033   Y 
B 0.138 −0.333 1.104 Z
Domain:
X ∈ [0; 0.951], Y ∈ [0; 1], Z ∈ [0; 1.088]

Parameter
. ImageInput1 (input iconic) . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte, uint2, int4, real )
Input image (channel 1).
. ImageInput2 (input iconic) . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte, uint2, int4, real )
Input image (channel 2).
. ImageInput3 (input iconic) . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte, uint2, int4, real )
Input image (channel 3).

HALCON/COM Reference Manual, 2008-5-13


3.4. EDGES 119

. ImageRed (output iconic) . . . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, uint2, int4, real )
Red channel.
. ImageGreen (output iconic) . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, uint2, int4, real )
Green channel.
. ImageBlue (output iconic) . . . . . . .image(-array) ; HImageX / HUntypedObjectX ( byte, uint2, int4, real )
Blue channel.
. ColorSpace (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Color space of the input image.
Default Value : ’hsv’
List of values : ColorSpace ∈ {’hsi’, ’yiq’, ’yuv’, ’argyb’, ’ciexyz’, ’ciexyz4’, ’cielab’, ’hls’, ’hsv’}
Example

/* Tranformation from rgb to hsv and conversely */


read_image(Image,’patras’)
disp_color(Image,WindowHandle)
decompose3(Image,Rimage,Gimage,Bimage)
trans_from_rgb(Rimage,Gimage,Bimage,Image1,Image2,Image3,’hsv’)
trans_to_rgb(Image1,Image2,Image3,ImageRed,ImageGreen,ImageBlue,’hsv’)
compose3(ImageRed,ImageGreen,ImageBlue,Multichannel)
disp_color(Multichannel,WindowHandle).

Result
TransToRgb returns TRUE if all parameters are correct. If the input is empty the behaviour can be set via
SetSystem(::’noObjectResult’,<Result>:). If necessary, an exception handling is raised.
Parallelization Information
TransToRgb is reentrant and automatically parallelized (on tuple level, domain level).
Possible Predecessors
Decompose3
Possible Successors
Compose3, DispColor
See also
Decompose3
Module
Foundation

3.4 Edges

[out] HRegionX RegionResult HRegionX.CloseEdges ([in] HImageX EdgeImage,


[in] long MinAmplitude )
void HOperatorSetX.CloseEdges ([in] IHObjectX Edges,
[in] IHObjectX EdgeImage, [out] HUntypedObjectX RegionResult,
[in] VARIANT MinAmplitude )

Close edge gaps using the edge amplitude image.


CloseEdges closes gaps in the output of an edge detector, and thus tries to produce complete object contours.
This is done by examining the neighbors of each edge point to determine the point with maximum amplitude (i.e.,
maximum gradient), and adding the point to the edge if its amplitude is larger than the minimum amplitude passed
in MinAmplitude. This operator expects as input the edges (Edges) and amplitude image (EdgeImage)
returned by typical edge operators, such as EdgesImage or SobelAmp. CloseEdges does not take into
account the edge directions that may be returned by an edge operator. Thus, in areas where the gradient is almost
constant the edges may become rather “wiggly.”

HALCON 8.0.2
120 CHAPTER 3. FILTER

Parameter
. Edges (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Region containing one pixel thick edges.
. EdgeImage (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, int4 )
Edge amplitude (gradient) image.
. RegionResult (output iconic) . . . . . . . . . . . . . . . . . . . . . . . .region(-array) ; HRegionX / HUntypedObjectX
Region containing closed edges.
. MinAmplitude (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Minimum edge amplitude.
Default Value : 16
Suggested values : MinAmplitude ∈ {5, 8, 10, 12, 16, 20, 25, 30, 40, 50}
Typical range of values : 1 ≤ MinAmplitude ≤ 1
Minimum Increment : 1
Recommended Increment : 1
Restriction : (M inAmplitude ≥ 0)
Result
CloseEdges returns TRUE if all parameters are correct. If the input is empty the behaviour can be set via
SetSystem(’noObjectResult’,<Result>). If necessary, an exception handling is raised.
Parallelization Information
CloseEdges is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
EdgesImage, SobelAmp, Threshold, Skeleton
Possible Successors
Skeleton
See also
GraySkeleton
Alternatives
CloseEdgesLength, Dilation1, Closing
Module
Foundation

[out] HRegionX ClosedEdges HRegionX.CloseEdgesLength


([in] HImageX Gradient, [in] long MinAmplitude, [in] long MaxGapLength )
void HOperatorSetX.CloseEdgesLength ([in] IHObjectX Edges,
[in] IHObjectX Gradient, [out] HUntypedObjectX ClosedEdges,
[in] VARIANT MinAmplitude, [in] VARIANT MaxGapLength )

Close edge gaps using the edge amplitude image.


CloseEdgesLength closes gaps in the output of an edge detector, and thus tries to produce complete object
contours. This operator expects as input the edges (Edges) and amplitude image (Gradient) returned by typical
edge operators, such as EdgesImage or SobelAmp.
Contours are closed in two steps: First, one pixel wide gaps in the input contours are closed, and isolated points are
eliminated. After this, open contours are extended by up to MaxGapLength points by adding edge points until
either the contour is closed or no more significant edge points can be found. A gradient is regarded as significant if
it is larger than MinAmplitude. The neighboring points examined as possible new edge points are the point in
the direction of the contour and its two adjacent points in an 8-neighborhood. For each of these points, the sum of
its gradient and the maximum gradient of that points three possible neighbors is calculated (look ahead of length
1). The point with the maximum sum is then chosen as the new edge point.
Parameter
. Edges (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Region containing one pixel thick edges.
. Gradient (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte )
Edge amplitude (gradient) image.

HALCON/COM Reference Manual, 2008-5-13


3.4. EDGES 121

. ClosedEdges (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX


Region containing closed edges.
. MinAmplitude (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Minimum edge amplitude.
Default Value : 16
Suggested values : MinAmplitude ∈ {5, 8, 10, 12, 16, 20, 25, 30, 40, 50}
Typical range of values : 1 ≤ MinAmplitude ≤ 1
Minimum Increment : 1
Recommended Increment : 1
Restriction : (M inAmplitude ≥ 0)
. MaxGapLength (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Maximal number of points by which edges are extended.
Default Value : 3
Suggested values : MaxGapLength ∈ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 15, 20, 30, 40, 50, 70, 100}
Typical range of values : 1 ≤ MaxGapLength ≤ 1
Minimum Increment : 1
Recommended Increment : 1
Restriction : ((M axGapLength > 0) ∧ (M axGapLength ≤ 127))
Result
CloseEdgesLength returns TRUE if all parameters are correct. If the input is empty the behaviour can be set
via SetSystem(’noObjectResult’,<Result>). If necessary, an exception handling is raised.
Parallelization Information
CloseEdgesLength is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
EdgesImage, SobelAmp, Threshold, Skeleton
Alternatives
CloseEdges, Dilation1, Closing
References
M. Üsbeck: “Untersuchungen zur echtzeitfähigen Segmentierung”; Studienarbeit, Bayerisches Forschungszentrum
für Wissensbasierte Systeme (FORWISS), Erlangen, 1993.
Module
Foundation

[out] HImageX DerivGauss HImageX.DerivateGauss ([in] VARIANT Sigma,


[in] String Component )
void HOperatorSetX.DerivateGauss ([in] IHObjectX Image,
[out] HUntypedObjectX DerivGauss, [in] VARIANT Sigma,
[in] VARIANT Component )

Convolve an image with derivatives of the Gaussian.


DerivateGauss convolves an image with the derivatives of a Gaussian and calculates various features derived
therefrom. Sigma is the parameter of the Gaussian (i.e., the amount of smoothing). If one value is passed in
Sigma the amount of smoothing in the column and row direction is identical. If two values are passed in Sigma
the first value specifies the amount of smoothing in the column direction, while the second value specifies the
amount of smoothing in the row direction. The possible values for Component are:

’none’ Smoothing only.


’x’ First derivative along x.
∂g(x, y)
g 0 (x, y) =
∂x
’y’ First derivative along y.
∂g(x, y)
g 0 (x, y) =
∂y

HALCON 8.0.2
122 CHAPTER 3. FILTER

’gradient’ Absolute value of the gradient.


s
0 ∂g(x, y)2 ∂g(x, y)2
g (x, y) =
∂x ∂y

’gradient_dir’ Gradient direction in radians

∂g(x, y) ∂g(x, y)
φ = atan2( , )
∂y ∂x

’xx’ Second derivative along x.


∂ 2 g(x, y)
g 0 (x, y) =
∂x2
’yy’ Second derivative along y.
∂ 2 g(x, y)
g 0 (x, y) =
∂y 2
’xy’ Second derivative along x and y.
∂ 2 g(x, y)
g 0 (x, y) =
∂x∂y
’xxx’ Third derivative along x.
∂ 3 g(x, y)
g 0 (x, y) =
∂x3
’yyy’ Third derivative along y.
∂ 3 g(x, y)
g 0 (x, y) =
∂y 3
’xxy’ Third derivative along x, x and y.
∂ 3 g(x, y)
g 0 (x, y) =
∂x2 ∂y
’xyy’ Third derivative along x, y and y.
∂ 3 g(x, y)
g 0 (x, y) =
∂x∂y 2
’det’ Determinant of the Hessian matrix:
2
∂ 2 g(x, y) ∂ 2 g(x, y) ∂ 2 g(x, y)

DET = −
∂x2 ∂y 2 ∂y∂x

’laplace’ Laplace operator (trace of the Hessian matrix):

∂ 2 g(x, y) ∂ 2 g(x, y)
TR = +
∂x2 ∂y 2

’mean_curvatue’ Mean curvature H

∂g(x, y)2 ∂ 2 g(x, y)


a = (1 + )
∂x ∂y 2
∂g(x, y) ∂g(x, y) ∂ 2 g(x, y)
b = 2
∂x ∂y ∂y∂x
∂g(x, y)2 ∂ 2 g(x, y)
c = (1 + )
∂y ∂x2
2
∂g(x, y) ∂g(x, y)2 3
d = (1 + + )2
∂x ∂y
a−b+c
H =
d
1
H = (κmin + κmax )
2

HALCON/COM Reference Manual, 2008-5-13


3.4. EDGES 123

’gauss_curvatue’ Gaussian curvature K


DET
K= ∂g(x,y)2 ∂g(x,y)2 2
(1 + ∂x + ∂y )

’area’ Differential Area A


A = EG − F 2
2
∂g(x, y)
E = 1+
∂x
∂g(x, y) ∂g(x, y)
F =
∂x ∂y
2
∂g(x, y)
G = 1+
∂y
’eigenvalue1’ First eigenvalue
∂ 2 g(x,y) ∂ 2 g(x,y)
∂x2 + ∂y 2
a =
s 2
∂ 2 g(x, y) ∂ 2 g(x, y) ∂ 2 g(x, y)2
λ1 = a+ a2 − ( − )
∂x2 ∂y 2 ∂y∂x

’eigenvalue2’ Second eigenvalue


∂ 2 g(x,y) ∂ 2 g(x,y)
∂x2 + ∂y 2
a =
s 2
∂ 2 g(x, y) ∂ 2 g(x, y) ∂ 2 g(x, y)2
λ2 = a− a2 − ( − )
∂x2 ∂y 2 ∂y∂x

’eigenvec_dir’ Direction of the eigenvector corresponding to the first eigenvalue in radians


’main1_curvature’ First principal curvature
p
κmax = H + H 2 − K
’main2_curvature’ Second principal curvature
p
κmin = H − H2 − K
’kitchen_rosenfeld’ Second derivative perpendicular to the gradient
∂ 2 g(x,y) ∂g(x,y)2 ∂ 2 g(x,y) ∂g(x,y)2 2
g(x,y) ∂g(x,y)2 ∂g(x,y)2
∂x2 ∂y + ∂y 2 ∂x − 2 ∂ ∂y∂x ∂x ∂y
k= ∂g(x,y)2 ∂g(x,y)2
∂x + ∂y

’zuniga_haralick’ Normalized second derivative perpendicular to the gradient


∂ 2 g(x,y) ∂g(x,y)2 ∂ 2 g(x,y) ∂g(x,y)2 2 2
∂g(x,y)2
∂x2 ∂y + ∂y 2 ∂x − 2 ∂ ∂y∂x
g(x,y) ∂g(x,y)
∂x ∂y
k=   23
∂g(x,y)2 ∂g(x,y)2

∂x + ∂y

’2nd_ddg’ Second derivative along the gradient


∂ 2 g(x,y) ∂g(x,y)2 2
∂ 2 g(x,y) ∂g(x,y)2
∂x2 ∂x + 2 ∂g(x,y)
∂x
∂g(x,y) ∂ g(x,y)
∂y ∂y∂x + ∂y 2 ∂y
k= ∂g(x,y)2 ∂g(x,y)2
∂x + ∂y

’de_saint_venant’ Second derivative along and perpendicular to the gradient


∂g(x,y) ∂g(x,y) ∂ 2 g(x,y) ∂ 2 g(x,y) ∂g(x,y)2 ∂g(x,y)2 ∂ 2 g(x,y)
∂x ∂y ( ∂x2 − ∂y 2 ) − ( ∂x − ∂y ) ∂x∂y
k= ∂g(x,y)2 ∂g(x,y)2
∂x + ∂y

HALCON 8.0.2
124 CHAPTER 3. FILTER

Parameter
. Image (input iconic) . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic,
int1, int2, uint2, int4, real )
Input image.
. DerivGauss (output iconic) . . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX ( real )
Filtered result image.
. Sigma (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Sigma of the Gaussian.
Default Value : 1.0
Suggested values : Sigma ∈ {0.7, 1.0, 1.5, 2.0, 3.0, 4.0, 5.0}
Typical range of values : 0.2 ≤ Sigma ≤ 0.2
Minimum Increment : 0.01
Recommended Increment : 0.1
Restriction : (Sigma > 0.0)
. Component (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Derivative or feature to be calculated.
Default Value : ’x’
List of values : Component ∈ {’none’, ’x’, ’y’, ’gradient’, ’xx’, ’yy’, ’xy’, ’xxx’, ’yyy’, ’xxy’, ’xyy’, ’det’,
’mean_curvature’, ’gauss_curvature’, ’eigenvalue1’, ’eigenvalue2’, ’main1_curvature’, ’main2_curvature’,
’kitchen_rosenfeld’, ’zuniga_haralick’, ’2nd_ddg’, ’de_saint_venant’, ’area’, ’laplace’, ’gradient_dir’,
’eigenvec_dir’}
Parallelization Information
DerivateGauss is reentrant and automatically parallelized (on tuple level, channel level, domain level).
Possible Successors
ZeroCrossing, DualThreshold
See also
ZeroCrossing, DualThreshold
Alternatives
Laplace, LaplaceOfGauss, BinomialFilter, GaussImage, SmoothImage,
IsotropicDiffusion
Module
Foundation

[out] HImageX DiffOfGauss HImageX.DiffOfGauss ([in] double Sigma,


[in] double SigFactor )
void HOperatorSetX.DiffOfGauss ([in] IHObjectX Image,
[out] HUntypedObjectX DiffOfGauss, [in] VARIANT Sigma,
[in] VARIANT SigFactor )

Approximate the LoG operator (Laplace of Gaussian).


DiffOfGauss approximates the Laplace-of-Gauss operator by a difference of Gaussians. The standard devia-
tions of these Gaussians can be calculated, according to Marr, from the Parameter Sigma of the LoG and the ratio
of the two standard deviations (SigFactor) as:
Sigma
sigma1 = r
log ( SigF1actor )
−2 SigFactor2 −1

sigma1
sigma2 =
SigFactor
DiffOfGauss = (Image ∗ gauss(sigma1)) − (Image ∗ gauss(sigma2))
For a SigFactor = 1.6, according to Marr, an approximation to the Mexican-Hat-Operator results. The resulting
image is stored in DiffOfGauss.

HALCON/COM Reference Manual, 2008-5-13


3.4. EDGES 125

Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte )


Input image
. DiffOfGauss (output iconic) . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX ( int2 )
LoG image.
. Sigma (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Smoothing parameter of the Laplace operator to approximate.
Default Value : 3.0
Suggested values : Sigma ∈ {2.0, 3.0, 4.0, 5.0}
Typical range of values : 0.2 ≤ Sigma ≤ 0.2
Minimum Increment : 0.01
Recommended Increment : 0.1
Restriction : (Sigma > 0.0)
. SigFactor (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Ratio of the standard deviations used (Marr recommends 1.6).
Default Value : 1.6
Typical range of values : 0.1 ≤ SigFactor ≤ 0.1
Minimum Increment : 0.01
Recommended Increment : 0.1
Restriction : (SigF actor > 0.0)
Example

read_image(Image,’fabrik’)
diff_of_gauss(Image,Laplace,2.0,1.6)
zero_crossing(Laplace,ZeroCrossings).

Complexity
The execution time depends linearly on the number of pixels and the size of sigma.
Result
DiffOfGauss returns TRUE if all parameters are correct. If the input is empty the behaviour can be set via
SetSystem(’noObjectResult’,<Result>). If necessary, an exception handling is raised.
Parallelization Information
DiffOfGauss is reentrant and automatically parallelized (on tuple level, channel level, domain level).
Possible Successors
ZeroCrossing, DualThreshold
Alternatives
Laplace, DerivateGauss
References
D. Marr: “Vision (A computational investigation into human representation and processing of visual information)”;
New York, W.H. Freeman and Company; 1982.
Module
Foundation

[out] HImageX ImaAmp HImageX.EdgesColor ([out] HImageX ImaDir,


[in] String Filter, [in] double Alpha, [in] String NMS, [in] long Low,
[in] long High )
void HOperatorSetX.EdgesColor ([in] IHObjectX Image,
[out] HUntypedObjectX ImaAmp, [out] HUntypedObjectX ImaDir,
[in] VARIANT Filter, [in] VARIANT Alpha, [in] VARIANT NMS, [in] VARIANT Low,
[in] VARIANT High )

Extract color edges using Canny, Deriche, or Shen filters.

HALCON 8.0.2
126 CHAPTER 3. FILTER

EdgesColor extracts color edges from the input image Image. To define color edges, the multi-channel image
Image is regarded as a mapping f : R2 7→ Rn , where n is the number of channels in Image. For such functions,
there is a natural extension of the gradient: the metric tensor G, which can be used to calculate for every direction,
given by the direction vector v, the rate of change of f in the direction v. For notational convenience, G will be
regarded as a two-dimensional matrix. Thus, the rate of change of the function f in the direction v is given by
v T Gv, where
 Xn n 
∂fi ∂fi X ∂fi ∂fi
fxT fx fxT fy  i=1 ∂x ∂x ∂x ∂y 
  
G= = X i=1 
.
n n
fxT fy fyT fy  ∂fi ∂fi X ∂fi ∂fi  
i=1
∂x ∂y i=1
∂y ∂y

The partial derivatives of the images, which are necessary to calculate the metric tensor, are calculated with the
corresponding edge filters, analogously to EdgesImage. For Filter = ’canny’, the partial derivatives of
the Gaussian smoothing masks are used (see DerivateGauss), for ’deriche1’ and Filter = ’deriche2’ the
corresponding Deriche filters, for Filter = ’shen’ the corresponding Shen filters, and for Filter = ’sobel_fast’
the Sobel filter. Analogously to single-channel images, the gradient direction is defined by the vector v in which the
rate of change f is maximum. The vector v is given by the eigenvector corresponding to the largest eigenvalue of
G. The square root of the eigenvalue is the equivalent of the gradient magnitude (the amplitude) for single-channel
images, and is returned in ImaAmp. For single-channel images, both definitions are equivalent. Since the gradient
magnitude may be larger than what can be represented in the input image data type (byte or uint2), it is stored in
the next larger data type (uint2 or int4) in ImaAmp. The eigenvector also is used to define the edge direction. In
contrast to single-channel images, the edge direction can only be defined modulo 180 degrees. Like in the output
of EdgesImage, the edge directions are stored in 2-degree steps, and are returned in ImaDir. Points with edge
amplitude 0 are assigned the edge direction 255 (undefined direction). For speed reasons, the edge directions are
not computed explicitly for Filter = ’sobel_fast’. Therefore, ImaDir is an empty object in this case.
The “filter width” (i.e., the amount of smoothing) can be chosen arbitrarilyfor all filters except ’sobel_fast’ (where
the filter width is 3 × 3 and Alpha is ignored), and can be estimated by calling InfoEdges for concrete values
of the parameter Alpha. It decreases for increasing Alpha for the Deriche and Shen filters and increases for
the Canny filter, where it is the standard deviation of the Gaussian on which the Canny operator is based. “Wide”
filters exhibit a larger invariance to noise, but also a decreased ability to detect small details. Non-recursive filters,
such as the Canny filter, are realized using filter masks, and thus the execution time increases for increasing filter
width. In contrast, the execution time for recursive filters does not depend on the filter width. Thus, arbitrary
filter widths are possible using the Deriche and Shen filters without increasing the run time of the operator. The
resulting advantage in speed compared to the Canny operator naturally increases for larger filter widths. As border
treatment, the recursive operators assume that the images are zero outside of the image, while the Canny operator
mirrors the gray value at the image border. Comparable filter widths can be obtained by the following choices of
Alpha:

Alpha(0 deriche20 ) = Alpha(0 deriche10 )/2


Alpha(0 shen0 ) = Alpha(0 deriche10 )/2
0 0
Alpha( canny ) = 1.77/Alpha(0 deriche10 )

EdgesColor optionally offers to apply a non-maximum-suppression (NMS = ’nms’/’inms’/’hvnms’; ’none’ if not


desired) and hysteresis threshold operation (Low,High; at least one negative if not desired) to the resulting edge
image. Conceptually, this corresponds to the following calls:

nonmax_suppression_dir(...,NMS,...)
hysteresis_threshold(...,Low,High,1000,...)

For ’sobel_fast’, the same non-maximum-suppression is performed for all values of NMS except ’none’. Further-
more, the hysteresis threshold operation is always performed. Additionally, for ’sobel_fast’ the resulting edges are
thinned to a width of one pixel.
Parameter
. Image (input iconic) . . . . . . . . . . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, uint2 )
Input image.
. ImaAmp (output iconic) . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX ( uint2, int4 )
Edge amplitude (gradient magnitude) image.

HALCON/COM Reference Manual, 2008-5-13


3.4. EDGES 127

. ImaDir (output iconic) . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX ( direction )


Edge direction image.
. Filter (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Edge operator to be applied.
Default Value : ’canny’
List of values : Filter ∈ {’canny’, ’deriche1’, ’deriche2’, ’shen’, ’sobel_fast’}
. Alpha (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Filter parameter: small values result in strong smoothing, and thus less detail (opposite for ’canny’).
Default Value : 1.0
Suggested values : Alpha ∈ {0.1, 0.2, 0.3, 0.4, 0.5, 0.7, 0.9, 1.0, 1.1, 1.2, 1.5, 2.0, 2.5, 3.0}
Typical range of values : 0.2 ≤ Alpha ≤ 0.2
Minimum Increment : 0.01
Recommended Increment : 0.1
Restriction : (Alpha > 0.0)
. NMS (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Non-maximum suppression (’none’, if not desired).
Default Value : ’nms’
List of values : NMS ∈ {’nms’, ’inms’, ’hvnms’, ’none’}
. Low (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Lower threshold for the hysteresis threshold operation (negative if no thresholding is desired).
Default Value : 20
Suggested values : Low ∈ {5, 10, 15, 20, 25, 30, 40}
Minimum Increment : 1
Recommended Increment : 5
Restriction : ((Low ≥ 1) ∨ (Low < 0))
. High (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Upper threshold for the hysteresis threshold operation (negative if no thresholding is desired).
Default Value : 40
Suggested values : High ∈ {10, 15, 20, 25, 30, 40, 50, 60, 70}
Minimum Increment : 1
Recommended Increment : 5
Restriction : (((High ≥ 1) ∨ (High < 0)) ∧ (High ≥ Low))
Example

Result
EdgesColor returns TRUE if all parameters are correct and no error occurs during execution. If the input is
empty the behavior can be set via SetSystem(’noObjectResult’,<Result>). If necessary, an excep-
tion handling is raised.
Parallelization Information
EdgesColor is reentrant and automatically parallelized (on tuple level).
Possible Successors
Threshold
See also
EdgesImage, EdgesSubPix, InfoEdges, NonmaxSuppressionAmp, HysteresisThreshold
Alternatives
EdgesColorSubPix
References
C. Steger: “Subpixel-Precise Extraction of Lines and Edges”; International Archives of Photogrammetry and
Remote Sensing, vol. XXXIII, part B3; pp. 141-156; 2000.
C. Steger: “Unbiased Extraction of Curvilinear Structures from 2D and 3D Images”; Herbert Utz Verlag, München;
1998.
S. Di Zenzo: “A Note on the Gradient of a Multi-Image”; Computer Vision, Graphics, and Image Processing, vol.
33; pp. 116-125; 1986.

HALCON 8.0.2
128 CHAPTER 3. FILTER

Aldo Cumani: “Edge Detection in Multispectral Images”; Computer Vision, Graphics, and Image Processing:
Graphical Models and Image Processing, vol. 53, no. 1; pp. 40-51; 1991.
J.Canny: “Finding Edges and Lines in Images”; Report, AI-TR-720; M.I.T. Artificial Intelligence Lab., Cambridge;
1983.
J.Canny: “A Computational Approach to Edge Detection”; IEEE Transactions on Pattern Analysis and Machine
Intelligence; PAMI-8, vol. 6; pp. 679-698; 1986.
R.Deriche: “Using Canny’s Criteria to Derive a Recursively Implemented Optimal Edge Detector”; International
Journal of Computer Vision; vol. 1, no. 2; pp. 167-187; 1987.
R.Deriche: “Fast Algorithms for Low-Level Vision”; IEEE Transactions on Pattern Analysis and Machine Intelli-
gence; PAMI-12, no. 1; pp. 78-87; 1990.
J. Shen, S. Castan: “An Optimal Linear Operator for Step Edge Detection”; Computer Vision, Graphics, and Image
Processing: Graphical Models and Image Processing, vol. 54, no. 2; pp. 112-133; 1992.
Module
Foundation

[out] HXLDContX Edges HImageX.EdgesColorSubPix ([in] String Filter,


[in] double Alpha, [in] VARIANT Low, [in] VARIANT High )
void HOperatorSetX.EdgesColorSubPix ([in] IHObjectX Image,
[out] HUntypedObjectX Edges, [in] VARIANT Filter, [in] VARIANT Alpha,
[in] VARIANT Low, [in] VARIANT High )

Extract subpixel precise color edges using Deriche, Shen, or Canny filters.
EdgesColorSubPix extracts subpixel precise color edges from the input image Image. The definition of color
edges is given in the description of EdgesColor. The same edge filters as in EdgesColor can be selected:
’canny’, ’deriche1’, ’deriche2’, and ’shen’. In addition, a fast Sobel filter can be selected with ’sobel_fast’. The
filters are specified by the parameter Filter.
The “filter width” (i.e., the amount of smoothing) can be chosen arbitrarily. For a detailed description of this
parameter see EdgesColor. This parameter is ignored for Filter = ’sobel_fast’.
The extracted edges are returned as subpixel precise XLD contours in Edges. For all edge operators except for
’sobel_fast’, the following attributes are defined for each edge point (see GetContourAttribXld):
’edge_direction’ Edge direction
’angle’ Direction of the normal vectors to the contour (oriented such that the normal vectors point to
the right side of the contour as the contour is traversed from start to end point; the angles are
given with respect to the row axis of the image.)
’response’ Edge amplitude (gradient magnitude)
EdgesColorSubPix links the edge points into edges by using an algorithm similar to a hysteresis threshold
operation, which is also used in EdgesSubPix and LinesGauss. Points with an amplitude larger than High
are immediately accepted as belonging to an edge, while points with an amplitude smaller than Low are rejected.
All other points are accepted as edges if they are connected to accepted edge points (see also LinesGauss and
HysteresisThreshold).
Because edge extractors are often unable to extract certain junctions, a mode that tries to extract these missing
junctions by different means can be selected by appending ’_junctions’ to the values of Filter that are described
above. This mode is analogous to the mode for completing junctions that is available in EdgesSubPix and
LinesGauss.
The edge operator ’sobel_fast’ has the same semantics as all the other edge operators. Internally, howver, it is
based on significantly simplified variants of the individual processing steps (hysteresis thresholding, edge point
linking, and extraction of the subpixel edge positions). Therefore, ’sobel_fast’ in some cases may return slightly
less accurate edge positions and may select different edge parts.
Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . (multichannel-)image ; HImageX / IHObjectX ( byte, uint2 )


Input image.

HALCON/COM Reference Manual, 2008-5-13


3.4. EDGES 129

. Edges (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xld_cont ; HXLDContX / HUntypedObjectX


Extracted edges.
. Filter (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Edge operator to be applied.
Default Value : ’canny’
List of values : Filter ∈ {’canny’, ’deriche1’, ’deriche2’, ’shen’, ’sobel_fast’, ’canny_junctions’,
’deriche1_junctions’, ’deriche2_junctions’, ’shen_junctions’}
. Alpha (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Filter parameter: small values result in strong smoothing, and thus less detail (opposite for ’canny’).
Default Value : 1.0
Suggested values : Alpha ∈ {0.1, 0.2, 0.3, 0.4, 0.5, 0.7, 0.9, 1.0, 1.1, 1.2, 1.5, 2.0, 2.5, 3.0}
Typical range of values : 0.7 ≤ Alpha ≤ 0.7
Minimum Increment : 0.01
Recommended Increment : 0.1
Restriction : (Alpha > 0.0)
. Low (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Lower threshold for the hysteresis threshold operation.
Default Value : 20
Suggested values : Low ∈ {5, 10, 15, 20, 25, 30, 40}
Minimum Increment : 1
Recommended Increment : 5
Restriction : (Low > 0)
. High (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Upper threshold for the hysteresis threshold operation.
Default Value : 40
Suggested values : High ∈ {10, 15, 20, 25, 30, 40, 50, 60, 70}
Minimum Increment : 1
Recommended Increment : 5
Restriction : ((High > 0) ∧ (High ≥ Low))
Example

Result
EdgesColorSubPix returns TRUE if all parameters are correct and no error occurs during execution. If the
input is empty the behavior can be set via SetSystem(’noObjectResult’,<Result>). If necessary, an
exception handling is raised.
Parallelization Information
EdgesColorSubPix is reentrant and processed without parallelization.
See also
EdgesImage, EdgesSubPix, InfoEdges, HysteresisThreshold, LinesGauss, LinesFacet
Alternatives
EdgesColor
References
C. Steger: “Subpixel-Precise Extraction of Lines and Edges”; International Archives of Photogrammetry and
Remote Sensing, vol. XXXIII, part B3; pp. 141-156; 2000.
C. Steger: “Unbiased Extraction of Curvilinear Structures from 2D and 3D Images”; Herbert Utz Verlag, München;
1998.
S. Di Zenzo: “A Note on the Gradient of a Multi-Image”; Computer Vision, Graphics, and Image Processing, vol.
33; pp. 116-125; 1986.
Aldo Cumani: “Edge Detection in Multispectral Images”; Computer Vision, Graphics, and Image Processing:
Graphical Models and Image Processing, vol. 53, no. 1; pp. 40-51; 1991.
J.Canny: “Finding Edges and Lines in Images”; Report, AI-TR-720; M.I.T. Artificial Intelligence Lab., Cambridge;
1983.

HALCON 8.0.2
130 CHAPTER 3. FILTER

J.Canny: “A Computational Approach to Edge Detection”; IEEE Transactions on Pattern Analysis and Machine
Intelligence; PAMI-8, vol. 6; pp. 679-698; 1986.
R.Deriche: “Using Canny’s Criteria to Derive a Recursively Implemented Optimal Edge Detector”; International
Journal of Computer Vision; vol. 1, no. 2; pp. 167-187; 1987.
R.Deriche: “Fast Algorithms for Low-Level Vision”; IEEE Transactions on Pattern Analysis and Machine Intelli-
gence; PAMI-12, no. 1; pp. 78-87; 1990.
J. Shen, S. Castan: “An Optimal Linear Operator for Step Edge Detection”; Computer Vision, Graphics, and Image
Processing: Graphical Models and Image Processing, vol. 54, no. 2; pp. 112-133; 1992.
Module
2D Metrology

[out] HImageX ImaAmp HImageX.EdgesImage ([out] HImageX ImaDir,


[in] String Filter, [in] double Alpha, [in] String NMS, [in] long Low,
[in] long High )
void HOperatorSetX.EdgesImage ([in] IHObjectX Image,
[out] HUntypedObjectX ImaAmp, [out] HUntypedObjectX ImaDir,
[in] VARIANT Filter, [in] VARIANT Alpha, [in] VARIANT NMS, [in] VARIANT Low,
[in] VARIANT High )

Extract edges using Deriche, Lanser, Shen, or Canny filters.


EdgesImage detects step edges using recursively implemented filters (according to Deriche, Lanser and Shen)
or the conventionally implemented “derivative of Gaussian” filter (using filter masks) proposed by Canny. Further-
more, a very fast variant of the Sobel filter can be used. Thus, the following edge operators are available:
’deriche1’, ’lanser1’, ’deriche1_int4’, ’deriche2’, ’lanser2’, ’deriche2_int4’, ’shen’, ’mshen’, ’canny’, and ’so-
bel_fast’
(parameter Filter).
The edge amplitudes (gradient magnitude) are returned in ImaAmp. It should be noted that for ’sobel_fast’ for
speed reasons internally an algorithm is used that computes the x and y derivatives with a restricted value range of
[−128, 127] for byte images and [−32768, 32767] for uint2 images. Consequently, an ideal horizontal or vertical
step edge with an amplitude of more than 128 can assume a maximum amplitude of 128 or 32768, respectively,
in ImaAmp, while an ideal 45 degree step edge can assume a maximum amplitude of 181 or 46341, respectively.
Since ideal step edges typically never occur in real images because the edges are smoothed by the optics and
camera this limitation very rarely has any influence on the application.
For all filters except ’sobel_fast’, the edge directions are returned in ImaDir. For ’sobel_fast’, the edge direction
is not computed to speed up the filter. Consequently, ImaDir is an empty image object. The edge operators
’deriche1’ bzw. ’deriche2’ are also available for int4-images, and return the signed filter response instead of its
absolute value. This behavior can be obtained for byte-images as well by selecting ’deriche1_int4’ bzw. ’de-
riche2_int4’ as filter. This can be used to calculate the second derivative of an image by applying EdgesImage
(with parameter ’lanser2’) to the signed first derivative. Edge directions are stored in 2-degree steps, i.e., an edge
direction of x degrees with respect to the horizontal axis is stored as x/2 in the edge direction image. Furthermore,
the direction of the change of intensity is taken into account. Let [Ex , Ey ] denote the image gradient. Then the
following edge directions are returned as r/2:

intensity increase Ex /Ey

edge direction r
from bottom to top 0/+ 0
from lower right to upper left +/− ]0, 90[
from right to left +/0 90
from upper right to lower left +/+ ]90, 180[
from top to bottom 0/+ 180
from upper left to lower right −/+ ]180, 270[
from left to right +/0 270
from lower left to upper right −/− ]270, 360[

HALCON/COM Reference Manual, 2008-5-13


3.4. EDGES 131

Points with edge amplitude 0 are assigned the edge direction 255 (undefined direction).
The “filter width” (i.e., the amount of smoothing) can be chosen arbitrarily for all filters except ’sobel_fast’ (where
the filter width is 3×3 and Alpha is ignored), and can be estimated by calling InfoEdges for concrete values of
the parameter Alpha. It decreases for increasing Alpha for the Deriche, Lanser and Shen filters and increases for
the Canny filter, where it is the standard deviation of the Gaussian on which the Canny operator is based. “Wide”
filters exhibit a larger invariance to noise, but also a decreased ability to detect small details. Non-recursive filters,
such as the Canny filter, are realized using filter masks, and thus the execution time increases for increasing filter
width. In contrast, the execution time for recursive filters does not depend on the filter width. Thus, arbitrary filter
widths are possible using the Deriche, Lanser and Shen filters without increasing the run time of the operator. The
resulting advantage in speed compared to the Canny operator naturally increases for larger filter widths. As border
treatment, the recursive operators assume that the images to be zero outside of the image, while the Canny operator
repeats the gray value at the image’s border. Comparable filter widths can be obtained by the following choices of
Alpha:

Alpha(0 lanser10 ) = Alpha(0 deriche10 )


Alpha(0 deriche20 ) = Alpha(0 deriche10 )/2
Alpha(0 lanser20 ) = Alpha(0 deriche20 )
Alpha(0 shen0 ) = Alpha(0 deriche10 )/2
Alpha(0 mshen0 ) = Alpha(0 shen0 )
Alpha(0 canny 0 ) = 1.77/Alpha(0 deriche10 )

The originally proposed recursive filters (’deriche1’, ’deriche2’, ’shen’) return a biased estimate of the amplitude
of diagonal edges. This bias is removed in the corresponding modified version of the operators (’lanser1’, ’lanser2’
und ’mshen’), while maintaining the same execution speed.
For relatively small filter widths (11 × 11), i.e., for Alpha (’lanser2’ = 0.5), all filters yield similar results. Only for
“wider” filters differences begin to appear: the Shen filters begin to yield qualitatively inferior results. However,
they are the fastest of the implemented operators — closely followed by the Deriche operators.
EdgesImage optionally offers to apply a non-maximum-suppression (NMS = ’nms’/’inms’/’hvnms’; ’none’ if
not desired) and hysteresis threshold operation (Low,High; at least one negative if not desired) to the resulting
edge image. Conceptually, this corresponds to the following calls:

nonmax_suppression_dir(...,NMS,...)
hysteresis_threshold(...,Low,High,999,...)

For ’sobel_fast’, the same non-maximum-suppression is performed for all values of NMS except ’none’. Further-
more, the hysteresis threshold operation is always performed. Additionally, for ’sobel_fast’ the resulting edges are
thinned to a width of one pixel.
Parameter
. Image (input iconic) . . . . . . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, uint2, int4 )
Input image.
. ImaAmp (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX ( byte, uint2,
int4, real )
Edge amplitude (gradient magnitude) image.
. ImaDir (output iconic) . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX ( direction )
Edge direction image.
. Filter (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Edge operator to be applied.
Default Value : ’lanser2’
List of values : Filter ∈ {’deriche1’, ’deriche1_int4’, ’deriche2’, ’deriche2_int4’, ’lanser1’, ’lanser2’,
’shen’, ’mshen’, ’canny’, ’sobel_fast’}
. Alpha (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Filter parameter: small values result in strong smoothing, and thus less detail (opposite for ’canny’).
Default Value : 0.5
Suggested values : Alpha ∈ {0.1, 0.2, 0.3, 0.4, 0.5, 0.7, 0.9, 1.1}
Typical range of values : 0.2 ≤ Alpha ≤ 0.2
Minimum Increment : 0.01
Recommended Increment : 0.1
Restriction : (Alpha > 0.0)

HALCON 8.0.2
132 CHAPTER 3. FILTER

. NMS (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT


Non-maximum suppression (’none’, if not desired).
Default Value : ’nms’
List of values : NMS ∈ {’nms’, ’inms’, ’hvnms’, ’none’}
. Low (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Lower threshold for the hysteresis threshold operation (negative, if no thresholding is desired).
Default Value : 20
Suggested values : Low ∈ {5, 10, 15, 20, 25, 30, 40}
Typical range of values : 1 ≤ Low ≤ 1
Minimum Increment : 1
Recommended Increment : 5
Restriction : ((Low > 1) ∨ (Low < 0))
. High (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Upper threshold for the hysteresis threshold operation (negative, if no thresholding is desired).
Default Value : 40
Suggested values : High ∈ {10, 15, 20, 25, 30, 40, 50, 60, 70}
Typical range of values : 1 ≤ High ≤ 1
Minimum Increment : 1
Recommended Increment : 5
Restriction : (((High > 1) ∨ (High < 0)) ∧ (High ≥ Low))
Example

read_image(Image,’fabrik’)
edges_image(Image,Amp,Dir,’lanser2’,0.5,’none’,-1,-1)
hysteresis_threshold(Amp,Margin,20,30,30).

Result
EdgesImage returns TRUE if all parameters are correct and no error occurs during execution. If the input
is empty the behaviour can be set via SetSystem(’noObjectResult’,<Result>). If necessary, an
exception handling is raised.
Parallelization Information
EdgesImage is reentrant and automatically parallelized (on tuple level, channel level).
Possible Predecessors
InfoEdges
Possible Successors
Threshold, HysteresisThreshold, CloseEdgesLength
See also
InfoEdges, NonmaxSuppressionAmp, HysteresisThreshold, BandpassImage
Alternatives
SobelDir, FreiDir, KirschDir, PrewittDir, RobinsonDir
References
S.Lanser, W.Eckstein: “Eine Modifikation des Deriche-Verfahrens zur Kantendetektion”; 13. DAGM-Symposium,
München; Informatik Fachberichte 290; Seite 151 - 158; Springer-Verlag; 1991.
S.Lanser: “Detektion von Stufenkanten mittels rekursiver Filter nach Deriche”; Diplomarbeit; Technische Univer-
sität München, Institut für Informatik, Lehrstuhl Prof. Radig; 1991.
J.Canny: “Finding Edges and Lines in Images”; Report, AI-TR-720; M.I.T. Artificial Intelligence Lab., Cambridge;
1983.
J.Canny: “A Computational Approach to Edge Detection”; IEEE Transactions on Pattern Analysis and Machine
Intelligence; PAMI-8, vol. 6; S. 679-698; 1986.
R.Deriche: “Using Canny’s Criteria to Derive a Recursively Implemented Optimal Edge Detector”; International
Journal of Computer Vision; vol. 1, no. 2; S. 167-187; 1987.
R.Deriche: “Optimal Edge Detection Using Recursive Filtering”; Proc. of the First International Conference on
Computer Vision, London; S. 501-505; 1987.

HALCON/COM Reference Manual, 2008-5-13


3.4. EDGES 133

R.Deriche: “Fast Algorithms for Low-Level Vision”; IEEE Transactions on Pattern Analysis and Machine Intelli-
gence; PAMI-12, no. 1; S. 78-87; 1990.
S.Castan, J.Zhao und J.Shen: “Optimal Filter for Edge Detection Methods and Results”; Proc. of the First Euro-
pean Conference on Computer Vision, Antibes; Lecture Notes on computer Science; no. 427; S. 12-17; Springer-
Verlag; 1990.
Module
Foundation

[out] HXLDContX Edges HImageX.EdgesSubPix ([in] String Filter,


[in] double Alpha, [in] long Low, [in] long High )
void HOperatorSetX.EdgesSubPix ([in] IHObjectX Image,
[out] HUntypedObjectX Edges, [in] VARIANT Filter, [in] VARIANT Alpha,
[in] VARIANT Low, [in] VARIANT High )

Extract sub-pixel precise edges using Deriche, Lanser, Shen, or Canny filters.
EdgesSubPix detects step edges using recursively implemented filters (according to Deriche, Lanser and Shen)
or the conventionally implemented “derivative of Gaussian” filter (using filter masks) proposed by Canny. Thus,
the following edge operators are available:
’deriche1’, ’lanser1’, ’deriche2’, ’lanser2’, ’shen’, ’mshen’, ’canny’, ’sobel’, and ’sobel_fast’
(parameter Filter).
The extracted edges are returned as sub-pixel precise XLD contours in Edges. For all edge operators except
’sobel_fast’, the following attributes are defined for each edge point (see GetContourAttribXld):
’edge_direction’ Edge direction
’angle’ Direction of the normal vectors to the contour (oriented such that the normal vectors point to
the right side of the contour as the contour is traversed from start to end point; the angles are
given with respect to the row axis of the image.)
’response’ Edge amplitude (gradient magnitude)
The “filter width” (i.e., the amount of smoothing) can be chosen arbitrarily for all edge operators except ’sobel
and ’sobel_fast’, and can be estimated by calling InfoEdges for concrete values of the parameter Alpha. It
decreases for increasing Alpha for the Deriche, Lanser and Shen filters and increases for the Canny filter, where
it is the standard deviation of the Gaussian on which the Canny operator is based. “Wide” filters exhibit a larger
invariance to noise, but also a decreased ability to detect small details. Non-recursive filters, such as the Canny
filter, are realized using filter masks, and thus the execution time increases for increasing filter width. In contrast,
the execution time for recursive filters does not depend on the filter width. Thus, arbitrary filter widths are possible
using the Deriche, Lanser and Shen filters without increasing the run time of the operator. The resulting advantage
in speed compared to the Canny operator naturally increases for larger filter widths. As border treatment, the
recursive operators assume that the images to be zero outside of the image, while the Canny operator repeats the
gray value at the image’s border. Comparable filter widths can be obtained by the following choices of Alpha:

Alpha(0 lanser10 ) = Alpha(0 deriche10 )


Alpha(0 deriche20 ) = Alpha(0 deriche10 )/2
Alpha(0 lanser20 ) = Alpha(0 deriche20 )
Alpha(0 shen0 ) = Alpha(0 deriche10 )/2
Alpha(0 mshen0 ) = Alpha(0 shen0 )
Alpha(0 canny 0 ) = 1.77/Alpha(0 deriche10 )

The originally proposed recursive filters (’deriche1’, ’deriche2’, ’shen’) return a biased estimate of the amplitude
of diagonal edges. This bias is removed in the corresponding modified version of the operators (’lanser1’, ’lanser2’
und ’mshen’), while maintaining the same execution speed.
For relatively small filter widths (11 × 11), i.e., for Alpha (’lanser2’ = 0.5), all filters yield similar results. Only for
“wider” filters differences begin to appear: the Shen filters begin to yield qualitatively inferior results. However,
they are the fastest of the implemented operators that supprt arbitrary mask sizes, closely followed by the Deriche
operators. The two Sobel filters, which use a fixed mask size of (3 × 3), are faster than the other filters. Of these
two, the filter ’sobel_fast’ is significantly faster than ’sobel’.

HALCON 8.0.2
134 CHAPTER 3. FILTER

EdgesSubPix links the edge points into edges by using an algorithm similar to a hysteresis threshold operation,
which is also used in LinesGauss. Points with an amplitude larger than High are immediately accepted as
belonging to an edge, while points with an amplitude smaller than Low are rejected. All other points are accepted
as edges if they are connected to accepted edge points (see also LinesGauss and HysteresisThreshold).
Because edge extractors are often unable to extract certain junctions, a mode that tries to extract these missing
junctions by different means can be selected by appending ’_junctions’ to the values of Filter that are described
above. This mode is analogous to the mode for completing junctions that is available in LinesGauss.
The edge operator ’sobel_fast’ has the same semantics as all the other edge operators. Internally, howver, it is
based on significantly simplified variants of the individual processing steps (hysteresis thresholding, edge point
linking, and extraction of the subpixel edge positions). Therefore, ’sobel_fast’ in some cases may return slightly
less accurate edge positions and may select different edge parts.
Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, uint2 )


Input image.
. Edges (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xld_cont ; HXLDContX / HUntypedObjectX
Extracted edges.
. Filter (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Edge operator to be applied.
Default Value : ’lanser2’
List of values : Filter ∈ {’deriche1’, ’lanser1’, ’deriche2’, ’lanser2’, ’shen’, ’mshen’, ’canny’, ’sobel’,
’sobel_fast’, ’deriche1_junctions’, ’lanser1_junctions’, ’deriche2_junctions’, ’lanser2_junctions’,
’shen_junctions’, ’mshen_junctions’, ’canny_junctions’, ’sobel_junctions’}
. Alpha (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Filter parameter: small values result in strong smoothing, and thus less detail (opposite for ’canny’).
Default Value : 0.5
Suggested values : Alpha ∈ {0.1, 0.2, 0.3, 0.4, 0.5, 0.7, 0.9, 1.1}
Typical range of values : 0.2 ≤ Alpha ≤ 0.2
Minimum Increment : 0.01
Recommended Increment : 0.1
Restriction : (Alpha > 0.0)
. Low (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Lower threshold for the hysteresis threshold operation.
Default Value : 20
Suggested values : Low ∈ {5, 10, 15, 20, 25, 30, 40}
Typical range of values : 1 ≤ Low ≤ 1
Minimum Increment : 1
Recommended Increment : 5
Restriction : (Low > 0)
. High (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Upper threshold for the hysteresis threshold operation.
Default Value : 40
Suggested values : High ∈ {10, 15, 20, 25, 30, 40, 50, 60, 70}
Typical range of values : 1 ≤ High ≤ 1
Minimum Increment : 1
Recommended Increment : 5
Restriction : ((High > 0) ∧ (High ≥ Low))
Example

read_image(Image,’fabrik’)
edges_sub_pix(Image,Edges,’lanser2’,0.5,20,40).

Complexity
Let A be the number of pixels in the domain of Image. Then the runtime complexity is O(A ∗ Sigma) for the
Canny filter and O(A) for the recursive Lanser, Deriche, and Shen filters.

HALCON/COM Reference Manual, 2008-5-13


3.4. EDGES 135

Let S = Width ∗ Height be the number of pixels of Image. Then EdgesSubPix requires at least 60 ∗ S bytes
of temporary memory during execution for all edge operators except ’sobel_fast’. For ’sobel_fast’, at least 9 ∗ S
bytes of temporary memory are required.
Result
EdgesSubPix returns TRUE if all parameters are correct and no error occurs during execution. If the input
is empty the behaviour can be set via SetSystem(’noObjectResult’,<Result>). If necessary, an
exception handling is raised.
Parallelization Information
EdgesSubPix is reentrant and automatically parallelized (on tuple level).
See also
InfoEdges, HysteresisThreshold, BandpassImage, LinesGauss, LinesFacet
Alternatives
SobelDir, FreiDir, KirschDir, PrewittDir, RobinsonDir, EdgesImage
References
S.Lanser, W.Eckstein: “Eine Modifikation des Deriche-Verfahrens zur Kantendetektion”; 13. DAGM-Symposium,
München; Informatik Fachberichte 290; Seite 151 - 158; Springer-Verlag; 1991.
S.Lanser: “Detektion von Stufenkanten mittels rekursiver Filter nach Deriche”; Diplomarbeit; Technische Univer-
sität München, Institut für Informatik, Lehrstuhl Prof. Radig; 1991.
J.Canny: “Finding Edges and Lines in Images”; Report, AI-TR-720; M.I.T. Artificial Intelligence Lab., Cambridge;
1983.
J.Canny: “A Computational Approach to Edge Detection”; IEEE Transactions on Pattern Analysis and Machine
Intelligence; PAMI-8, vol. 6; S. 679-698; 1986.
R.Deriche: “Using Canny’s Criteria to Derive a Recursively Implemented Optimal Edge Detector”; International
Journal of Computer Vision; vol. 1, no. 2; S. 167-187; 1987.
R.Deriche: “Optimal Edge Detection Using Recursive Filtering”; Proc. of the First International Conference on
Computer Vision, London; S. 501-505; 1987.
R.Deriche: “Fast Algorithms for Low-Level Vision”; IEEE Transactions on Pattern Analysis and Machine Intelli-
gence; PAMI-12, no. 1; S. 78-87; 1990.
S.Castan, J.Zhao und J.Shen: “Optimal Filter for Edge Detection Methods and Results”; Proc. of the First Euro-
pean Conference on Computer Vision, Antibes; Lecture Notes on computer Science; no. 427; S. 12-17; Springer-
Verlag; 1990.
Module
2D Metrology

HImageX.FreiAmp ( )
[out] HImageX ImageEdgeAmp
void HOperatorSetX.FreiAmp ([in] IHObjectX Image,
[out] HUntypedObjectX ImageEdgeAmp )

Detect edges (amplitude) using the Frei-Chen operator.


FreiAmp calculates an approximation of the first derivative of the image data and is used as an edge detector. The
filter is based on the following filter masks:

1 1 1
A= 0 0 0
−1 −1 −1

1 0 −1
B= 1 0 −1
1 0 −1
The result image contains the maximum response of the masks A and B.

HALCON 8.0.2
136 CHAPTER 3. FILTER

Parameter

. Image (input iconic) . . . . . . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, int2, uint2 )


Input image.
. ImageEdgeAmp (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX (
byte, int2, uint2 )
Edge amplitude (gradient magnitude) image.
Example

read_image(Image,’fabrik’)
frei_amp(Image,Frei_amp)
threshold(Frei_amp,Edges,128,255).

Result
FreiAmp always returns TRUE. If the input is empty the behaviour can be set via SetSystem
(’noObjectResult’,<Result>). If necessary, an exception handling is raised.
Parallelization Information
FreiAmp is reentrant and automatically parallelized (on tuple level, channel level, domain level).
Possible Predecessors
BinomialFilter, GaussImage, SigmaImage, MedianImage, SmoothImage
See also
BandpassImage, LaplaceOfGauss
Alternatives
SobelAmp, KirschAmp, PrewittAmp, RobinsonAmp, Roberts
Module
Foundation

HImageX.FreiDir ([out] HImageX ImageEdgeDir )


[out] HImageX ImageEdgeAmp
void HOperatorSetX.FreiDir ([in] IHObjectX Image,
[out] HUntypedObjectX ImageEdgeAmp, [out] HUntypedObjectX ImageEdgeDir )

Detect edges (amplitude and direction) using the Frei-Chen operator.


FreiDir calculates an approximation of the first derivative of the image data and is used as an edge detector. The
filter is based on the following filter masks:

1 2 1
A= 0 √ 0 0
−1 − 2 −1

√1 0 −1

B= 2 0 − 2
1 0 −1

The result image contains the maximum response of the masks A and B. The edge directions are returned in
ImageEdgeDir, and are stored in 2-degree steps, i.e., an edge direction of x degrees with respect to the horizontal
axis is stored as x/2 in the edge direction image. Furthermore, the direction of the change of intensity is taken into
account. Let [Ex , Ey ] denote the image gradient. Then the following edge directions are returned as r/2:

HALCON/COM Reference Manual, 2008-5-13


3.4. EDGES 137

intensity increase Ex /Ey

edge direction r
from bottom to top 0/+ 0
from lower right to upper left +/− ]0, 90[
from right to left +/0 90
from upper right to lower left +/+ ]90, 180[
from top to bottom 0/+ 180
from upper left to lower right −/+ ]180, 270[
from left to right +/0 270
from lower left to upper right −/− ]270, 360[

Points with edge amplitude 0 are assigned the edge direction 255 (undefined direction).
Parameter
. Image (input iconic) . . . . . . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, int2, uint2 )
Input image.
. ImageEdgeAmp (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX (
byte, int2, uint2 )
Edge amplitude (gradient magnitude) image.
. ImageEdgeDir (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX ( di-
rection )
Edge direction image.
Example

read_image(Image,’fabrik’)
frei_dir(Image,Frei_dirA,Frei_dirD)
threshold(Frei_dirA,Res,128,255).

Result
FreiDir always returns TRUE. If the input is empty the behaviour can be set via SetSystem
(’noObjectResult’,<Result>). If necessary, an exception handling is raised.
Parallelization Information
FreiDir is reentrant and automatically parallelized (on tuple level, channel level, domain level).
Possible Predecessors
BinomialFilter, GaussImage, SigmaImage, MedianImage, SmoothImage
Possible Successors
HysteresisThreshold, Threshold, GraySkeleton, NonmaxSuppressionDir, CloseEdges,
CloseEdgesLength
See also
BandpassImage, LaplaceOfGauss
Alternatives
EdgesImage, SobelDir, RobinsonDir, PrewittDir, KirschDir
Module
Foundation

[out] HImageX Highpass HImageX.HighpassImage ([in] long Width,


[in] long Height )
void HOperatorSetX.HighpassImage ([in] IHObjectX Image,
[out] HUntypedObjectX Highpass, [in] VARIANT Width, [in] VARIANT Height )

Extract high frequency components from an image.

HALCON 8.0.2
138 CHAPTER 3. FILTER

HighpassImage extracts high frequency components in an image by applying a linear filter with the following
matrix (in case of a 7 × 5 matrix):

1 1 1 1 1 1 1
1 1 1 1 1 1 1
1 1 1 −35 1 1 1
1 1 1 1 1 1 1
1 1 1 1 1 1 1

This corresponds to applying a mean operator ( MeanImage), and then subtracting the original gray value. A
value of 128 is added to the result, i.e., zero crossings occur for 128.
This filter emphasizes high frequency components (edges and corners). The cutoff frequency is determined by the
size (Height × Width) of the filter matrix: the larger the matrix, the smaller the cutoff frequency is.
At the image borders the pixels’ gray values are mirrored. In case of over- or underflow the gray values are clipped
(255 and 0, resp.).
Attention
If even values are passed for Height or Width, the operator uses the next larger odd value instead. Thus, the
center of the filter mask is always uniquely determined.
Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte )


Input image.
. Highpass (output iconic) . . . . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX ( byte )
High-pass-filtered result image.
. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; long / VARIANT
Width of the filter mask.
Default Value : 9
Suggested values : Width ∈ {3, 5, 7, 9, 11, 13, 17, 21, 29, 41, 51, 73, 101}
Typical range of values : 3 ≤ Width ≤ 3
Minimum Increment : 2
Recommended Increment : 2
Restriction : (W idth ∧ odd)
. Height (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; long / VARIANT
Height of the filter mask.
Default Value : 9
Suggested values : Height ∈ {3, 5, 7, 9, 11, 13, 17, 21, 29, 41, 51, 73, 101}
Typical range of values : 3 ≤ Height ≤ 3
Minimum Increment : 2
Recommended Increment : 2
Restriction : (Height ∧ odd)
Result
HighpassImage returns TRUE if all parameters are correct. If the input is empty the behaviour can be set via
SetSystem(’noObjectResult’,<Result>). If necessary, an exception handling is raised.
Parallelization Information
HighpassImage is reentrant and automatically parallelized (on tuple level, channel level, domain level).
Possible Successors
Threshold, Skeleton
See also
DynThreshold
Alternatives
MeanImage, SubImage, ConvolImage, BandpassImage
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


3.4. EDGES 139

[out] long Size HMiscX.InfoEdges ([in] String Filter, [in] String Mode,
[in] double Alpha, [out] VARIANT Coeffs )
void HOperatorSetX.InfoEdges ([in] VARIANT Filter, [in] VARIANT Mode,
[in] VARIANT Alpha, [out] VARIANT Size, [out] VARIANT Coeffs )

Estimate the width of a filter in EdgesImage.


InfoEdges returns an estimate of the width of any of the filters used in EdgesImage. To do so, the corre-
sponding continuous impulse responses of the filters are sampled until the first filter coefficient is smaller than five
percent of the largest coefficient. Alpha is the filter parameter (see EdgesImage). Seven edge operators are
supported (parameter Filter):
’deriche1’, ’lanser1’, ’deriche2’, ’lanser2’, ’shen’, ’mshen’ und ’canny’.
The parameter Mode (’edge’/’smooth’) is used to determine whether the corresponding edge or smoothing operator
is to be sampled. The Canny operator (which uses the Gaussian for smoothing) is implemented using conventional
filter masks, while all other filters are implemented recursively. Therefore, for the Canny filter the coefficients of
the one-dimensional impulse responses f (n) with n ≥ 0 are returned in Coeffs in addition to the filter width.
Parameter
. Filter (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Name of the edge operator.
Default Value : ’lanser2’
List of values : Filter ∈ {’deriche1’, ’lanser1’, ’deriche2’, ’lanser2’, ’shen’, ’mshen’, ’canny’}
. Mode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
1D edge filter (’edge’) or 1D smoothing filter (’smooth’).
Default Value : ’edge’
List of values : Mode ∈ {’edge’, ’smooth’}
. Alpha (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Filter parameter: small values result in strong smoothing, and thus less detail (opposite for ’canny’).
Default Value : 0.5
Typical range of values : 0.2 ≤ Alpha ≤ 0.2
Minimum Increment : 0.01
Recommended Increment : 0.1
Restriction : (Alpha > 0.0)
. Size (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Filter width in pixels.
. Coeffs (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
For Canny filters: Coefficients of the “positive” half of the 1D impulse response.
Example

read_image(Image,’fabrik’)
info_edges(’lanser2’,’edge’,0.5,Size,Coeffs)
edges_image(Image,Amp,Dir,’lanser2’,0.5,’none’,-1,-1)
hysteresis_threshold(Amp,Margin,20,30,30).

Result
InfoEdges returns TRUE if all parameters are correct. If the input is empty the behaviour can be set via
SetSystem(’noObjectResult’,<Result>). If necessary, an exception handling is raised.
Parallelization Information
InfoEdges is reentrant and processed without parallelization.
Possible Successors
EdgesImage, Threshold, Skeleton
See also
EdgesImage
Module
Foundation

HALCON 8.0.2
140 CHAPTER 3. FILTER

HImageX.KirschAmp ( )
[out] HImageX ImageEdgeAmp
void HOperatorSetX.KirschAmp ([in] IHObjectX Image,
[out] HUntypedObjectX ImageEdgeAmp )

Detect edges (amplitude) using the Kirsch operator.


KirschAmp calculates an approximation of the first derivative of the image data and is used as an edge detector.
The filter is based on the following filter masks:

−3 −3 5
−3 0 5
−3 −3 5

−3 5 5
−3 0 5
−3 −3 −3
5 5 5
−3 0 −3
−3 −3 −3
5 5 −3
5 0 −3
−3 −3 −3
5 −3 −3
5 0 −3
5 −3 −3
−3 −3 −3
5 0 −3
5 5 −3
−3 −3 −3
−3 0 −3
5 5 5
−3 −3 −3
−3 0 5
−3 5 5

The result image contains the maximum response of all masks.


Parameter

. Image (input iconic) . . . . . . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, int2, uint2 )


Input image.
. ImageEdgeAmp (output iconic) . . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, int2, uint2 )
Edge amplitude (gradient magnitude) image.
Example

read_image(Image,’fabrik’)
kirsch_amp(Image,Kirsch_amp)
threshold(Kirsch_amp,Edges,128,255).

Result
KirschAmp always returns TRUE. If the input is empty the behaviour can be set via SetSystem
(’noObjectResult’,<Result>). If necessary, an exception handling is raised.
Parallelization Information
KirschAmp is reentrant and automatically parallelized (on tuple level, channel level, domain level).

HALCON/COM Reference Manual, 2008-5-13


3.4. EDGES 141

Possible Predecessors
BinomialFilter, GaussImage, SigmaImage, MedianImage, SmoothImage
See also
BandpassImage, LaplaceOfGauss
Alternatives
SobelAmp, FreiAmp, PrewittAmp, RobinsonAmp, Roberts
Module
Foundation

[out] HImageX ImageEdgeAmp HImageX.KirschDir


([out] HImageX ImageEdgeDir )
void HOperatorSetX.KirschDir ([in] IHObjectX Image,
[out] HUntypedObjectX ImageEdgeAmp, [out] HUntypedObjectX ImageEdgeDir )

Detect edges (amplitude and direction) using the Kirsch operator.


KirschDir calculates an approximation of the first derivative of the image data and is used as an edge detector.
The filter is based on the following filter masks:

−3 −3 5
−3 0 5
−3 −3 5

−3 5 5
−3 0 5
−3 −3 −3
5 5 5
−3 0 −3
−3 −3 −3
5 5 −3
5 0 −3
−3 −3 −3
5 −3 −3
5 0 −3
5 −3 −3
−3 −3 −3
5 0 −3
5 5 −3
−3 −3 −3
−3 0 −3
5 5 5
−3 −3 −3
−3 0 5
−3 5 5

The result image contains the maximum response of all masks. The edge directions are returned in
ImageEdgeDir, and are stored as x/2. They correspond to the direction of the mask yielding the maximum
response.

HALCON 8.0.2
142 CHAPTER 3. FILTER

Parameter
. Image (input iconic) . . . . . . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, int2, uint2 )
Input image.
. ImageEdgeAmp (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX (
byte, int2, uint2 )
Edge amplitude (gradient magnitude) image.
. ImageEdgeDir (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX ( di-
rection )
Edge direction image.
Example

read_image(Image,’fabrik’)
kirsch_dir(Image,Kirsch_dirA,Kirsch_dirD)
threshold(Kirsch_dirA,Res,128,255).

Result
KirschDir always returns TRUE. If the input is empty the behaviour can be set via SetSystem
(’noObjectResult’,<Result>). If necessary, an exception handling is raised.
Parallelization Information
KirschDir is reentrant and automatically parallelized (on tuple level, channel level, domain level).
Possible Predecessors
BinomialFilter, GaussImage, SigmaImage, MedianImage, SmoothImage
Possible Successors
HysteresisThreshold, Threshold, GraySkeleton, NonmaxSuppressionDir, CloseEdges,
CloseEdgesLength
See also
BandpassImage, LaplaceOfGauss
Alternatives
EdgesImage, SobelDir, RobinsonDir, PrewittDir, FreiDir
Module
Foundation

[out] HImageX ImageLaplace HImageX.Laplace ([in] String ResultType,


[in] VARIANT MaskSize, [in] String FilterMask )
void HOperatorSetX.Laplace ([in] IHObjectX Image,
[out] HUntypedObjectX ImageLaplace, [in] VARIANT ResultType,
[in] VARIANT MaskSize, [in] VARIANT FilterMask )

Calculate the Laplace operator by using finite differences.


Laplace filters the input images Image using a Laplace operator. Depending on the parameter FilterMask
the following approximations of the Laplace operator are used:
’n_4’

1
1 −4 1
1

’n_8’

1 1 1
1 −8 1
1 1 1

HALCON/COM Reference Manual, 2008-5-13


3.4. EDGES 143

’n_8_isotropic’

10 22 10
22 −128 22
10 22 10

For the three filter masks the following normelizations of the resulting gray values is applied, (i.e., by dividing
the result by the given divisor): ’n_4’ normalization by 1, ’n_8’, normalization by 2 and for ’n_8_isotropic’
normalization by 32.
For a Laplace operator with size 3 × 3, the corresponding filter is applied directly, while for larger filter sizes
the input image is first smoothed using using a Gaussian filter (see GaussImage) or a binomial filter (see
BinomialFilter) of size MaskSize-2. The Gaussian filter is selected for the above values of ResultType.
Here, MaskSize = 5, 7, 9, 11, or 13 must be used. The binomial filter is selected by appending ’_binomial’ to the
above values of ResultType. Here, MaskSize can be selected between 5 and 39. Furthermore, it is possible
to select different amounts of smoothing for the column and row direction by passing two values in MaskSize.
Here, the first value of MaskSize corresponds to the mask width (smoothing in the column direction), while the
second value corresponds to the mask height (smoothing in the row direction) of the binomial filter. Therefore,

laplace(O:R:’absolute’,MaskSize,N:)

for MaskSize > is equivalent to

gauss_image(O:G:MaskSize-2:) .
laplace(G:R:’absolute’,MaskSize,N:).

and

laplace(O:R:’absolute_binomial’,MaskSize,N:)
is equivalent to

binomial_filter(O:B:MaskSize-2,MaskSize-2:) .
laplace(B:R:’absolute’,3,N:)

Laplace either returns the absolute value of the Laplace filtered image (ResultType = ’absolute’) in a byte
or uint2 image or the signed result (ResultType = ’signed’ or ’signed_clipped’). Here, the output image type
has the same number of bytes per pixel as the input image (i.e., int1 or int2) for ’signed_clipped’, while the output
image has the next larger number of pixels (i.e., int2 or int4) for ’signed’.
Parameter
. Image (input iconic) . . . . . . . . . . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, uint2 )
Input image.
. ImageLaplace (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX (
byte, uint2, int2, int2, int4 )
Laplace-filtered result image.
. ResultType (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Type of the result image, whereas for byte and uint2 the absolute value is used.
Default Value : ’absolute’
List of values : ResultType ∈ {’absolute’, ’signed_clipped’, ’signed’, ’absolute_binomial’,
’signed_clipped_binomial’, ’signed_binomial’}
. MaskSize (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Size of filter mask.
Default Value : 3
List of values : MaskSize ∈ {3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39}
. FilterMask (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Filter mask used in the Laplace operator
Default Value : ’n_4’
List of values : FilterMask ∈ {’n_4’, ’n_8’, ’n_8_isotropic’}

HALCON 8.0.2
144 CHAPTER 3. FILTER

Result
Laplace returns TRUE if all parameters are correct. If the input is empty the behaviour can be set via
SetSystem(’noObjectResult’,<Result>). If necessary, an exception handling is raised.
Parallelization Information
Laplace is reentrant and automatically parallelized (on tuple level, channel level, domain level).
Possible Successors
ZeroCrossing, DualThreshold, Threshold
See also
HighpassImage, EdgesImage
Alternatives
DiffOfGauss, LaplaceOfGauss, DerivateGauss
Module
Foundation

[out] HImageX ImageLaplace HImageX.LaplaceOfGauss ([in] VARIANT Sigma )


void HOperatorSetX.LaplaceOfGauss ([in] IHObjectX Image,
[out] HUntypedObjectX ImageLaplace, [in] VARIANT Sigma )

LoG-Operator (Laplace of Gaussian).


LaplaceOfGauss calculates the Laplace-of-Gaussian operator, i.e., the Laplace operator on a Gaussian
smoothed image, for arbitrary smoothing parameters Sigma. The Laplace operator is given by:

∂ 2 g(x, y) ∂ 2 g(x, y)
∆g(x, y) = +
∂x2 ∂y 2

The derivatives in LaplaceOfGauss are calculated by appropriate derivatives of the Gaussian, resulting in the
following formula for the convolution mask:

∆Gσ (x, y) =
 2
x + y2
 2
x + y2
 
1
− 1 exp −
2πσ 4 2σ 2 2σ 2

Parameter

. Image (input iconic) . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, int1, int2, uint2,
int4, real )
Input image.
. ImageLaplace (output iconic) . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX ( int2 )
Laplace filtered image.
. Sigma (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Smoothing parameter of the Gaussian.
Default Value : 2.0
Suggested values : Sigma ∈ {0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 4.0, 5.0, 7.0}
Typical range of values : 0.7 ≤ Sigma ≤ 0.7
Minimum Increment : 0.01
Recommended Increment : 0.1
Restriction : ((Sigma > 0.7) ∧ (Sigma ≤ 25.0))
Parallelization Information
LaplaceOfGauss is reentrant and automatically parallelized (on tuple level, channel level, domain level).
Possible Successors
ZeroCrossing, DualThreshold
See also
DerivateGauss

HALCON/COM Reference Manual, 2008-5-13


3.4. EDGES 145

Alternatives
Laplace, DiffOfGauss, DerivateGauss
Module
Foundation

HImageX.PrewittAmp ( )
[out] HImageX ImageEdgeAmp
void HOperatorSetX.PrewittAmp ([in] IHObjectX Image,
[out] HUntypedObjectX ImageEdgeAmp )

Detect edges (amplitude) using the Prewitt operator.


PrewittAmp calculates an approximation of the first derivative of the image data and is used as an edge detector.
The filter is based on the following filter masks:

1 1 1
A= 0 0 0
−1 −1 −1

1 0 −1
B= 1 0 −1
1 0 −1

The result image contains the maximum response of the masks A and B.
Parameter

. Image (input iconic) . . . . . . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, int2, uint2 )


Input image.
. ImageEdgeAmp (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX (
byte, int2, uint2 )
Edge amplitude (gradient magnitude) image.
Example

read_image(Image,’fabrik’)
prewitt_amp(Image,Prewitt)
threshold(Prewitt,Edges,128,255).

Result
PrewittAmp always returns TRUE. If the input is empty the behaviour can be set via SetSystem
(’noObjectResult’,<Result>). If necessary, an exception handling is raised.
Parallelization Information
PrewittAmp is reentrant and automatically parallelized (on tuple level, channel level, domain level).
Possible Predecessors
BinomialFilter, GaussImage, SigmaImage, MedianImage, SmoothImage
Possible Successors
Threshold, GraySkeleton, NonmaxSuppressionAmp, CloseEdges, CloseEdgesLength
See also
BandpassImage, LaplaceOfGauss
Alternatives
SobelAmp, KirschAmp, FreiAmp, RobinsonAmp, Roberts
Module
Foundation

HALCON 8.0.2
146 CHAPTER 3. FILTER

[out] HImageX ImageEdgeAmp HImageX.PrewittDir


([out] HImageX ImageEdgeDir )
void HOperatorSetX.PrewittDir ([in] IHObjectX Image,
[out] HUntypedObjectX ImageEdgeAmp, [out] HUntypedObjectX ImageEdgeDir )

Detect edges (amplitude and direction) using the Prewitt operator.


PrewittDir calculates an approximation of the first derivative of the image data and is used as an edge detector.
The filter is based on the following filter masks:

1 1 1
A= 0 0 0
−1 −1 −1

1 0 −1
B= 1 0 −1
1 0 −1

The result image contains the maximum response of the masks A and B. The edge directions are returned in
ImageEdgeDir, and are stored in 2-degree steps, i.e., an edge direction of x degrees with respect to the horizontal
axis is stored as x/2 in the edge direction image. Furthermore, the direction of the change of intensity is taken into
account. Let [Ex , Ey ] denote the image gradient. Then the following edge directions are returned as r/2:

intensity increase Ex /Ey

edge direction r
from bottom to top 0/+ 0
from lower right to upper left +/− ]0, 90[
from right to left +/0 90
from upper right to lower left +/+ ]90, 180[
from top to bottom 0/+ 180
from upper left to lower right −/+ ]180, 270[
from left to right +/0 270
from lower left to upper right −/− ]270, 360[

Points with edge amplitude 0 are assigned the edge direction 255 (undefined direction).
Parameter
. Image (input iconic) . . . . . . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, int2, uint2 )
Input image.
. ImageEdgeAmp (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX (
byte, int2, uint2 )
Edge amplitude (gradient magnitude) image.
. ImageEdgeDir (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX ( di-
rection )
Edge direction image.
Example

read_image(Image,’fabrik’)
prewitt_dir(Image,PrewittA,PrewittD)
threshold(PrewittA,Edges,128,255).

Result
PrewittDir always returns TRUE. If the input is empty the behaviour can be set via SetSystem
(’noObjectResult’,<Result>). If necessary, an exception handling is raised.
Parallelization Information
PrewittDir is reentrant and automatically parallelized (on tuple level, channel level, domain level).

HALCON/COM Reference Manual, 2008-5-13


3.4. EDGES 147

Possible Predecessors
BinomialFilter, GaussImage, SigmaImage, MedianImage, SmoothImage
Possible Successors
HysteresisThreshold, Threshold, GraySkeleton, NonmaxSuppressionDir, CloseEdges,
CloseEdgesLength
See also
BandpassImage, LaplaceOfGauss
Alternatives
EdgesImage, SobelDir, RobinsonDir, FreiDir, KirschDir
Module
Foundation

HImageX.Roberts ([in] String FilterType )


[out] HImageX ImageRoberts
void HOperatorSetX.Roberts ([in] IHObjectX Image,
[out] HUntypedObjectX ImageRoberts, [in] VARIANT FilterType )

Detect edges using the Roberts filter.


Roberts calculates the first derivative of an image and is used as an edge operator. If the following mask describes
a part of the image,

A B
C D

the different filter types are defined as follows:

’roberts_max’ max(|A − D|, |B − C|)


’gradient_max’ max(|A + B − (C + D)|, |A + C − (B + D)|)
’gradient_sum’ |A + B − (C + D)| + |A + C − (B + D)|

If an overflow occurs the result is clipped. The result of the operator is stored at the pixel with the coordinates of
“D”.
Parameter
. Image (input iconic) . . . . . . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, int2, uint2 )
Input image.
. ImageRoberts (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX (
byte, int2, uint2 )
Roberts-filtered result images.
. FilterType (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Filter type.
Default Value : ’gradient_sum’
List of values : FilterType ∈ {’roberts_max’, ’gradient_max’, ’gradient_sum’}
Example

read_image(Image,’fabrik’)
roberts(Image,Roberts,’roberts_max’)
threshold(Roberts,Margin,128,255).

Result
Roberts returns TRUE if all parameters are correct. If the input is empty the behaviour can be set via
SetSystem(’noObjectResult’,<Result>). If necessary, an exception handling is raised.
Parallelization Information
Roberts is reentrant and automatically parallelized (on tuple level, channel level, domain level).

HALCON 8.0.2
148 CHAPTER 3. FILTER

Possible Predecessors
BinomialFilter, GaussImage
Possible Successors
Threshold, Skeleton
See also
Laplace, HighpassImage, BandpassImage
Alternatives
EdgesImage, SobelAmp, FreiAmp, KirschAmp, PrewittAmp
Module
Foundation

[out] HImageX ImageEdgeAmp HImageX.RobinsonAmp ( )


void HOperatorSetX.RobinsonAmp ([in] IHObjectX Image,
[out] HUntypedObjectX ImageEdgeAmp )

Detect edges (amplitude) using the Robinson operator.


RobinsonAmp calculates an approximation of the first derivative of the image data and is used as an edge detector.
In RobinsonAmp the following four of the originally proposed eight 3 × 3 filter masks are convolved with the
image. The other four masks are obtained by a multiplication by -1. All masks contain only the values 0,1,-1,2,-2.

−1 0 1
−2 0 2
−1 0 1

2 1 0
1 0 −1
0 −1 −2
0 1 2
−1 0 1
−2 −1 0
1 2 1
0 0 0
−1 −2 −1

The result image contains the maximum response of all masks.


Parameter
. Image (input iconic) . . . . . . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, int2, uint2 )
Input image.
. ImageEdgeAmp (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX (
byte, int2, uint2 )
Edge amplitude (gradient magnitude) image.
Example

read_image(Image,’fabrik’)
robinson_amp(Image,Robinson_amp)
threshold(Robinson_amp,Edges,128,255).

Result
RobinsonAmp always returns TRUE. If the input is empty the behaviour can be set via SetSystem
(’noObjectResult’,<Result>). If necessary, an exception handling is raised.
Parallelization Information
RobinsonAmp is reentrant and automatically parallelized (on tuple level, channel level, domain level).

HALCON/COM Reference Manual, 2008-5-13


3.4. EDGES 149

Possible Predecessors
BinomialFilter, GaussImage, SigmaImage, MedianImage, SmoothImage
See also
BandpassImage, LaplaceOfGauss
Alternatives
SobelAmp, FreiAmp, PrewittAmp, RobinsonAmp, Roberts
Module
Foundation

[out] HImageX ImageEdgeAmp HImageX.RobinsonDir


([out] HImageX ImageEdgeDir )
void HOperatorSetX.RobinsonDir ([in] IHObjectX Image,
[out] HUntypedObjectX ImageEdgeAmp, [out] HUntypedObjectX ImageEdgeDir )

Detect edges (amplitude and direction) using the Robinson operator.


RobinsonDir calculates an approximation of the first derivative of the image data and is used as an edge detector.
In RobinsonAmp the following four of the originally proposed eight 3 × 3 filter masks are convolved with the
image. The other four masks are obtained by a multiplication by -1. All masks contain only the values 0,1,-1,2,-2.

−1 0 1
−2 0 2
−1 0 1

2 1 0
1 0 −1
0 −1 −2
0 1 2
−1 0 1
−2 −1 0
1 2 1
0 0 0
−1 −2 −1

The result image contains the maximum response of all masks. The edge directions are returned in
ImageEdgeDir, and are stored as x/2. They correspond to the direction of the mask yielding the maximum
response.
Parameter

. Image (input iconic) . . . . . . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, int2, uint2 )


Input image.
. ImageEdgeAmp (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX (
byte, int2, uint2 )
Edge amplitude (gradient magnitude) image.
. ImageEdgeDir (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX ( di-
rection )
Edge direction image.
Example

read_image(Image,’fabrik’)
robinson_dir(Image,Robinson_dirA,Robinson_dirD)
threshold(Robinson_dirA,Res,128,255).

HALCON 8.0.2
150 CHAPTER 3. FILTER

Result
RobinsonDir always returns TRUE. If the input is empty the behaviour can be set via SetSystem
(’noObjectResult’,<Result>). If necessary, an exception handling is raised.
Parallelization Information
RobinsonDir is reentrant and automatically parallelized (on tuple level, channel level, domain level).
Possible Predecessors
BinomialFilter, GaussImage, SigmaImage, MedianImage, SmoothImage
Possible Successors
HysteresisThreshold, Threshold, GraySkeleton, NonmaxSuppressionDir, CloseEdges,
CloseEdgesLength
See also
BandpassImage, LaplaceOfGauss
Alternatives
EdgesImage, SobelDir, KirschDir, PrewittDir, FreiDir
Module
Foundation

[out] HImageX EdgeAmplitude HImageX.SobelAmp ([in] String FilterType,


[in] VARIANT Size )
void HOperatorSetX.SobelAmp ([in] IHObjectX Image,
[out] HUntypedObjectX EdgeAmplitude, [in] VARIANT FilterType,
[in] VARIANT Size )

Detect edges (amplitude) using the Sobel operator.


SobelAmp calculates first derivative of an image and is used as an edge detector. The filter is based on the
following filter masks:

1 2 1
A= 0 0 0
−1 −2 −1

1 0 −1
B= 2 0 −2
1 0 −1

These masks are used differently, according to the selected filter type. (In the following, a und b denote the results
of convolving an image with A und B for one particular pixel.)

’sum_sqrt’ a2 + b2 /4
’sum_abs’ (|a| + |b|)/4
’thin_sum_abs’ (thin(|a|) + thin(|b|))/4
’thin_max_abs’ max(thin(|a|), thin(|b|))/4
’x’ b/4
’y’ a/4

Here, thin(x) is equal to x for a vertical maximum (mask A) and a horizontal maximum (mask B), respectively,
and 0 otherwise. Thus, for ’thin_sum_abs’ and ’thin_max_abs’ the gradient image is thinned. For the filter types
’x’ and ’y’ if the input image is of type byte the output image is of type int1, of type int2 otherwise. For a Sobel
operator with size 3 × 3, the corresponding filters A and B are applied directly, while for larger filter sizes the input
image is first smoothed using a Gaussian filter (see GaussImage) or a binomial filter (see BinomialFilter)
of size Size-2. The Gaussian filter is selected for the above values of FilterType. Here, Size = 5, 7, 9, 11, or
13 must be used. The binomial filter is selected by appending ’_binomial’ to the above values of FilterType.
Here, Size can be selected between 5 and 39. Furthermore, it is possible to select different amounts of smoothing
the the column and row direction by passing two values in Size. Here, the first value of Size corresponds
to the mask width (smoothing in the column direction), while the second value corresponds to the mask height

HALCON/COM Reference Manual, 2008-5-13


3.4. EDGES 151

(smoothing in the row direction) of the binomial filter. The binomial filter can only be used for images of type
byte and uint2. Since smoothing reduces the edge amplitudes, in this case the edge amplitudes are multiplied by a
factor of 2 to prevent information loss. Therefore,

sobel_amp(I,E,Dir,FilterTyp,S)

for Size > 3 is conceptually equivalent to

scale_image(I,F,2,0)
gauss_image(F,G,S-2)
sobel_amp(G,E,FilterType,3)

or to

scale_image(I,F,2,0)
binomial_filter(F,G,S[0]-2,S[1]-2)
sobel_amp(G,E,FilterType,3).

For SobelAmp special optimizations are implemented FilterType = 0 sum_abs 0 that use SIMD technology.
The actual application of these special optimizations is controlled by the system parameter ’mmx_enable’ (see
SetSystem). If ’mmx_enable’ is set to ’true’ (and the SIMD instruction set is available), the internal calculations
are performed using SIMD technology. Note that SIMD technology performs best on large, compact input regions.
Depending on the input region and the capabilities of the hardware the execution of SobelAmp might even take
significantly more time with SIMD technology than without.
Parameter
. Image (input iconic) . . . . . . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, int2, uint2 )
Input image.
. EdgeAmplitude (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX (
int1, int2, uint2 )
Edge amplitude (gradient magnitude) image.
. FilterType (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Filter type.
Default Value : ’sum_abs’
List of values : FilterType ∈ {’sum_abs’, ’thin_sum_abs’, ’thin_max_abs’, ’sum_sqrt’, ’x’, ’y’,
’sum_abs_binomial’, ’thin_sum_abs_binomial’, ’thin_max_abs_binomial’, ’sum_sqrt_binomial’,
’x_binomial’, ’y_binomial’}
. Size (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Size of filter mask.
Default Value : 3
List of values : Size ∈ {3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39}
Example

read_image(Image,’fabrik’)
sobel_amp(Image,Amp,’sum_abs’,3)
threshold(Amp,Edg,128,255).

Result
SobelAmp returns TRUE if all parameters are correct. If the input is empty the behaviour can be set via
SetSystem(’noObjectResult’,<Result>). If necessary, an exception handling is raised.
Parallelization Information
SobelAmp is reentrant and automatically parallelized (on tuple level, channel level, domain level).
Possible Predecessors
BinomialFilter, GaussImage, MeanImage, AnisotropicDiffusion, SigmaImage
Possible Successors
Threshold, NonmaxSuppressionAmp, GraySkeleton

HALCON 8.0.2
152 CHAPTER 3. FILTER

See also
Laplace, HighpassImage, BandpassImage
Alternatives
FreiAmp, Roberts, KirschAmp, PrewittAmp, RobinsonAmp
Module
Foundation

[out] HImageX EdgeAmplitude HImageX.SobelDir


([out] HImageX EdgeDirection, [in] String FilterType, [in] VARIANT Size )
void HOperatorSetX.SobelDir ([in] IHObjectX Image,
[out] HUntypedObjectX EdgeAmplitude, [out] HUntypedObjectX EdgeDirection,
[in] VARIANT FilterType, [in] VARIANT Size )

Detect edges (amplitude and direction) using the Sobel operator.


SobelDir calculates first derivative of an image and is used as an edge detector. The filter is based on the
following filter masks:

1 2 1
A= 0 0 0
−1 −2 −1

1 0 −1
B= 2 0 −2
1 0 −1

These masks are used differently, according to the selected filter type. (In the following, a und b denote the results
of convolving an image with A und B for one particular pixel.)

’sum_sqrt’ a2 + b2 /4
’sum_abs’ (|a| + |b|)/4

For a Sobel operator with size 3 × 3, the corresponding filters A and B are applied directly, while for larger
filter sizes the input image is first smoothed using a Gaussian filter (see GaussImage) or a binomial filter (see
BinomialFilter) of size Size-2. The Gaussian filter is selected for the above values of FilterType. Here,
Size = 5, 7, 9, 11, or 13 must be used. The binomial filter is selected by appending ’_binomial’ to the above values
of FilterType. Here, Size can be selected between 5 and 39. Furthermore, it is possible to select different
amounts of smoothing the the column and row direction by passing two values in Size. Here, the first value of
Size corresponds to the mask width (smoothing in the column direction), while the second value corresponds to
the mask height (smoothing in the row direction) of the binomial filter. The binomial filter can only be used for
images of type byte and uint2. Since smoothing reduces the edge amplitudes, in this case the edge amplitudes are
multiplied by a factor of 2 to prevent information loss. Therefore,

sobel_dir(I:Amp,Dir:FilterTyp,S:)

for Size > 3 is conceptually equivalent to

scale_image(I,F,2,0)
gauss_image(F,G,S-2)
sobel_dir(G,Amp,Dir,FilterType,3:)

or to

scale_image(I,F,2,0)
binomial_filter(F,G,S[0]-2,S[1]-2)
sobel_dir(G,Amp,Dir,FilterType,3:).

HALCON/COM Reference Manual, 2008-5-13


3.4. EDGES 153

The edge directions are returned in EdgeDirection, and are stored in 2-degree steps, i.e., an edge direction of x
degrees with respect to the horizontal axis is stored as x/2 in the edge direction image. Furthermore, the direction
of the change of intensity is taken into account. Let [Ex , Ey ] denote the image gradient. Then the following edge
directions are returned as r/2:

intensity increase Ex /Ey

edge direction r
from bottom to top 0/+ 0
from lower right to upper left +/− ]0, 90[
from right to left +/0 90
from upper right to lower left +/+ ]90, 180[
from top to bottom 0/+ 180
from upper left to lower right −/+ ]180, 270[
from left to right +/0 270
from lower left to upper right −/− ]270, 360[

Points with edge amplitude 0 are assigned the edge direction 255 (undefined direction).
Parameter
. Image (input iconic) . . . . . . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, int2, uint2 )
Input image.
. EdgeAmplitude (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX (
byte, int2, uint2 )
Edge amplitude (gradient magnitude) image.
. EdgeDirection (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX (
direction )
Edge direction image.
. FilterType (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Filter type.
Default Value : ’sum_abs’
List of values : FilterType ∈ {’sum_abs’, ’sum_sqrt’, ’sum_abs_binomial’, ’sum_sqrt_binomial’}
. Size (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Size of filter mask.
Default Value : 3
List of values : Size ∈ {3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39}
Example

read_image(Image,’fabrik’)
sobel_dir(Image,Amp,Dir,’sum_abs’,3)
threshold(Amp,Edg,128,255).

Result
SobelDir returns TRUE if all parameters are correct. If the input is empty the behaviour can be set via
SetSystem(’noObjectResult’,<Result>). If necessary, an exception handling is raised.
Parallelization Information
SobelDir is reentrant and automatically parallelized (on tuple level, channel level).
Possible Predecessors
BinomialFilter, GaussImage, MeanImage, AnisotropicDiffusion, SigmaImage
Possible Successors
NonmaxSuppressionDir, HysteresisThreshold, Threshold
See also
Roberts, Laplace, HighpassImage, BandpassImage
Alternatives
EdgesImage, FreiDir, KirschDir, PrewittDir, RobinsonDir
Module
Foundation

HALCON 8.0.2
154 CHAPTER 3. FILTER

3.5 Enhancement
[out] HImageX CorrectedImages HImageX.AdjustMosaicImages
([in] VARIANT From, [in] VARIANT To, [in] long ReferenceImage,
[in] VARIANT HomMatrices2D, [in] String EstimationMethod,
[in] String EstimateParameters, [in] String OECFModel )
void HOperatorSetX.AdjustMosaicImages ([in] IHObjectX Images,
[out] HUntypedObjectX CorrectedImages, [in] VARIANT From, [in] VARIANT To,
[in] VARIANT ReferenceImage, [in] VARIANT HomMatrices2D,
[in] VARIANT EstimationMethod, [in] VARIANT EstimateParameters,
[in] VARIANT OECFModel )

Automatic color correction of panorama images.


AdjustMosaicImages performs the radiometric adjustment of images in panoramas. The images to be cor-
rected have to be passed in Images, the corrected images will be returned in CorrectedImages.
The parameters From and To must contain the source and destination indices of all image pairs in the panorama.
The projective 3x3-matrix of each image pair has to be passed in HomMatrices2D. The image, which will be
used as the reference for brightness and white balance, is selected with the parameter ReferenceImage.
EstimationMethod is used for choosing whether a fast but less accurate, or a slower but more accurate
determination method should be used. This is done by setting EstimationMethod either to ’standard’ or
’gold_standard’. The availability of the individual method is depending on the selected EstimateParameters,
which determines the model to be used for estimating the radiometric adjustment terms. It is always pos-
sible to determine the amount of vignetting in the images by selecting ’vignetting’. However, if selected,
EstimationMethod must be set to ’gold_standard’. For the remainder of the radiometric adjustment three
different options are available:
1. Image adjustment with the additive model. This should only be used to adjust images with very small differences
in exposure or white balance. To choose this method, EstimateParameters must be set to ’add_gray’. This
model can be selected either exclusively and only with EstimationMethod = ’standard’ or in combination
with EstimateParameters = ’vignetting’ and only with EstimationMethod = ’gold_standard’.
2. Image adjustment with the linear model. In this model, images are expected to be taken with a camera using
a linear transfer function. The adjustment terms are consequently represented as multiplication factors. To select
this model, EstimateParameters must be set to ’mult_gray’. It can be called with EstimationMethod
= ’standard’ or EstimationMethod = ’gold_standard’. A combined call with EstimateParameters =
’vignetting’ is also possible, EstimationMethod must be set to ’gold_standard’ in that case.
3. Image adjustment with the calibrated model. In this model, images are assumed to be taken with a camera using
a nonlinear transfer function. A function of the OECF class selected with OECFModel is used to approximate
the actually used OECF in the process of image acquisition. As with the linear model, the correction terms
are represented as multiplication factors. This model can be selected by choosing EstimateParameters =
[’mult_gray’,’response’] and must be called with EstimationMethod = ’gold_standard’. It is possible to
determine the amount of vignetting as well in this case by choosing EstimateParameters = ’vignetting’.
This model is similar to the linear model. However, in this case the camera may have a nonlinear response. This
means that before the gray values of the images can be multiplied by their respective correction factor, the gray
values must be backprojected to a linear response. To do so, the camera’s response must be determined. Since the
response usually does not change over an image sequence, this parameter is assumed to be constant throughout the
whole image sequence.
Any kind of function could be considered to be used as an OECF. As in the operator
RadiometricSelfCalibration, a polynomial fitting might be used, but for typical images in a mo-
saicking application this would not work very well. The reason for this is that polynomial fitting has too many
parameters that need to be determined. Instead, only simpler types of response functions can be estimated.
Currently, only so-called Laguerre-functions are available.
The response of a Laguerre-type OECF is determined by only one parameter called Phi. In a first step, the whole
gray value spectrum (in case of 8bit images the values 0 to 255) is converted to floating point numbers in the
interval [0:1]. Then, the OECF backprojection is calculated based on this and the resulting gray values are once
again converted to the original interval.
The inverse transform of the gray values back to linear values based on a Laguerre-type OECF is described by the
following equation:

HALCON/COM Reference Manual, 2008-5-13


3.5. ENHANCEMENT 155

2 P hi · sin(π · I_nl)
I_l = I_nl + · arctan( )
π 1 − P hi · cos(π · I_nl)

with I_l the linear gray value and I_nl the (nonlinear) gray value.
The parameter OECFModel is only used if the calibrated model has been chosen. Otherwise, any input for
OECFModel will be ignored.
The parameter EstimateParameters can also be used to influence the performance and memory consumption
of the operator. With ’no_cache’ the internal caching mechanism can be disabled. This switch only has and influ-
ence if EstimationMethod is set to ’gold_standard’. Otherwise this switch will be ignored. When disabling
the internal caching, the operator uses far less memory, but therefore calculates the corresponding grayvalue pairs
in each iteration of the minimization algorithm again. Therefore, disabling caching is only advisable if all physical
memory is used up at some point of the calculation and the operating system starts using swap space.
A second option to inluence the performance is using subsampling. When setting EstimateParameters to
’subsampling_2’, images are internally zoomed down by a factor of 2. Despite the suggested value list, not only
factors of 2 and 4 are available, but any integer number might be specified by appending it to subsampling_ in
EstimateParameters. With this, the amount of image data is tremendously reduced, which leads to a much
faster computation of the internal minimization. In fact, using moderate subsampling might even lead to better
results since it also decreases the influence of slightly misaligned pixels. Although subsampling also influences
the minimization if EstimationMethod is set to ’standard’, it is mostly useful for ’gold_standard’.
Some more general remarks on using adjust_mosaic_images in applications:

• Estimation of vignetting will only work well if significant vignetting is visible in the images. Otherwise, the
operator may lead to erratic results.
• Estimation of the response is rather slow because the problem is quite complex. Therefore, it is advisable not
to determine the response in time critical applications. Apart from this, the response can only be determined
correctly if there are relatively large brightness differences between the images.
• It is not possible to correct saturation. If there are saturated areas in an image, they will remain saturated.
• adjust_mosaic_images can only be used to correct different brightness in images, which is caused by different
exposure (shutter time, aperture) or different light intensity. It cannot be used to correct brightness differences
based on inhomogeneous illumination within each image.

Parameter

. Images (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . (multichannel-)image ; HImageX / IHObjectX ( byte )


Input images.
. CorrectedImages (output iconic) . . . . . . (multichannel-)image ; HImageX / HUntypedObjectX ( byte )
Output images.
. From (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
List of source images.
. To (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
List of destination images.
. ReferenceImage (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Reference image.
. HomMatrices2D (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Projective matrices.
. EstimationMethod (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Estimation algorithm for the correction.
Default Value : ’standard’
List of values : EstimationMethod ∈ {’standard’, ’gold_standard’}
. EstimateParameters (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Parameters to be estimated.
Default Value : [’mult_gray’]
List of values : EstimateParameters ∈ {’add_gray’, ’mult_gray’, ’response’, ’vignetting’,
’subsampling_2’, ’subsampling_4’, ’no_cache’}

HALCON 8.0.2
156 CHAPTER 3. FILTER

. OECFModel (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT


Model of OECF to be used.
Default Value : [’laguerre’]
List of values : OECFModel ∈ {’laguerre’}
Example

* For the input data to stationary_camera_self_calibration, please


* refer to the example for stationary_camera_self_calibration.
stationary_camera_self_calibration (4, 640, 480, 1, From, To,
HomMatrices2D, Rows1, Cols1,
Rows2, Cols2, NumMatches,
’gold_standard’,
[’focus’,’principal_point’],
’true’, CameraMatrix, Kappa,
RotationMatrices, X, Y, Z, Error)
adjust_mosaic_images(Images,CorrectedImages,From,To,1,HomMatrices2D,
’gold_standard’,[’mult_gray’,’response’])

Result
If the parameters are valid, the operator AdjustMosaicImages returns the value TRUE. If necessary an
exception handling is raised.
Parallelization Information
AdjustMosaicImages is reentrant and processed without parallelization.
Possible Predecessors
StationaryCameraSelfCalibration
Possible Successors
GenSphericalMosaic
References
David Hasler, Sabine S"usstrunk: Mapping colour in image stitching applications. Journal of Visual Communica-
tion and Image Representation, 15(1):65-90, 2004.
Module
Foundation

[out] HImageX ImageCED HImageX.CoherenceEnhancingDiff


([in] double Sigma, [in] double Rho, [in] double Theta, [in] long Iterations )
void HOperatorSetX.CoherenceEnhancingDiff ([in] IHObjectX Image,
[out] HUntypedObjectX ImageCED, [in] VARIANT Sigma, [in] VARIANT Rho,
[in] VARIANT Theta, [in] VARIANT Iterations )

Perform a coherence enhancing diffusion of an image.


The operator CoherenceEnhancingDiff performs an anisotropic diffusion process on the input image
Image to increase the coherence of the image structures contained in Image. In particular, noncontinuous image
edges are connected by diffusion, without being smoothed perpendicular to their dominating direction. For this,
CoherenceEnhancingDiff uses the anisotropic diffusion equation

ut = div(G(u)∇u)

formulated by Weickert. With a 2 × 2 coefficient matrix G that depends on the gray values in Image, this is an
enhancement of the mean curvature flow or intrinsic heat equation

∇u
ut = div( )|∇u| = curv(u)|∇u|
|∇u|

HALCON/COM Reference Manual, 2008-5-13


3.5. ENHANCEMENT 157

on the gray value function u defined by the input image Image at a time t0 = 0. The smoothing operator
MeanCurvatureFlow is a direct application of the mean curvature flow equation. The discrete diffusion equa-
tion is solved in Iterations time steps of length Theta, so that the output image ImageCED contains the
gray value function at the time Iterations · Theta.
To detect the edge direction more robustly, in particular on noisy input data, an additional isotropic smoothing
step can precede the computation of the gray value gradients. The parameter Sigma determines the magnitude of
the smoothing by means of the standard deviation of a corresponding Gaussian convolution kernel, as used in the
operator IsotropicDiffusion for isotropic image smoothing.
While the matrix G is given by

1
GM CF (u) = I − ∇u(∇u)T ,
|∇u|2

in the case of the operator MeanCurvatureFlow, where I denotes the unit matrix, GMCF is again smoothed
componentwise by a Gaussian filter of standard deviation Rho for CoherenceEnhancingDiff. Then, the
final coefficient matrix

GCED = g1 (λ1 − λ2 )2 w1 (w1 )T + g2 (λ1 − λ2 )2 w2 (w2 )T


 

is constructed from the eigenvalues λ1 , λ2 and eigenvectors w1 , w2 of the resulting intermediate matrix, where the
functions

g1 (p) = 0.001  
−1
g2 (p) = 0.001 + 0.999 exp
p

were determined empirically and taken from the publication of Weickert.


Hence, the diffusion direction in MeanCurvatureFlow is only determined by the local direction of the gray
value gradient, while GCED considers the macroscopic structure of the image objects on the scale Rho and the
magnitude of the diffusion in CoherenceEnhancingDiff depends on how well this structure is defined.
Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte, uint2, real )


Input image.
. ImageCED (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX
Output image.
. Sigma (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Smoothing for derivative operator.
Default Value : 0.5
Suggested values : Sigma ∈ {0.0, 0.1, 0.5, 1.0}
Restriction : (Sigma ≥ 0)
. Rho (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Smoothing for diffusion coefficients.
Default Value : 3.0
Suggested values : Rho ∈ {0.0, 1.0, 3.0, 5.0, 10.0, 30.0}
Restriction : (Rho ≥ 0)
. Theta (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Time step.
Default Value : 0.5
Suggested values : Theta ∈ {0.1, 0.2, 0.3, 0.4, 0.5}
Restriction : ((0 < T heta) ≤ 0.5)
. Iterations (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of iterations.
Default Value : 10
Suggested values : Iterations ∈ {1, 5, 10, 20, 50, 100, 500}
Restriction : (Iterations ≥ 1)

HALCON 8.0.2
158 CHAPTER 3. FILTER

Parallelization Information
CoherenceEnhancingDiff is reentrant and automatically parallelized (on tuple level).
References
J. Weickert, V. Hlavac, R. Sara; “Multiscale texture enhancement”; Computer analysis of images and patterns,
Lecture Notes in Computer Science, Vol. 970, pp. 230-237; Springer, Berlin; 1995.
J. Weickert, B. ter Haar Romeny, L. Florack, J. Koenderink, M. Viergever; “A review of nonlinear diffusion
filtering”; Scale-Space Theory in Computer Vision, Lecture Notes in Comp. Science, Vol. 1252, pp. 3-28;
Springer, Berlin; 1997.
Module
Foundation

[out] HImageX ImageEmphasize HImageX.Emphasize ([in] long MaskWidth,


[in] long MaskHeight, [in] double Factor )
void HOperatorSetX.Emphasize ([in] IHObjectX Image,
[out] HUntypedObjectX ImageEmphasize, [in] VARIANT MaskWidth,
[in] VARIANT MaskHeight, [in] VARIANT Factor )

Enhance contrast of the image.


The operator Emphasize emphasizes high frequency areas of the image (edges and corners). The resulting
images appears sharper.
First the procedure carries out a filtering with the low pass ( MeanImage). The resulting gray values (res) are
calculated from the obtained gray values (mean) and the original gray values (orig) as follows:

res := round((orig − mean) ∗ Factor) + orig

Factor serves as measurement of the increase in contrast. The division frequency is determined via the size of
the filter matrix: The larger the matrix, the lower the disivion frequency.
As an edge treatment the gray values are mirrored at the edges of the image. Overflow and/or underflow of gray
values is clipped.
Attention

Parameter

. Image (input iconic) . . . . . . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, int2, uint2 )


Image to be enhanced.
. ImageEmphasize (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX (
byte, int2, uint2 )
contrast enhanced image.
. MaskWidth (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; long / VARIANT
Width of low pass mask.
Default Value : 7
Suggested values : MaskWidth ∈ {3, 5, 7, 9, 11, 15, 21, 25, 31, 39}
Typical range of values : 3 ≤ MaskWidth ≤ 3
Minimum Increment : 2
Recommended Increment : 2
. MaskHeight (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; long / VARIANT
Height of the low pass mask.
Default Value : 7
Suggested values : MaskHeight ∈ {3, 5, 7, 9, 11, 15, 21, 25, 31, 39}
Typical range of values : 3 ≤ MaskHeight ≤ 3
Minimum Increment : 2
Recommended Increment : 2

HALCON/COM Reference Manual, 2008-5-13


3.5. ENHANCEMENT 159

. Factor (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT


Intensity of contrast emphasis.
Default Value : 1.0
Suggested values : Factor ∈ {0.3, 0.5, 0.7, 1.0, 1.4, 1.8, 2.0}
Typical range of values : 0.0 ≤ Factor ≤ 0.0(sqrt)
Minimum Increment : 0.01
Recommended Increment : 0.2
Restriction : ((0 < F actor) ∧ (F actor < 20))
Example

read_image(Image,’mreut’)
disp_image(Image,WindowHandle)
draw_region(Region,WindowHandle)
reduce_domain(Image,Region,Mask)
emphasize(Mask,Sharp,7,7,2.0)
disp_image(Sharp,WindowHandle).

Result
If the parameter values are correct the operator Emphasize returns the value TRUE The behav-
ior in case of empty input (no input images available) is set via the operator SetSystem(::
’noObjectResult’,<Result>:). If necessary an exception handling is raised.
Parallelization Information
Emphasize is reentrant and automatically parallelized (on tuple level, channel level, domain level).
Possible Successors
DispImage
See also
MeanImage, HighpassImage
Alternatives
MeanImage, SubImage, Laplace, AddImage
Module
Foundation

HImageX.EquHistoImage ( )
[out] HImageX ImageEquHisto
void HOperatorSetX.EquHistoImage ([in] IHObjectX Image,
[out] HUntypedObjectX ImageEquHisto )

Histogram linearisation of images


The operator EquHistoImage enhances the contrast. The starting point is the histogram of the input images.
The following simple gray value transformation f (g) is carried out for byte images:
X
f (g) = 255 h(x)
x=0...g

h(x) describes the relative frequency of the occurrence of the gray value x. For uint2 images, the only difference
is that the value 255 is replaced with a different maximum value. The maximum value is computed from the
number of significant bits stored with the input image, provided that this value is set. If not, the value of the system
parameter ’int2_bits’ is used (see SetSystem), if this value is set (i.e., different from -1). If none of the two
values is set, the number of significant bits is set to 16.
This transformation linearises the cumulative histogram. Maxima in the original histogram are "‘spreaded"’ and
thus the contrast in image regions with these frequently occuring gray values is increased. Supposedly homogenous
regions receive more easily visible structures. On the other hand, of course, the noise in the image increases cor-
respondlingly. Minima in the original histogram are dually "‘compressed"’. The transformed histogram contains
gaps, but the remaining gray values used occur approximately at the same frequency ("‘histogram equalization"’).

HALCON 8.0.2
160 CHAPTER 3. FILTER

Attention
The operator EquHistoImage primarily serves for optical processing of images for a human viewer. For
example, the (local) contrast spreading can lead to a detection of fictitious edges.
Parameter
. Image (input iconic) . . . . . . . . . . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, uint2 )
Image to be enhanced.
. ImageEquHisto (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX (
byte, uint2 )
Image with linearized gray values.
Parallelization Information
EquHistoImage is reentrant and automatically parallelized (on tuple level, channel level).
Possible Successors
DispImage
See also
ScaleImage
Alternatives
ScaleImage, ScaleImageMax, Illuminate
References
R.C. Gonzales, P. Wintz: "‘Digital Image Processing"’; Second edition; Addison Wesley; 1987.
Module
Foundation

[out] HImageX ImageIlluminate HImageX.Illuminate ([in] long MaskWidth,


[in] long MaskHeight, [in] double Factor )
void HOperatorSetX.Illuminate ([in] IHObjectX Image,
[out] HUntypedObjectX ImageIlluminate, [in] VARIANT MaskWidth,
[in] VARIANT MaskHeight, [in] VARIANT Factor )

Illuminate image.
The operator Illuminate enhances contrast. Very dark parts of the image are "‘illuminated"’ more strongly,
very light ones are "‘darkened"’. If orig is the original gray value and mean is the corresponding gray value of
the low pass filtered image detected via the operators MeanImage and filter size MaskHeight x MaskWidth.
For byte-images val equals 127, for int2-images and uint2-images val equals the median value. The resulting gray
value is new:

new := round((val − mean) ∗ Factor + orig)


The low pass should have rather large dimensions (30 x 30 to 200 x 200). Reasonable parameter combinations
might be:

MaskHeight MaskWidth Factor


40 40 0.55
100 100 0.7
150 150 0.8
i.e. the larger the low pass mask is chosen, the larger Factor should be as well.
The following "‘spotlight effect"’ should be noted: If, for example, a dark object is in front of a light wall the object
as well as the wall, which is already light in the immediate proximity of the object contours, are lightened by the
operator Illuminate. This corresponds roughly to the effect that is produced when the object is illuminated
by a strong spotlight. The same applies to light objects in front of a darker background. In this case, however, the
fictitious "‘spotlight"’ darkens objects.
Attention

HALCON/COM Reference Manual, 2008-5-13


3.5. ENHANCEMENT 161

Parameter

. Image (input iconic) . . . . . . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, int2, uint2 )


Image to be enhanced.
. ImageIlluminate (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX
( byte, int2, uint2 )
"‘Illuminated"’ image.
. MaskWidth (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; long / VARIANT
Width of low pass mask.
Default Value : 101
Suggested values : MaskWidth ∈ {31, 41, 51, 71, 101, 121, 151, 201}
Typical range of values : 3 ≤ MaskWidth ≤ 3
Minimum Increment : 2
Recommended Increment : 10
. MaskHeight (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; long / VARIANT
Height of low pass mask.
Default Value : 101
Suggested values : MaskHeight ∈ {31, 41, 51, 71, 101, 121, 151, 201}
Typical range of values : 3 ≤ MaskHeight ≤ 3
Minimum Increment : 2
Recommended Increment : 10
. Factor (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Scales the "‘correction gray value"’ added to the original gray values.
Default Value : 0.7
Suggested values : Factor ∈ {0.3, 0.5, 0.7, 1.0, 1.5, 2.0, 3.0, 5.0}
Typical range of values : 0.0 ≤ Factor ≤ 0.0
Minimum Increment : 0.01
Recommended Increment : 0.2
Restriction : ((0 < F actor) ∧ (F actor < 5))
Example

read_image(Image,’fabrik’)
disp_image(Image,WindowHandle)
illuminate(Image,Better,40,40,0.55)
disp_image(Better,WindowHandle).

Result
If the parameter values are correct the operator Illuminate returns the value TRUE The behav-
ior in case of empty input (no input images available) is set via the operator SetSystem(::
’noObjectResult’,<Result>:). If necessary an exception handling is raised.
Parallelization Information
Illuminate is reentrant and automatically parallelized (on tuple level, channel level, domain level).
Possible Successors
DispImage
See also
Emphasize, GrayHisto
Alternatives
ScaleImageMax, EquHistoImage, MeanImage, SubImage
Module
Foundation

HALCON 8.0.2
162 CHAPTER 3. FILTER

[out] HImageX ImageMCF HImageX.MeanCurvatureFlow ([in] double Sigma,


[in] double Theta, [in] long Iterations )
void HOperatorSetX.MeanCurvatureFlow ([in] IHObjectX Image,
[out] HUntypedObjectX ImageMCF, [in] VARIANT Sigma, [in] VARIANT Theta,
[in] VARIANT Iterations )

Apply the mean curvature flow to an image.


The operator MeanCurvatureFlow applies the mean curvature flow or intrinsic heat equatio

∇u
ut = div( )|∇u| = curv(u)|∇u|
|∇u|

to the gray value function u defined by the input image Image at a time t0 = 0. The discretized equation is solved
in Iterations time steps of length Theta, so that the output image contains the gray value function at the time
Iterations · Theta.
The mean curvature flow causes a smoothing of Image in the direction of the edges in the image, i.e. along the
contour lines of u, while perpendicular to the edge direction no smoothing is performed and hence the boundaries
of image objects are not smoothed. To detect the image direction more robustly, in particular on noisy input data,
an additional isotropic smoothing step can precede the computation of the gray value gradients. The parameter
Sigma determines the magnitude of the smoothing by means of the standard deviation of a corresponding Gaussian
convolution kernel, as used in the operator IsotropicDiffusion for isotropic image smoothing.
Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte, uint2, real )


Input image.
. ImageMCF (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX
Output image.
. Sigma (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Smoothing parameter for derivative operator.
Default Value : 0.5
Suggested values : Sigma ∈ {0.0, 0.1, 0.5, 1.0}
Restriction : (Sigma ≥ 0)
. Theta (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Time step.
Default Value : 0.5
Suggested values : Theta ∈ {0.1, 0.2, 0.3, 0.4, 0.5}
Restriction : ((0 < T heta) ≤ 0.5)
. Iterations (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of iterations.
Default Value : 10
Suggested values : Iterations ∈ {1, 5, 10, 20, 50, 100, 500}
Restriction : (Iterations ≥ 1)
Parallelization Information
MeanCurvatureFlow is reentrant and automatically parallelized (on tuple level).
References
M. G. Crandall, P. Lions; “Convergent Difference Schemes for Nonlinear Parabolic Equations and Mean Curvature
Motion”; Numer. Math. 75 pp. 17-41; 1996.
G. Aubert, P. Kornprobst; “Mathematical Problems in Image Processing”; Applied Mathematical Sciences 147;
Springer, New York; 2002.
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


3.5. ENHANCEMENT 163

HImageX.ScaleImageMax ( )
[out] HImageX ImageScaleMax
void HOperatorSetX.ScaleImageMax ([in] IHObjectX Image,
[out] HUntypedObjectX ImageScaleMax )

Maximum gray value spreading in the value range 0 to 255.


The operator ScaleImageMax calculates the minimum and maximum and scales the image to the maximum
value range of a byte image. This way the dynamics (value range) is fully exploited. The number of different gray
scales does not change, but in general the visual impression is enhanced. The gray values of images of the real,
int2, uint2 and int4 type are scaled to the range 0 to 255 and returned as byte images.
Attention
The output always is an image of the type byte.
Parameter

. Image (input iconic) . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, int2, uint2, int4,
real )
Image to be scaled.
. ImageScaleMax (output iconic) . . . . . . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte )
contrast enhanced image.
Parallelization Information
ScaleImageMax is reentrant and automatically parallelized (on tuple level, channel level).
Possible Successors
DispImage
See also
MinMaxGray, GrayHisto
Alternatives
EquHistoImage, ScaleImage, Illuminate, ConvertImageType
Module
Foundation

[out] HImageX SharpenedImage HImageX.ShockFilter ([in] double Theta,


[in] long Iterations, [in] String Mode, [in] double Sigma )
void HOperatorSetX.ShockFilter ([in] IHObjectX Image,
[out] HUntypedObjectX SharpenedImage, [in] VARIANT Theta,
[in] VARIANT Iterations, [in] VARIANT Mode, [in] VARIANT Sigma )

Apply a shock filter to an image.


The operator ShockFilter applies a shock filter to the input image Image to sharpen the edges contained in
it. The principle of the shock filter is based on the transport of the gray values of the image towards an edge from
both sides through dilation and erosion and satisfies the differential equation

ut = s |∇u|

on the function u defined by the gray values in Image at a time t0 = 0. The discretized equation is solved in
Iterations time steps of length Theta, so that the output image SharpenedImage contains the gray value
function at the time Iterations · Theta.
The decision between dilation and erosion is made using the sign function s ∈ {−1, 0, +1} on a conventional edge
detector. The detector of Canny
 
∇u ∇u
2
s = −sgn D u( , )
|∇u| |∇u|

is available with Mode = 0 canny 0 and the detector of Marr/Hildreth (the Laplace operator)

HALCON 8.0.2
164 CHAPTER 3. FILTER

s = −sgn(∆u)

can be selected by Mode = 0 laplace 0 .


To make the edge detection more robust, in particular on noisy images, it can be performed on a smoothed image
matrix. This is done by giving the standard deviation of a Gaussian kernel for convolution with the image matrix
in the parameter Sigma.
Parameter
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte, uint2, real )
Input image.
. SharpenedImage (output iconic) . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX
Output image.
. Theta (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Time step.
Default Value : 0.5
Suggested values : Theta ∈ {0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7}
Restriction : ((0 < T heta) ≤ 0.7)
. Iterations (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of iterations.
Default Value : 10
Suggested values : Iterations ∈ {1, 3, 10, 100}
Restriction : (Iterations ≥ 1)
. Mode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Type of edge detector.
Default Value : ’canny’
List of values : Mode ∈ {’laplace’, ’canny’}
. Sigma (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Smoothing of edge detector.
Default Value : 1.0
Suggested values : Sigma ∈ {0.0, 0.5, 1.0, 2.0, 5.0}
Restriction : (T heta ≥ 0)
Parallelization Information
ShockFilter is reentrant and automatically parallelized (on tuple level).
References
F. Guichard, J. Morel; “A Note on Two Classical Shock Filters and Their Asymptotics”; Michael Kerckhove (Ed.):
Scale-Space and Morphology in Computer Vision, LNCS 2106, pp. 75-84; Springer, New York; 2001.
G. Aubert, P. Kornprobst; “Mathematical Problems in Image Processing”; Applied Mathematical Sciences 147;
Springer, New York; 2002.
Module
Foundation

3.6 FFT
HImageX.ConvolFft ([in] HImageX ImageFilter )
[out] HImageX ImageConvol
void HOperatorSetX.ConvolFft ([in] IHObjectX ImageFFT,
[in] IHObjectX ImageFilter, [out] HUntypedObjectX ImageConvol )

Convolve an image with a filter in the frequency domain.


ConvolFft convolves two (Fourier-transformed) images in the frequency domain, i.e., the pixels of the complex
image ImageFFT are multiplied by the corresponding pixels of the filter ImageFilter.
Attention
The filtering is always done on the entire image, i.e., the region of the image is ignored.

HALCON/COM Reference Manual, 2008-5-13


3.6. FFT 165

Parameter
. ImageFFT (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( complex )
Complex input image.
. ImageFilter (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( real, complex )
Filter in frequency domain.
. ImageConvol (output iconic) . . . . . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX ( complex )
Result of applying the filter.
Example

gen_highpass(Highpass,0.2,’n’,’dc_edge’,Width,Height)
fft_generic(Image,ImageFFT,’to_freq’,-1,’none’,’dc_edge’,’complex’)
convol_fft(ImageFFT,Highpass:ImageConvol)
fft_generic(ImageConvol,ImageResult,’from_freq’,1,’none’,’dc_edge’,’byte’)

Result
ConvolFft returns TRUE if all parameters are correct. If the input is empty the behavior can be set via
SetSystem(::’noObjectResult’,<Result>:). If necessary, an exception handling is raised.
Parallelization Information
ConvolFft is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
FftImage, FftGeneric, RftGeneric, GenHighpass, GenLowpass, GenBandpass,
GenBandfilter
Possible Successors
PowerByte, PowerReal, PowerLn, FftImageInv, FftGeneric, RftGeneric
See also
GenGabor, GenHighpass, GenLowpass, GenBandpass, ConvolGabor, FftImageInv
Alternatives
ConvolGabor
Module
Foundation

[out] HImageX ImageResultGabor HImageX.ConvolGabor


([in] HImageX GaborFilter, [out] HImageX ImageResultHilbert )
void HOperatorSetX.ConvolGabor ([in] IHObjectX ImageFFT,
[in] IHObjectX GaborFilter, [out] HUntypedObjectX ImageResultGabor,
[out] HUntypedObjectX ImageResultHilbert )

Convolve an image with a Gabor filter in the frequency domain.


ConvolGabor convolves a Fourier-transformed image with a Gabor filter GaborFilter (see GenGabor)
and its Hilbert transform in the frequency domain. The result image is of type ’complex’.
Attention
The filtering is always done on the entire image, i.e., the region of the image is ignored.
Parameter
. ImageFFT (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( complex )
Input image.
. GaborFilter (input iconic) . . . . . . . . . . . . . . . . multichannel-image-array ; HImageX / IHObjectX ( real )
Gabor/Hilbert-Filter.
. ImageResultGabor (output iconic) . . . . . . . . image(-array) ; HImageX / HUntypedObjectX ( complex )
Result of the Gabor filter.
. ImageResultHilbert (output iconic) . . . . . image(-array) ; HImageX / HUntypedObjectX ( complex )
Result of the Hilbert filter.

HALCON 8.0.2
166 CHAPTER 3. FILTER

Example

gen_gabor(Filter,1.4,0.4,1.0,1.5,’n’,’dc_edge’,512,512)
fft_generic(Image,ImageFFT,’to_freq’,-1,’none’,’dc_edge’,’complex’)
convol_gabor(ImageFFT,Filter,Gabor,Hilbert,’dc_edge’)
fft_generic(Gabor,GaborInv,’from_freq’,1,’none’,’dc_edge’,’byte’)
fft_generic(Hilbert,HilbertInv,’from_freq’,1,’none’,’dc_edge’,’byte’)
energy_gabor(GaborInv,HilbertInv,Energy)

Result
ConvolGabor returns TRUE if all images are of correct type. If the input is empty the behavior can be set via
SetSystem(::’noObjectResult’,<Result>:). If necessary, an exception handling is raised.
Parallelization Information
ConvolGabor is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
FftImage, FftGeneric, GenGabor
Possible Successors
PowerByte, PowerReal, PowerLn, FftImageInv, FftGeneric
See also
ConvolImage
Alternatives
ConvolFft
Module
Foundation

[out] HImageX ImageCorrelation HImageX.CorrelationFft


([in] HImageX ImageFFT2 )
void HOperatorSetX.CorrelationFft ([in] IHObjectX ImageFFT1,
[in] IHObjectX ImageFFT2, [out] HUntypedObjectX ImageCorrelation )

Compute the correlation of two images in the frequency domain.


CorrelationFft calculates the correlation of the Fourier-transformed input images in the frequency do-
main. The correlation is calculated by multiplying ImageFFT1 with the complex conjugate of ImageFFT2.
It should be noted that in order to achieve a correct scaling of the correlation in the spatial domain, the operators
FftGeneric or RftGeneric with Norm = ’none’ must be used for the forward transform and FftGeneric
or RftGeneric with Norm = ’n’ for the reverse transform. If ImageFFT1 and ImageFFT2 contain the same
number of images, the corresponding images are correlated pairwise. Otherwise, ImageFFT2 must contain only
one single image. In this case, the correlation is performed for each image of ImageFFT1 with ImageFFT2 .
Attention
The filtering is always performed on the entire image, i.e., the domain of the image is ignored.
Parameter

. ImageFFT1 (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( complex )


Fourier-transformed input image 1.
. ImageFFT2 (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( complex )
Fourier-transformed input image 2.
Number of elements : ((ImageF F T 2 = ImageF F T 1) ∨ (ImageF F T 2 = 1))
. ImageCorrelation (output iconic) . . . . . . . . image(-array) ; HImageX / HUntypedObjectX ( complex )
Correlation of the input images in the frequency domain.
Example

HALCON/COM Reference Manual, 2008-5-13


3.6. FFT 167

/* Compute the auto-correlation of an image. */


get_image_pointer1(Image,Pointer,Type,Width,Height)
rft_generic(Image,ImageFFT,’to_freq’,’none’,’complex’,Width)
correlation_fft(ImageFFT,ImageFFT:Correlation)
rft_generic(Correlation,AutoCorrelation,’from_freq’,’n’,’real’,Width)

Result
ConvolFft returns TRUE if all parameters are correct. If the input is empty the behavior can be set via
SetSystem(::’noObjectResult’,<Result>:). If necessary, an exception handling is raised.
Parallelization Information
CorrelationFft is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
FftGeneric, FftImage, RftGeneric
Possible Successors
FftGeneric, FftImageInv, RftGeneric
Module
Foundation

HImageX.EnergyGabor ([in] HImageX ImageHilbert )


[out] HImageX Energy
void HOperatorSetX.EnergyGabor ([in] IHObjectX ImageGabor,
[in] IHObjectX ImageHilbert, [out] HUntypedObjectX Energy )

Calculate the energy of a two-channel image.


EnergyGabor calculates the local contrast (Energy) of the two input images. The energy of the resulting image
is then defined as

Energy = channel12 + channel22 .

Often the calculation of the energy is preceded by the convolution of an image with a Gabor filter and the
Hilbert transform of the Gabor filter (see ConvolGabor). In this case, the first channel of the image passed
to EnergyGabor is the Gabor-filtered image, transformed back into the spatial domain (see FftImageInv),
and the second channel the result of the convolution with the Hilbert transform, also transformed back into the
spatial domain. The local energy is a measure for the local contrast of structures (e.g., edges and lines) in the
image.
Parameter

. ImageGabor (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte, real )


1st channel of input image (usually: Gabor image).
. ImageHilbert (input iconic) . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte, real )
2nd channel of input image (usually: Hilbert image).
. Energy (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX ( real )
Image containing the local energy.
Result
EnergyGabor returns TRUE if all parameters are correct. If the input is empty the behavior can be set via
SetSystem(::’noObjectResult’,<Result>:). If necessary, an exception handling is raised.
Parallelization Information
EnergyGabor is reentrant and automatically parallelized (on tuple level, domain level).
Possible Predecessors
GenGabor, ConvolGabor, FftImageInv
Module
Foundation

HALCON 8.0.2
168 CHAPTER 3. FILTER

[out] HImageX ImageFFT HImageX.FftGeneric ([in] String Direction,


[in] long Exponent, [in] String Norm, [in] String Mode,
[in] String ResultType )
void HOperatorSetX.FftGeneric ([in] IHObjectX Image,
[out] HUntypedObjectX ImageFFT, [in] VARIANT Direction,
[in] VARIANT Exponent, [in] VARIANT Norm, [in] VARIANT Mode,
[in] VARIANT ResultType )

Compute the fast Fourier transform of an image.


FftGeneric computes the fast Fourier transform of the input image Image. Because several definitions of the
forward and reverse transforms exist in the literature, this operator allows the user to select the most convenient
definition.
The general definition of a Fourier transform is as follows:
M −1 N −1
1 X X s2πi(km/M +ln/N )
F (m, n) = e f (k, l)
c
k=0 l=0

Opinions vary on whether the sign s in the exponent should be set to 1 or -1 for the forward transform, i.e., the
transform for going to the frequency domain. There is also disagreement on the magnitude of the normalizing
factor c. This is √
sometimes set to 1 for the forward transform, sometimes to M N , and sometimes (in case of the
unitary FFT) to M N . Especially in image processing applications the DC term is shifted to the center of the
image.
FftGeneric allows to select these choices individually. The parameter Direction allows to select the logical
direction of the FFT. (This parameter is not unnecessary; it is needed to discern how to shift the image if the
DC term should rest in the center of the image.) Possible values are ’to_freq’ and ’from_freq’. The parameter
Exponent is used to determine the sign of the exponent. It can be set to 1 or -1. The normalizing factor can be
set with Norm, and can take on the values ’none’, ’sqrt’ and ’n’. The parameter Mode determines the location of
the DC term of the FFT. It can be set to ’dc_center’ or ’dc_edge’.
In any case, the user must ensure the consistent use of the parameters. This means that the normalizing factors
used for the forward and backward transform must yield M N when multiplied, the exponents must be of opposite
sign, and Mode must be equal for both transforms.
A consistent combination is, for example (’to_freq’,-1,’n’,’dc_edge’) for the forward transform and
(’from_freq’,1,’none’,’dc_edge’) for the reverse transform. In this case, the FFT can be interpreted as interpo-
lation with trigonometric basis functions. Another possible combination is (’to_freq’,-1,’sqrt’,’dc_center’) and
(’from_freq’,1,’sqrt’,’dc_center’).
The parameter ResultType can be used to specify the result image type of the reverse transform (Direction
= ’from_freq’). In the forward transform (Direction = ’to_freq’), ResultType must be set to ’complex’.
Parameter
. Image (input iconic) . . . . . . image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2,
uint2, int4, real, complex )
Input image.
. ImageFFT (output iconic) . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, direction, cyclic,
int1, int2, uint2, int4, real, complex )
Fourier-transformed image.
. Direction (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Calculate forward or reverse transform.
Default Value : ’to_freq’
List of values : Direction ∈ {’to_freq’, ’from_freq’}
. Exponent (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Sign of the exponent.
Default Value : -1
List of values : Exponent ∈ {-1, 1}
. Norm (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Normalizing factor of the transform.
Default Value : ’sqrt’
List of values : Norm ∈ {’none’, ’sqrt’, ’n’}

HALCON/COM Reference Manual, 2008-5-13


3.6. FFT 169

. Mode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT


Location of the DC term in the frequency domain.
Default Value : ’dc_center’
List of values : Mode ∈ {’dc_center’, ’dc_edge’}
. ResultType (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Image type of the output image.
Default Value : ’complex’
List of values : ResultType ∈ {’complex’, ’byte’, ’int1’, ’int2’, ’uint2’, ’int4’, ’real’, ’direction’, ’cyclic’}
Result
FftGeneric returns TRUE if all parameters are correct. If the input is empty the behavior can be set via
SetSystem(::’noObjectResult’,<Result>:). If necessary, an exception handling is raised.
Parallelization Information
FftGeneric is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
OptimizeFftSpeed, ReadFftOptimizationData
Possible Successors
ConvolFft, ConvolGabor, ConvertImageType, PowerByte, PowerReal, PowerLn, PhaseDeg,
PhaseRad, EnergyGabor
Alternatives
FftImage, FftImageInv, RftGeneric
Module
Foundation

[out] HImageX ImageFFT HImageX.FftImage ( )


void HOperatorSetX.FftImage ([in] IHObjectX Image,
[out] HUntypedObjectX ImageFFT )

Compute the fast Fourier transform of an image.


FftImage calculates the Fourier transform of the input image (Image), i.e., it transforms the image into the
frequency domain. The algorithm used is the fast Fourier transform. This corresponds to the call

FftGeneric(Image,ImageFFT,’toFreq’,-1,’sqrt’,’dcCenter’,’complex’)

.
Attention
The filtering is always done on the entire image, i.e., the region of the image is ignored.
Parameter
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte, real )
Input image.
. ImageFFT (output iconic) . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX ( complex )
Fourier-transformed image.
Result
FftImage returns TRUE if the input image is of correct type. If the input is empty the behavior can be set via
SetSystem(::’noObjectResult’,<Result>:). If necessary, an exception handling is raised.
Parallelization Information
FftImage is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
OptimizeFftSpeed, ReadFftOptimizationData
Possible Successors
ConvolFft, ConvolGabor, ConvertImageType, PowerByte, PowerReal, PowerLn, PhaseDeg,
PhaseRad
See also
FftImageInv

HALCON 8.0.2
170 CHAPTER 3. FILTER

Alternatives
FftGeneric, RftGeneric
Module
Foundation

[out] HImageX ImageFFTInv HImageX.FftImageInv ( )


void HOperatorSetX.FftImageInv ([in] IHObjectX Image,
[out] HUntypedObjectX ImageFFTInv )

Compute the inverse fast Fourier transform of an image.


FftImageInv calculates the inverse Fourier transform of the input image (Image), i.e., it transforms the image
back into the spatial domain. This corresponds to the call

FftGeneric(Image,ImageFFT,’fromFreq’,1,’sqrt’,’dcCenter’,’byte’)

.
Attention
The filtering is always done on the entire image, i.e., the region of the image is ignored.
Parameter
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( complex )
Input image.
. ImageFFTInv (output iconic) . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte )
Inverse-Fourier-transformed image.
Result
FftImageInv returns TRUE if the input image is of correct type. If the input is empty the behavior can be set
via SetSystem(::’noObjectResult’,<Result>:). If necessary, an exception handling is raised.
Parallelization Information
FftImageInv is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
ConvolFft, ConvolGabor, FftImage, OptimizeFftSpeed, ReadFftOptimizationData
Possible Successors
ConvertImageType, EnergyGabor
See also
FftImage, FftGeneric, EnergyGabor
Alternatives
FftGeneric, RftGeneric
Module
Foundation

void HImageX.GenBandfilter ([in] double MinFrequency,


[in] double MaxFrequency, [in] String Norm, [in] String Mode, [in] long Width,
[in] long Height )
void HOperatorSetX.GenBandfilter ([out] HUntypedObjectX ImageFilter,
[in] VARIANT MinFrequency, [in] VARIANT MaxFrequency, [in] VARIANT Norm,
[in] VARIANT Mode, [in] VARIANT Width, [in] VARIANT Height )

Generate an ideal band filter.


GenBandfilter generates an ideal band filter in the frequency domain. The parameters MinFrequency
and MaxFrequency determine the cutoff frequencies of the filter as a fraction of the maximum (horizontal and
vertical) frequency that can be represented in an image of size Width × Height, i.e., MinFrequency and
MaxFrequency should lie between 0 and 1. To achieve a maximum efficiency of the filtering operation, the

HALCON/COM Reference Manual, 2008-5-13


3.6. FFT 171

parameter Norm can be used to specify the normalization factor of the filter. If FftGeneric and Norm = ’n’
is used the normalization in the FFT can be avoided. Mode can be used to determine where the DC term of the
filter lies or whether the filter should be used in the real-valued FFT. If FftGeneric is used, ’dc_edge’ can be
used to gain efficiency. If FftImage and FftImageInv are used for filtering, Norm = ’none’ and Mode =
’dc_center’ must be used. If RftGeneric is used, Mode = ’rft’ must be used. The resulting image contains an
annulus with the value 0, and a value determined by the normalization outside of this annulus.
Parameter
. ImageFilter (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / HUntypedObjectX ( real )
Band filter in the frequency domain.
. MinFrequency (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Minimum frequency.
Default Value : 0.1
Suggested values : MinFrequency ∈ {0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}
Restriction : (M inF requency ≥ 0)
. MaxFrequency (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Maximum frequency.
Default Value : 0.2
Suggested values : MaxFrequency ∈ {0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}
Restriction : ((M axF requency ≥ 0) ∧ (M axF requency ≥ M inF requency))
. Norm (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Normalizing factor of the filter.
Default Value : ’none’
List of values : Norm ∈ {’none’, ’n’}
. Mode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Location of the DC term in the frequency domain.
Default Value : ’dc_center’
List of values : Mode ∈ {’dc_center’, ’dc_edge’, ’rft’}
. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Width of the image (filter).
Default Value : 512
List of values : Width ∈ {128, 160, 192, 256, 320, 384, 512, 640, 768, 1024, 2048, 4096, 8192}
. Height (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Height of the image (filter).
Default Value : 512
List of values : Height ∈ {120, 128, 144, 240, 256, 288, 480, 512, 576, 1024, 2048, 4096, 8192}
Example

/* Filtering with maximum efficiency with fft_generic. */


gen_bandpass(Bandfilter,0.2,0.4,’n’,’dc_edge’,Width,Height)
fft_generic(Image,ImageFFT,’to_freq’,-1,’none’,’dc_edge’,’complex’)
convol_fft(ImageFFT,Bandfilter:ImageConvol)
fft_generic(ImageConvol,ImageResult,’from_freq’,1,’none’,’dc_edge’,’byte’)

Result
GenBandfilter returns TRUE if all parameters are correct. If necessary, an exception handling is raised.
Parallelization Information
GenBandfilter is reentrant and processed without parallelization.
Possible Successors
ConvolFft
See also
GenHighpass, GenLowpass, GenBandpass, GenGaussFilter, GenDerivativeFilter
Alternatives
GenCircle, PaintRegion
Module
Foundation

HALCON 8.0.2
172 CHAPTER 3. FILTER

void HImageX.GenBandpass ([in] double MinFrequency,


[in] double MaxFrequency, [in] String Norm, [in] String Mode, [in] long Width,
[in] long Height )
void HOperatorSetX.GenBandpass ([out] HUntypedObjectX ImageBandpass,
[in] VARIANT MinFrequency, [in] VARIANT MaxFrequency, [in] VARIANT Norm,
[in] VARIANT Mode, [in] VARIANT Width, [in] VARIANT Height )

Generate an ideal bandpass filter.


GenBandpass generates an ideal bandpass filter in the frequency domain. The parameters MinFrequency
and MaxFrequency determine the cutoff frequencies of the filter as a fraction of the maximum (horizontal and
vertical) frequency that can be represented in an image of size Width × Height, i.e., MinFrequency and
MaxFrequency should lie between 0 and 1. To achieve a maximum efficiency of the filtering operation, the
parameter Norm can be used to specify the normalization factor of the filter. If FftGeneric and Norm = ’n’
is used the normalization in the FFT can be avoided. Mode can be used to determine where the DC term of the
filter lies or whether the filter should be used in the real-valued FFT. If FftGeneric is used, ’dc_edge’ can be
used to gain efficiency. If FftImage and FftImageInv are used for filtering, Norm = ’none’ and Mode =
’dc_center’ must be used. If RftGeneric is used, Mode = ’rft’ must be used. The resulting image contains an
annulus with the value 255, and the value 0 outside of this annulus.
Parameter

. ImageBandpass (output iconic) . . . . . . . . . . . . . . . . . . . . . . . .image ; HImageX / HUntypedObjectX ( real )


Bandpass filter in the frequency domain.
. MinFrequency (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Minimum frequency.
Default Value : 0.1
Suggested values : MinFrequency ∈ {0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}
Restriction : (M inF requency ≥ 0)
. MaxFrequency (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Maximum frequency.
Default Value : 0.2
Suggested values : MaxFrequency ∈ {0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}
Restriction : ((M axF requency ≥ 0) ∧ (M axF requency ≥ M inF requency))
. Norm (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Normalizing factor of the filter.
Default Value : ’none’
List of values : Norm ∈ {’none’, ’n’}
. Mode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Location of the DC term in the frequency domain.
Default Value : ’dc_center’
List of values : Mode ∈ {’dc_center’, ’dc_edge’, ’rft’}
. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Width of the image (filter).
Default Value : 512
List of values : Width ∈ {128, 160, 192, 256, 320, 384, 512, 640, 768, 1024, 2048, 4096, 8192}
. Height (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Height of the image (filter).
Default Value : 512
List of values : Height ∈ {120, 128, 144, 240, 256, 288, 480, 512, 576, 1024, 2048, 4096, 8192}
Example

/* Filtering with maximum efficiency with fft_generic. */


gen_bandpass(Bandpass,0.2,0.4,’n’,’dc_edge’,Width,Height)
fft_generic(Image,ImageFFT,’to_freq’,-1,’none’,’dc_edge’,’complex’)
convol_fft(ImageFFT,Bandpass:ImageConvol)
fft_generic(ImageConvol,ImageResult,’from_freq’,1,’none’,’dc_edge’,’byte’)

HALCON/COM Reference Manual, 2008-5-13


3.6. FFT 173

Result
GenBandpass returns TRUE if all parameters are correct. If necessary, an exception handling is raised.
Parallelization Information
GenBandpass is reentrant and processed without parallelization.
Possible Successors
ConvolFft
See also
GenHighpass, GenLowpass, GenBandfilter, GenGaussFilter, GenDerivativeFilter
Module
Foundation

void HImageX.GenDerivativeFilter ([in] String Derivative,


[in] long Exponent, [in] String Norm, [in] String Mode, [in] long Width,
[in] long Height )
void HOperatorSetX.GenDerivativeFilter
([out] HUntypedObjectX ImageDerivative, [in] VARIANT Derivative,
[in] VARIANT Exponent, [in] VARIANT Norm, [in] VARIANT Mode,
[in] VARIANT Width, [in] VARIANT Height )

Generate a derivative filter in the frequency domain.


GenDerivativeFilter generates a derivative filter in the frequency domain. The derivative to be computed
is determined by Derivative. Exponent specifies the exponent used in the reverse transform. It must be set
to the same value that is used in FftGeneric. If FftImageInv is used in the reverse transform, Exponent
= 1 must be used. However, since the derivative image typically contains negative values, FftGeneric should
always be used for the reverse transform. To achieve a maximum efficiency of the filtering operation, the parameter
Norm can be used to specify the normalization factor of the filter. If FftGeneric and Norm = ’n’ is used the
normalization in the FFT can be avoided. Mode can be used to determine where the DC term of the filter lies or
whether the filter should be used in the real-valued FFT. If FftGeneric is used, ’dc_edge’ can be used to gain
efficiency. If FftImage and FftImageInv are used for filtering, Norm = ’none’ and Mode = ’dc_center’
must be used. If RftGeneric is used, Mode = ’rft’ must be used.
Parameter

. ImageDerivative (output iconic) . . . . . . . . . . . . . . . . image ; HImageX / HUntypedObjectX ( complex )


Derivative filter as image in the frequency domain.
. Derivative (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Derivative to be computed.
Default Value : ’x’
Suggested values : Derivative ∈ {’x’, ’y’, ’xx’, ’xy’, ’yy’, ’xxx’, ’xxy’, ’xyy’, ’yyy’}
. Exponent (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Exponent used in the reverse transform.
Default Value : 1
Suggested values : Exponent ∈ {-1, 1}
. Norm (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Normalizing factor of the filter.
Default Value : ’none’
List of values : Norm ∈ {’none’, ’n’}
. Mode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Location of the DC term in the frequency domain.
Default Value : ’dc_center’
List of values : Mode ∈ {’dc_center’, ’dc_edge’, ’rft’}
. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Width of the image (filter).
Default Value : 512
List of values : Width ∈ {128, 160, 192, 256, 320, 384, 512, 640, 768, 1024, 2048, 4096, 8192}

HALCON 8.0.2
174 CHAPTER 3. FILTER

. Height (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT


Height of the image (filter).
Default Value : 512
List of values : Height ∈ {120, 128, 144, 240, 256, 288, 480, 512, 576, 1024, 2048, 4096, 8192}
Example

/* Generate a smoothed derivative filter. */


gen_gauss_filter (ImageGauss, Sigma, Sigma, 0, ’n’, ’dc_edge’, 512, 512)
convert_image_type (ImageGauss, ImageGaussComplex, ’complex’)
gen_derivative_filter (ImageDerivX, ’x’, 1, ’none’, ’dc_edge’, 512, 512)
mult_image (ImageGaussComplex, ImageDerivX, ImageDerivXGauss, 1, 0)
/* Filter an image with the smoothed derivative filter. */
fft_generic (Image, ImageFFT, ’to_freq’, -1, ’none’, ’dc_edge’, ’complex’)
convol_fft (ImageFFT, ImageDerivXGauss, Filtered)
fft_generic (Filtered, ImageX, ’from_freq’, 1, ’none’, ’dc_edge’, ’real’)

Result
GenDerivativeFilter returns TRUE if all parameters are correct. If necessary, an exception handling is
raised.
Parallelization Information
GenDerivativeFilter is reentrant and processed without parallelization.
Possible Predecessors
FftImage, FftGeneric, RftGeneric
Possible Successors
ConvolFft
See also
FftImageInv, GenGaussFilter, GenLowpass, GenBandpass, GenBandfilter, GenHighpass
Module
Foundation

void HImageX.GenFilterMask ([in] VARIANT FilterMask, [in] double Scale,


[in] long Width, [in] long Height )
void HOperatorSetX.GenFilterMask ([out] HUntypedObjectX ImageFilter,
[in] VARIANT FilterMask, [in] VARIANT Scale, [in] VARIANT Width,
[in] VARIANT Height )

Store a filter mask in the spatial domain as a real-image.


GenFilterMask stores a filter mask in the spatial domain as a real-image. The center of the filter mask lies
in the center of the resulting image. The parameter Scale determines by which amount the values of the filter
mask are multiplied (this results in larger values of the Fourier transform of the filter). The corresponding filter
matrix, which is given in FilterMask can be generated either from a file or a tuple. The format of the filter
matrix is described with the operator ConvolImage. Example filter masks can be found in the directory “filter”
in the HALCON home directory. This operator is useful for visualizing the frequency response of filter masks (by
applying a Fourier transform to the result image of this operator).
Parameter

. ImageFilter (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / HUntypedObjectX ( real )


Filter in the spatial domain.
. FilterMask (input control) . . . . . . . . . . . . . . . . . . . . . . . filename.read(-array) ; VARIANT ( integer, string )
Filter mask as file name or tuple.
Default Value : ’gauss’
Suggested values : FilterMask ∈ {’gauss’, ’laplace4’, ’laplace8’, ’lowpas_3_3’, ’lowpas_5_5’,
’lowpas_7_7’, ’lowpas_9_9’, ’sobel_c’, ’sobel_l’}

HALCON/COM Reference Manual, 2008-5-13


3.6. FFT 175

. Scale (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT


Scaling factor.
Default Value : 1.0
Suggested values : Scale ∈ {0.3, 0.5, 0.75, 1.0, 1.25, 1.5, 2.0}
Typical range of values : 0.001 ≤ Scale ≤ 0.001
Minimum Increment : 0.001
Recommended Increment : 0.1
Restriction : (Scale > 0.0)
. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Width of the image (filter).
Default Value : 512
List of values : Width ∈ {128, 160, 192, 256, 320, 384, 512, 640, 768, 1024, 2048, 4096, 8192}
. Height (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Height of the image (filter).
Default Value : 512
List of values : Height ∈ {120, 128, 144, 240, 256, 288, 480, 512, 576, 1024, 2048, 4096, 8192}
Example

* If the filter should be read from a file:


gen_filter_mask (Filter, ’lowpas_3_3’, 1.0, 512, 512)
* If the filter should be directly passed as a tuple:
gen_filter_mask (Filter, [3,3,9,1,1,1,1,1,1,1,1,1], 1.0, 512, 512)
fft_image (Filter, FilterFFT)
set_paint (WindowHandle, ’3D-plot_hidden’)
disp_image (FilterFFT, WindowHandle)

Parallelization Information
GenFilterMask is reentrant and processed without parallelization.
Possible Successors
FftImage, FftGeneric
See also
ConvolImage
Module
Foundation

void HImageX.GenGabor ([in] double Angle, [in] double Frequency,


[in] double Bandwidth, [in] double Orientation, [in] String Norm,
[in] String Mode, [in] long Width, [in] long Height )
void HOperatorSetX.GenGabor ([out] HUntypedObjectX ImageFilter,
[in] VARIANT Angle, [in] VARIANT Frequency, [in] VARIANT Bandwidth,
[in] VARIANT Orientation, [in] VARIANT Norm, [in] VARIANT Mode,
[in] VARIANT Width, [in] VARIANT Height )

Generate a Gabor filter.


GenGabor generates a Gabor filter with a user-definable bandpass frequency range and sign for the Hilbert trans-
form. This is done by calculating a symmetrical filter in the frequency domain, which can be adapted by the
parameters Angle, Frequency, Bandwidth und Orientation such that a certain frequency band and a
certain direction range in the spatial domain is filtered out in the frequency domain.
The parameters Frequency (central frequency = distance from the DC term) and Orientation (direction)
determine the center of the filter. Larger values of Frequency result in higher frequencies being passed. A value
of 0 for Orientation generates a horizontally oriented “crescent” (the bulge of the crescent points upward).
Higher values of Orientation result in the counterclockwise rotation of the crescent.

HALCON 8.0.2
176 CHAPTER 3. FILTER

The parameters Angle and Bandwidth are used to determine the range of frequencies and angles being passed
by the filter. The larger Angle is, the smaller the range of angles passed by the filter gets (because the “cres-
cent” gets narrower). The larger Bandwidth is, the smaller the frequency band being passed gets (because the
“crescent” gets thinner).
To achieve a maximum efficiency of the filtering operation, the parameter Norm can be used to specify the normal-
ization factor of the filter. If FftGeneric and Norm = ’n’ is used the normalization in the FFT can be avoided.
Mode can be used to determine where the DC term of the filter lies. If FftGeneric is used, ’dc_edge’ can be
used to gain efficiency. If FftImage and FftImageInv are used for filtering, Norm = ’none’ and Mode =
’dc_center’ must be used. Note that GenGabor cannot create a filter that can be used with RftGeneric.
The resulting image is a two-channel real-image, containing the Gabor filter in the first channel and the corre-
sponding Hilbert filter in the second channel.
Parameter

. ImageFilter (output iconic) . . . . . . . . multichannel-image-array ; HImageX / HUntypedObjectX ( real )


Gabor and Hilbert filter.
. Angle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Angle range, inversely proportional to the range of orientations.
Default Value : 1.4
Suggested values : Angle ∈ {1.0, 1.2, 1.4, 1.6, 2.0, 2.5, 3.0, 5.0, 6.0, 10.0, 20.0, 30.0, 50.0, 70.0, 100.0}
Typical range of values : 1.0 ≤ Angle ≤ 1.0
Minimum Increment : 0.001
Recommended Increment : 0.1
. Frequency (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Distance of the center of the filter to the DC term.
Default Value : 0.4
Suggested values : Frequency ∈ {0.0, 0.05, 0.1, 0.15, 0.2, 0.25, 0.3, 0.35, 0.4, 0.45, 0.50, 0.55, 0.60, 0.65,
0.699}
Typical range of values : 0.0 ≤ Frequency ≤ 0.0
Minimum Increment : 0.00001
Recommended Increment : 0.005
. Bandwidth (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Bandwidth range, inversely proportional to the range of frequencies being passed.
Default Value : 1.0
Suggested values : Bandwidth ∈ {0.1, 0.3, 0.7, 1.0, 1.5, 2.0, 3.0, 5.0, 7.0, 10.0, 15.0, 20.0, 30.0, 50.0}
Typical range of values : 0.05 ≤ Bandwidth ≤ 0.05
Minimum Increment : 0.001
Recommended Increment : 0.1
. Orientation (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Angle of the principal orientation.
Default Value : 1.5
Suggested values : Orientation ∈ {0.0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.8, 2.0, 2.2, 2.4, 2.6, 2.8, 3.0,
3.14}
Typical range of values : 0.0 ≤ Orientation ≤ 0.0
Minimum Increment : 0.0001
Recommended Increment : 0.05
. Norm (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Normalizing factor of the filter.
Default Value : ’none’
List of values : Norm ∈ {’none’, ’n’}
. Mode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Location of the DC term in the frequency domain.
Default Value : ’dc_center’
List of values : Mode ∈ {’dc_center’, ’dc_edge’}
. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Width of the image (filter).
Default Value : 512
List of values : Width ∈ {128, 160, 192, 256, 320, 384, 512, 640, 768, 1024, 2048, 4096, 8192}

HALCON/COM Reference Manual, 2008-5-13


3.6. FFT 177

. Height (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT


Height of the image (filter).
Default Value : 512
List of values : Height ∈ {120, 128, 144, 240, 256, 288, 480, 512, 576, 1024, 2048, 4096, 8192}
Example

gen_gabor(Filter,1.4,0.4,1.0,1.5,’n’,’dc_edge’,512,512)
fft_generic(Image,ImageFFT,’to_freq’,-1,’none’,’dc_edge’,’complex’)
convol_gabor(ImageFFT,Filter,Gabor,Hilbert,’dc_edge’)
fft_generic(Gabor,GaborInv,’from_freq’,1,’none’,’dc_edge’,’byte’)
fft_generic(Hilbert,HilbertInv,’from_freq’,1,’none’,’dc_edge’,’byte’)
energy_gabor(GaborInv,HilbertInv,Energy)

Result
GenGabor returns TRUE if all parameters are correct. If necessary, an exception handling is raised.
Parallelization Information
GenGabor is reentrant and processed without parallelization.
Possible Predecessors
FftImage, FftGeneric
Possible Successors
ConvolGabor
See also
FftImageInv, EnergyGabor
Alternatives
GenBandpass, GenBandfilter, GenHighpass, GenLowpass
Module
Foundation

void HImageX.GenGaussFilter ([in] double Sigma1, [in] double Sigma2,


[in] double Phi, [in] String Norm, [in] String Mode, [in] long Width,
[in] long Height )
void HOperatorSetX.GenGaussFilter ([out] HUntypedObjectX ImageGauss,
[in] VARIANT Sigma1, [in] VARIANT Sigma2, [in] VARIANT Phi, [in] VARIANT Norm,
[in] VARIANT Mode, [in] VARIANT Width, [in] VARIANT Height )

Generate a Gaussian filter in the frequency domain.


GenGaussFilter generates a (possibly anisotropic) Gaussian filter in the frequency domain. The standard
deviations (i.e., the amount of smoothing) of the Gaussian in the spatial domain are determined by Sigma1 and
Sigma2. Sigma1 is the standard deviation in the principal direction of the filter in the spatial domain determined
by the angle Phi. To achieve a maximum efficiency of the filtering operation, the parameter Norm can be used
to specify the normalization factor of the filter. If FftGeneric and Norm = ’n’ is used the normalization in
the FFT can be avoided. Mode can be used to determine where the DC term of the filter lies or whether the filter
should be used in the real-valued FFT. If FftGeneric is used, ’dc_edge’ can be used to gain efficiency. If
FftImage and FftImageInv are used for filtering, Norm = ’none’ and Mode = ’dc_center’ must be used. If
RftGeneric is used, Mode = ’rft’ must be used.
Parameter
. ImageGauss (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / HUntypedObjectX ( real )
Gaussian filter as image in the frequency domain.
. Sigma1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Standard deviation of the Gaussian in the principal direction of the filter in the spatial domain.
Default Value : 1.0
Suggested values : Sigma1 ∈ {0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.5, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0}
Restriction : (Sigma1 ≥ 0)

HALCON 8.0.2
178 CHAPTER 3. FILTER

. Sigma2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT


Standard deviation of the Gaussian perpendicular to the principal direction of the filter in the spatial domain.
Default Value : 1.0
Suggested values : Sigma2 ∈ {0.7, 0.8, 0.9, 1.0, 1.1, 1.2, 1.5, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0}
Restriction : (Sigma2 ≥ 0)
. Phi (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; double / VARIANT
Principal direction of the filter in the spatial domain.
Default Value : 0.0
Suggested values : Phi ∈ {0.0, 0.523599, 0.785398, 1.047198, 1.570796, 2.094395, 2.356194, 2.617994,
3.141593}
. Norm (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Normalizing factor of the filter.
Default Value : ’none’
List of values : Norm ∈ {’none’, ’n’}
. Mode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Location of the DC term in the frequency domain.
Default Value : ’dc_center’
List of values : Mode ∈ {’dc_center’, ’dc_edge’, ’rft’}
. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Width of the image (filter).
Default Value : 512
List of values : Width ∈ {128, 160, 192, 256, 320, 384, 512, 640, 768, 1024, 2048, 4096, 8192}
. Height (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Height of the image (filter).
Default Value : 512
List of values : Height ∈ {120, 128, 144, 240, 256, 288, 480, 512, 576, 1024, 2048, 4096, 8192}
Example

/* Generate a smoothed derivative filter. */


gen_gauss_filter (ImageGauss, Sigma, Sigma, 0, ’n’, ’dc_edge’, 512, 512)
convert_image_type (ImageGauss, ImageGaussComplex, ’complex’)
gen_derivative_filter (ImageDerivX, ’x’, 1, ’none’, ’dc_edge’, 512, 512)
mult_image (ImageGaussComplex, ImageDerivX, ImageDerivXGauss, 1, 0)
/* Filter an image with the smoothed derivative filter. */
fft_generic (Image, ImageFFT, ’to_freq’, -1, ’none’, ’dc_edge’, ’complex’)
convol_fft (ImageFFT, ImageDerivXGauss, Filtered)
fft_generic (Filtered, ImageX, ’from_freq’, 1, ’none’, ’dc_edge’, ’real’)

Result
GenGaussFilter returns TRUE if all parameters are correct. If necessary, an exception handling is raised.
Parallelization Information
GenGaussFilter is reentrant and processed without parallelization.
Possible Predecessors
FftImage, FftGeneric, RftGeneric
Possible Successors
ConvolFft
See also
FftImageInv, GenGaussFilter, GenLowpass, GenBandpass, GenBandfilter, GenHighpass
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


3.6. FFT 179

void HImageX.GenHighpass ([in] double Frequency, [in] String Norm,


[in] String Mode, [in] long Width, [in] long Height )
void HOperatorSetX.GenHighpass ([out] HUntypedObjectX ImageHighpass,
[in] VARIANT Frequency, [in] VARIANT Norm, [in] VARIANT Mode,
[in] VARIANT Width, [in] VARIANT Height )

Generate an ideal highpass filter.


GenHighpass generates an ideal highpass filter in the frequency domain. The parameter Frequency deter-
mines the cutoff frequency of the filter as a fraction of the maximum (horizontal and vertical) frequency that can
be represented in an image of size Width × Height, i.e., Frequency should lie between 0 and 1. To achieve a
maximum efficiency of the filtering operation, the parameter Norm can be used to specify the normalization factor
of the filter. If FftGeneric and Norm = ’n’ is used the normalization in the FFT can be avoided. Mode can be
used to determine where the DC term of the filter lies or whether the filter should be used in the real-valued FFT.
If FftGeneric is used, ’dc_edge’ can be used to gain efficiency. If FftImage and FftImageInv are used
for filtering, Norm = ’none’ and Mode = ’dc_center’ must be used. If RftGeneric is used, Mode = ’rft’ must
be used. The resulting image has an inner part with the value 0, and an outer part with the value determined by the
normalization factor.
Parameter
. ImageHighpass (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / HUntypedObjectX ( real )
Highpass filter in the frequency domain.
. Frequency (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Cutoff frequency.
Default Value : 0.1
Suggested values : Frequency ∈ {0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}
Restriction : (F requency ≥ 0)
. Norm (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Normalizing factor of the filter.
Default Value : ’none’
List of values : Norm ∈ {’none’, ’n’}
. Mode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Location of the DC term in the frequency domain.
Default Value : ’dc_center’
List of values : Mode ∈ {’dc_center’, ’dc_edge’, ’rft’}
. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Width of the image (filter).
Default Value : 512
List of values : Width ∈ {128, 160, 192, 256, 320, 384, 512, 640, 768, 1024, 2048, 4096, 8192}
. Height (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Height of the image (filter).
Default Value : 512
List of values : Height ∈ {120, 128, 144, 240, 256, 288, 480, 512, 576, 1024, 2048, 4096, 8192}
Example

/* Filtering with maximum efficiency with fft_generic. */


gen_highpass(Highpass,0.2,’n’,’dc_edge’,Width,Height)
fft_generic(Image,ImageFFT,’to_freq’,-1,’none’,’dc_edge’,’complex’)
convol_fft(ImageFFT,Highpass:ImageConvol)
fft_generic(ImageConvol,ImageResult,’from_freq’,1,’none’,’dc_edge’,’byte’)

Result
GenHighpass returns TRUE if all parameters are correct. If necessary, an exception handling is raised.
Parallelization Information
GenHighpass is reentrant and processed without parallelization.
Possible Successors
ConvolFft

HALCON 8.0.2
180 CHAPTER 3. FILTER

See also
ConvolFft, GenLowpass, GenBandpass, GenBandfilter, GenGaussFilter,
GenDerivativeFilter
Module
Foundation

void HImageX.GenLowpass ([in] double Frequency, [in] String Norm,


[in] String Mode, [in] long Width, [in] long Height )
void HOperatorSetX.GenLowpass ([out] HUntypedObjectX ImageLowpass,
[in] VARIANT Frequency, [in] VARIANT Norm, [in] VARIANT Mode,
[in] VARIANT Width, [in] VARIANT Height )

Generate an ideal lowpass filter.


GenLowpass generates an ideal lowpass filter in the frequency domain. The parameter Frequency determines
the cutoff frequency of the filter as a fraction of the maximum (horizontal and vertical) frequency that can be
represented in an image of size Width × Height, i.e., Frequency should lie between 0 and 1. To achieve a
maximum efficiency of the filtering operation, the parameter Norm can be used to specify the normalization factor
of the filter. If FftGeneric and Norm = ’n’ is used the normalization in the FFT can be avoided. Mode can be
used to determine where the DC term of the filter lies or whether the filter should be used in the real-valued FFT.
If FftGeneric is used, ’dc_edge’ can be used to gain efficiency. If FftImage and FftImageInv are used
for filtering, Norm = ’none’ and Mode = ’dc_center’ must be used. If RftGeneric is used, Mode = ’rft’ must
be used. The resulting image has an inner part with the value set to the normalization factor, and an outer part with
the value 0.
Parameter

. ImageLowpass (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / HUntypedObjectX ( real )


Lowpass filter in the frequency domain.
. Frequency (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Cutoff frequency.
Default Value : 0.1
Suggested values : Frequency ∈ {0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}
Restriction : (F requency ≥ 0)
. Norm (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Normalizing factor of the filter.
Default Value : ’none’
List of values : Norm ∈ {’none’, ’n’}
. Mode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Location of the DC term in the frequency domain.
Default Value : ’dc_center’
List of values : Mode ∈ {’dc_center’, ’dc_edge’, ’rft’}
. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Width of the image (filter).
Default Value : 512
List of values : Width ∈ {128, 160, 192, 256, 320, 384, 512, 640, 768, 1024, 2048, 4096, 8192}
. Height (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Height of the image (filter).
Default Value : 512
List of values : Height ∈ {120, 128, 144, 240, 256, 288, 480, 512, 576, 1024, 2048, 4096, 8192}
Result
GenLowpass returns TRUE if all parameters are correct. If necessary, an exception handling is raised.
Parallelization Information
GenLowpass is reentrant and processed without parallelization.
Possible Successors
ConvolFft

HALCON/COM Reference Manual, 2008-5-13


3.6. FFT 181

See also
GenHighpass, GenBandpass, GenBandfilter, GenGaussFilter, GenDerivativeFilter
Module
Foundation

void HImageX.GenSinBandpass ([in] double Frequency, [in] String Norm,


[in] String Mode, [in] long Width, [in] long Height )
void HOperatorSetX.GenSinBandpass ([out] HUntypedObjectX ImageFilter,
[in] VARIANT Frequency, [in] VARIANT Norm, [in] VARIANT Mode,
[in] VARIANT Width, [in] VARIANT Height )

Generate a bandpass filter with sinusoidal shape.


GenSinBandpass generates a rotationally invariant bandpass filter with the response being a sinusoidal function
in the frequency domain. The maximum of the sine is determined by Frequency, which is given as a fraction of
the maximum (horizontal and vertical) frequency that can be represented in an image of size Width × Height,
i.e., Frequency should lie between 0 and 1. To achieve a maximum efficiency of the filtering operation, the
parameter Norm can be used to specify the normalization factor of the filter. If FftGeneric and Norm = ’n’
is used the normalization in the FFT can be avoided. Mode can be used to determine where the DC term of the
filter lies or whether the filter should be used in the real-valued FFT. If FftGeneric is used, ’dc_edge’ can be
used to gain efficiency. If FftImage and FftImageInv are used for filtering, Norm = ’none’ and Mode =
’dc_center’ must be used. If RftGeneric is used, Mode = ’rft’ must be used. The filter is always zero for the
DC term, rises with the sine function up to Frequency, and drops for higher frequencies accordingly. The range
of the sine used is from 0 to π. All other points are set to zero.
Parameter

. ImageFilter (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / HUntypedObjectX ( real )


Bandpass filter as image in the frequency domain.
. Frequency (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Distance of the filter’s maximum from the DC term.
Default Value : 0.1
Suggested values : Frequency ∈ {0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}
Restriction : (F requency ≥ 0)
. Norm (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Normalizing factor of the filter.
Default Value : ’none’
List of values : Norm ∈ {’none’, ’n’}
. Mode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Location of the DC term in the frequency domain.
Default Value : ’dc_center’
List of values : Mode ∈ {’dc_center’, ’dc_edge’, ’rft’}
. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Width of the image (filter).
Default Value : 512
List of values : Width ∈ {128, 160, 192, 256, 320, 384, 512, 640, 768, 1024, 2048, 4096, 8192}
. Height (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Height of the image (filter).
Default Value : 512
List of values : Height ∈ {120, 128, 144, 240, 256, 288, 480, 512, 576, 1024, 2048, 4096, 8192}
Result
GenSinBandpass returns TRUE if all parameters are correct. If necessary, an exception handling is raised.
Parallelization Information
GenSinBandpass is reentrant and processed without parallelization.
Possible Predecessors
FftImage, FftGeneric, RftGeneric

HALCON 8.0.2
182 CHAPTER 3. FILTER

Possible Successors
ConvolFft
See also
FftImageInv, GenGaussFilter, GenDerivativeFilter, GenBandpass, GenBandfilter,
GenHighpass, GenLowpass
Alternatives
GenStdBandpass
Module
Foundation

void HImageX.GenStdBandpass ([in] double Frequency, [in] double Sigma,


[in] String Type, [in] String Norm, [in] String Mode, [in] long Width,
[in] long Height )
void HOperatorSetX.GenStdBandpass ([out] HUntypedObjectX ImageFilter,
[in] VARIANT Frequency, [in] VARIANT Sigma, [in] VARIANT Type,
[in] VARIANT Norm, [in] VARIANT Mode, [in] VARIANT Width,
[in] VARIANT Height )

Generate a bandpass filter with Gaussian or sinusoidal shape.


GenStdBandpass generates a rotationally invariant bandpass filter with the response being determined by the
parameters Frequency and Sigma: Frequency determines the location of the maximum response with respect
to the DC term, while Sigma determines the width of the frequency band that passes the filter. Frequency and
Sigma are specified as a fraction of the maximum (horizontal and vertical) frequency that can be represented in
an image of size Width × Height. Frequency should lie between 0 and 1. For Type = ’gauss’, a Gaussian
response is generated with Sigma being the standard deviation. For Type = ’sin’, a sine function is generated with
the maximum at Frequency and the extent Sigma. To achieve a maximum efficiency of the filtering operation,
the parameter Norm can be used to specify the normalization factor of the filter. If FftGeneric and Norm =
’n’ is used the normalization in the FFT can be avoided. Mode can be used to determine where the DC term of the
filter lies or whether the filter should be used in the real-valued FFT. If FftGeneric is used, ’dc_edge’ can be
used to gain efficiency. If FftImage and FftImageInv are used for filtering, Norm = ’none’ and Mode =
’dc_center’ must be used. If RftGeneric is used, Mode = ’rft’ must be used.
Parameter

. ImageFilter (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / HUntypedObjectX ( real )


Bandpass filter as image in the frequency domain.
. Frequency (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Distance of the filter’s maximum from the DC term.
Default Value : 0.1
Suggested values : Frequency ∈ {0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}
Restriction : (F requency ≥ 0)
. Sigma (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Bandwidth of the filter (standard deviation).
Default Value : 0.01
Suggested values : Sigma ∈ {0.002, 0.005, 0.01, 0.02, 0.05, 0.1, 0.2, 0.3, 0.4, 0.5, 0.7, 1.0}
Restriction : (Sigma ≥ 0)
. Type (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Filter type.
Default Value : ’sin’
List of values : Type ∈ {’sin’, ’gauss’}
. Norm (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Normalizing factor of the filter.
Default Value : ’none’
List of values : Norm ∈ {’none’, ’n’}

HALCON/COM Reference Manual, 2008-5-13


3.6. FFT 183

. Mode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT


Location of the DC term in the frequency domain.
Default Value : ’dc_center’
List of values : Mode ∈ {’dc_center’, ’dc_edge’, ’rft’}
. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Width of the image (filter).
Default Value : 512
List of values : Width ∈ {128, 160, 192, 256, 320, 384, 512, 640, 768, 1024, 2048, 4096, 8192}
. Height (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Height of the image (filter).
Default Value : 512
List of values : Height ∈ {120, 128, 144, 240, 256, 288, 480, 512, 576, 1024, 2048, 4096, 8192}
Result
GenStdBandpass returns TRUE if all parameters are correct. If necessary, an exception handling is raised.
Parallelization Information
GenStdBandpass is reentrant and processed without parallelization.
Possible Predecessors
FftImage, FftGeneric, RftGeneric
Possible Successors
ConvolFft
See also
FftImageInv, GenGaussFilter, GenDerivativeFilter, GenBandpass, GenBandfilter,
GenHighpass, GenLowpass
Alternatives
GenSinBandpass
Module
Foundation

void HMiscX.OptimizeFftSpeed ([in] long Width, [in] long Height,


[in] String Mode )
void HOperatorSetX.OptimizeFftSpeed ([in] VARIANT Width,
[in] VARIANT Height, [in] VARIANT Mode )

Optimize the runtime of the FFT.


OptimizeFftSpeed determines a method that achieves an optimum runtime of the FFT for an image of size
Width × Height. The data that are determined for one image size do not influence the methods used for other
image sizes. Consequently, OptimizeFftSpeed can be called multiple times with different values for Width
and Height to achieve an optimum runtime for all image sizes that are used in an application. The parameter
Mode determines the thoroughness of the search for the fastest method. For Mode = ’standard’ a fast search
is used, which typically takes a few seconds. The method thus determined results in very good runtimes, which
are not always optimal. For Mode = ’patient’ a more thorough search is performed, which typically takes sev-
eral seconds and in most cases leads to optimum runtimes. For Mode = ’exhaustive’ an exhaustive search is
performed, which typically takes several minutes and always results in the optimum runtime. In most applica-
tions, Mode = ’standard’ results in the best compromise between the runtime of the FFT and the time required
for the search of the optimum runtime. The data determined with OptimizeFftSpeed can be saved with
WriteFftOptimizationData and can be loaded with ReadFftOptimizationData.
OptimizeFftSpeed influences the runtime of the following operators, which use the FFT: FftGeneric,
FftImage, FftImageInv, WienerFilter, WienerFilterNi, PhotStereo, SfsPentland,
SfsModLr, SfsOrigLr.
Parameter
. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Width of the image for which the runtime should be optimized.
Default Value : 512
Suggested values : Width ∈ {128, 160, 192, 256, 320, 384, 512, 640, 768, 1024, 2048}

HALCON 8.0.2
184 CHAPTER 3. FILTER

. Height (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT


Height of the image for which the runtime should be optimized.
Default Value : 512
Suggested values : Height ∈ {120, 128, 144, 240, 256, 288, 480, 512, 576, 1024, 2048}
. Mode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Thoroughness of the search for the optimum runtime.
Default Value : ’standard’
List of values : Mode ∈ {’standard’, ’patient’, ’exhaustive’}
Result
OptimizeFftSpeed returns TRUE if all parameters are correct. If necessary, an exception handling is raised.
Parallelization Information
OptimizeFftSpeed is reentrant and processed without parallelization.
Possible Successors
FftGeneric, FftImage, FftImageInv, WienerFilter, WienerFilterNi, PhotStereo,
SfsPentland, SfsModLr, SfsOrigLr, WriteFftOptimizationData
See also
OptimizeRftSpeed
Alternatives
ReadFftOptimizationData
Module
Foundation

void HMiscX.OptimizeRftSpeed ([in] long Width, [in] long Height,


[in] String Mode )
void HOperatorSetX.OptimizeRftSpeed ([in] VARIANT Width,
[in] VARIANT Height, [in] VARIANT Mode )

Optimize the runtime of the real-valued FFT.


OptimizeRftSpeed determines a method that achieves an optimum runtime of the real-valued FFT for an
image of size Width × Height. The data that are determined for one image size do not influence the methods
used for other image sizes. Consequently, OptimizeRftSpeed can be called multiple times with different
values for Width and Height to achieve an optimum runtime for all image sizes that are used in an application.
The parameter Mode determines the thoroughness of the search for the fastest method. For Mode = ’standard’ a
fast search is used, which typically takes a few seconds. The method thus determined results in very good runtimes,
which are not always optimal. For Mode = ’patient’ a more thorough search is performed, which typically takes
several seconds and in most cases leads to optimum runtimes. For Mode = ’exhaustive’ an exhaustive search is
performed, which typically takes several minutes and always results in the optimum runtime. In most applications,
Mode = ’standard’ results in the best compromise between the runtime of the real-valued FFT and the time
required for the search of the optimum runtime. The data determined with OptimizeRftSpeed can be saved
with WriteFftOptimizationData and can be loaded with ReadFftOptimizationData.
OptimizeRftSpeed influences the runtime of RftGeneric.
Parameter
. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Width of the image for which the runtime should be optimized.
Default Value : 512
Suggested values : Width ∈ {128, 160, 192, 256, 320, 384, 512, 640, 768, 1024, 2048}
. Height (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Height of the image for which the runtime should be optimized.
Default Value : 512
Suggested values : Height ∈ {120, 128, 144, 240, 256, 288, 480, 512, 576, 1024, 2048}
. Mode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Thoroughness of the search for the optimum runtime.
Default Value : ’standard’
List of values : Mode ∈ {’standard’, ’patient’, ’exhaustive’}

HALCON/COM Reference Manual, 2008-5-13


3.6. FFT 185

Result
OptimizeRftSpeed returns TRUE if all parameters are correct. If necessary, an exception handling is raised.
Parallelization Information
OptimizeRftSpeed is reentrant and processed without parallelization.
Possible Successors
RftGeneric, WriteFftOptimizationData
See also
OptimizeFftSpeed
Alternatives
ReadFftOptimizationData
Module
Foundation

HImageX.PhaseDeg ( )
[out] HImageX ImagePhase
void HOperatorSetX.PhaseDeg ([in] IHObjectX ImageComplex,
[out] HUntypedObjectX ImagePhase )

Return the phase of a complex image in degrees.


PhaseDeg computes the phase of a complex image in degrees. The following formula is used:

90
phase = atan2(imaginary part, real part) .
π

Hence, ImagePhase contains half the phase angle. For negative phase angles, 180 is added.
Parameter
. ImageComplex (input iconic) . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( complex )
Input image in frequency domain.
. ImagePhase (output iconic) . . . . . . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX ( direction )
Phase of the image in degrees.
Result
PhaseDeg returns TRUE if the image is of correct type. If the input is empty the behavior can be set via
SetSystem(::’noObjectResult’,<Result>:). If necessary, an exception handling is raised.
Parallelization Information
PhaseDeg is reentrant and automatically parallelized (on tuple level, domain level).
Possible Predecessors
FftImage, FftGeneric, RftGeneric
Possible Successors
DispImage
See also
FftImageInv
Alternatives
PhaseRad
Module
Foundation

HImageX.PhaseRad ( )
[out] HImageX ImagePhase
void HOperatorSetX.PhaseRad ([in] IHObjectX ImageComplex,
[out] HUntypedObjectX ImagePhase )

Return the phase of a complex image in radians.

HALCON 8.0.2
186 CHAPTER 3. FILTER

PhaseRad computes the phase of a complex image in radians. The following formula is used:

phase = atan2(imaginary part, real part) .

Parameter

. ImageComplex (input iconic) . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( complex )


Input image in frequency domain.
. ImagePhase (output iconic) . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX ( real )
Phase of the image in radians.
Result
PhaseRad returns TRUE if the image is of correct type. If the input is empty the behavior can be set via
SetSystem(::’noObjectResult’,<Result>:). If necessary, an exception handling is raised.
Parallelization Information
PhaseRad is reentrant and automatically parallelized (on tuple level, domain level).
Possible Predecessors
FftImage, FftGeneric, RftGeneric
Possible Successors
DispImage
See also
FftImageInv, FftGeneric, RftGeneric
Alternatives
PhaseDeg
Module
Foundation

HImageX.PowerByte ( )
[out] HImageX PowerByte
void HOperatorSetX.PowerByte ([in] IHObjectX Image,
[out] HUntypedObjectX PowerByte )

Return the power spectrum of a complex image.


PowerByte computes the power spectrum from the real and imaginary parts of a Fourier-transformed image (see
FftImage), i.e., the modulus of the frequencies. The result image is of type ’byte’. The following formula is
used:
p
realpart2 + imaginarypart2 .

Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( complex )


Input image in frequency domain.
. PowerByte (output iconic) . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte )
Power spectrum of the input image.
Result
PowerByte returns TRUE if the image is of correct type. If the input is empty the behavior can be set via
SetSystem(::’noObjectResult’,<Result>:). If necessary, an exception handling is raised.
Parallelization Information
PowerByte is reentrant and automatically parallelized (on tuple level, domain level).
Possible Predecessors
FftImage, FftGeneric, RftGeneric, ConvolFft, ConvolGabor
Possible Successors
DispImage

HALCON/COM Reference Manual, 2008-5-13


3.6. FFT 187

See also
FftImage, FftGeneric, RftGeneric
Alternatives
AbsImage, ConvertImageType, PowerReal, PowerLn
Module
Foundation

HImageX.PowerLn ( )
[out] HImageX ImageResult
void HOperatorSetX.PowerLn ([in] IHObjectX Image,
[out] HUntypedObjectX ImageResult )

Return the power spectrum of a complex image.


PowerLn computes the power spectrum from the real and imaginary parts of a Fourier-transformed image (see
FftImage), i.e., the modulus of the frequencies. Additionally, the natural logarithm is applied to the result. The
result image is of type ’real’. The following formula is used:
p 
ln realpart2 + imaginarypart2 .

Parameter
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( complex )
Input image in frequency domain.
. ImageResult (output iconic) . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX ( real )
Power spectrum of the input image.
Result
PowerLn returns TRUE if the image is of correct type. If the input is empty the behavior can be set via
SetSystem(::’noObjectResult’,<Result>:). If necessary, an exception handling is raised.
Parallelization Information
PowerLn is reentrant and automatically parallelized (on tuple level, domain level).
Possible Predecessors
FftImage, FftGeneric, RftGeneric, ConvolFft, ConvolGabor
Possible Successors
DispImage, ConvertImageType, ScaleImage
See also
FftImage, FftGeneric, RftGeneric
Alternatives
AbsImage, ConvertImageType, PowerReal, PowerByte
Module
Foundation

HImageX.PowerReal ( )
[out] HImageX ImageResult
void HOperatorSetX.PowerReal ([in] IHObjectX Image,
[out] HUntypedObjectX ImageResult )

Return the power spectrum of a complex image.


PowerReal computes the power spectrum from the real and imaginary parts of a Fourier-transformed image (see
FftImage), i.e., the modulus of the frequencies. The result image is of type ’real’. The following formula is
used:
p
realpart2 + imaginarypart2 .

HALCON 8.0.2
188 CHAPTER 3. FILTER

Parameter
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( complex )
Input image in frequency domain.
. ImageResult (output iconic) . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX ( real )
Power spectrum of the input image.
Result
PowerReal returns TRUE if the image is of correct type. If the input is empty the behavior can be set via
SetSystem(::’noObjectResult’,<Result>:). If necessary, an exception handling is raised.
Parallelization Information
PowerReal is reentrant and automatically parallelized (on tuple level, domain level).
Possible Predecessors
FftImage, FftGeneric, RftGeneric, ConvolFft, ConvolGabor
Possible Successors
DispImage, ConvertImageType, ScaleImage
See also
FftImage, FftGeneric, RftGeneric
Alternatives
AbsImage, ConvertImageType, PowerByte, PowerLn
Module
Foundation

void HMiscX.ReadFftOptimizationData ([in] String FileName )


void HOperatorSetX.ReadFftOptimizationData ([in] VARIANT FileName )

Load FFT speed optimization data from a file.


ReadFftOptimizationData loads data for optimizing the runtime of the FFT from the file given by
FileName. The optimization data must have been determined previously with OptimizeFftSpeed and
must have been stored with WriteFftOptimizationData. If the stored data have been determined for the
image sizes to be used in the application, a call to OptimizeFftSpeed is unnecessary. It should be noted that
the data should only be used on the same machine on which they were determined with OptimizeFftSpeed.
If this is not observed the runtimes will not be optimal. Furthermore, it should be noted that optimization data that
were created with Standard HALCON cannot be used with Parallel HALCON and vice versa.
ReadFftOptimizationData influences the runtime of the following operators, which use the FFT:
FftGeneric, FftImage, FftImageInv, WienerFilter, WienerFilterNi, PhotStereo,
SfsPentland, SfsModLr, SfsOrigLr.
Parameter
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.read ; String / VARIANT
File name of the optimization data.
Default Value : ’fft_opt.dat’
Result
ReadFftOptimizationData returns TRUE if all parameters are correct. If necessary, an exception handling
is raised.
Parallelization Information
ReadFftOptimizationData is reentrant and processed without parallelization.
Possible Successors
FftGeneric, FftImage, FftImageInv, RftGeneric, WienerFilter, WienerFilterNi,
PhotStereo, SfsPentland, SfsModLr, SfsOrigLr
See also
WriteFftOptimizationData
Alternatives
OptimizeFftSpeed, OptimizeRftSpeed

HALCON/COM Reference Manual, 2008-5-13


3.6. FFT 189

Module
Foundation

[out] HImageX ImageFFT HImageX.RftGeneric ([in] String Direction,


[in] String Norm, [in] String ResultType, [in] long Width )
void HOperatorSetX.RftGeneric ([in] IHObjectX Image,
[out] HUntypedObjectX ImageFFT, [in] VARIANT Direction, [in] VARIANT Norm,
[in] VARIANT ResultType, [in] VARIANT Width )

Compute the real-valued fast Fourier transform of an image.


RftGeneric computes the fast Fourier transform of the input image Image. In contrast to FftGeneric,
FftImage, and FftImageInv, the fact that the input image in the forward transform is a real-valued image
(i.e., not a complex image) is used. In this case, the complex output image has a redundancy. The values in
the right half of the image are the complex conjugates of the corresponding values in the left half of the image.
Consequently, runtime and memory can be saved by only computing and storing the left half of the complex image.
The parameter ResultType can be used to specify the result image type of the reverse transform (Direction
= ’from_freq’). In the forward transform (Direction = ’to_freq’), ResultType must be set to ’complex’.
The parameter direction determines whether the transform should be performed to the frequency domain or back
into the spatial domain. For Direction = ’to_freq’ the input image must have a real-valued type, i.e., a complex
image may not be used as input. All image types that can be converted into an image of type real are supported. In
this case, the output is a complex image of dimension (w/2 + 1) × h, where w and h are the width and height of
the input image. In this mode, the exponent -1 is used in the transform (see FftGeneric). For Direction =
’from_freq’, the input image must be complex. In this case, the size of the input image is insufficient to determine
the size of the output image. This must be done by setting Width to a valid value, i.e., to 2w − 2 or 2w − 1, where
w is the width of the complex image. In this mode, the exponent 1 is used in the transform.
The normalizing factor can be set with Norm, and can take on the values ’none’, ’sqrt’ and ’n’. The user must
ensure the consistent use of the parameters. This means that the normalizing factors used for the forward and
backward transform must yield wh when multiplied.
Parameter
. Image (input iconic) . . . . . . image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2,
uint2, int4, real, complex )
Input image.
. ImageFFT (output iconic) . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, direction, cyclic,
int1, int2, uint2, int4, real, complex )
Fourier-transformed image.
. Direction (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Calculate forward or reverse transform.
Default Value : ’to_freq’
List of values : Direction ∈ {’to_freq’, ’from_freq’}
. Norm (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Normalizing factor of the transform.
Default Value : ’sqrt’
List of values : Norm ∈ {’none’, ’sqrt’, ’n’}
. ResultType (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Image type of the output image.
Default Value : ’complex’
List of values : ResultType ∈ {’complex’, ’byte’, ’int1’, ’int2’, ’uint2’, ’int4’, ’real’, ’direction’, ’cyclic’}
. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Width of the image for which the runtime should be optimized.
Default Value : 512
Suggested values : Width ∈ {128, 160, 192, 256, 320, 384, 512, 640, 768, 1024, 2048}
Result
RftGeneric returns TRUE if all parameters are correct. If the input is empty the behavior can be set via
SetSystem(::’noObjectResult’,<Result>:). If necessary, an exception handling is raised.

HALCON 8.0.2
190 CHAPTER 3. FILTER

Parallelization Information
RftGeneric is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
OptimizeRftSpeed, ReadFftOptimizationData
Possible Successors
ConvolFft, ConvertImageType, PowerByte, PowerReal, PowerLn, PhaseDeg, PhaseRad
Alternatives
FftGeneric, FftImage, FftImageInv
Module
Foundation

void HMiscX.WriteFftOptimizationData ([in] String FileName )


void HOperatorSetX.WriteFftOptimizationData
([in] VARIANT FileName )

Store FFT speed optimization data in a file.


WriteFftOptimizationData stores the data for the optimization of the runtime of the FFT that were
determined with OptimizeFftSpeed in the file given by FileName. The data can be loaded with
ReadFftOptimizationData.
Parameter

. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.write ; String / VARIANT


File name of the optimization data.
Default Value : ’fft_opt.dat’
Result
WriteFftOptimizationData returns TRUE if all parameters are correct. If necessary, an exception handling
is raised.
Parallelization Information
WriteFftOptimizationData is reentrant and processed without parallelization.
Possible Predecessors
OptimizeFftSpeed, OptimizeRftSpeed
See also
FftGeneric, FftImage, FftImageInv, WienerFilter, WienerFilterNi, PhotStereo,
SfsPentland, SfsModLr, SfsOrigLr, ReadFftOptimizationData
Module
Foundation

3.7 Geometric-Transformations
[out] HImageX ImageAffinTrans HImageX.AffineTransImage
([in] HHomMat2dX HomMat2D, [in] String Interpolation,
[in] String AdaptImageSize )
[out] HImageX ImageAffinTrans HHomMat2dX.AffineTransImage
([in] HImageX Image, [in] String Interpolation, [in] String AdaptImageSize )
void HOperatorSetX.AffineTransImage ([in] IHObjectX Image,
[out] HUntypedObjectX ImageAffinTrans, [in] VARIANT HomMat2D,
[in] VARIANT Interpolation, [in] VARIANT AdaptImageSize )

Apply an arbitrary affine 2D transformation to images.


AffineTransImage applies an arbitrary affine 2D transformation, i.e., scaling, rotation, translation, and
slant (skewing), to the images given in Image and returns the transformed images in ImageAffinTrans.

HALCON/COM Reference Manual, 2008-5-13


3.7. GEOMETRIC-TRANSFORMATIONS 191

The affine transformation is described by the homogeneous transformation matrix given in HomMat2D, which
can be created using the operators HomMat2dIdentity, HomMat2dScale, HomMat2dRotate,
HomMat2dTranslate, etc., or be the result of operators like VectorAngleToRigid.
The components of the homogeneous transformation matrix are interpreted as follows: The row coordinate of the
image corresponds to x and the col coordinate corresponds to y of the coordinate system in which the transforma-
tion matrix was defined. This is necessary to obtain a right-handed coordinate system for the image. In particular,
this assures that rotations are performed in the correct direction. Note that the (x,y) order of the matrices quite
naturally corresponds to the usual (row,column) order for coordinates in the image.
The region of the input image is ignored, i.e., assumed to be the full rectangle of the image. The region of the
resulting image is set to the transformed rectangle of the input image. If necessary, the resulting image is filled
with zero (black) outside of the region of the original image.
Generally, transformed points will lie between pixel coordinates. Therefore, an appropriate interpolation scheme
has to be used. The interpolation can also be used to avoid aliasing effects for scaled images. The quality and
speed of the interpolation can be set by the parameter Interpolation:
none Nearest-neighbor interpolation: The gray value is determined from the nearest pixel’s gray value (pos-
sibly low quality, very fast).
constant Bilinear interpolation. The gray value is determined from the four nearest pixels through bilinear
interpolation. If the affine transformation contains a scaling with a scale factor < 1, a kind of mean
filter is used to prevent aliasing effects (medium quality and run time).
weighted Bilinear interpolation. The gray value is determined from the four nearest pixels through bilinear
interpolation. If the affine transformation contains a scaling with a scale factor < 1, a kind of Gaussian
filter is used to prevent aliasing effects (best quality, slow).
In addition, the system parameter ’int_zooming’ (see SetSystem) affects the accuracy of the transformation. If
’int_zooming’ is set to ’true’, the transformation for byte, int2 and uint2 images is carried out internally using fixed
point arithmetic, leading to much shorter execution times. However, the accuracy of the transformed gray values
is smaller in this case. For byte images, the differences to the more accurate calculation (using ’int_zooming’ =
’false’) is typically less than two gray levels. Correspondingly, for int2 and uint2 images, the gray value differences
are less than 1/128 times the dynamic gray value range of the image, i.e., they can be as large as 512 gray levels if
the entire dynamic range of 16 bit is used. Additionally, if a large scale factor is applied and a large output image
is obtained, then undefined gray values at the lower and at the right image border may result. The maximum width
Bmax of this border of undefined gray values can be estimated as Bmax = 0.5 · S · I/215 , where S is the scale
factor in one dimension and I is the size of the output image in the corresponding dimension. For real images, the
parameter ’int_zooming’ does not affect the accuracy, since the internal calculations are always done using floating
point arithmetic.
The size of the target image can be controlled by the parameter AdaptImageSize: With value ’true’ the size
will be adapted so that no clipping occurs at the right or lower edge. With value ’false’ the target image has the
same size as the input image. Note that, independent of AdaptImageSize, the image is always clipped at the
left and upper edge, i.e., all image parts that have negative coordinates after the transformation are clipped.
Attention
The region of the input image is ignored.
The used coordinate system is the same as in AffineTransPixel. This means that in fact not HomMat2D
is applied but a modified version. Therefore, applying AffineTransImage corresponds to the following
chain of transformations, which is applied to each point (Row_i, Col_i) of the image (input and output pixels as
homogeneous vectors):
       
RowT rans_i 1 0 −0.5 1 0 +0.5 Row_i
 ColT rans_i  =  0 1 −0.5  · HomMat2D ·  0 1 +0.5  ·  Col_i 
1 0 0 1 0 0 1 1

As an effect, you might get unexpected results when creating affine transformations based on coordinates that are
derived from the image, e.g., by operators like AreaCenterGray. For example, if you use this operator to
calculate the center of gravity of a rotationally symmetric image and then rotate the image around this point using
HomMat2dRotate, the resulting image will not lie on the original one. In such a case, you can compensate this
effect by applying the following translations to HomMat2D before using it in AffineTransImage:
hom_mat2d_translate(HomMat2D, 0.5, 0.5, HomMat2DTmp)
hom_mat2d_translate_local(HomMat2DTmp, -0.5, -0.5, HomMat2DAdapted)

HALCON 8.0.2
192 CHAPTER 3. FILTER

affine_trans_image(Image, ImageAffinTrans, HomMat2DAdapted, ’constant’,


’false’)

Parameter
. Image (input iconic) . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, int2, uint2, real )
Input image.
. ImageAffinTrans (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX
( byte, int2, uint2, real )
Transformed image.
. HomMat2D (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )
Input transformation matrix.
. Interpolation (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Type of interpolation.
Default Value : ’constant’
List of values : Interpolation ∈ {’none’, ’constant’, ’weighted’}
. AdaptImageSize (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Adaption of size of result image.
Default Value : ’false’
List of values : AdaptImageSize ∈ {’true’, ’false’}
Example

/* Reduction of an image (512 x 512 Pixels) by 50%, rotation */


/* by 180 degrees and translation to the upper-left corner: */

hom_mat2d_identity(Matrix1)
hom_mat2d_scale(Matrix1,0.5,0.5,256.0,256.0,Matrix2)
hom_mat2d_rotate(Matrix2,3.14,256.0,256.0,Matrix3)
hom_mat2d_translate(Matrix3,-128.0,-128.0,Matrix4,)
affine_trans_image(Image,TransImage,Matrix4,1).

/* Enlarging the part of an image in the interactively */


/* chosen rectangular window sector: */

draw_rectangle2(WindowHandle,L,C,Phi,L1,L2)
hom_mat2d_identity(Matrix1)
get_system(width,Width)
get_system(height,Height)
hom_mat2d_translate(Matrix1,Height/2.0-L,Width/2.0-C,Matrix2)
hom_mat2d_rotate(Matrix2,3.14-Phi,Height/2.0,Width/2.0,Matrix3)
hom_mat2d_scale(Matrix3,Height/(2.0*L2),Width/(2.0*L1),
Height/2.0,Width/2.0,Matrix4)
affine_trans_image(Image,Matrix4,TransImage,1).

Result
If the matrix HomMat2D represents an affine transformation (i.e., not a projective transformation),
AffineTransImage returns TRUE. If the input is empty the behavior can be set via SetSystem(::
’noObjectResult’,<Result>:). If necessary, an exception handling is raised.
Parallelization Information
AffineTransImage is reentrant and automatically parallelized (on tuple level, channel level).
Possible Predecessors
HomMat2dIdentity, HomMat2dTranslate, HomMat2dRotate, HomMat2dScale
See also
SetPartStyle
Alternatives
AffineTransImageSize, ZoomImageSize, ZoomImageFactor, MirrorImage, RotateImage,
AffineTransRegion

HALCON/COM Reference Manual, 2008-5-13


3.7. GEOMETRIC-TRANSFORMATIONS 193

Module
Foundation

[out] HImageX ImageAffinTrans HImageX.AffineTransImageSize


([in] HHomMat2dX HomMat2D, [in] String Interpolation, [in] long Width,
[in] long Height )
[out] HImageX ImageAffinTrans HHomMat2dX.AffineTransImageSize
([in] HImageX Image, [in] String Interpolation, [in] long Width,
[in] long Height )
void HOperatorSetX.AffineTransImageSize ([in] IHObjectX Image,
[out] HUntypedObjectX ImageAffinTrans, [in] VARIANT HomMat2D,
[in] VARIANT Interpolation, [in] VARIANT Width, [in] VARIANT Height )

Apply an arbitrary affine 2D transformation to an image and specify the output image size.
AffineTransImageSize applies an arbitrary affine 2D transformation, i.e., scaling, rotation, translation, and
slant (skewing), to the images given in Image and returns the transformed images in ImageAffinTrans.
The affine transformation is described by the homogeneous transformation matrix given in HomMat2D, which
can be created using the operators HomMat2dIdentity, HomMat2dScale, HomMat2dRotate,
HomMat2dTranslate, etc., or be the result of operators like VectorAngleToRigid.
The components of the homogeneous transformation matrix are interpreted as follows: The row coordinate of the
image corresponds to x and the col coordinate corresponds to y of the coordinate system in which the transforma-
tion matrix was defined. This is necessary to obtain a right-handed coordinate system for the image. In particular,
this assures that rotations are performed in the correct direction. Note that the (x,y) order of the matrices quite
naturally corresponds to the usual (row,column) order for coordinates in the image.
The region of the input image is ignored, i.e., assumed to be the full rectangle of the image. The region of the
resulting image is set to the transformed rectangle of the input image. If necessary, the resulting image is filled
with zero (black) outside of the region of the original image.
Generally, transformed points will lie between pixel coordinates. Therefore, an appropriate interpolation scheme
has to be used. The interpolation can also be used to avoid aliasing effects for scaled images. The quality and
speed of the interpolation can be set by the parameter Interpolation:
none Nearest-neighbor interpolation: The gray value is determined from the nearest pixel’s gray value (pos-
sibly low quality, very fast).
constant Bilinear interpolation. The gray value is determined from the four nearest pixels through bilinear
interpolation. If the affine transformation contains a scaling with a scale factor < 1, a kind of mean
filter is used to prevent aliasing effects (medium quality and run time).
weighted Bilinear interpolation. The gray value is determined from the four nearest pixels through bilinear
interpolation. If the affine transformation contains a scaling with a scale factor < 1, a kind of Gaussian
filter is used to prevent aliasing effects (best quality, slow).
In addition, the system parameter ’int_zooming’ (see SetSystem) affects the accuracy of the transformation. If
’int_zooming’ is set to ’true’, the transformation for byte, int2 and uint2 images is carried out internally using fixed
point arithmetic, leading to much shorter execution times. However, the accuracy of the transformed gray values
is smaller in this case. For byte images, the differences to the more accurate calculation (using ’int_zooming’ =
’false’) is typically less than two gray levels. Correspondingly, for int2 and uint2 images, the gray value differences
are less than 1/128 times the dynamic gray value range of the image, i.e., they can be as large as 512 gray levels if
the entire dynamic range of 16 bit is used. Additionally, if a large scale factor is applied and a large output image
is obtained, then undefined gray values at the lower and at the right image border may result. The maximum width
Bmax of this border of undefined gray values can be estimated as Bmax = 0.5 · S · I/215 , where S is the scale
factor in one dimension and I is the size of the output image in the corresponding dimension. For real images, the
parameter ’int_zooming’ does not affect the accuracy, since the internal calculations are always done using floating
point arithmetic.
The size of the target image is specifed by the parameters Width and Height. Note that the image is always
clipped at the left and upper edge, i.e., all image parts that have negative coordinates after the transformation are
clipped. If the affine transformation (in particular, the translation) is chosen appropriately, a part of the image
can be transformed as well as cropped in one call. This is useful, for example, when using the variation model

HALCON 8.0.2
194 CHAPTER 3. FILTER

(see CompareVariationModel), because with this mechanism only the parts of the image that should be
examined, are transformed.
Attention
The region of the input image is ignored.
The used coordinate system is the same as in AffineTransPixel. This means that in fact not HomMat2D is
applied but a modified version. Therefore, applying AffineTransImageSize corresponds to the following
chain of transformations, which is applied to each point (Row_i, Col_i) of the image (input and output pixels as
homogeneous vectors):
       
RowT rans_i 1 0 −0.5 1 0 +0.5 Row_i
 ColT rans_i  =  0 1 −0.5  · HomMat2D ·  0 1 +0.5  ·  Col_i 
1 0 0 1 0 0 1 1

As an effect, you might get unexpected results when creating affine transformations based on coordinates that are
derived from the image, e.g., by operators like AreaCenterGray. For example, if you use this operator to
calculate the center of gravity of a rotationally symmetric image and then rotate the image around this point using
HomMat2dRotate, the resulting image will not lie on the original one. In such a case, you can compensate this
effect by applying the following translations to HomMat2D before using it in AffineTransImageSize:
hom_mat2d_translate(HomMat2D, 0.5, 0.5, HomMat2DTmp)
hom_mat2d_translate_local(HomMat2DTmp, -0.5, -0.5, HomMat2DAdapted)
affine_trans_image_size(Image, ImageAffinTrans, HomMat2DAdapted,
’constant’, Width, Height)

Parameter
. Image (input iconic) . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, int2, uint2, real )
Input image.
. ImageAffinTrans (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX
( byte, int2, uint2, real )
Transformed image.
. HomMat2D (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )
Input transformation matrix.
. Interpolation (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Type of interpolation.
Default Value : ’constant’
List of values : Interpolation ∈ {’none’, ’constant’, ’weighted’}
. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; long / VARIANT
Width of the output image.
Default Value : 640
Suggested values : Width ∈ {128, 160, 192, 256, 320, 384, 512, 640, 768}
. Height (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; long / VARIANT
Height of the output image.
Default Value : 480
Suggested values : Height ∈ {120, 128, 144, 240, 256, 288, 480, 512, 576}
Result
If the matrix HomMat2D represents an affine transformation (i.e., not a projective transformation),
AffineTransImageSize returns TRUE. If the input is empty the behavior can be set via SetSystem(::
’noObjectResult’,<Result>:). If necessary, an exception handling is raised.
Parallelization Information
AffineTransImageSize is reentrant and automatically parallelized (on tuple level, channel level).
Possible Predecessors
HomMat2dIdentity, HomMat2dTranslate, HomMat2dRotate, HomMat2dScale
See also
SetPartStyle
Alternatives
AffineTransImage, ZoomImageSize, ZoomImageFactor, MirrorImage, RotateImage,
AffineTransRegion

HALCON/COM Reference Manual, 2008-5-13


3.7. GEOMETRIC-TRANSFORMATIONS 195

Module
Foundation

[out] HImageX MosaicImage HImageX.GenBundleAdjustedMosaic


([in] HHomMat2dX HomMatrices2D, [in] VARIANT StackingOrder,
[in] String TransformRegion, [out] HHomMat2dX TransMat2D )
void HOperatorSetX.GenBundleAdjustedMosaic ([in] IHObjectX Images,
[out] HUntypedObjectX MosaicImage, [in] VARIANT HomMatrices2D,
[in] VARIANT StackingOrder, [in] VARIANT TransformRegion,
[out] VARIANT TransMat2D )

Combine multiple images into a mosaic image.


GenBundleAdjustedMosaic combines the input images contained in the object Images into a mosaic image
MosaicImage. The relative positions of the images are defined by 3 × 3 projective transformation matrices. The
array HomMatrices2D contains a sequence of these linearized matrices. The transformation matrices can be
computed with BundleAdjustMosaic.
The origin of MosaicImage and its size are automatically chosen so that all of the input images are completely
visible.
The order in which the images are added to the mosaic is given by the array StackingOrder. The first index in
this array will end up at the bottom of the image stack while the last one will be on top. If ’default’ is given instead
of an array of integers, the canonical order (images in the order used in Images) will be used.
The parameter TransformRegion can be used to determine whether the domains of Images are also trans-
formed. Since the transformation of the domains costs runtime, this parameter should be used to specify whether
this is desired or not. If TransformRegion is set to ’false’ the domain of the input images is ignored and the
complete images are transformed.
On output, the parameter TransMat2D contains a 3 × 3 projective transformation matrix that describes the
translation that was necessary to transform all images completely into the output image.
Parameter
. Images (input iconic) . . . . . . . . . . . . . . . . (multichannel-)image ; HImageX / IHObjectX ( byte, uint2, real )
Input images.
. MosaicImage (output iconic) . . . . . . (multichannel-)image ; HImageX / HUntypedObjectX ( byte, uint2,
real )
Output image.
. HomMatrices2D (input control) . . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )
Array of 3 × 3 projective transformation matrices.
. StackingOrder (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string, integer )
Stacking order of the images in the mosaic.
Default Value : ’default’
Suggested values : StackingOrder ∈ {’default’}
. TransformRegion (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Should the domains of the input images also be transformed?
Default Value : ’false’
List of values : TransformRegion ∈ {’true’, ’false’}
. TransMat2D (output control) . . . . . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )
3 × 3 projective transformation matrix that describes the translation that was necessary to transform all images
completely into the output image.
Parallelization Information
GenBundleAdjustedMosaic is reentrant and processed without parallelization.
Possible Predecessors
BundleAdjustMosaic
See also
ProjectiveTransImage, ProjectiveTransImageSize, ProjectiveTransRegion,
ProjectiveTransContourXld, ProjectiveTransPoint2D, ProjectiveTransPixel

HALCON 8.0.2
196 CHAPTER 3. FILTER

Alternatives
GenProjectiveMosaic
References
Richard Hartley, Andrew Zisserman: “Multiple View Geometry in Computer Vision”; Cambridge University Press,
Cambridge; 2000.
Olivier Faugeras, Quang-Tuan Luong: “The Geometry of Multiple Images: The Laws That Govern the Formation
of Multiple Images of a Scene and Some of Their Applications”; MIT Press, Cambridge, MA; 2001.
Module
Matching

[out] HImageX Front HImageX.GenCubeMapMosaic ([out] HImageX Rear,


[out] HImageX Left, [out] HImageX Right, [out] HImageX Top,
[out] HImageX Bottom, [in] HHomMat2dX CameraMatrices,
[in] HHomMat2dX RotationMatrices, [in] long CubeMapDimension,
[in] VARIANT StackingOrder, [in] String Interpolation )
void HOperatorSetX.GenCubeMapMosaic ([in] IHObjectX Images,
[out] HUntypedObjectX Front, [out] HUntypedObjectX Rear,
[out] HUntypedObjectX Left, [out] HUntypedObjectX Right,
[out] HUntypedObjectX Top, [out] HUntypedObjectX Bottom,
[in] VARIANT CameraMatrices, [in] VARIANT RotationMatrices,
[in] VARIANT CubeMapDimension, [in] VARIANT StackingOrder,
[in] VARIANT Interpolation )

Create 6 cube map images of a spherical mosaic.


GenCubeMapMosaic creates 6 cube map images of a spherical mosaic Front, Left, Rear, Right,
Top and Bottom from the input images passed in Images. The pose of the images in space, which
is used to compute the position of the images with respect to the surface of the sphere, can be deter-
mined with StationaryCameraSelfCalibration. The camera and rotation matrices computed with
StationaryCameraSelfCalibration can be used in CameraMatrices and RotationMatrices.
A spherical mosaic can only be created from images that were taken with a stationary camera (see
StationaryCameraSelfCalibration).
The width and height of the output cube map images can be selected by setting the parameter
CubeMapDimension. The value represents the width and height in pixels.
The mode in which the images are added to the mosaic is given by StackingOrder. For StackingOrder =
0
voronoi 0 , the points in the mosaic image are determined from the Voronoi cell of the respective input image. This
means that the gray values are taken from the points of the input image to whose center the pixel in the mosaic
image has the smallest distance on the sphere. This mode has the advantage that vignetting and uncorrected
radial distortions are less noticeable in the mosaic image because they typically are symmetric with respect to the
image center. Alternatively, with the choice of parameters described in the following, a mode can be selected that
has the same effect as if the images were painted successively into the mosaic image. Here, the order in which
the images are added to the mosaic image is important. Therefore, an array of integer values can be passed in
StackingOrder. The first index in this array will end up at the bottom of the image stack while the last one
will be on top. If ’default’ is given instead of an array of integers, the canonical order (images in the order used
in Images) will be used. Hence, if neither ’voronoi’ nor ’default’ are used, StackingOrder must contain a
permutation of the numbers 1,...,n, where n is the number of images passed in Images. It should be noted that
the mode ’voronoi’ cannot always be used. For example, at least two images must be passed to use this mode.
Furthermore, for very special configurations of the positions of the image centers on the sphere, the Voronoi cells
cannot be determined uniquely. With StackingOrder = 0 blend 0 , an additional mode is available, which blends
the images of the mosaic smoothly. This way seams between the images become less apparent. The seam lines
between the images are the same as in ’voronoi’. This mode leads to visually more appealing images, but requires
significantly more resources. If the mode ’voronoi’ or ’blend’ cannot be used for whatever reason the mode is
switched internally to ’default’ automatically.
The parameter Interpolation can be used to select the desired interpolation mode for creating the cube maps.
Bilinear and bicubic interpolation is available.

HALCON/COM Reference Manual, 2008-5-13


3.7. GEOMETRIC-TRANSFORMATIONS 197

Parameter

. Images (input iconic) . . . . . . . . . . . . . . . . (multichannel-)image ; HImageX / IHObjectX ( byte, uint2, real )


Input images.
. Front (output iconic) . . . . . . . . . (multichannel-)image ; HImageX / HUntypedObjectX ( byte, uint2, real )
Front cube map.
. Rear (output iconic) . . . . . . . . . . . (multichannel-)image ; HImageX / HUntypedObjectX ( byte, uint2, real )
Rear cube map.
. Left (output iconic) . . . . . . . . . . . (multichannel-)image ; HImageX / HUntypedObjectX ( byte, uint2, real )
Left cube map.
. Right (output iconic) . . . . . . . . . (multichannel-)image ; HImageX / HUntypedObjectX ( byte, uint2, real )
Right cube map.
. Top (output iconic) . . . . . . . . . . . . (multichannel-)image ; HImageX / HUntypedObjectX ( byte, uint2, real )
Top cube map.
. Bottom (output iconic) . . . . . . . . (multichannel-)image ; HImageX / HUntypedObjectX ( byte, uint2, real )
Bottom cube map.
. CameraMatrices (input control) . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )
(Array of) 3 × 3 projective camera matrices that determine the interior camera parameters.
. RotationMatrices (input control) . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )
Array of 3 × 3 transformation matrices that determine rotation of the camera in the respective image.
. CubeMapDimension (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; long / VARIANT
Width and height of the resulting cube maps.
Default Value : 1000
Restriction : (CubeM apDimension ≥ 0)
. StackingOrder (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string, integer )
Mode of adding the images to the mosaic image.
Default Value : ’voronoi’
Suggested values : StackingOrder ∈ {’blend’, ’voronoi’, ’default’}
. Interpolation (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Mode of image interpolation.
Default Value : ’bilinear’
Suggested values : Interpolation ∈ {’bilinear’, ’bicubic’}
Example

* For the input data to stationary_camera_self_calibration, please


* refer to the example for stationary_camera_self_calibration.
stationary_camera_self_calibration (4, 640, 480, 1, From, To,
HomMatrices2D, Rows1, Cols1,
Rows2, Cols2, NumMatches,
’gold_standard’,
[’focus’,’principal_point’],
’true’, CameraMatrix, Kappa,
RotationMatrices, X, Y, Z, Error)
gen_cube_map_mosaic (Images, Front, Left, Rear, Right, Top, Bottom,
CameraMatrix, RotationMatrices, 1000, ’default’,
’bicubic’)

* Alternatively, if kappa should be determined, the following calls


* can be made:
stationary_camera_self_calibration (4, 640, 480, 1, From, To,
HomMatrices2D, Rows1, Cols1,
Rows2, Cols2, NumMatches,
’gold_standard’,
[’focus’,’principal_point’,’kappa’],
’true’, CameraMatrix, Kappa,
RotationMatrices, X, Y, Z, Error)
cam_mat_to_cam_par (CameraMatrix, Kappa, 640, 480, CamParam)

HALCON 8.0.2
198 CHAPTER 3. FILTER

change_radial_distortion_cam_par (’fixed’, CamParam, 0, CamParOut)


gen_radial_distortion_map (Map, CamParam, CamParOut, ’bilinear’)
map_image (Images, Map, ImagesRect)
gen_cube_map_mosaic (Images, Front, Left, Rear, Right, Top, Bottom,
CameraMatrix, RotationMatrices, 1000, ’default’,
’bicubic’)

Result
If the parameters are valid, the operator GenCubeMapMosaic returns the value TRUE. If necessary an exception
handling is raised.
Parallelization Information
GenCubeMapMosaic is reentrant and processed without parallelization.
Possible Predecessors
StationaryCameraSelfCalibration
Alternatives
GenSphericalMosaic, GenProjectiveMosaic
References
Lourdes Agapito, E. Hayman, I. Reid: “Self-Calibration of Rotating and Zooming Cameras”; International Journal
of Computer Vision; vol. 45, no. 2; pp. 107–127; 2001.
Olivier Faugeras, Quang-Tuan Luong: “The Geometry of Multiple Images: The Laws That Govern the Formation
of Multiple Images of a Scene and Some of Their Applications”; MIT Press, Cambridge, MA; 2001.
Module
Matching

[out] HImageX MosaicImage HImageX.GenProjectiveMosaic


([in] long StartImage, [in] VARIANT MappingSource, [in] VARIANT MappingDest,
[in] HHomMat2dX HomMatrices2D, [in] VARIANT StackingOrder,
[in] String TransformRegion, [out] HHomMat2dX MosaicMatrices2D )
void HOperatorSetX.GenProjectiveMosaic ([in] IHObjectX Images,
[out] HUntypedObjectX MosaicImage, [in] VARIANT StartImage,
[in] VARIANT MappingSource, [in] VARIANT MappingDest,
[in] VARIANT HomMatrices2D, [in] VARIANT StackingOrder,
[in] VARIANT TransformRegion, [out] VARIANT MosaicMatrices2D )

Combine multiple images into a mosaic image.


GenProjectiveMosaic combines the input images contained in the object Images into a mosaic image
MosaicImage. The relative positions of the images are defined by 3 × 3 projective transformation matrices. The
array HomMatrices2D contains a sequence of these linearized matrices. The values in MappingSource and
MappingDest are the indices of the images that the corresponding matrix applies to. MappingSource=4 and
MappingDest=7 means that the matrix describes the transformation of the image number 4 into the projective
plane of image 7. The transformation matrices between the respective image pairs given by MappingSource
and MappingDest are typically determined with ProjMatchPointsRansac.
As usual for operators that access image objects (e.g., SelectObj), the images are numbered starting from 1,
i.e., MappingSource, MappingDest, StartImage, and StackingOrder) must contain values between
1 and the number of images passed in Images.
The parameter StartImage states which image defines the image plane of the final image, that is, which input
image remains unchanged in the output image. This is usually an image that is located near the center of the image
mosaic.
The origin of MosaicImage and its size are automatically chosen so that all of the input images are completely
visible.

HALCON/COM Reference Manual, 2008-5-13


3.7. GEOMETRIC-TRANSFORMATIONS 199

The order in which the images are added to the mosaic is given by the array StackingOrder. The first index in
this array will end up at the bottom of the image stack while the last one will be on top. If ’default’ is given instead
of an array of integers, the canonical order (images in the order used in Images) will be used.
The parameter TransformRegion can be used to determine whether the domains of Images are also trans-
formed. Since the transformation of the domains costs runtime, this parameter should be used to specify whether
this is desired or not. If TransformRegion is set to ’false’ the domain of the input images is ignored and the
complete images are transformed.
On output, the parameter MosaicMatrices2D contains a set of 3 × 3 projective transformation matrices that
describe for each image in Images the mapping of the image to its position in the mosaic.
Parameter
. Images (input iconic) . . . . . . . . . . . . . . . . (multichannel-)image ; HImageX / IHObjectX ( byte, uint2, real )
Input images.
. MosaicImage (output iconic) . . . . . . (multichannel-)image ; HImageX / HUntypedObjectX ( byte, uint2,
real )
Output image.
. StartImage (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Index of the central input image.
. MappingSource (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Indices of the source images of the transformations.
. MappingDest (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Indices of the target images of the transformations.
. HomMatrices2D (input control) . . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )
Array of 3 × 3 projective transformation matrices.
. StackingOrder (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string, integer )
Stacking order of the images in the mosaic.
Default Value : ’default’
Suggested values : StackingOrder ∈ {’default’}
. TransformRegion (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Should the domains of the input images also be transformed?
Default Value : ’false’
List of values : TransformRegion ∈ {’true’, ’false’}
. MosaicMatrices2D (output control) . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )
Array of 3 × 3 projective transformation matrices that determine the position of the images in the mosaic.
Example

gen_empty_obj (Images)
for J := 1 to 6 by 1
read_image (Image, ’mosaic/pcb_’+J$’02’)
concat_obj (Images, Image, Images)
endfor
From := [1,2,3,4,5]
To := [2,3,4,5,6]
Num := |From|
ProjMatrices := []
for J := 0 to Num-1 by 1
F := From[J]
T := To[J]
select_obj (Images, F, ImageF)
select_obj (Images, T, ImageT)
points_foerstner (ImageF, 1, 2, 3, 200, 0.3, ’gauss’, ’false’,
RowJunctionsF, ColJunctionsF, CoRRJunctionsF,
CoRCJunctionsF, CoCCJunctionsF, RowAreaF,
ColAreaF, CoRRAreaF, CoRCAreaF, CoCCAreaF)
points_foerstner (ImageT, 1, 2, 3, 200, 0.3, ’gauss’, ’false’,
RowJunctionsT, ColJunctionsT, CoRRJunctionsT,
CoRCJunctionsT, CoCCJunctionsT, RowAreaT,

HALCON 8.0.2
200 CHAPTER 3. FILTER

ColAreaT, CoRRAreaT, CoRCAreaT, CoCCAreaT)


proj_match_points_ransac (ImageF, ImageT, RowJunctionsF,
ColJunctionsF, RowJunctionsT,
ColJunctionsT, ’ncc’, 21, 0, 0, 480, 640,
0, 0.5, ’gold_standard’, 1, 4364537,
ProjMatrix, Points1, Points2)
ProjMatrices := [ProjMatrices,ProjMatrix]
endfor
gen_projective_mosaic (Images, MosaicImage, 2, From, To, ProjMatrices,
’default’, ’false’, MosaicMatrices2D)

Parallelization Information
GenProjectiveMosaic is reentrant and processed without parallelization.
Possible Predecessors
ProjMatchPointsRansac, VectorToProjHomMat2d, HomVectorToProjHomMat2d
See also
ProjectiveTransImage, ProjectiveTransImageSize, ProjectiveTransRegion,
ProjectiveTransContourXld, ProjectiveTransPoint2D, ProjectiveTransPixel
References
Richard Hartley, Andrew Zisserman: “Multiple View Geometry in Computer Vision”; Cambridge University Press,
Cambridge; 2000.
Olivier Faugeras, Quang-Tuan Luong: “The Geometry of Multiple Images: The Laws That Govern the Formation
of Multiple Images of a Scene and Some of Their Applications”; MIT Press, Cambridge, MA; 2001.
Module
Matching

[out] HImageX MosaicImage HImageX.GenSphericalMosaic


([in] HHomMat2dX CameraMatrices, [in] HHomMat2dX RotationMatrices,
[in] VARIANT LatMin, [in] VARIANT LatMax, [in] VARIANT LongMin,
[in] VARIANT LongMax, [in] VARIANT LatLongStep, [in] VARIANT StackingOrder,
[in] VARIANT Interpolation )
void HOperatorSetX.GenSphericalMosaic ([in] IHObjectX Images,
[out] HUntypedObjectX MosaicImage, [in] VARIANT CameraMatrices,
[in] VARIANT RotationMatrices, [in] VARIANT LatMin, [in] VARIANT LatMax,
[in] VARIANT LongMin, [in] VARIANT LongMax, [in] VARIANT LatLongStep,
[in] VARIANT StackingOrder, [in] VARIANT Interpolation )

Create a spherical mosaic image.


GenSphericalMosaic creates a spherical mosaic image MosaicImage from the input images passed in
Images. The pose of the images in space, which is used to compute the position of the images with respect to the
surface of the sphere, can be determined with StationaryCameraSelfCalibration. The camera and ro-
tation matrices computed with StationaryCameraSelfCalibration can be used in CameraMatrices
and RotationMatrices. A spherical mosaic can only be created from images that were taken with a stationary
camera (see StationaryCameraSelfCalibration).
The mosaic is computed in spherical coordinates (longitude and latitude). The row axis of MosaicImage corre-
sponds to the latitude, while the column axis corresponds to the longitude. The part of the sphere that is computed
by GenSphericalMosaic is determined by LatMin, LatMax, LongMin, and LongMax. These parameters
are specified in degrees and determine a rectangular part of the latitude and longitude coordinates. The latitude -90
corresponds to the north pole (i.e., the straight up viewing direction), while 90 corresponds to the south pole (i.e.,
the straight down viewing direction). The longitude 0 corresponds to the straight ahead viewing direction. Negative
longitudes correspond to viewing directions to the left, while positive longitudes correspond to viewing directions
to the right. Hence, to obtain a complete image of the sphere, LatMin = -90, LatMax = 90, LongMin = -180,
and LongMax = 180 must be used. In many cases, the mosaic will not cover the entire sphere. In these cases, it is
useful to select the desired part of the sphere with the above parameters. This can be done by explicitly specifying

HALCON/COM Reference Manual, 2008-5-13


3.7. GEOMETRIC-TRANSFORMATIONS 201

the desired rectangle. However, often it is desirable to determine the smallest rectangle that encloses all images
automatically. This can be done by using LatMin < -90, LatMax > 90, LongMin < -180, and LongMax >
180. Only the parameters that lie outside the normal range of values are determined automatically.
The angle step per pixel in MosaicImage can be selected with LatLongStep, which also is an angle specified
in degrees. With this, the resolution of the mosaic image can be controlled. If LatLongStep is set to 0 the angle
step is calculated automatically by trying to preserve the pixel size of the original images as well as possible.
The mode in which the images are added to the mosaic is given by StackingOrder. For StackingOrder =
0
voronoi 0 , the points in the mosaic image are determined from the Voronoi cell of the respective input image. This
means that the gray values are taken from the points of the input image to whose center the pixel in the mosaic
image has the smallest distance on the sphere. This mode has the advantage that vignetting and uncorrected radial
distortions are less noticeable in the mosaic image because they typically are symmetric with respect to the image
center. Alternatively, with the choice of parameters described described in the following, a mode can be selected
that has the same effect as if the images were painted successively into the mosaic image. Here, the order in which
the images are added to the mosaic image is important. Therefore, an array of integer values can be passed in
StackingOrder. The first index in this array will end up at the bottom of the image stack while the last one
will be on top. If ’default’ is given instead of an array of integers, the canonical order (images in the order used
in Images) will be used. Hence, if neither ’voronoi’ nor ’default’ are used, StackingOrder must contain a
permutation of the numbers 1,...,n, where n is the number of images passed in Images. It should be noted that
the mode ’voronoi’ cannot always be used. For example, at least two images must be passed to use this mode.
Furthermore, for very special configurations of the positions of the image centers on the sphere, the Voronoi cells
cannot be determined uniquely. With StackingOrder = 0 blend 0 , an additional mode is available, which blends
the images of the mosaic smoothly. This way seams between the images become less apparent. The seam lines
between the images are the same as in ’voronoi’. This mode leads to visually more appealing images, but requires
significantly more resources. If the mode ’voronoi’ or ’blend’ cannot be used for whatever reason the mode is
switched internally to ’default’ automatically.
The parameter Interpolation can be used to select the desired interpolation mode for creating the mosaic.
Bilinear and bicubic interpolation is available.
Parameter
. Images (input iconic) . . . . . . . . . . . . . . . . (multichannel-)image ; HImageX / IHObjectX ( byte, uint2, real )
Input images.
. MosaicImage (output iconic) . . . . . . (multichannel-)image ; HImageX / HUntypedObjectX ( byte, uint2,
real )
Output image.
. CameraMatrices (input control) . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )
(Array of) 3 × 3 projective camera matrices that determine the interior camera parameters.
. RotationMatrices (input control) . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )
Array of 3 × 3 transformation matrices that determine rotation of the camera in the respective image.
. LatMin (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.deg ; VARIANT ( real, integer )
Minimum latitude of points in the spherical mosaic image.
Default Value : -90
Suggested values : LatMin ∈ {-100, -90, -80, -70, -60, -50, -40, -30, -20, -10}
Restriction : (LatM in ≤ 90)
. LatMax (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.deg ; VARIANT ( real, integer )
Maximum latitude of points in the spherical mosaic image.
Default Value : 90
Suggested values : LatMax ∈ {10, 20, 30, 40, 50, 60, 70, 80, 90, 100}
Restriction : ((LatM ax ≥ −90) ∧ (LatM ax > LatM in))
. LongMin (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.deg ; VARIANT ( real, integer )
Minimum longitude of points in the spherical mosaic image.
Default Value : -180
Suggested values : LongMin ∈ {-200, -180, -160, -140, -120, -100, -90, -80, -70, -60, -50, -40, -30, -20, -10}
Restriction : (LongM in ≤ 180)
. LongMax (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.deg ; VARIANT ( real, integer )
Maximum longitude of points in the spherical mosaic image.
Default Value : 180
Suggested values : LongMax ∈ {10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 120, 140, 160, 180, 200}
Restriction : ((LongM ax ≥ −90) ∧ (LongM ax > LongM in))

HALCON 8.0.2
202 CHAPTER 3. FILTER

. LatLongStep (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.deg ; VARIANT ( real, integer )


Latitude and longitude angle step width.
Default Value : 0.1
Suggested values : LatLongStep ∈ {0, 0.02, 0.05, 0.1, 0.2, 0.5, 1}
Restriction : (LatLongStep ≥ 0)
. StackingOrder (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string, integer )
Mode of adding the images to the mosaic image.
Default Value : ’voronoi’
Suggested values : StackingOrder ∈ {’blend’, ’voronoi’, ’default’}
. Interpolation (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( string, integer )
Mode of interpolation when creating the mosaic image.
Default Value : ’bilinear’
Suggested values : Interpolation ∈ {’bilinear’, ’bicubic’}
Example

* For the input data to stationary_camera_self_calibration, please


* refer to the example for stationary_camera_self_calibration.
stationary_camera_self_calibration (4, 640, 480, 1, From, To,
HomMatrices2D, Rows1, Cols1,
Rows2, Cols2, NumMatches,
’gold_standard’,
[’focus’,’principal_point’],
’true’, CameraMatrix, Kappa,
RotationMatrices, X, Y, Z, Error)
gen_spherical_mosaic (Images, MosaicImage, CameraMatrix,
RotationMatrices, -100, 100, -200, 200, 0,
’default’)

* Alternatively, if kappa should be determined, the following calls


* can be made:
stationary_camera_self_calibration (4, 640, 480, 1, From, To,
HomMatrices2D, Rows1, Cols1,
Rows2, Cols2, NumMatches,
’gold_standard’,
[’focus’,’principal_point’,’kappa’],
’true’, CameraMatrix, Kappa,
RotationMatrices, X, Y, Z, Error)
cam_mat_to_cam_par (CameraMatrix, Kappa, 640, 480, CamParam)
change_radial_distortion_cam_par (’fixed’, CamParam, 0, CamParOut)
gen_radial_distortion_map (Map, CamParam, CamParOut, ’bilinear’)
map_image (Images, Map, ImagesRect)
gen_spherical_mosaic (ImagesRect, MosaicImage, CameraMatrix,
RotationMatrices, -100, 100, -200, 200, 0,
’default’)

Result
If the parameters are valid, the operator GenSphericalMosaic returns the value TRUE. If necessary an
exception handling is raised.
Parallelization Information
GenSphericalMosaic is reentrant and processed without parallelization.
Possible Predecessors
StationaryCameraSelfCalibration
Alternatives
GenCubeMapMosaic, GenProjectiveMosaic
References
Lourdes Agapito, E. Hayman, I. Reid: “Self-Calibration of Rotating and Zooming Cameras”; International Journal
of Computer Vision; vol. 45, no. 2; pp. 107–127; 2001.

HALCON/COM Reference Manual, 2008-5-13


3.7. GEOMETRIC-TRANSFORMATIONS 203

Olivier Faugeras, Quang-Tuan Luong: “The Geometry of Multiple Images: The Laws That Govern the Formation
of Multiple Images of a Scene and Some of Their Applications”; MIT Press, Cambridge, MA; 2001.
Module
Matching

HImageX.MapImage ([in] HImageX Map )


[out] HImageX ImageMapped
void HOperatorSetX.MapImage ([in] IHObjectX Image, [in] IHObjectX Map,
[out] HUntypedObjectX ImageMapped )

Apply a general transformation to an image.


MapImage transforms an image Image using an arbitrary transformation Map which, for example, was previ-
ously generated using GenImageToWorldPlaneMap or GenRadialDistortionMap. The multi-channel
image Map must be organized as follows:
The height and the width of Map define the size of the output image ImageMapped. The number of channels
in Map defines whether no interpolation or bilinear interpolation should be used. If Map only consists of one
channel, no interpolation is applied during the transformation. This channel containes ’int4’ values that describe
the geometric transformation: For each pixel in the output image ImageMapped the linearized coordinate of the
pixel in the input image Image from which the gray value should be taken is stored.
If bilinear interpolation between the pixels in the input image should be applied, Map must consist of 5 channels.
The first channel again consists of an ’int4’ image and describes the geometric transformation. The channels 2-5
consist of an ’uint2’ image each and contain the weights [0...1] of the four neighboring pixels that are used during
bilinear interpolation. If the overall brightness of the output image ImageMapped should not differ from the
overall brighntess of the input image Image, the sum of the four unscaled weights must be 1 for each pixel. The
weights [0...1] are scaled to the range of values of the ’uint2’ image and therefore hold integer values from 0 bis
65535.
Furthermore, the weights must be chosen in a way that the range of values of the output image ImageMapped is
not exceeded. The geometric relation between the four channels 2-5 is illustrated in the following sketch:
2 3
4 5
The reference point of the four pixels is the upper left pixel. The linearized coordinate of the reference point is
stored in the first channel.
Attention
The weights must be choosen in a way that the range of values of the output image ImageMapped is not exceeded.
For runtime reasons during the mapping process, it is not checked whether the linearized coordinates which are
stored in the first channel of Map, lie inside the input image. Thus, it must be ensured by the user that this constraint
is fulfilled. Otherwise, the program may crash!
Parameter
. Image (input iconic) . . . . . . . . . . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, uint2 )
Image to be mapped.
. Map (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . (multichannel-)image ; HImageX / IHObjectX ( int4, uint2 )
Image containing the mapping data.
. ImageMapped (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX (
byte, uint2 )
Mapped image.
Result
MapImage returns TRUE if all parameter values are correct. If necessary, an exception handling is raised.
Parallelization Information
MapImage is reentrant and processed without parallelization.
Possible Predecessors
GenImageToWorldPlaneMap, GenRadialDistortionMap
See also
AffineTransImage, RotateImage

HALCON 8.0.2
204 CHAPTER 3. FILTER

Module
Foundation

HImageX.MirrorImage ([in] String Mode )


[out] HImageX ImageMirror
void HOperatorSetX.MirrorImage ([in] IHObjectX Image,
[out] HUntypedObjectX ImageMirror, [in] VARIANT Mode )

Mirror an image.
MirrorImage reflects an image Image about one of three possible axes. If Mode is set to ’row’, it is reflected
about the horizontal axis, if Mode is set to ’column’, about the vertical axis, and if Mode is set to ’main’, about
the main diagonal x = y.
Parameter
. Image (input iconic) . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, int2, uint2, int4,
real )
Input image.
. ImageMirror (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX (
byte, int2, uint2, int4, real )
Reflected image.
. Mode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Axis of reflection.
Default Value : ’row’
List of values : Mode ∈ {’row’, ’column’, ’main’}
Example

read_image(Image,’affe’)
disp_image(Image,WindowHandle)
mirror_image(Image,MirImage,’row’).
disp_image(MirImage,WindowHandle)

Parallelization Information
MirrorImage is reentrant and automatically parallelized (on tuple level, channel level).
See also
RotateImage, HomMat2dRotate
Alternatives
HomMat2dRotate, AffineTransImage, RotateImage
Module
Foundation

[out] HImageX ImagePolar HImageX.PolarTransImage ([in] long Row,


[in] long Column, [in] long Width, [in] long Height )
void HOperatorSetX.PolarTransImage ([in] IHObjectX ImageXY,
[out] HUntypedObjectX ImagePolar, [in] VARIANT Row, [in] VARIANT Column,
[in] VARIANT Width, [in] VARIANT Height )

Transform an image to polar coordinates


PolarTransImage transforms an image in cartesian coordinates to an image in polar coordinates. The size
of the resulting image is selected with Width and Height. Width determines the angular resolution, while
Height determines the resolution of the radius. Row and Column determine the center of the polar coordinate
system in the original image ImageXY. This point is mapped to the upper row of ImagePolar.
A point (x’,y’) in the result image corresponds to the point (x,y) in the original image in the following manner:

HALCON/COM Reference Manual, 2008-5-13


3.7. GEOMETRIC-TRANSFORMATIONS 205

x = y 0 cos(2π(x0 /resultwidth)) + Columny = y 0 sin(2π(x0 /resultwidth)) + Row .

Parameter

. ImageXY (input iconic) . . . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, int2, uint2 )


Input image in cartesian coordinates.
. ImagePolar (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX ( byte,
int2, uint2 )
Result image in polar coordinates.
. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; long / VARIANT
Row coordinate of the center of the coordinate system.
Default Value : 100
Suggested values : Row ∈ {0, 10, 100, 200}
Typical range of values : 0 ≤ Row ≤ 0
Minimum Increment : 1
Recommended Increment : 1
. Column (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; long / VARIANT
Column coordinate of the center of the coordinate system.
Default Value : 100
Suggested values : Column ∈ {0, 10, 100, 200}
Typical range of values : 0 ≤ Column ≤ 0
Minimum Increment : 1
Recommended Increment : 1
. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; long / VARIANT
Width of the result image.
Default Value : 314
Suggested values : Width ∈ {100, 200, 157, 314, 512}
Typical range of values : 2 ≤ Width ≤ 2
Minimum Increment : 1
Recommended Increment : 10
. Height (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; long / VARIANT
Height of the result image.
Default Value : 200
Suggested values : Height ∈ {100, 128, 256, 512}
Typical range of values : 2 ≤ Height ≤ 2
Minimum Increment : 1
Recommended Increment : 10
Example

read_image(Image,’affe’)
disp_image(Image,WindowHandle)
polar_trans_image(Image,PolarImage,100,100,314,200).
disp_image(PolarImage,WindowHandle)

Parallelization Information
PolarTransImage is reentrant and automatically parallelized (on tuple level, channel level).
See also
PolarTransImageInv, PolarTransRegion, PolarTransRegionInv,
PolarTransContourXld, PolarTransContourXldInv, AffineTransImage
Alternatives
PolarTransImageExt
Module
Foundation

HALCON 8.0.2
206 CHAPTER 3. FILTER

[out] HImageX PolarTransImage HImageX.PolarTransImageExt


([in] VARIANT Row, [in] VARIANT Column, [in] double AngleStart,
[in] double AngleEnd, [in] VARIANT RadiusStart, [in] VARIANT RadiusEnd,
[in] long Width, [in] long Height, [in] String Interpolation )
void HOperatorSetX.PolarTransImageExt ([in] IHObjectX Image,
[out] HUntypedObjectX PolarTransImage, [in] VARIANT Row, [in] VARIANT Column,
[in] VARIANT AngleStart, [in] VARIANT AngleEnd, [in] VARIANT RadiusStart,
[in] VARIANT RadiusEnd, [in] VARIANT Width, [in] VARIANT Height,
[in] VARIANT Interpolation )

Transform an annular arc in an image to polar coordinates.


PolarTransImageExt transforms the annular arc specified by the center point (Row, Column), the radii
RadiusStart and RadiusEnd and the angles AngleStart and AngleEnd in the image Image to its polar
coordinate version in the image PolarTransImage of the dimensions Width × Height.
The upper left pixel in the output image always corresponds to the point in the input image that is specified by
RadiusStart and AngleStart. Analogously, the lower right pixel in the output image always corresponds to
the point in the input image that is specified by RadiusEnd and AngleEnd. In the usual mode (AngleStart
< AngleEnd and RadiusStart < RadiusEnd), the polar transformation is performed in the mathemati-
cally positive orientation (counterclockwise). Furthermore, points with smaller radii lie in the upper part of the
output image. By suitably exchanging the values of these parameters (e.g., AngleStart > AngleEnd or
RadiusStart > RadiusEnd), any desired orientation of the output image can be achieved.
The parameter Interpolation is used to select the interpolation method ’bilinear’ or ’nearest_neighbor’. With
’nearest_neighbor’, the gray value of a pixel in the output image is determined by the gray value of the closest
pixel in the input image. With ’bilinear’, the gray value of a pixel in the output image is determined by bilinear
interpolation of the gray values of the four closest pixels in the input image. The mode ’bilinear’ results in images
of better quality, but is slower than the mode ’nearest_neighbor’.
The angles can be chosen from all real numbers. Center point and radii can be real as well. However, if they are
both integers and the difference of RadiusEnd and RadiusStart equals the height Height of the destination
image, calculation will be sped up through an optimized routine.
The radii and angles are inclusive, which means that the first row of the target image contains the circle with radius
RadiusStart and the last row contains the circle with radius RadiusEnd. For complete circles, where the
difference between AngleStart and AngleEnd equals 2π (360 degrees), this also means that the first column
of the target image will be the same as the last.
1
To avoid this, do not make this difference 2π, but 2π(1 − Width ) degrees instead.
The call:
polar_trans_image(Image, PolarTransImage, Row, Column, Width, Height)
produces the same result as the call:
polar_trans_image_ext(Image, PolarTransImage, Row-0.5, Column-0.5,
6.2831853, 6.2831853/Width, 0, Height-1, Width, Height, ’nearest_neighbor’)
The offset of 0.5 is necessary since PolarTransImage does not do exact nearest neighbor interpolation
and the radii and angles can be calculated using the information in the above paragraph and knowing that
PolarTransImage does not handle its arguments inclusively. The start angle is bigger than the end angle
to make PolarTransImageExt go clockwise, just like PolarTransImage does.
Attention
For speed reasons, the domain of the input image is ignored. The output image always has a complete rectangle as
its domain.
Parameter

. Image (input iconic) . . . . . . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, int2, uint2 )


Input image.
. PolarTransImage (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX
( byte, int2, uint2 )
Output image.

HALCON/COM Reference Manual, 2008-5-13


3.7. GEOMETRIC-TRANSFORMATIONS 207

. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )


Row coordinate of the center of the arc.
Default Value : 256
Suggested values : Row ∈ {0, 16, 32, 64, 128, 240, 256, 480, 512}
. Column (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Column coordinate of the center of the arc.
Default Value : 256
Suggested values : Column ∈ {0, 16, 32, 64, 128, 256, 320, 512, 640}
. AngleStart (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Angle of the ray to be mapped to the first column of the output image.
Default Value : 0.0
Suggested values : AngleStart ∈ {0.0, 0.78539816, 1.57079632, 3.141592654, 6.2831853,
12.566370616}
. AngleEnd (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Angle of the ray to be mapped to the last column of the output image.
Default Value : 6.2831853
Suggested values : AngleEnd ∈ {0.0, 0.78539816, 1.57079632, 3.141592654, 6.2831853, 12.566370616}
. RadiusStart (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Radius of the circle to be mapped to the first row of the output image.
Default Value : 0
Suggested values : RadiusStart ∈ {0, 16, 32, 64, 100, 128, 256, 512}
. RadiusEnd (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Radius of the circle to be mapped to the last row of the output image.
Default Value : 100
Suggested values : RadiusEnd ∈ {0, 16, 32, 64, 100, 128, 256, 512}
. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; long / VARIANT
Width of the output image.
Default Value : 512
Suggested values : Width ∈ {256, 320, 512, 640, 800, 1024}
Typical range of values : 0 ≤ Width ≤ 0
. Height (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; long / VARIANT
Height of the output image.
Default Value : 512
Suggested values : Height ∈ {240, 256, 480, 512, 600, 1024}
Typical range of values : 0 ≤ Height ≤ 0
. Interpolation (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Interpolation method for the transformation.
Default Value : ’nearest_neighbor’
List of values : Interpolation ∈ {’nearest_neighbor’, ’bilinear’}
Parallelization Information
PolarTransImageExt is reentrant and automatically parallelized (on tuple level, channel level).
See also
PolarTransImage, PolarTransImageInv, PolarTransRegion, PolarTransRegionInv,
PolarTransContourXld, PolarTransContourXldInv
Module
Foundation

HALCON 8.0.2
208 CHAPTER 3. FILTER

[out] HImageX XYTransImage HImageX.PolarTransImageInv


([in] VARIANT Row, [in] VARIANT Column, [in] double AngleStart,
[in] double AngleEnd, [in] VARIANT RadiusStart, [in] VARIANT RadiusEnd,
[in] long Width, [in] long Height, [in] String Interpolation )
void HOperatorSetX.PolarTransImageInv ([in] IHObjectX PolarImage,
[out] HUntypedObjectX XYTransImage, [in] VARIANT Row, [in] VARIANT Column,
[in] VARIANT AngleStart, [in] VARIANT AngleEnd, [in] VARIANT RadiusStart,
[in] VARIANT RadiusEnd, [in] VARIANT Width, [in] VARIANT Height,
[in] VARIANT Interpolation )

Transform an image in polar coordinates back to cartesian coordinates


PolarTransImageInv transforms the polar coordinate representation of an image, stored in PolarImage,
back onto an annular arc in cartesian coordinates, described by the radii RadiusStart and RadiusEnd and
the angles AngleStart and AngleEnd with the center point located at (Row, Column). All of these values
can be chosen as real numbers. The overall size of the target image will be Width × Height pixels.
The parameter Interpolation is used to select the interpolation method ’bilinear’ or ’nearest_neighbor’. With
’nearest_neighbor’, the gray value of a pixel in the output image is determined by the gray value of the closest
pixel in the input image. With ’bilinear’, the gray value of a pixel in the output image is determined by bilinear
interpolation of the gray values of the four closest pixels in the input image. The mode ’bilinear’ results in images
of better quality, but is slower than the mode ’nearest_neighbor’.
The angles and radii are inclusive, which means that the first row of the input image will be mapped onto a circle
with a distance of RadiusStart pixels from the specified center and the last row will be mapped onto a circle
of radius RadiusEnd.
PolarTransImageInv is the inverse function of PolarTransImageExt.
The call sequence:
polar_trans_image_ext(Image, PolarImage, Row, Column, rad(360), 0, 0,
Radius, Width, Height, Interpolation)
polar_trans_image_inv(PolarImage, XYTransImage, Row, Column, rad(360), 0,
0, Radius, Width, Height, Interpolation)
returns the image Image, restricted to the circle around (Row, Column) with radius Radius, as its output image
XYTransImage.
Parameter
. PolarImage (input iconic) . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, int2, uint2 )
Input image.
. XYTransImage (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX (
byte, int2, uint2 )
Output image.
. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Row coordinate of the center of the arc.
Default Value : 256
Suggested values : Row ∈ {0, 16, 32, 64, 128, 240, 256, 480, 512}
Typical range of values : 0 ≤ Row ≤ 0
. Column (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Column coordinate of the center of the arc.
Default Value : 256
Suggested values : Column ∈ {0, 16, 32, 64, 128, 256, 320, 512, 640}
Typical range of values : 0 ≤ Column ≤ 0
. AngleStart (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Angle of the ray to map the first column of the input image to.
Default Value : 0.0
Suggested values : AngleStart ∈ {0.0, 0.78539816, 1.57079632, 3.141592654, 6.2831853}
. AngleEnd (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Angle of the ray to map the last column of the input image to.
Default Value : 6.2831853
Suggested values : AngleEnd ∈ {0.0, 0.78539816, 1.57079632, 3.141592654, 6.2831853}

HALCON/COM Reference Manual, 2008-5-13


3.7. GEOMETRIC-TRANSFORMATIONS 209

. RadiusStart (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )


Radius of the circle to map the first row of the input image to.
Default Value : 0
Suggested values : RadiusStart ∈ {0, 16, 32, 64, 100, 128, 256, 512}
. RadiusEnd (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Radius of the circle to map the last row of the input image to.
Default Value : 100
Suggested values : RadiusEnd ∈ {0, 16, 32, 64, 100, 128, 256, 512}
. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; long / VARIANT
Width of the output image.
Default Value : 512
Suggested values : Width ∈ {256, 320, 512, 640, 800, 1024}
Typical range of values : 0 ≤ Width ≤ 0
. Height (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; long / VARIANT
Height of the output image.
Default Value : 512
Suggested values : Height ∈ {240, 256, 480, 512, 600, 1024}
Typical range of values : 0 ≤ Height ≤ 0
. Interpolation (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Interpolation method for the transformation.
Default Value : ’nearest_neighbor’
List of values : Interpolation ∈ {’nearest_neighbor’, ’bilinear’}
Parallelization Information
PolarTransImageInv is reentrant and automatically parallelized (on tuple level, channel level).
See also
PolarTransImage, PolarTransImageExt, PolarTransRegion, PolarTransRegionInv,
PolarTransContourXld, PolarTransContourXldInv
Module
Foundation

[out] HImageX TransImage HImageX.ProjectiveTransImage


([in] HHomMat2dX HomMat2D, [in] String Interpolation,
[in] String AdaptImageSize, [in] String TransformRegion )
[out] HImageX TransImage HHomMat2dX.ProjectiveTransImage
([in] HImageX Image, [in] String Interpolation, [in] String AdaptImageSize,
[in] String TransformRegion )
void HOperatorSetX.ProjectiveTransImage ([in] IHObjectX Image,
[out] HUntypedObjectX TransImage, [in] VARIANT HomMat2D,
[in] VARIANT Interpolation, [in] VARIANT AdaptImageSize,
[in] VARIANT TransformRegion )

Apply a projective transformation to an image.


ProjectiveTransImage applies the projective transformation (homography) determined by the homoge-
neous transformation matrix HomMat2D on the input image Image and stores the result into the output image
TransImage.
If the parameter AdaptImageSize ist set to ’false’, TransImage will have the same size as Image; if
AdaptImageSize is ’true’, the output image size will be automatically adapted so that all non-negative points
of the transformed image are visible.
The parameter Interpolation determines, which interpolation method is used to determine the gray values
of the output image. For Interpolation = ’nearest_neighbor’, the gray value is determined from the nearest
pixel in the input image. This mode is very fast, but also leads to the typical “jagged” appearance for large
enlargements of the image. For Interpolation = ’bilinear’, the gray values are interpolated bilinearly, leading
to longer runtimes, but also to significantly improved results.

HALCON 8.0.2
210 CHAPTER 3. FILTER

The parameter TransformRegion can be used to determine whether the domain of Image is also transformed.
Since the transformation of the domain costs runtime, this parameter should be used to specify whether this is
desired or not. If TransformRegion is set to ’false’ the domain of the input image is ignored and the complete
image is transformed.
The projective transformation matrix could for example be created using the operator
VectorToProjHomMat2d.
In a homography the points to be projected are represented by homogeneous vectors of the form (x, y, w). A
x y
Euclidean point can be derived as (x’,y’) = ( w , w ).
Just like in AffineTransImage, x represents the row coordinate while y represents the column coordinate
in ProjectiveTransImage. With this convention, affine transformations are a special case of projective
transformations in which the last row of HomMat2D is of the form (0, 0, c).
For images of type byte or uint2 the system parameter ’int_zooming’ selects between fast calculation in fixed point
arithmetics (’int_zooming’ = ’true’) and highly accurate calculation in floating point arithmetics (’int_zooming’ =
’false’). Especially for Interpolation = ’bilinear’, however, fixed point calculation can lead to minor gray
1
value deviations since the faster algorithm achieves an accuracy of no more than 16 pixels. Therefore, when
applying large scales ’int_zooming’ = ’false’ is recommended.
Parameter

. Image (input iconic) . . . . . . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, uint2, real )


Input image.
. TransImage (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX ( byte,
uint2, real )
Output image.
. HomMat2D (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )
Homogeneous projective transformation matrix.
. Interpolation (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Interpolation method for the transformation.
Default Value : ’bilinear’
List of values : Interpolation ∈ {’nearest_neighbor’, ’bilinear’}
. AdaptImageSize (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Adapt the size of the output image automatically?
Default Value : ’false’
List of values : AdaptImageSize ∈ {’true’, ’false’}
. TransformRegion (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Should the domain of the input image also be transformed?
Default Value : ’false’
List of values : TransformRegion ∈ {’true’, ’false’}
Parallelization Information
ProjectiveTransImage is reentrant and automatically parallelized (on tuple level, channel level).
Possible Predecessors
VectorToProjHomMat2d, HomVectorToProjHomMat2d, ProjMatchPointsRansac,
HomMat3dProject
See also
ProjectiveTransImageSize, ProjectiveTransContourXld, ProjectiveTransRegion,
ProjectiveTransPoint2D, ProjectiveTransPixel
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


3.7. GEOMETRIC-TRANSFORMATIONS 211

[out] HImageX TransImage HImageX.ProjectiveTransImageSize


([in] HHomMat2dX HomMat2D, [in] String Interpolation, [in] long Width,
[in] long Height, [in] String TransformRegion )
[out] HImageX TransImage HHomMat2dX.ProjectiveTransImageSize
([in] HImageX Image, [in] String Interpolation, [in] long Width,
[in] long Height, [in] String TransformRegion )
void HOperatorSetX.ProjectiveTransImageSize ([in] IHObjectX Image,
[out] HUntypedObjectX TransImage, [in] VARIANT HomMat2D,
[in] VARIANT Interpolation, [in] VARIANT Width, [in] VARIANT Height,
[in] VARIANT TransformRegion )

Apply a projective transformation to an image and specify the output image size.
ProjectiveTransImageSize applies the projective transformation (homography) determined by the homo-
geneous transformation matrix HomMat2D on the input image Image and stores the result into the output image
TransImage.
TransImage will be clipped at the output dimensions Height×Width. Apart from this,
ProjectiveTransImageSize is identical to its alternative version ProjectiveTransImage.
Parameter

. Image (input iconic) . . . . . . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, uint2, real )


Input image.
. TransImage (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX ( byte,
uint2, real )
Output image.
. HomMat2D (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )
Homogeneous projective transformation matrix.
. Interpolation (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Interpolation method for the transformation.
Default Value : ’bilinear’
List of values : Interpolation ∈ {’nearest_neighbor’, ’bilinear’}
. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; long / VARIANT
Output image width.
. Height (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; long / VARIANT
Output image height.
. TransformRegion (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Should the domain of the input image also be transformed?
Default Value : ’false’
List of values : TransformRegion ∈ {’true’, ’false’}
Parallelization Information
ProjectiveTransImageSize is reentrant and automatically parallelized (on tuple level, channel level).
Possible Predecessors
VectorToProjHomMat2d, HomVectorToProjHomMat2d, ProjMatchPointsRansac,
HomMat3dProject
See also
ProjectiveTransImage, ProjectiveTransContourXld, ProjectiveTransRegion,
ProjectiveTransPoint2D, ProjectiveTransPixel
Module
Foundation

HALCON 8.0.2
212 CHAPTER 3. FILTER

[out] HImageX ImageRotate HImageX.RotateImage ([in] VARIANT Phi,


[in] String Interpolation )
void HOperatorSetX.RotateImage ([in] IHObjectX Image,
[out] HUntypedObjectX ImageRotate, [in] VARIANT Phi,
[in] VARIANT Interpolation )

Rotate an image about its center.


RotateImage rotates the image Image counterclockwise by Phi degrees about its center. This operator is
much faster if Phi is a multiple of 90 degrees than the general operator AffineTransImage. For rotations by
90, 180, and 270 degrees, the region is rotated accordingly. For all other rotations the region is set to the maximum
region, i.e., to the extent of the resulting image. The effect of the parameter Interpolation is the same as in
AffineTransImage. It is ignored for rotations by 90, 180, and 270 degrees. The size of the resulting image is
the same as that of the input image, with the exception of rotations by 90 and 270 degrees, where the width and
height will be exchanged.
Attention
The angle Phi is given in degrees, not in radians.
Parameter

. Image (input iconic) . . . . . . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, int2, uint2 )


Input image.
. ImageRotate (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX (
byte, int2, uint2 )
Rotated image.
. Phi (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.deg ; VARIANT ( integer, real )
Rotation angle.
Default Value : 90
Suggested values : Phi ∈ {90, 180, 270}
Typical range of values : 0 ≤ Phi ≤ 0
Minimum Increment : 0.001
Recommended Increment : 0.2
. Interpolation (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Type of interpolation.
Default Value : ’constant’
List of values : Interpolation ∈ {’none’, ’constant’, ’weighted’}
Example

read_image(Image,’affe’)
disp_image(Image,WindowHandle)
rotate_image(ImageRotImage,270).
disp_image(RotImage,WindowHandle)

Parallelization Information
RotateImage is reentrant and automatically parallelized (on tuple level, channel level).
See also
MirrorImage
Alternatives
HomMat2dRotate, AffineTransImage
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


3.7. GEOMETRIC-TRANSFORMATIONS 213

[out] HImageX ImageZoomed HImageX.ZoomImageFactor


([in] double ScaleWidth, [in] double ScaleHeight, [in] String Interpolation )
void HOperatorSetX.ZoomImageFactor ([in] IHObjectX Image,
[out] HUntypedObjectX ImageZoomed, [in] VARIANT ScaleWidth,
[in] VARIANT ScaleHeight, [in] VARIANT Interpolation )

Zoom an image by a given factor.


ZoomImageFactor scales the image Image by a factor of ScaleWidth in width and a factor
ScaleHeight in height. The parameter Interpolation determines the type of interpolation used (see
AffineTransImage).
Attention
If the system parameter ’int_zooming’ is set to ’true’, the internally used integer arithmetic may lead to errors in
the following two cases: First, if ZoomImageFactor is used on an uint2 or int2 image with high dynamics
(i.e. images containing values close to the respective limits) in combination with scale factors smaller than 0.5,
then the gray values of the output image may be erroneous. Second, if Interpolation is set to a value other
than ’none’, a large scale factor is applied, and a large output image is obtained, then undefined gray values at the
lower and at the right image border may result. The maximum width Bmax of this border of undefined gray values
can be estimated as Bmax = 0.5 · S · I/215 , where S is the scale factor in one dimension and I is the size of the
output image in the corresponding dimension. In both cases, it is recommended to set ’int_zooming’ to ’false’ via
the operator SetSystem.
Parameter
. Image (input iconic) . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, int2, uint2, real )
Input image.
. ImageZoomed (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX (
byte, int2, uint2, real )
Scaled image.
. ScaleWidth (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; double / VARIANT
Scale factor for the width of the image.
Default Value : 0.5
Suggested values : ScaleWidth ∈ {0.25, 0.5, 1.5, 2.0}
Typical range of values : 0.001 ≤ ScaleWidth ≤ 0.001
Minimum Increment : 0.001
Recommended Increment : 0.1
. ScaleHeight (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; double / VARIANT
Scale factor for the height of the image.
Default Value : 0.5
Suggested values : ScaleHeight ∈ {0.25, 0.5, 1.5, 2.0}
Typical range of values : 0.001 ≤ ScaleHeight ≤ 0.001
Minimum Increment : 0.001
Recommended Increment : 0.1
. Interpolation (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Type of interpolation.
Default Value : ’constant’
List of values : Interpolation ∈ {’none’, ’constant’, ’weighted’}
Example

read_image(Image,’affe’)
disp_image(Image,WindowHandle)
zoom_image_factor(Image,ZooImage,0,0.5,0.5).
disp_image(ZooImage,WindowHandle)

Parallelization Information
ZoomImageFactor is reentrant and automatically parallelized (on tuple level, channel level).
See also
HomMat2dScale, AffineTransImage

HALCON 8.0.2
214 CHAPTER 3. FILTER

Alternatives
ZoomImageSize, AffineTransImage, HomMat2dScale
Module
Foundation

[out] HImageX ImageZoom HImageX.ZoomImageSize ([in] long Width,


[in] long Height, [in] String Interpolation )
void HOperatorSetX.ZoomImageSize ([in] IHObjectX Image,
[out] HUntypedObjectX ImageZoom, [in] VARIANT Width, [in] VARIANT Height,
[in] VARIANT Interpolation )

Zoom an image to a given size.


ZoomImageSize scales the image Image to the size given by Width and Height. The parameter
Interpolation determines the type of interpolation used (see AffineTransImage).
Attention
If the system parameter ’int_zooming’ is set to ’true’, the internally used integer arithmetic may lead to errors in the
following two cases: First, if ZoomImageSize is used on an uint2 or int2 image with high dynamics (i.e. images
containing values close to the respective limits) in combination with scale factors (ratio of output to input image
size) smaller than 0.5, then the gray values of the output image may be erroneous. Second, if Interpolation is
set to a value other than ’none’, a large scale factor is applied, and a large output image is obtained, then undefined
gray values at the lower and at the right image border may result. The maximum width Bmax of this border of
undefined gray values can be estimated as Bmax = 0.5 · S · I/215 , where S is the scale factor in one dimension
and I is the size of the output image in the corresponding dimension. In both cases, it is recommended to set
’int_zooming’ to ’false’ via the operator SetSystem.
Parameter
. Image (input iconic) . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, int2, uint2, real )
Input image.
. ImageZoom (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX ( byte,
int2, uint2, real )
Scaled image.
. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; long / VARIANT
Width of the resulting image.
Default Value : 512
Suggested values : Width ∈ {128, 256, 512}
Typical range of values : 2 ≤ Width ≤ 2
Minimum Increment : 1
Recommended Increment : 10
. Height (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; long / VARIANT
Height of the resulting image.
Default Value : 512
Suggested values : Height ∈ {128, 256, 512}
Typical range of values : 2 ≤ Height ≤ 2
Minimum Increment : 1
Recommended Increment : 10
. Interpolation (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Type of interpolation.
Default Value : ’constant’
List of values : Interpolation ∈ {’none’, ’constant’, ’weighted’}
Example

read_image(Image,’affe’)
disp_image(Image,WindowHandle)
zoom_image_size(Image,ZooImage,0,200,200).
disp_image(ZooImage,WindowHandle)

HALCON/COM Reference Manual, 2008-5-13


3.8. INPAINTING 215

Parallelization Information
ZoomImageSize is reentrant and automatically parallelized (on tuple level, channel level).
See also
HomMat2dScale, AffineTransImage
Alternatives
ZoomImageFactor, AffineTransImage, HomMat2dScale
Module
Foundation

3.8 Inpainting

[out] HImageX InpaintedImage HImageX.HarmonicInterpolation


([in] HRegionX Region, [in] double Precision )
void HOperatorSetX.HarmonicInterpolation ([in] IHObjectX Image,
[in] IHObjectX Region, [out] HUntypedObjectX InpaintedImage,
[in] VARIANT Precision )

Perform a harmonic interpolation on an image region.


The operator HarmonicInterpolation reconstructs the destroyed image data of Image inside the region
Region by solving the discrete Laplace equation uxx + uyy = 0 for the corresponding gray value function u.
The unique solution, which exists under Dirichlet boundary conditions given by Image outside of Region, is
returned in InpaintedImage.
This technique is called harmonic interpolation since in function theory the solutions of the Laplace equation are
referred to as harmonic functions.
If Region touches the border of the gray value matrix of Image and thus some Dirichlet boundary values do
not exist, von Neumann boundary conditions are used instead. This means that the gray values are mirrored at the
border of Image. If no Dirichlet boundary values exist at all, a constant image with gray value 0 is returned.
The spatial derivatives are discretized as uxx (x, y) = u(x − 1, y) − 2u(x, y) + u(x + 1, y) and
uyy (x, y) = u(x, y − 1) − 2u(x, y) + u(x, y + 1). The equation is solved by an iterative conjugate gradi-
ent solver, which iteratively improves the computational error until the maximum norm of its update step becomes
a smaller fraction than Precision of the norm of the input data or a maximum of 1000 iterations is reached.
Precision = 0 .01 thus means a relative computational accuracy of 1%.
Parameter
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte, uint2, real )
Input image.
. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
Inpainting region.
. InpaintedImage (output iconic) . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX
Output image.
. Precision (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Computational accuracy.
Default Value : 0.001
Suggested values : Precision ∈ {0.0, 0.0001, 0.001, 0.01}
Restriction : (P recision ≥ 0.0)
Parallelization Information
HarmonicInterpolation is reentrant and automatically parallelized (on tuple level).
Alternatives
InpaintingCt, InpaintingAniso, InpaintingMcf, InpaintingTexture, InpaintingCed
References
L.C. Evans; “Partial Differential Equations”; AMS, Providence; 1998.
W. Hackbusch; “Iterative Lösung großer schwachbesetzter Gleichungssysteme”; Teubner, Stuttgart;1991.
Module
Foundation

HALCON 8.0.2
216 CHAPTER 3. FILTER

[out] HImageX InpaintedImage HImageX.InpaintingAniso


([in] HRegionX Region, [in] String Mode, [in] double Contrast,
[in] double Theta, [in] long Iterations, [in] double Rho )
void HOperatorSetX.InpaintingAniso ([in] IHObjectX Image,
[in] IHObjectX Region, [out] HUntypedObjectX InpaintedImage,
[in] VARIANT Mode, [in] VARIANT Contrast, [in] VARIANT Theta,
[in] VARIANT Iterations, [in] VARIANT Rho )

Perform an inpainting by anisotropic diffusion.


The operator InpaintingAniso uses the anisotropic diffusion according to the model of Perona and Malik, to
continue image edges that cross the border of the region Region and to connect them inside of Region.
With this, the structure of the edges in Region will be made consistent with the surrounding image matrix, so that
an occlusion of errors or unwanted objects in the input image, a so called inpainting, is less visible to the human
beholder, since there remain no obvious artefacts or smudges.
Considering the image as a gray value function u, the algorithm is a discretization of the partial differential equation

ut = div(g(|∇u|2 , c)∇u)

with the initial value u = u0 defined by Image at a time t0 = 0. The equation is iterated Iterations times in
time steps of length Theta, so that the output image InpaintedImage contains the gray value function at the
time Iterations · Theta.
The primary goal of the anisotropic diffusion, which is also referred to as nonlinear isotropic diffusion, is the
elimination of image noise in constant image patches while preserving the edges in the image. The distinction
between edges and constant patches is achieved using the threshold Contrast on the magnitude of the gray
value differences between adjacent pixels. Contrast is referred to as the contrast parameter and is abbreviated
with the letter c. If the edge information is distributed in an environment of the already existing edges by smoothing
the edge amplitude matrix, it is furthermore possible to continue edges into the computation area Region. The
standard deviation of this smoothing process is determined by the parameter Rho.
The algorithm used is basically the same as in the anisotropic diffusion filter AnisotropicDiffusion, except
that here, border treatment is not done by mirroring the gray values at the border of Region. Instead, this
procedure is only applicable on regions that keep a distance of at least 3 pixels to the border of the image matrix
of Image, since the gray values on this band around Region are used to define the boundary conditions for the
respective differential equation and thus assure consistency with the neighborhood of Region. Please note that
the inpainting progress is restricted to those pixels that are included in the ROI of the input image Image. If the
ROI does not include the entire region Region, a band around the intersection of Region and the ROI is used to
define the boundary values.
The result of the diffusion process depends on the gray values in the computation area of the input image Image.
It must be pointed out that already exisiting image edges are preserved within Region. In particular, this holds
for gray value jumps at the border of Region, which can result for example from a previous inpainting with
constant gray value. If the procedure is to be used for inpainting, it is recommended to apply the operator
HarmonicInterpolation first to remove all unwanted edges inside the computation area and to minimize the
gray value difference between adjacent pixels, unless the input image already contains information inside Region
that should be preserved.
The variable diffusion coefficient g can be chosen to follow different monotonically decreasing functions with
values between 0 and 1 and determines the response of the diffusion process to an edge. With the parameter Mode,
the following functions can be selected:

1
g1 (x, c) = p
1 + 2 cx2

Choosing the function g1 by setting Mode to ’parabolic’ guarantees that the associated differential equation is
parabolic, so that a well-posedness theory exists for the problem and the procedure is stable for an arbitrary step
size Theta. In this case however, there remains a slight diffusion even across edges of an amplitude larger than c.

1
g2 (x, c) =
1 + cx2

HALCON/COM Reference Manual, 2008-5-13


3.8. INPAINTING 217

The choice of ’perona-malik’ for Mode, as used in the publication of Perona and Malik, does not possess the
theoretical properties of g1 , but in practice it has proved to be sufficiently stable and is thus widely used. The
theoretical instability results in a slight sharpening of strong edges.

c8
g3 (x, c) = 1 − exp(−C )
x4

The function g3 with the constant C = 3.31488, proposed by Weickert, and selectable by setting Mode to ’weick-
ert’ is an improvement of g2 with respect to edge sharpening. The transition between smoothing and sharpening
happens very abruptly at x = c2 .
Furthermore, the choice of the value ’shock’ is possible for Mode to select a contrast invariant modification of the
anisotropic diffusion. In this variant, the generation of edges is not achieved by variation of the diffusion coefficient
g, but the constant coefficient g = 1 and thus isotropic diffusion is used. Additionally, a shock filter of type

ut = −sgn(∇|∇u|)|∇u|

is applied, which, just like a negative diffusion coefficient, causes a sharpening of the edges, but works independent
of the absolute value of |∇u|. In this mode, Contrast does not have the meaning of a contrast parameter,
but specifies the ratio between the diffusion and the shock filter part applied at each iteration step. Hence, the
value 0 would correspond to pure isotropic diffusion, as used in the operator IsotropicDiffusion. The
parameter is scaled in such a way that diffusion and sharpening cancel each other out for Contrast = 1 . A
value Contrast > 1 should not be used, since it would make the algorithm unstable.
Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte, uint2, real )


Input image.
. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
Inpainting region.
. InpaintedImage (output iconic) . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX
Output image.
. Mode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Type of edge sharpening algorithm.
Default Value : ’weickert’
List of values : Mode ∈ {’weickert’, ’perona-malik’, ’parabolic’, ’shock’}
. Contrast (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Contrast parameter.
Default Value : 5.0
Suggested values : Contrast ∈ {0.5, 2.0, 5.0, 10.0, 20.0, 50.0, 100.0}
Restriction : (Contrast > 0)
. Theta (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Step size.
Default Value : 0.5
Suggested values : Theta ∈ {0.5, 1.0, 5.0, 10.0, 30.0, 100.0}
Restriction : (T heta > 0)
. Iterations (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of iterations.
Default Value : 10
Suggested values : Iterations ∈ {1, 3, 10, 100, 500}
Restriction : (Iterations ≥ 1)
. Rho (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Smoothing coefficient for edge information.
Default Value : 3.0
Suggested values : Rho ∈ {0.0, 0.1, 0.5, 1.0, 3.0, 10.0}
Restriction : (Rho ≥ 0)
Parallelization Information
InpaintingAniso is reentrant and automatically parallelized (on tuple level).

HALCON 8.0.2
218 CHAPTER 3. FILTER

Alternatives
HarmonicInterpolation, InpaintingCt, InpaintingMcf, InpaintingTexture,
InpaintingCed
References
J. Weickert; “’Anisotropic Diffusion in Image Processing’; PhD Thesis; Fachbereich Mathematik, Universität
Kaiserslautern; 1996.
P. Perona, J. Malik; “Scale-space and edge detection using anisotropic diffusion”; Transactions on Pattern Analysis
and Machine Intelligence 12(7), pp. 629-639; IEEE; 1990.
G. Aubert, P. Kornprobst; “Mathematical Problems in Image Processing”; Applied Mathematical Sciences 147;
Springer, New York; 2002.
Module
Foundation

[out] HImageX InpaintedImage HImageX.InpaintingCed


([in] HRegionX Region, [in] double Sigma, [in] double Rho, [in] double Theta,
[in] long Iterations )
void HOperatorSetX.InpaintingCed ([in] IHObjectX Image,
[in] IHObjectX Region, [out] HUntypedObjectX InpaintedImage,
[in] VARIANT Sigma, [in] VARIANT Rho, [in] VARIANT Theta,
[in] VARIANT Iterations )

Perform an inpainting by coherence enhancing diffusion.


The operator InpaintingCed performs an anisotropic diffusion process on the region Region of the input
image Image with the objective of completing discontinuous image edges diffusively by increasing the coherence
of the image structures contained in Image and without smoothing these edges perpendicular to their dominating
direction. The mechanism is the same as in the operator CoherenceEnhancingDiff, which is based on a
discretization of the anisotropic diffusion equation

ut = div(G(u)∇u)

formulated by Weickert. With a 2 × 2 coefficient matrix G that depends on the gray values in Image, this is an
enhancement of the mean curvature flow or intrinsic heat equation

∇u
ut = div( )|∇u| = curv(u)|∇u|
|∇u|

on the gray value function u defined by the input image Image at a time t0 = 0. The smoothing oper-
ator MeanCurvatureFlow is a direct application of the mean curvature flow equation. With the opera-
tor InpaintingMcf, it can also be used for image inpainting. The discrete diffusion equation is solved in
Iterations time steps of length Theta, so that the output image InpaintedImage contains the gray value
function at the time Iterations · Theta.
To detect the image direction more robustly, in particular on noisy input data, an additional isotropic smoothing
step can precede the computation of the gray value gradients. The parameter Sigma determines the magnitude of
the smoothing by means of the standard deviation of a corresponding Gaussian convolution kernel, as used in the
operator IsotropicDiffusion for isotropic image smoothing.
Similar to the operator InpaintingMcf, the structure of the image data in Region is simplified by smoothing
the level lines of Image. By this, image errors and unwanted objects can be removed from the image, while the
edges in the neighborhood are extended continuously. This procedure is called image inpainting. The objective is
to introduce a minimum amount of artefacts or smoothing effects, so that the image manipulation is least visible to
a human beholder.
While the matrix G is given by

1
GM CF (u) = I − ∇u(∇u)T ,
|∇u|2

HALCON/COM Reference Manual, 2008-5-13


3.8. INPAINTING 219

in the case of the operator InpaintingMcf, where I denotes the unit matrix, GM CF is again smoothed com-
ponentwise by a Gaussian filter of standard deviation Rho for CoherenceEnhancingDiff. Then, the final
coefficient matrix

GCED = g1 (λ1 − λ2 )2 w1 (w1 )T + g2 (λ1 − λ2 )2 w2 (w2 )T


 

is constructed from the eigenvalues λ1 , λ2 and eigenvectors w1 , w2 of the resulting intermediate matrix, where the
functions

g1 (p) = 0.001  
−1
g2 (p) = 0.001 + 0.999 exp
p

were determined empirically and taken from the publication of Weickert.


Hence, the diffusion direction in MeanCurvatureFlow is only determined by the local direction of the gray
value gradient, while GCED considers the macroscopic structure of the image objects on the scale Rho and the
magnitude of the diffusion in CoherenceEnhancingDiff depends on how well this structure is defined.
To achieve the highest possible consistency of the newly created edges with the image data from the neighbour-
hood, the gray values are not mirrored at the border of Region to compute the convolution with the smoothing
filter mask of scale Rho on the pixels close to the border, although this would be the common approach for filter
operators. Instead, the existence of gray values on a band of width ceil(3.1 ∗ Rho) + 2 pixels around Region
is presumed and these values are used in the convolution. This means that Region must keep this much dis-
tance to the border of the image matrix Image. By involving the gray values and directional information from
this extended area, it can be achieved that the continuation of the edges is not only continuous, but also smooth,
which means without kinks. Please note that the inpainting progress is restricted to those pixels that are included
in the ROI of the input image Image. If the ROI does not include the entire region Region, a band around the
intersection of Region and the ROI is used to define the boundary values.
To decrease the number of iterations required for attaining a satisfactory result, it may be useful to initialize the gray
value matrix in Region with the harmonic interpolant, a continuous function of minimal curvature, by applying
the operator HarmonicInterpolation to Image before calling InpaintingCed.
Parameter
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte, uint2, real )
Input image.
. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
Inpainting region.
. InpaintedImage (output iconic) . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX
Output image.
. Sigma (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Smoothing for derivative operator.
Default Value : 0.5
Suggested values : Sigma ∈ {0.0, 0.1, 0.5, 1.0}
Restriction : (Sigma ≥ 0)
. Rho (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Smoothing for diffusion coefficients.
Default Value : 3.0
Suggested values : Rho ∈ {0.0, 1.0, 3.0, 5.0, 10.0, 30.0}
Restriction : (Rho ≥ 0)
. Theta (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Time step.
Default Value : 0.5
Suggested values : Theta ∈ {0.1, 0.2, 0.3, 0.4, 0.5}
Restriction : ((0 < T heta) ≤ 0.5)
. Iterations (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of iterations.
Default Value : 10
Suggested values : Iterations ∈ {1, 5, 10, 20, 50, 100, 500}
Restriction : (Iterations ≥ 1)

HALCON 8.0.2
220 CHAPTER 3. FILTER

Parallelization Information
InpaintingCed is reentrant and automatically parallelized (on tuple level).
Alternatives
HarmonicInterpolation, InpaintingCt, InpaintingAniso, InpaintingMcf,
InpaintingTexture
References
J. Weickert, V. Hlavac, R. Sara; “Multiscale texture enhancement”; Computer analysis of images and patterns,
Lecture Notes in Computer Science, Vol. 970, pp. 230-237; Springer, Berlin; 1995.
J. Weickert, B. ter Haar Romeny, L. Florack, J. Koenderink, M. Viergever; “A review of nonlinear diffusion
filtering”; Scale-Space Theory in Computer Vision, Lecture Notes in Comp. Science, Vol. 1252, pp. 3-28;
Springer, Berlin; 1997.
Module
Foundation

[out] HImageX InpaintedImage HImageX.InpaintingCt ([in] HRegionX Region,


[in] double Epsilon, [in] double Kappa, [in] double Sigma, [in] double Rho,
[in] VARIANT ChannelCoefficients )
void HOperatorSetX.InpaintingCt ([in] IHObjectX Image,
[in] IHObjectX Region, [out] HUntypedObjectX InpaintedImage,
[in] VARIANT Epsilon, [in] VARIANT Kappa, [in] VARIANT Sigma,
[in] VARIANT Rho, [in] VARIANT ChannelCoefficients )

Perform an inpainting by coherence transport.


The operator InpaintingCt inpaints a missing region Region of an image Image by transporting image
information from the region’s boundary along the coherence direction into this region.
Since this operator’s basic concept is inpainting by continuing broken contour lines, the image content and in-
painting region must be such that this idea makes sense. That is, if a contour line hits the region to inpaint at a
pixel p, there should be some opposite point q where this contour line continues so that the continuation of contour
lines from two opposite sides can succeed. In cases where there is less geometry in the image, a diffusion-based
inpainter, e.g., HarmonicInterpolation may yield better results. Alternatively, Kappa can be set to 0. An
extreme situation with little global geometries are pure textures. Then the idea behind this operator will fail to
produce good results (think of a checkerboard with a big region to inpaint relative to the checker fields). For these
kinds of images, a texture-based inpaiting, e.g., InpaintingTexture, can be used instead.
The operator uses a so-called upwind scheme to assign gray values to the missing pixels, i.e.,:

• The order of the pixels to process is given by their Euclidean distance to the boundary of the region to inpaint.
• A new value ui is computed as a weighted average of already known values uj within a disc of radius
Epsilon around the current pixel. The disc is restricted to already known pixels.
• The size of this scheme’s mask depends on Epsilon.

The initially used image data comes from a stripe of thickness Epsilon around the region to inpaint. Thus,
Epsilon must be at least 1 for the scheme to work, but should be greater. The maximum value for Epsilon
depends on the gray values that should be transported into the region. Choosing Epsilon = 5 can be used in
many cases.
Since the goal is to close broken contour lines, the direction of the level lines must be estimated and used in the
weight. This estimated direction is called the coherence direction, and is computed by means of the structure tensor
S.

S = Gρ ∗ DvDv T

and

v = Gσ ∗ u

HALCON/COM Reference Manual, 2008-5-13


3.8. INPAINTING 221

where ∗ denotes the convolution, u denotes the gray value image, D the derivative and G Gaussian kernels with
standard deviation σ and ρ. These standard deviations are defined by the operator’s parameters Sigma and Rho.
Sigma should have the size of the noise or uninportant little objects, which are then not considered in the estima-
tion step by the pre-smoothing. Rho gives the size of the window around a pixel that will be used for direction
estimation. The coherence direction c then is given by the eigendirection of S with respect to the minimal eigen-
value λ, i.e.

Sc = λc, |c| = 1

For multichannel or color images, the scheme above is applied to each channel separately, but the weights must be
the same for all channels to propagate information in the same direction. Since the weight depends on the coherence
direction, the common direction is given by the eigendirection of a composite structure tensor. If u1 , ..., un denote
the n channels of the image, the channel structure tensors S1 , ..., Sn are computed and then combined to the
composite structure tensor S.

n
X
S= ai Si
i=1

The coefficients ai are passed in ChannelCoefficients, which is a tuple of length n or length 1. If the tuple’s
length is 1, the arithmetic mean is used, i.e., ai = 1/n. If the length of ChannelCoefficients matches the
number of channels, the ai are set to

ChannelCoefficientsi
ai = Pn
i=1 ChannelCoefficientsi

in order to get a well-defined convex combination. Hence, the ChannelCoefficients must be greater than or
equal to zero and their sum must be greater than zero. If the tuple’s length is neither 1 nor the number of channels
or the requirement above is not satisfied, the operator returns an error message.
The purpose of using other ChannelCoefficients than the arithmetic mean is to adapt to different color
codes. The coherence direction is a geometrical information of the composite image, which is given by high
contrasts such as edges. Thus the more contrast a channel has, the more geometrical information it contains, and
consequently the greater its coefficient should be chosen (relative to the others). For RGB images, [0.299, 0.587,
0.114] is a good choice.
The weight in the scheme is the product of a directional component and a distance component. If p is the 2D
coordinate vector of the current pixel to be inpainted and q the 2D coordinate of a pixel in the neighborhood (the
disc restricted to already known pixels), the directional component measures the deviation of the vector p − q
from the coherence direction. If the deviation exponentially scaled by β is large, a low directional component is
assigned, whereas if it is small, a large directional component is assigned. β is controlled by Kappa (in percent):

β = 20 ∗ Epsilon ∗ Kappa/100

Kappa defines how important it is to propagate information along the coherence direction, so a large Kappa
yields sharp edges, while a low Kappa allows for more diffusion.
A special case is when Kappa is zero: In this case the directional component of the weight is constant (one).
The direction estimation step is then skipped to save computational costs and the parameters Sigma, Rho,
ChannelCoefficients become meaningless, i.e, the propagation of information is not based on the struc-
tures visible in the image.
The distance component is 1/|p − q|. Consequently, if q is far away from p, a low distance component is assigned,
whereas if it is near to p, a high distance component is assigned.
Parameter

. Image (input iconic) . . . . . . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, uint2, real )


Input image.
. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
Inpainting region.

HALCON 8.0.2
222 CHAPTER 3. FILTER

. InpaintedImage (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX (


byte, uint2, real )
Output image.
. Epsilon (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Radius of the pixel neighborhood.
Default Value : 5.0
Typical range of values : 1.0 ≤ Epsilon ≤ 1.0
Minimum Increment : 1.0
Recommended Increment : 1.0
. Kappa (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Sharpness parameter in percent.
Default Value : 25.0
Typical range of values : 0.0 ≤ Kappa ≤ 0.0
Minimum Increment : 1.0
Recommended Increment : 1.0
. Sigma (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Pre-smoothing parameter.
Default Value : 1.41
Typical range of values : 0.0 ≤ Sigma ≤ 0.0
Minimum Increment : 0.001
Recommended Increment : 0.01
. Rho (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Smoothing parameter for the direction estimation.
Default Value : 4.0
Typical range of values : 0.001 ≤ Rho ≤ 0.001
Minimum Increment : 0.001
Recommended Increment : 0.01
. ChannelCoefficients (input control) . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( real )
Channel weights.
Default Value : 1
Example

read_image (Image, ’claudia’)


gen_circle (Circle, 333, 164, 35)
inpainting_ct (Image, Circle, InpaintedImage, 15, 25, 1.5, 3,1.0)

Parallelization Information
InpaintingCt is reentrant and automatically parallelized (on tuple level).
Alternatives
HarmonicInterpolation, InpaintingAniso, InpaintingMcf, InpaintingCed,
InpaintingTexture
References
Folkmar Bornemann, Tom März: “Fast Image Inpainting Based On Coherence Transport”; Journal of Mathemati-
cal Imaging and Vision; vol. 28, no. 3; pp. 259-278; 2007.
Module
Foundation

[out] HImageX InpaintedImage HImageX.InpaintingMcf


([in] HRegionX Region, [in] double Sigma, [in] double Theta,
[in] long Iterations )
void HOperatorSetX.InpaintingMcf ([in] IHObjectX Image,
[in] IHObjectX Region, [out] HUntypedObjectX InpaintedImage,
[in] VARIANT Sigma, [in] VARIANT Theta, [in] VARIANT Iterations )

Perform an inpainting by smoothing of level lines.

HALCON/COM Reference Manual, 2008-5-13


3.8. INPAINTING 223

The operator InpaintingMcf extends the image edges that adjoin the region Region of the input image
Image into the interior of Region and connects their ends by smoothing the level lines of the gray value function
of Image.
This happens through the application of the mean curvature flow or intrinsic heat equation

∇u
ut = div( )|∇u| = curv(u)|∇u|
|∇u|

on the gray value function u defined in the region Region by the input image Image at a time t0 = 0.
The discretized equation is solved in Iterations time steps of length Theta, so that the output image
InpaintedImage contains the gray value function at the time Iterations · Theta.
A stationary state of the mean curvature flow equation, which is also the basis of the operator
MeanCurvatureFlow, has the special property that the level lines of u all have the curvature 0. This means that
after sufficiently many iterations there are only straight edges left inside the computation area of the output image
InpaintedImage. By this, the structure of objects inside of Region can be simplified, while the remaining
edges are continuously connected to those of the surrounding image matrix. This allows for a removal of image
errors and unwanted objects in the input image, a so called image inpainting, which is only weakly visible to a
human beholder since there remain no obvious artefacts or smudges.
To detect the image direction more robustly, in particular on noisy input data, an additional isotropic smoothing
step can precede the computation of the gray value gradients. The parameter Sigma determines the magnitude of
the smoothing by means of the standard deviation of a corresponding Gaussian convolution kernel, as used in the
operator IsotropicDiffusion for isotropic image smoothing.
Parameter
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte, uint2, real )
Input image.
. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
Inpainting region.
. InpaintedImage (output iconic) . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX
Output image.
. Sigma (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Smoothing for derivative operator.
Default Value : 0.5
Suggested values : Sigma ∈ {0.0, 0.1, 0.5, 1.0}
Restriction : (Sigma ≥ 0)
. Theta (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Time step.
Default Value : 0.5
Suggested values : Theta ∈ {0.1, 0.2, 0.3, 0.4, 0.5}
Restriction : ((0 < T heta) ≤ 0.5)
. Iterations (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of iterations.
Default Value : 10
Suggested values : Iterations ∈ {1, 5, 10, 20, 50, 100, 500}
Restriction : (Iterations ≥ 1)
Parallelization Information
InpaintingMcf is reentrant and automatically parallelized (on tuple level).
Alternatives
HarmonicInterpolation, InpaintingCt, InpaintingAniso, InpaintingCed,
InpaintingTexture
References
M. G. Crandall, P. Lions; “Convergent Difference Schemes for Nonlinear Parabolic Equations and Mean Curvature
Motion”; Numer. Math. 75 pp. 17-41; 1996.
G. Aubert, P. Kornprobst; “Mathematical Problems in Image Processing”; Applied Mathematical Sciences 147;
Springer, New York; 2002.
Module
Foundation

HALCON 8.0.2
224 CHAPTER 3. FILTER

[out] HImageX InpaintedImage HImageX.InpaintingTexture


([in] HRegionX Region, [in] long MaskSize, [in] long SearchSize,
[in] double Anisotropy, [in] String PostIteration, [in] double Smoothness )
void HOperatorSetX.InpaintingTexture ([in] IHObjectX Image,
[in] IHObjectX Region, [out] HUntypedObjectX InpaintedImage,
[in] VARIANT MaskSize, [in] VARIANT SearchSize, [in] VARIANT Anisotropy,
[in] VARIANT PostIteration, [in] VARIANT Smoothness )

Perform an inpainting by texture propagation.


The operator InpaintingTexture is used for removing large objects and image errors from the region
Region of the input image Image. Image blocks of side length MaskSize are copied from the intact part
of the image to the border of the computation area, until that area has been filled up with new gray values. This
process is called image inpainting. Hence, the computation area is also referred to as the inpainting area and is
reduced with every inserted rectangle, starting with Region. Let the center of the current block be at the point
x. Since x is always chosen from the border of the inpainting area the current block overlaps with the known or
already filled-in gray values. The gray value correlation with the overlapping part of this block is used to determine
which other image block fits at the position x. As the correlation function, the sum of the squared gray value differ-
ences is used. The image blocks that are taken into account for the correlation, and hence as candidates for the data
source of the next inpainting step, are called comparison blocks. The search area for suitable gray value patterns
in which the centers of the comparison blocks is searched is limited to a square of side length 2 · SearchSize
around the point x.
On the one hand, the order in which the pixels of Region are filled in depends on the size of the overlapping area
and thus the number of pixels available for the correlation. On the other hand, the absolute value of the derivative
of the gray value function tangential to the border of the computation area is also considered. The larger the value
of the parameter Anisotropy is, the more the points in which the derivative is large are preferred. This way it
can be achieved that, e.g., straight lines which are represented by large gradients, are continued through the entire
computation area without being interrupted by the inpainting of image structures from other parts of the border
when the size of the inpainting area becomes small. On the other hand, a large value of Anisotropy also means
that possible phantom edges, i.e., unwanted random structures that have developed during the inpainting process,
are also propagated and the magnitude of those image disturbances is increased.
To confine the formation of such artifacts, the original algorithm can be extended by a post-iteration step that selects
smooth and inconspicuous image patches as data sources for the inpainting. If the parameter PostIteration
is set to ’min_grad’ the sum of the squares of the gray value gradients is minimized on the comparison blocks.
With the value ’min_range_extension’, the growth of the gray value interval of the comparison blocks with respect
to the reference block around the point x is minimized. If PostIteration has the value ’none’ no post-
iteration is performed. The choice of feasible blocks for this minimization process is determined by the parameter
Smoothness, which is an upper limit to the permitted increase of the mean absolute gray value difference
between the comparison blocks and the reference block with respect to the block that was selected by the original
algorithm. With increasing value of Smoothness, the inpainting result becomes smoother and loses structure.
The matching accuracy of the selected comparison blocks decreases. If Smoothness is set to 0, the post-iteration
only considers comparison blocks with an equally high correlation to the reference block.
If the inpainting process cannot be completed because there are points x, for which no complete block of intact gray
value information is contained in the search area of size SearchSize, the remaining pixels keep their initial gray
value and the ROI of the output image InpaintedImage is reduced by the region that could not be processed.
If the structure size of the ROI of Image or of the computation area Region is smaller than MaskSize, the
execution time of the algorithm can increase extremely. Hence, it is recommended to only use clearly structured
input regions.
Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte, uint2, real )


Input image.
. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
Inpainting region.
. InpaintedImage (output iconic) . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX
Output image.

HALCON/COM Reference Manual, 2008-5-13


3.9. LINES 225

. MaskSize (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT


Size of the inpainting blocks.
Default Value : 9
Suggested values : MaskSize ∈ {7, 9, 11, 15, 21}
Restriction : (M askSize ∧ odd)
. SearchSize (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Size of the search window.
Default Value : 30
Suggested values : SearchSize ∈ {15, 30, 50, 100, 1000}
Restriction : ((2 · SearchSize) > M askSize)
. Anisotropy (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Influence of the edge amplitude on the inpainting order.
Default Value : 1.0
Suggested values : Anisotropy ∈ {0.0, 0.01, 0.1, 0.5, 1.0, 10.0}
Restriction : (Anisotropy ≥ 0)
. PostIteration (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Post-iteration for artifact reduction.
Default Value : ’none’
List of values : PostIteration ∈ {’none’, ’min_grad’, ’min_range_extension’}
. Smoothness (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Gray value tolerance for post-iteration.
Default Value : 1.0
Suggested values : Smoothness ∈ {0.0, 0.1, 0.2, 0.5, 1.0}
Restriction : (Smoothness ≥ 0)
Parallelization Information
InpaintingTexture is reentrant and processed without parallelization.
Module
Foundation

3.9 Lines
[out] HImageX ImageBandpass HImageX.BandpassImage
([in] String FilterType )
void HOperatorSetX.BandpassImage ([in] IHObjectX Image,
[out] HUntypedObjectX ImageBandpass, [in] VARIANT FilterType )

Edge extraction using bandpass filters.


BandpassImage serves as an edge filter. It applies a linear filter with the following convolution mask to Image:

FilterType: ’lines’
In contrast to the edge operator SobelAmp this filter detects lines instead of edges, i.e., two closely adjacent
edges.

0 −2 −2 −2 0
−2 0 3 0 −2
−2 3 12 3 −2
−2 0 3 0 −2
0 −2 −2 −2 0

At the border of the image the gray values are mirrored. Over- and underflows of gray values are clipped. The
resulting images are returned in ImageBandpass.
Attention

HALCON 8.0.2
226 CHAPTER 3. FILTER

Parameter

. Image (input iconic) . . . . . . . . . . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, uint2 )


Input images.
. ImageBandpass (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX (
byte, uint2 )
Bandpass-filtered images.
. FilterType (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Filter type: currently only ’lines’ is supported.
Default Value : ’lines’
List of values : FilterType ∈ {’lines’}
Result
BandpassImage returns TRUE if all parameters are correct. If the input is empty the behaviour can be set via
SetSystem(::’noObjectResult’,<Result>:). If necessary, an exception handling is raised.
Parallelization Information
BandpassImage is reentrant and automatically parallelized (on tuple level, channel level, domain level).
Possible Successors
Threshold, Skeleton
See also
HighpassImage, GraySkeleton
Alternatives
ConvolImage, TopographicSketch, TextureLaws
Module
Foundation

[out] HXLDContX Lines HImageX.LinesColor ([in] VARIANT Sigma,


[in] VARIANT Low, [in] VARIANT High, [in] String ExtractWidth,
[in] String CompleteJunctions )
void HOperatorSetX.LinesColor ([in] IHObjectX Image,
[out] HUntypedObjectX Lines, [in] VARIANT Sigma, [in] VARIANT Low,
[in] VARIANT High, [in] VARIANT ExtractWidth,
[in] VARIANT CompleteJunctions )

Detect color lines and their width.


LinesColor extracts color lines from the input image Image and returns the extracted lines as subpixel precise
XLD-contours in Lines. Color lines are defined as dark lines in the amplitude image of the color edge filter (see
EdgesColor). LinesColor always uses the Canny color edge filter. Hence, the required partial derivatives
of the image are always computed by convolution with the respective partial derivatives of the Gaussian smoothing
masks (see DerivateGauss). The corresponding smoothing is determined by the parameter Sigma.
By defining color lines as dark lines in the amplitude image, in contrast to LinesGauss, for single-channel
images no distinction is made whether the lines are darker or brighter than their surroundings. Furthermore,
LinesColor also returns staircase lines, i.e., lines for which the gray value of the lines lies between the gray
values in the surrounding area to the left and right sides of the line. In multi-channel images, the above definition
allows each channel to have a different line type. For example, in a three-channel image the first channel may have
a dark line, the second channel a bright line, and the third channel a staircase line at the same position.
If ExtractWidth is set to ’true’ the line width is extracted for each line point. Because the line extractor is
unable to extract certain junctions because of differential geometric reasons, it tries to extract these by different
means if CompleteJunctions is set to ’true’.
LinesColor links the line points into lines by using an algorithm similar to a hysteresis threshold operation,
which is also used in LinesGauss and EdgesColorSubPix. Points with an amplitude larger than High
are immediately accepted as belonging to a line, while points with an amplitude smaller than Low are rejected.
All other points are accepted as lines if they are connected to accepted line points (see also LinesGauss).
Here, amplitude means the line amplitude of the dark line (see LinesGauss and LinesFacet). This value

HALCON/COM Reference Manual, 2008-5-13


3.9. LINES 227

corresponds to the third directional derivative of the smoothed input image in the direction perpendicular to the
line.
For the choice of the thresholds High and Low one has to keep in mind that the third directional derivative depends
on the amplitude and width of the line as well as the choice of Sigma. The value of the third derivative depends
linearly on the amplitude, i.e., the larger the amplitude, the larger the response. For the width of the line there
is an inverse dependence: The wider the line is, the smaller the response gets. This holds analogously for the
dependence on Sigma: The larger Sigma is chosen, the smaller the second derivative will be. This means that
for larger smoothing correspondingly smaller values for High and Low should be chosen.
The extracted lines are returned in a topologically sound data structure in Lines. This means that lines are
correctly split at junction points.
LinesColor defines the following attributes for each line point if ExtractWidth was set to ’false’:
’angle’ The angle of the direction perpendicular to the line (oriented such that the normal vectors point to
the right side of the line as the line is traversed from start to end point; the angles are given with
respect to the row axis of the image.)
’response’ The magnitude of the second derivative
If ExtractWidth was set to ’true’, additionally the following attributes are defined:
’width_left’ The line width to the left of the line
’width_right’ The line width to the right of the line
All these attributes can be queried via the operator GetContourAttribXld.
Attention √
In general, but in particular if the line width is to be extracted, Sigma ≥ w/ 3 should be selected, where w is
the width (half the diameter) of the lines in the image. As the lowest allowable value Sigma ≥ w/2.5 must be
selected. If, for example, lines with a width of 4 pixels (diameter 8 pixels) are to be extracted, Sigma ≥ 2.3
should be selected. If it is expected that staircase lines are present in at least one channel, and if such lines should
be extracted, in addition to the above restriction, Sigma ≤ w should be selected. This is necessary because
staircase lines turn into normal step edges for large amounts of smoothing, and therefore no longer appear as dark
lines in the amplitude image of the color edge filter.
Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . (multichannel-)image ; HImageX / IHObjectX ( byte, uint2 )


Input image.
. Lines (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xld_cont ; HXLDContX / HUntypedObjectX
Extracted lines.
. Sigma (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Amount of Gaussian smoothing to be applied.
Default Value : 1.5
Suggested values : Sigma ∈ {1, 1.2, 1.5, 1.8, 2, 2.5, 3, 4, 5}
Typical range of values : 0.7 ≤ Sigma ≤ 0.7
Recommended Increment : 0.1
. Low (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Lower threshold for the hysteresis threshold operation.
Default Value : 3
Suggested values : Low ∈ {0, 0.5, 1, 2, 3, 4, 5, 8, 10}
Recommended Increment : 0.5
Restriction : (Low ≥ 0)
. High (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Upper threshold for the hysteresis threshold operation.
Default Value : 8
Suggested values : High ∈ {0, 0.5, 1, 2, 3, 4, 5, 8, 10, 12, 15, 18, 20, 25}
Recommended Increment : 0.5
Restriction : ((High ≥ 0) ∧ (High ≥ Low))
. ExtractWidth (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Should the line width be extracted?
Default Value : ’true’
List of values : ExtractWidth ∈ {’true’, ’false’}

HALCON 8.0.2
228 CHAPTER 3. FILTER

. CompleteJunctions (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT


Should junctions be added where they cannot be extracted?
Default Value : ’true’
List of values : CompleteJunctions ∈ {’true’, ’false’}
Example

Result
LinesColor returns TRUE if all parameters are correct and no error occurs during execution. If the input is
empty the behavior can be set via SetSystem(::’noObjectResult’,<Result>:). If necessary, an
exception handling is raised.
Parallelization Information
LinesColor is reentrant and processed without parallelization.
Possible Successors
GenPolygonsXld
See also
EdgesColor, EdgesColorSubPix
Alternatives
LinesGauss, LinesFacet
References
C. Steger: “Subpixel-Precise Extraction of Lines and Edges”; International Archives of Photogrammetry and
Remote Sensing, vol. XXXIII, part B3; pp. 141-156; 2000.
C. Steger: “An Unbiased Detector of Curvilinear Structures”; IEEE Transactions on Pattern Analysis and Machine
Intelligence; vol. 20, no. 2; pp. 113-125; 1998.
C. Steger: “Unbiased Extraction of Curvilinear Structures from 2D and 3D Images”; Herbert Utz Verlag, München;
1998.
Module
2D Metrology

[out] HXLDContX Lines HImageX.LinesFacet ([in] long MaskSize,


[in] VARIANT Low, [in] VARIANT High, [in] String LightDark )
void HOperatorSetX.LinesFacet ([in] IHObjectX Image,
[out] HUntypedObjectX Lines, [in] VARIANT MaskSize, [in] VARIANT Low,
[in] VARIANT High, [in] VARIANT LightDark )

Detection of lines using the facet model.


The operator LinesFacet can be used to extract lines (curvilinear structures) from the image Image. The
extracted lines are returned in Lines as sub-pixel precise XLD-contours. The parameter LightDark determines,
whether bright or dark lines are extracted.
The extraction is done by using the facet model, i.e., a least squares fit, to determine the parameters of a quadratic
polynomial in x and y for each point of the image. The parameter MaskSize determines the size of the window
used for the least squares fit. Larger values of MaskSize lead to a larger smoothing of the image, but can
lead to worse localization of the line. The parameters of the polynomial are used to calculate the line direction
for each pixel. Pixels which exhibit a local maximum in the second directional derivative perpendicular to the
line direction are marked as line points. The line points found in this manner are then linked to contours. This
is done by immediately accepting line points that have a second derivative larger than High. Points that have
a second derivative smaller than Low are rejected. All other line points are accepted if they are connected to
accepted points by a connected path. This is similar to a hysteresis threshold operation with infinite path length (see
HysteresisThreshold). However, this function is not used internally since it does not allow the extraction
of sub-pixel precise contours.
The gist of how to select the thresholds in the description of LinesGauss also holds for this operator. A value
of Sigma = 1.5 there roughly corresponds to a MaskSize of 5 here.

HALCON/COM Reference Manual, 2008-5-13


3.9. LINES 229

The extracted lines are returned in a topologically sound data structure in Lines. This means that lines are
correctly split at junction points.
LinesFacet defines the following attributes for each line point:
’angle’ The angle of the direction perpendicular to the line
’response’ The magnitude of the second derivative
These attributes can be queried via the operator GetContourAttribXld.
Attention
The smaller the filter size MaskSize is chosen, the more short, fragmented lines will be extracted. This can lead
to considerably longer execution times.
Parameter
. Image (input iconic) . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, int1, int2, uint2, int4, real )
Input image.
. Lines (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xld_cont ; HXLDContX / HUntypedObjectX
Extracted lines.
. MaskSize (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Size of the facet model mask.
Default Value : 5
List of values : MaskSize ∈ {3, 5, 7, 9, 11}
. Low (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Lower threshold for the hysteresis threshold operation.
Default Value : 3
Suggested values : Low ∈ {0, 0.5, 1, 2, 3, 4, 5, 8, 10}
Typical range of values : 0 ≤ Low ≤ 0
Recommended Increment : 0.5
Restriction : (Low ≥ 0)
. High (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Upper threshold for the hysteresis threshold operation.
Default Value : 8
Suggested values : High ∈ {0, 0.5, 1, 2, 3, 4, 5, 8, 10, 12, 15, 18, 20, 25}
Typical range of values : 0 ≤ High ≤ 0
Recommended Increment : 0.5
Restriction : ((High ≥ 0) ∧ (High ≥ Low))
. LightDark (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Extract bright or dark lines.
Default Value : ’light’
List of values : LightDark ∈ {’dark’, ’light’}
Example

/* Detection of lines in an aerial image */


read_image(Image,’mreut4_3’)
lines_facet(Image,Lines,5,3,8,’light’)
disp_xld(Lines,WindowHandle).

Complexity
Let A be the number of pixels in the domain of Image. Then the runtime complexity is O(A ∗ MaskSize).
Let S = Width ∗ Height be the number of pixels of Image. Then LinesFacet requires at least 55 ∗ S bytes of
temporary memory during execution.
Result
LinesFacet returns TRUE if all parameters are correct and no error occurs during execution. If the input is
empty the behaviour can be set via SetSystem(::’noObjectResult’,<Result>:). If necessary, an
exception handling is raised.
Parallelization Information
LinesFacet is reentrant and processed without parallelization.
Possible Successors
GenPolygonsXld

HALCON 8.0.2
230 CHAPTER 3. FILTER

See also
BandpassImage, DynThreshold, TopographicSketch
Alternatives
LinesGauss
References
A. Busch: "‘Fast Recognition of Lines in Digital Images Without User-Supplied Parameters"’. In H. Ebner, C.
Heipke, K.Eder, eds., "‘Spatial Information from Digital Photogrammetry and Computer Vision"’, International
Archives of Photogrammetry and Remote Sensing, Vol. 30, Part 3/1, pp. 91-97, 1994.
Module
2D Metrology

[out] HXLDContX Lines HImageX.LinesGauss ([in] VARIANT Sigma,


[in] VARIANT Low, [in] VARIANT High, [in] String LightDark,
[in] String ExtractWidth, [in] String CorrectPositions,
[in] String CompleteJunctions )
void HOperatorSetX.LinesGauss ([in] IHObjectX Image,
[out] HUntypedObjectX Lines, [in] VARIANT Sigma, [in] VARIANT Low,
[in] VARIANT High, [in] VARIANT LightDark, [in] VARIANT ExtractWidth,
[in] VARIANT CorrectPositions, [in] VARIANT CompleteJunctions )

Detect lines and their width.


The operator LinesGauss can be used to extract lines (curvilinear structures) from the image Image. The ex-
tracted lines are returned in Lines as sub-pixel precise XLD-contours. The parameter LightDark determines,
whether bright or dark lines are extracted. If ExtractWidth is set to ’true’ the line width is extracted for each
line point. If CorrectPositions is set to ’true’, LinesGauss compensates the effect of asymmetrical lines
(lines having different contrast on each side of the line), and corrects the position and width of the line. This param-
eter is only meaningful if ExtractWidth=’true’. Because the line extractor is unable to extract certain junctions
because of differential geometric reasons, it tries to extract these by different means if CompleteJunctions is
set to ’true’.
The extraction is done by using partial derivatives of a Gaussian smoothing kernel to determine the parameters
of a quadratic polynomial in x and y for each point of the image. The parameter Sigma determines the amount
of smoothing to be performed. Larger values of Sigma lead to a larger smoothing of the image, but can lead
to worse localization of the line. Generally, the localization will be much better than that of lines returned by
LinesFacet with comparable parameters. The parameters of the polynomial are used to calculate the line
direction for each pixel. Pixels which exhibit a local maximum in the second directional derivative perpendicular
to the line direction are marked as line points. The line points found in this manner are then linked to contours.
This is done by immediately accepting line points that have a second derivative larger than High. Points that
have a second derivative smaller than Low are rejected. All other line points are accepted if they are connected to
accepted points by a connected path. This is similar to a hysteresis threshold operation with infinite path length (see
HysteresisThreshold). However, this function is not used internally since it does not allow the extraction
of sub-pixel precise contours.
For the choice of the thresholds High and Low one has to keep in mind that the second directional derivative
depends on the amplitude and width of the line as well as the choice of Sigma. The value of the second derivative
depends linearly on the amplitude, i.e., the larger the amplitude, the larger the response. For the width of the
line there is an approximately inverse exponential dependence: The wider the line is, the smaller the response
gets. This holds analogously for the dependence on Sigma: The larger Sigma is chosen, the smaller the second
derivative will be. This means that for larger smoothing correspondingly smaller values for High and Low have
to be chosen. Two examples help to illustrate this: If 5 pixel wide lines with an amplitude larger than 100 are to be
extracted from an image with a smoothing of Sigma = 1.5, High should be chosen larger than 14. If, on the other
hand, 10 pixel wide lines with an amplitude larger than 100 and a Sigma = 3 are to be detected, High should be
chosen larger than 3.5. For the choice of Low values between 0.25 High and 0.5 High are appropriate.
The extracted lines are returned in a topologically sound data structure in Lines. This means that lines are
correctly split at junction points.
LinesGauss defines the following attributes for each line point if ExtractWidth was set to ’false’:

HALCON/COM Reference Manual, 2008-5-13


3.9. LINES 231

’angle’ The angle of the direction perpendicular to the line


’response’ The magnitude of the second derivative
If ExtractWidth was set to ’true’ and CorrectPositions to ’false’, the following attributes are defined in
addition to the above ones:
’width_left’ The line width to the left of the line
’width_right’ The line width to the right of the line
Finally, if CorrectPositions was set to ’true’, additionally the following attributes are defined:
’asymmetry’ The asymmetry of the line point
’contrast’ The contrast of the line point
Here, the asymmetry is positive if the asymmetric part, i.e., the part with the weaker gradient, is on the right side of
the line, while it is negative if the asymmetric part is on the left side of the line. All these attributes can be queried
via the operator GetContourAttribXld.
Attention √
In general, but in particular if the line width is to be extracted, Sigma ≥ w/ 3 should be selected, where w is
the width (half the diameter) of the lines in the image. As the lowest allowable value Sigma ≥ w/2.5 must be
selected. If, for example, lines with a width of 4 pixels (diameter 8 pixels) are to be extracted, Sigma ≥ 2.3
should be selected.
Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, int1, int2, uint2, int4, real )
Input image.
. Lines (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xld_cont ; HXLDContX / HUntypedObjectX
Extracted lines.
. Sigma (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Amount of Gaussian smoothing to be applied.
Default Value : 1.5
Suggested values : Sigma ∈ {1, 1.2, 1.5, 1.8, 2, 2.5, 3, 4, 5}
Typical range of values : 0.7 ≤ Sigma ≤ 0.7
Recommended Increment : 0.1
. Low (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Lower threshold for the hysteresis threshold operation.
Default Value : 3
Suggested values : Low ∈ {0, 0.5, 1, 2, 3, 4, 5, 8, 10}
Typical range of values : 0 ≤ Low ≤ 0
Recommended Increment : 0.5
Restriction : (Low ≥ 0)
. High (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Upper threshold for the hysteresis threshold operation.
Default Value : 8
Suggested values : High ∈ {0, 0.5, 1, 2, 3, 4, 5, 8, 10, 12, 15, 18, 20, 25}
Typical range of values : 0 ≤ High ≤ 0
Recommended Increment : 0.5
Restriction : ((High ≥ 0) ∧ (High ≥ Low))
. LightDark (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Extract bright or dark lines.
Default Value : ’light’
List of values : LightDark ∈ {’dark’, ’light’}
. ExtractWidth (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Should the line width be extracted?
Default Value : ’true’
List of values : ExtractWidth ∈ {’true’, ’false’}
. CorrectPositions (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Should the line position and width be corrected?
Default Value : ’true’
List of values : CorrectPositions ∈ {’true’, ’false’}

HALCON 8.0.2
232 CHAPTER 3. FILTER

. CompleteJunctions (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT


Should junctions be added where they cannot be extracted?
Default Value : ’true’
List of values : CompleteJunctions ∈ {’true’, ’false’}
Example

/* Detection of lines in an aerial image */


read_image(Image,’mreut4_3’)
lines_gauss(Image,Lines,1.5,3,8,’light’,’true’,’true’,’true’)
disp_xld(Lines,WindowHandle).

Complexity
Let A be the number of pixels in the domain of Image. Then the runtime complexity is O(A ∗ Sigma).
Let S = Width ∗ Height be the number of pixels of Image. Then LinesGauss requires at least 55 ∗ S bytes of
temporary memory during execution.
Result
LinesGauss returns TRUE if all parameters are correct and no error occurs during execution. If the input is
empty the behaviour can be set via SetSystem(::’noObjectResult’,<Result>:). If necessary, an
exception handling is raised.
Parallelization Information
LinesGauss is reentrant and processed without parallelization.
Possible Successors
GenPolygonsXld
See also
BandpassImage, DynThreshold, TopographicSketch
Alternatives
LinesFacet
References
C. Steger: “Extracting Curvilinear Structures: A Differential Geometric Approach”. In B. Buxton, R. Cipolla, eds.,
“Fourth European Conference on Computer Vision”, Lecture Notes in Computer Science, Volume 1064, Springer
Verlag, pp. 630-641, 1996.
C. Steger: “Extraction of Curved Lines from Images”. In “13th International Conference on Pattern Recognition”,
Volume II, pp. 251-255, 1996.
C. Steger: “An Unbiased Detector of Curvilinear Structures”. Technical Report FGBV-96-03, Forschungsgruppe
Bildverstehen (FG BV), Informatik IX, Technische Universit"at M"unchen, July 1996.
Module
2D Metrology

3.10 Match
[out] HImageX ImageMatch HImageX.ExhaustiveMatch
([in] HRegionX RegionOfInterest, [in] HImageX ImageTemplate,
[in] String Mode )
void HOperatorSetX.ExhaustiveMatch ([in] IHObjectX Image,
[in] IHObjectX RegionOfInterest, [in] IHObjectX ImageTemplate,
[out] HUntypedObjectX ImageMatch, [in] VARIANT Mode )

Matching of a template and an image.


The operator ExhaustiveMatch matches ImageTemplate and Image within the region of interest
RegionOfInterest. Hereby the ImageTemplate will be moved over all points of Image which lie within
the RegionOfInterest. With regard to the parameter Mode, a matching criterion will be calculated. The
result values will be stored in ImageMatch.
The following matching criteria (Mode) are available:

HALCON/COM Reference Manual, 2008-5-13


3.10. MATCH 233

’norm_correlation’
P
(Image[i − u][j − v] · ImageTemplate[l − u][c − v])
u,v
ImageMatch[i][j] = 255 · qP P
2 2
u,v (Image[i − u][j − v] ) · u,v (ImageTemplate[l − u][c − v] )

whereby X[i][j] indicates the grayvalue in the ith column and jth row of the image X. (l, c) is the centre of
the region of ImageTemplate. u and v are chosen so that all points of the template will be reached, i, j
run accross the RegionOfInterest. At the image frame only those parts of ImageTemplate will be
considered which lie inside the image (i.e. u and v will be restricted correspondingly). Range of values: 0 -
255 (best fit).
’dfd’ Calculating the average “displaced frame difference”:
P
u,v |Image[i − u][j − v] − ImageTemplate[l − u][c − v]|
ImageMatch[i][j] =
AREA(ImageT emplate)

The terms are the same as in ’norm_correlation’. AREA ( X ) means the area of the region X. Range of value
0 (best fit) - 255.

To calculate the normalized correlation as well as the “displaced frame difference” is (with regard to the
area of ImageTemplate) very time consuming. Therefore it is important to restrict the input region
(RegionOfInterest if possible, i.e. to apply the filter only in a very confined “region of interest”.
As far as quality is concerned, both modes return comparable results, whereby the mode ’dfd’ is faster by a factor
of about 3.5.
Parameter
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte )
Input image.
. RegionOfInterest (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
Area to be searched in the input image.
. ImageTemplate (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte )
This area will be “matched” by Image within the RegionOfInterest.
. ImageMatch (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / HUntypedObjectX ( byte )
Result image: values of the matching criterion.
. Mode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Desired matching criterion.
Default Value : ’dfd’
List of values : Mode ∈ {’norm_correlation’, ’dfd’}
Example

read_image(Image,’monkey’)
disp_image(Image,WindowHandle)
draw_rectangle2(WindowHandle,Row,Column,Phi,Length1,Length2)
gen_rectangle2(Rectangle,Row,Column,Phi,Length1,Length2)
reduce_domain(Image,Rectangle,Template)
exhaustive_match(Image,Image,Template,ImageMatch,’dfd’)
invert_image(ImageMatch,ImageInvert)
local_max(Image,Maxima)
union1(Maxima,AllMaxima)
add_channels(AllMaxima,ImageInvert,FitMaxima)
threshold(FitMaxima,BestFit,230.0,255.0)
disp_region(BestFit,WindowHandle).

Result
If the parameter values are correct, the operator ExhaustiveMatch returns the value TRUE. If
the input is empty (no input images are available) the behaviour can be set via SetSystem
(’noObjectResult’,<Result>). If necessary, an exception handling is raised.

HALCON 8.0.2
234 CHAPTER 3. FILTER

Parallelization Information
ExhaustiveMatch is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
DrawRegion, DrawRectangle1
Possible Successors
LocalMax, Threshold
Alternatives
ExhaustiveMatchMg
Module
Foundation

[out] HImageX ImageMatch HImageX.ExhaustiveMatchMg


([in] HImageX ImageTemplate, [in] String Mode, [in] long Level,
[in] long Threshold )
void HOperatorSetX.ExhaustiveMatchMg ([in] IHObjectX Image,
[in] IHObjectX ImageTemplate, [out] HUntypedObjectX ImageMatch,
[in] VARIANT Mode, [in] VARIANT Level, [in] VARIANT Threshold )

Matching a template and an image in a resolution pyramid.


The operator ExhaustiveMatchMg is an additional option for the operator ExhaustiveMatch performing
a matching of the image Image and the template ImageTemplate. Hereby ImageTemplate will be moved
over all points of the region of Image, a matching criterion will be calculated with regard to the parameter Mode
and the result values will be stored in ImageMatch.
Of images having been filtered this way, normally only those areas with good matching results are of interest. The
size of the area to be searched, i.e. the region of the input image Image, determines decisively the runtime of
the matching filter. Therefore it is recommendable to use at first ExhaustiveMatchMg with reduced image
resolution in order to determine a “region of interest” in which good matching results can be expected; then in this
restricted area only the real matching (see also ExhaustiveMatch) will be executed with normal resolution.
Hereby the Gauss-pyramids of Image and ImageTemplate will be composed (in particular the corresponding
regions will be transformed as well). Then on each level of the resolution pyramids - starting with the startlevel
Level - the matching inside the current “region of interest” will be executed. Whereby the “region of interest” on
the startlevel is equivalent to the region of the input image Image. After the filtering, a new “region of interest” is
determined with the help of a threshold operation and will be transformed on the next resolution level:
Threshold(..0,Threshold..), if Mode = ’dfd’
Threshold(..Threshold,255..), if Mode = ’norm_correlation’
The final matching in the determined “region of interest” will then be calculated with the highest resolution (Level
0). The output image ImageMatch includes the corresponding filter result and the final “region of interest”, which
is determined on the result image with the help of a threshold operation.
The operator ExhaustiveMatchMg therefore is not simply a filter, but can also be considered as a member of
the class of region transformations.
Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte )


Input image.
. ImageTemplate (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte )
The domain of this image will be matched with Image.
. ImageMatch (output iconic) . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte )
Result image and result region: values of the matching criterion within the determined “region of interest”.
Number of elements : (ImageM atch = Image)
. Mode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Desired matching criterion.
Default Value : ’dfd’
List of values : Mode ∈ {’norm_correlation’, ’dfd’}

HALCON/COM Reference Manual, 2008-5-13


3.10. MATCH 235

. Level (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT


Startlevel in the resolution pyramid (highest resolution: Level 0).
Default Value : 1
List of values : Level ∈ {0, 1, 2, 3, 4, 5, 6, 7, 8}
Restriction : (Image ∧ (height < ld))
. Threshold (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Threshold to determine the “region of interest”.
Default Value : 30
Suggested values : Threshold ∈ {5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90, 95,
100, 105, 110, 115, 120, 125, 130, 135, 140, 145, 150, 155, 160, 165, 170, 175, 180, 185, 190, 195, 200, 205,
210, 215, 220, 225, 230, 235, 240, 245, 250}
Typical range of values : 0 ≤ Threshold ≤ 0
Minimum Increment : 1
Recommended Increment : 5
Result
If the parameter values are correct, the operator ExhaustiveMatchMg returns the value TRUE.
If the input is empty (no input images are available) the behaviour can be set via SetSystem
(’noObjectResult’,<Result>). If necessary, an exception handling is raised.
Parallelization Information
ExhaustiveMatchMg is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
DrawRegion, DrawRectangle1
Possible Successors
Threshold, LocalMax
See also
GenGaussPyramid
Alternatives
ExhaustiveMatch
Module
Foundation

[out] HImageX ImagePyramid HImageX.GenGaussPyramid ([in] String Mode,


[in] double Scale )
void HOperatorSetX.GenGaussPyramid ([in] IHObjectX Image,
[out] HUntypedObjectX ImagePyramid, [in] VARIANT Mode, [in] VARIANT Scale )

Calculating a Gauss pyramid.


The operator GenGaussPyramid calculates a pyramid of scaled down images. The scale by which the next
image will be reduced is determined by the parameter Scale. For instance, a value of 0.5 for Scale will shorten
the edge length of Image by 50%. This is exactly equivalent to the “normal” pyramid.
The parameter Mode determines the way of averaging. For a more detailed description concerning this parameter
see also AffineTransImage. In the case that Scale is equal 0.5 there are the additional modes ’min’ and
’max’ available. In this case the minimum or the maximum of the four neighboring pixels is selected.
Please note that each level will be returned as an individual image, i.e., as one iconic objekt, with one matrix and
its own domain. Single or multiple levels can be selected by using SelectObj or CopyObj, respectively.
Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . (multichannel-)image ; HImageX / IHObjectX ( byte, uint2, real )


Input image.
. ImagePyramid (output iconic) . . . . . . (multichannel-)image ; HImageX / HUntypedObjectX ( byte,
uint2, real )
Output images.
Number of elements : (ImageP yramid > Image)

HALCON 8.0.2
236 CHAPTER 3. FILTER

. Mode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT


Kind of filtermask.
Default Value : ’weighted’
List of values : Mode ∈ {’none’, ’constant’, ’weighted’, ’min’, ’max’}
. Scale (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Factor for scaling down.
Default Value : 0.5
Suggested values : Scale ∈ {0.2, 0.3, 0.4, 0.5, 0.6}
Typical range of values : 0.1 ≤ Scale ≤ 0.1
Minimum Increment : 0.01
Recommended Increment : 0.1
Restriction : ((0.1 < Scale) ∧ (Scale < 0.9))
Parallelization Information
GenGaussPyramid is reentrant and automatically parallelized (on channel level).
Possible Successors
ImageToChannels, CountObj, SelectObj, CopyObj
See also
AffineTransImage
Alternatives
ZoomImageSize, ZoomImageFactor
Module
Foundation

HImageX.Monotony ( )
[out] HImageX ImageMonotony
void HOperatorSetX.Monotony ([in] IHObjectX Image,
[out] HUntypedObjectX ImageMonotony )

Calculating the monotony operation.


The operator Monotony calculates the monotony operator. Thereby the points which are strictly smaller than the
current grayvalue will be counted in the 8 neighborhood. This number will be entered into the output imaged.
If there is a strict maximum, the value 8 is returned; in case of a minimum or a plateau, the value 0 will be returned.
A ridge or a slope will return the corresponding intermediate values.
The monotony operator is often used to prepare matching operations as it is invariant with regard to lightness
modifications.
Parameter

. Image (input iconic) . . . . . . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, int2, uint2 )


Input image.
. ImageMonotony (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX (
byte, int2, uint2 )
Result of the monotony operator.
Number of elements : (ImageM onotony = Image)
Parallelization Information
Monotony is reentrant and automatically parallelized (on tuple level, channel level, domain level).
Possible Predecessors
BinomialFilter, GaussImage, MedianImage, MeanImage, SmoothImage, InvertImage
Possible Successors
Threshold, ExhaustiveMatch, DispImage
Alternatives
LocalMax, TopographicSketch, CornerResponse
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


3.11. MISC 237

3.11 Misc
[out] HImageX ImageResult HImageX.ConvolImage ([in] VARIANT FilterMask,
[in] VARIANT Margin )
void HOperatorSetX.ConvolImage ([in] IHObjectX Image,
[out] HUntypedObjectX ImageResult, [in] VARIANT FilterMask,
[in] VARIANT Margin )

Convolve an image with an arbitrary filter mask.


ConvolImage convolves the input image Image with an arbitrary linear filter. The corresponding filter mask,
which is given in FilterMask can be generated either from a file or a tuple. Several options for the treatment at
the image’s borders can be chosen (Margin):

gray value Pixels outside of the image edges are assumued


to be constant (with the indicated gray value).
’continued’ Continuation of edge pixels.
’cyclic’ Cyclic continuation of image edges.
’mirrored’ Reflection of pixels at the image edges.

All image points are convolved with the filter mask. If an overflow or underflow occurs, the resulting gray value
is clipped. Hence, if filters that result in negative output values are used (e.g., derivative filters) the input image
should be of type int2. If a filename is given in FilterMask the filter mask is read from a text file with the
following structure:
hMask sizei
hInverse weight of the maski
hMatrixi
The first line contains the size of the filter mask, given as two numbers separated by white space (e.g., 3 3 for
3 × 3). Here, the first number defines the height of the filter mask, while the second number defines its width. The
next line contains the inverse weight of the mask, i.e., the number by which the convolution of a particular image
point is divided. The remaining lines contain the filter mask as integer numbers (separated by white space), one
line of the mask per line in the file. The file must have the extension “.fil”. This extension must not be passed to
the operator. If the filter mask is to be computed from a tuple, the tuple given in FilterMask must also satisfy
the structure described above. However, in this case the line feed is omitted.
For example, lets assume we want to use the following filter mask:
 
1 2 1
1 
16
2 4 2 
1 2 1
If the filter mask should be generated from a file, then the file should look like this:
33
16
121
242
121
In contrast, if the filter mask should be generated from a tuple, then the following tuple must be passed in
FilterMask:
[3,3,16,1,2,1,2,4,2,1,2,1]
Parameter
. Image (input iconic) . . . . . . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, int2, uint2 )
Image to be convolved.
. ImageResult (output iconic) . . . . . . multichannel-image-array ; HImageX / HUntypedObjectX ( byte,
int2, uint2 )
Convolved result image.
. FilterMask (input control) . . . . . . . . . . . . . . . . . . . . . . . filename.read(-array) ; VARIANT ( integer, string )
Filter mask as file name or tuple.
Default Value : ’sobel’
Suggested values : FilterMask ∈ {’sobel’, ’laplace4’, ’lowpas_3_3’}

HALCON 8.0.2
238 CHAPTER 3. FILTER

. Margin (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( integer, real, string )


Border treatment.
Default Value : ’mirrored’
Suggested values : Margin ∈ {’mirrored’, ’cyclic’, ’continued’, 0, 30, 60, 90, 120, 150, 180, 210, 240, 255}
Parallelization Information
ConvolImage is reentrant and automatically parallelized (on tuple level, channel level).
Module
Foundation

[out] HImageX ExpandedImage HImageX.ExpandDomainGray


([in] long ExpansionRange )
void HOperatorSetX.ExpandDomainGray ([in] IHObjectX InputImage,
[out] HUntypedObjectX ExpandedImage, [in] VARIANT ExpansionRange )

Expand the domain of an image and set the gray values in the expanded domain.
ExpandDomainGray expands the border gray values of the domain outwards. The width of the expansion
is set by the parameter ExpansionRange. All filters in HALCON use gray values of the pixels outside the
domain depending on the filter width. This may lead to undesirable side effects especially in the border region
of the domain. For example, if the foreground (domain) and the background of the image differ strongly in
brightness, the result of a filter operation may lead to undesired darkening or brightening at the border of the
domain. In order to avoid this drawback, the domain is expanded by ExpandDomainGray in a preliminary
stage, copying the gray values of the border pixels to the outside of the domain. In addition, the domain itself
is also expanded to reflect the newly set pixels. Therefore, in many cases it is reasonable to reduce the domain
again ( ReduceDomain or ChangeDomain) after using ExpandDomainGray and call the filter operation
afterwards. ExpansionRange should be set to the half of the filter width.
Parameter

. InputImage (input iconic) . . . . image(-array) ; HImageX / IHObjectX ( byte, int1, int2, uint2, int4, real )
Input image with domain to be expanded.
. ExpandedImage (output iconic) . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, int1, int2,
uint2, int4, real )
Output image with new gray values in the expanded domain.
. ExpansionRange (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Radius of the gray value expansion, measured in pixels.
Default Value : 2
Suggested values : ExpansionRange ∈ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 14, 16}
Restriction : (ExpansionRange ≥ 1)
Example

read_image(Fabrik, ’fabrik.tif’);
gen_rectangle2(Rectangle_Label,243,320,-1.55,62,28);
reduce_domain(Fabrik, Rectangle_Label, Fabrik_Label);
/* Character extraction without gray value expansion: */
mean_image(Fabrik_Label,Label_Mean_normal,31,31);
dyn_threshold(Fabrik_Label,Label_Mean_normal,Characters_normal,10,’dark’);
dev_display(Fabrik);
dev_display(Characters_normal);
/* The characters in the border region are not extracted ! */
stop();
/* Character extraction with gray value expansion: */
expand_domain_gray(Fabrik_Label, Label_expanded,15);
reduce_domain(Label_expanded,Rectangle_Label, Label_expanded_reduced);
mean_image(Label_expanded_reduced,Label_Mean_expanded,31,31);
dyn_threshold(Fabrik_Label,Label_Mean_expanded,Characters_expanded,10,’dark’);
dev_display(Fabrik);

HALCON/COM Reference Manual, 2008-5-13


3.11. MISC 239

dev_display(Characters_expanded);
/* Now, even in the border region the characters are recognized */

Complexity
Let L the perimeter of the domain. Then the runtime complexity is approximately O(L) ∗ ExpansionRange.
Result
ExpandDomainGray returns TRUE if all parameters are correct. If necessary, an exception handling is raised.
Parallelization Information
ExpandDomainGray is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
ReduceDomain
Possible Successors
ReduceDomain, MeanImage, DynThreshold
See also
ReduceDomain, MeanImage
Module
Foundation

HImageX.GrayInside ( )
[out] HImageX ImageDist
void HOperatorSetX.GrayInside ([in] IHObjectX Image,
[out] HUntypedObjectX ImageDist )

Calculate the lowest possible gray value on an arbitrary path to the image border for each point in the image.
GrayInside determines the “cheapest” path to the image border for each point in the image, i.e., the path on
which the lowest gray values have to be overcome. The resulting image contains the difference of the gray value
of the particular point and the maximum gray value on the path. Bright areas in the result image therefore signify
that these areas (which are typically dark in the original image) are surrounded by bright areas. Dark areas in the
result image signify that there are only small gray value differences between them and the image border (which
doesn’t mean that they are surrounded by dark areas; a small “gap” of dark values suffices). The value 0 (black) in
the result image signnifies that only darker or equally bright pixels exist on the path to the image border.
The operator is implemented by first segmenting into basins and watersheds the image using the Watersheds
operator. If the image is regarded as a gray value mountain range, basins are the places where water accumulates
and the mountain ridges are the watersheds. Then, the watersheds are distributed to adjacent basins, thus leaving
only basins. The border of the domain (region) of the original image is now searched for the lowest gray value,
and the region in which it resides is given its result values. If the lowest gray value resides on the image border,
all result values can be calculated immediately using the gray value differences to the darkest point. If the smalles
found gray value lies in the interior of a basin, the lowest possible gray value has to be determined from the already
processed adjacent basins in order to compute the new values. An 8-neighborhood is used to determine adjacency.
The found region is subtracted from the regions yet to process, and the whole process is repeated. Thus, the image
is “stripped” form the outside.
Analogously to Watersheds, it is advisable to apply a smoothing operation before calling Watersheds, e.g.,
BinomialFilter or GaussImage, in order to reduce the amount of regions that result from the watershed
algorithm, and thus to speed up the processing time.
Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte )


Image being processed.
. ImageDist (output iconic) . . . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX ( int2 )
Result image.
Example

read_image(Bild,’coin’)
gauss_image (Bild,G_Bild,11)

HALCON 8.0.2
240 CHAPTER 3. FILTER

open_window (0,0,512,512,0,’visible’,’’,WindowHandle)
gray_inside(G_Bild,Ausgabebild)
disp_image (Ausgabebild,WindowHandle).

Result
GrayInside always returns TRUE.
Parallelization Information
GrayInside is reentrant and automatically parallelized (on tuple level, channel level).
Possible Predecessors
BinomialFilter, GaussImage, SmoothImage, MeanImage, MedianImage
Possible Successors
SelectShape, AreaCenter, CountObj
See also
Watersheds
Module
Foundation

[out] HImageX GraySkeleton HImageX.GraySkeleton ( )


void HOperatorSetX.GraySkeleton ([in] IHObjectX Image,
[out] HUntypedObjectX GraySkeleton )

Thinning of gray value images.


GraySkeleton applies a gray value thinning operation to the input image Image. Figuratively, the gray
value “mountain range” is reduced to its ridge lines by setting the gray value of “hillsides” to the gray value
at the corresponding valley bottom. The resulting ridge lines are at most two pixels wide. This operator is es-
pecially useful for thinning edge images, and is thus an alternative to NonmaxSuppressionAmp. In con-
trast to NonmaxSuppressionAmp, GraySkeleton preserves contours, but is much slower. In contrast to
Skeleton, this operator changes the gray values of an image while leaving its region unchanged.
Parameter
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte )
Image to be thinned.
. GraySkeleton (output iconic) . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX ( byte )
Thinned image.
Example

/* Seeking leafs of a beech tree in an aerial picture: */


read_image(Image,’wald1’)
gray_skeleton(Image,Skelett)
mean_image(Skelett,MeanSkelett,7,7)
dyn_threshold(Skelett,MeanSkelett,Leafs,3,’light’).

Result
GraySkeleton returns TRUE if all parameters are correct. If the input is empty the behavior can be set via
SetSystem(’noObjectResult’,<Result>). If necessary, an exception is raised.
Parallelization Information
GraySkeleton is reentrant and automatically parallelized (on tuple level, channel level).
Possible Successors
MeanImage
See also
Skeleton, GrayDilationRect

HALCON/COM Reference Manual, 2008-5-13


3.11. MISC 241

Alternatives
NonmaxSuppressionAmp, NonmaxSuppressionDir, LocalMax
Module
Foundation

HImageX.LutTrans ([in] VARIANT Lut )


[out] HImageX ImageResult
void HOperatorSetX.LutTrans ([in] IHObjectX Image,
[out] HUntypedObjectX ImageResult, [in] VARIANT Lut )

Transform an image with a gray-value look-up-table


LutTrans transforms an image Image by using a gray value look-up-table Lut. This table acts as a transfor-
mation function. In the case of byte-images, Lut has to be a tuple of length 256. In the case of int2-images, Lut
has to be a tuple of length 256 <= length <= 65536. If the length of the Lut is <= 32768, the transformation is
applied to the positive gray values only, i.e., the first element of the Lut specifies the new gray value for the gray
value 0. If the Lut is longer than 32768, exactly 65536 must be passed. In this case, the positive and negative gray
values are transformed. In this case, the first element indicates the new gray value for the gray value -32768 of the
input image, while the last element of the tuple indicates the new gray value for the gray value 32767. In all cases,
the gray values of values outside the range of Lut are set to 0. In the case of uint2-images, Lut has to be a tuple
of length 256 <= length <= 65536. Gray values outside the range of Lut are set to 0.
Parameter

. Image (input iconic) . . . . . . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, int2, uint2 )


Image whose gray values are to be transformed.
. ImageResult (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX (
byte, int2, uint2 )
Transformed image.
. Lut (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Table containing the transformation.
Example

/* To get the inverse of an image: */


read_image(Image,’wald1’)
def_tab(Tab,0)
lut_trans(Image,Invers,Tab,1,1)

def_tab(Tab,I) :- I=255
Tab = 0
def_tab([Tk|Ts],I) :-
Tk is 255 - I
Iw is I -1
def_tab(Ts,Iw)

Result
The operator LutTrans returns the value TRUE if the parameters are correct. Otherwise an exception is raised.
Parallelization Information
LutTrans is reentrant and automatically parallelized (on tuple level, channel level, domain level).
Module
Foundation

HALCON 8.0.2
242 CHAPTER 3. FILTER

[out] HImageX ImageSymmetry HImageX.Symmetry ([in] long MaskSize,


[in] double Direction, [in] double Exponent )
void HOperatorSetX.Symmetry ([in] IHObjectX Image,
[out] HUntypedObjectX ImageSymmetry, [in] VARIANT MaskSize,
[in] VARIANT Direction, [in] VARIANT Exponent )

Symmentry of gray values along a row.


Symmetry calculates the symmetry along a line. For each pixel the gray values of both sides of the line are
compared: The absolut value of the differences of gray values with same distance to the pixel is computed. Each
of these differences is weighted by the exponent (after division by 255) and the summed up.

MaskSize  Exponent
255 X |g(i) − g(−i)|
sym := 255 −
MaskSize i=1
255

Pixels with a high symmetry have large gray values.


Attention
Currently only horizontal search lines are implemented
Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte )


Input image.
. ImageSymmetry (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX (
byte )
Symmetry image.
. MaskSize (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; long / VARIANT
Extension of search area.
Default Value : 40
Suggested values : MaskSize ∈ {3, 5, 7, 10, 15, 20, 25, 30, 40, 50, 60, 70, 80, 100, 120, 140, 180}
Typical range of values : 3 ≤ MaskSize ≤ 3
Minimum Increment : 1
Recommended Increment : 2
. Direction (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Angle of test direction.
Default Value : 0.0
Suggested values : Direction ∈ {0.0}
Typical range of values : 0.0 ≤ Direction ≤ 0.0
. Exponent (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Exponent for weighting.
Default Value : 0.5
Suggested values : Exponent ∈ {0.1, 0.2, 0.3, 0.4, 0.5, 0.7, 0.8, 0.9, 1.0}
Typical range of values : 0.05 ≤ Exponent ≤ 0.05
Minimum Increment : 0.01
Recommended Increment : 0.1
Restriction : ((0 < Exponent) ∧ (Exponent ≤ 1))
Example

read_image(Image,’monkey’)
symmetry(Image,ImageSymmetry,70,0.0,0.5)
threshold(ImageSymmetry,SymmPoints,170,255)

Result
If the parameter values are correct the operator Symmetry returns the value TRUE The behavior in case of empty
input (no input images available) is set via the operator SetSystem(::’noObjectResult’,<Result>:
). If necessary an exception handling is raised.

HALCON/COM Reference Manual, 2008-5-13


3.11. MISC 243

Parallelization Information
Symmetry is reentrant and automatically parallelized (on tuple level, channel level, domain level).
Possible Successors
Threshold
Module
Foundation

HImageX.TopographicSketch ( )
[out] HImageX Sketch
void HOperatorSetX.TopographicSketch ([in] IHObjectX Image,
[out] HUntypedObjectX Sketch )

Compute the topographic primal sketch of an image.


TopographicSketch computes the topographic primal sketch of the input image Image. This is done by
approximating the image locally by a bicubic polynomial (“facet model”). It serves to calculate the first and
second partial derivatives of the image, and thus to classify the image into 11 classes. These classes are coded in
the output image Sketch as numbers from 1 to 11. The classes are as follows:
Peak 1
Pit 2
Ridge 3
Ravine 4
Saddle 5
Flat 6
Hillside Slope 7
Hillside Convex 8
Hillside Concave 9
Hillside Saddle 10
Hillside Inflection 11
In order to obtain the separate classes as regions, a threshold operation has to be applied to the result image with
the appropriate thresholds.
Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte )


Image for which the topographic primal sketch is to be computed.
. Sketch (output iconic) . . . . . . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX ( byte )
Label image containing the 11 classes.
Example

/* To extract the Ridges from a Image */


read_image(Image,’sinus’)
topographic_sketch(Image,Sketch)
threshold(Sketch,Ridges,3,3).

Complexity
Let n be the number of pixels in the image. Then O(n) operations are performed.
Result
TopographicSketch returns TRUE if all parameters are correct. If the input is empty the behavior can be set
via SetSystem(’noObjectResult’,<Result>). If necessary, an exception is raised.
Parallelization Information
TopographicSketch is reentrant and automatically parallelized (on tuple level, channel level).
Possible Successors
Threshold

HALCON 8.0.2
244 CHAPTER 3. FILTER

References
R. Haralick, L. Shapiro: “Computer and Robot Vision, Volume I”; Reading, Massachusetts, Addison-Wesley;
1992; Kapitel 8.13.
Module
Foundation

3.12 Noise
[out] HImageX ImageNoise HImageX.AddNoiseDistribution
([in] VARIANT Distribution )
void HOperatorSetX.AddNoiseDistribution ([in] IHObjectX Image,
[out] HUntypedObjectX ImageNoise, [in] VARIANT Distribution )

Add noise to an image.


AddNoiseDistribution adds noise distributed according to Distribution to the Image. The resulting
gray values are clipped to the range of the corresponding pixel type.
The Distribution is stored in a tuple of length 513. The individual values of this tuple define the frequency
of noise with a specific amplitude defined by the position within the tuple. The central value, i.e., the value at
the position 256 in the tuple defines the frequency of pixels that are not changed. The value at the position 255
defines the frequency of pixels for which the grayvalue is decreased by 1. The value at the position 254 defines the
respective frequency for a grayvalue decrease of 2, and so on. Analogously, the value at position 257 defines the
frequency of pixels for which the grayvalue is increased by 1.
The Distribution represents salt and pepper noise if at most one value at a position smaller than 256 is not
equal to zero and at most one value at a position larger than 256 is not equal to zero. In case of salt and pepper
noise, the noisified pixels are set to the minimum (pepper) and maximum (salt) values that can be represented by
ImageNoise if the amount of pepper is indicated by the value at position 0 and the amount of salt is indicated
by the value at position 512 in the tuple.
Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, int2 )


Input image.
. ImageNoise (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX ( byte,
int2 )
Noisy image.
Number of elements : (ImageN oise = Image)
. Distribution (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . distribution.values ; VARIANT ( real )
Noise distribution.
Number of elements : 513
Example

read_image(Image,’mreut’)
disp_image(Image,WindowHandle)
sp_distribution(30,30,Dist)
add_noise_distribution(Image,ImageNoise,Dist)
disp_image(ImageNoise,WindowHandle).

Result
AddNoiseDistribution returns TRUE if all parameters are correct. If the input is empty the behaviour can
be set via SetSystem(’noObjectResult’,<Result>). If necessary, an exception handling is raised.
Parallelization Information
AddNoiseDistribution is reentrant and automatically parallelized (on tuple level, channel level, domain
level).
Possible Predecessors
GaussDistribution, SpDistribution, NoiseDistributionMean

HALCON/COM Reference Manual, 2008-5-13


3.12. NOISE 245

See also
SpDistribution, GaussDistribution, NoiseDistributionMean, AddNoiseWhite
Alternatives
AddNoiseWhite
Module
Foundation

HImageX.AddNoiseWhite ([in] double Amp )


[out] HImageX ImageNoise
void HOperatorSetX.AddNoiseWhite ([in] IHObjectX Image,
[out] HUntypedObjectX ImageNoise, [in] VARIANT Amp )

Add noise to an image.


AddNoiseWhite adds noise to the image Image. The noise is white noise, equally distributed in the interval
[-Amp,Amp], and is generated by using the C function “drand48” with an initial time dependent seed. The resulting
gray values are clipped to the range of the corresponding pixel type.
Parameter

. Image (input iconic) . . . . . . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, int2, uint2 )


Input image.
. ImageNoise (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX ( byte,
int2, uint2 )
Noisy image.
Number of elements : (ImageN oise = Image)
. Amp (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Maximum noise amplitude.
Default Value : 60.0
Suggested values : Amp ∈ {1.0, 2.0, 5.0, 10.0, 20.0, 40.0, 60.0, 90.0}
Typical range of values : 1.0 ≤ Amp ≤ 1.0
Minimum Increment : 1.0
Recommended Increment : 10.0
Restriction : (Amp > 0)
Example

read_image(Image,’fabrik’)
disp_image(Image,WindowHandle)
add_noise_white(Image,ImageNoise,90)
disp_image(ImageNoise,WindowHandle).

Result
AddNoiseWhite returns TRUE if all parameters are correct. If the input is empty the behaviour can be set via
SetSystem(’noObjectResult’,<Result>). If necessary, an exception handling is raised.
Parallelization Information
AddNoiseWhite is reentrant and automatically parallelized (on tuple level, channel level, domain level).
See also
AddNoiseDistribution, NoiseDistributionMean, GaussDistribution, SpDistribution
Alternatives
AddNoiseDistribution
Module
Foundation

HALCON 8.0.2
246 CHAPTER 3. FILTER

[out] VARIANT Distribution HMiscX.GaussDistribution


([in] double Sigma )
void HOperatorSetX.GaussDistribution ([in] VARIANT Sigma,
[out] VARIANT Distribution )

Generate a Gaussian noise distribution.


GaussDistribution generates a Gaussian noise distribution. The parameter Sigma determines the
noise’s standard deviation. Usually, the result Distribution is used as input for the operator
AddNoiseDistribution.
Parameter

. Sigma (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT


Standard deviation of the Gaussian noise distribution.
Default Value : 2.0
Suggested values : Sigma ∈ {1.5, 2.0, 3.0, 5.0, 10.0}
Typical range of values : 0.0 ≤ Sigma ≤ 0.0
Minimum Increment : 0.1
Recommended Increment : 1.0
. Distribution (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . distribution.values ; VARIANT ( real )
Resulting Gaussian noise distribution.
Number of elements : 513
Example

read_image(Image,’fabrik’)
disp_image(Image,WindowHandle)
gauss_distribution(30,Dist)
add_noise_distribution(Image,ImageNoise,Dist)
disp_image(ImageNoise,WindowHandle).

Parallelization Information
GaussDistribution is reentrant and processed without parallelization.
Possible Successors
AddNoiseDistribution
See also
SpDistribution, AddNoiseWhite, NoiseDistributionMean
Alternatives
SpDistribution, NoiseDistributionMean
Module
Foundation

[out] VARIANT Distribution HRegionX.NoiseDistributionMean


([in] HImageX Image, [in] long FilterSize )
[out] VARIANT Distribution HImageX.NoiseDistributionMean
([in] HRegionX ConstRegion, [in] long FilterSize )
void HOperatorSetX.NoiseDistributionMean
([in] IHObjectX ConstRegion, [in] IHObjectX Image, [in] VARIANT FilterSize,
[out] VARIANT Distribution )

Determine the noise distribution of an image.


NoiseDistributionMean calculates the noise distribution in a region of the image Image. The parameter
ConstRegion determines a region of the image with approximately constant gray values. Ideally, the changes
in gray values should only be caused by noise in this region. From this region the noise distribution is determined

HALCON/COM Reference Manual, 2008-5-13


3.12. NOISE 247

by using the MeanImage operator to smooth the image, and to use the gray value differences in this area as an
estimate for the noise distribution, which is returned in Distribution.
Attention
It is important to ensure that the region ConstRegion is not too close to a large gradient in the image, because
the gradient values are then used for calculating the mean. This means the the distance of ConstRegion must
be at least as large as the filter size FilterSize used for calculating the mean.
Parameter

. ConstRegion (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Region from which the noise distribution is to be estimated.
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte )
Corresponding image.
. FilterSize (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Size of the mean filter.
Default Value : 21
Suggested values : FilterSize ∈ {5, 11, 15, 21, 31, 51, 101}
Typical range of values : 3 ≤ FilterSize ≤ 3(lin)
Minimum Increment : 2
Recommended Increment : 2
. Distribution (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . distribution.values ; VARIANT ( real )
Noise distribution of all input regions.
Parallelization Information
NoiseDistributionMean is reentrant and processed without parallelization.
Possible Predecessors
DrawRegion, GenCircle, GenEllipse, GenRectangle1, GenRectangle2, Threshold,
ErosionCircle, BinomialFilter, GaussImage, SmoothImage, SubImage
Possible Successors
AddNoiseDistribution, DispDistribution
See also
MeanImage, GaussDistribution
Module
Foundation

[out] VARIANT Distribution HMiscX.SpDistribution


([in] VARIANT PercentSalt, [in] VARIANT PercentPepper )
void HOperatorSetX.SpDistribution ([in] VARIANT PercentSalt,
[in] VARIANT PercentPepper, [out] VARIANT Distribution )

Generate a salt-and-pepper noise distribution.


SpDistribution generates a noise distribution with the values 0 and 255. The parameters PercentSalt
and PercentPepper determine the percentage of white and black noise pixels, respectively. The sum of these
parameters must be smaller than 100. Usually, the result Distribution is used as input for the operator
AddNoiseDistribution.
Parameter

. PercentSalt (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )


Percentage of salt (white noise pixels).
Default Value : 5.0
Suggested values : PercentSalt ∈ {1.0, 2.0, 5.0, 7.0, 10.0, 15.0, 20.0, 30.0}
Typical range of values : 0.0 ≤ PercentSalt ≤ 0.0
Minimum Increment : 0.1
Recommended Increment : 1.0
Restriction : ((0.0 ≤ P ercentSalt) ∧ (P ercentSalt ≤ 100.0))

HALCON 8.0.2
248 CHAPTER 3. FILTER

. PercentPepper (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )


Percentage of pepper (black noise pixels).
Default Value : 5.0
Suggested values : PercentPepper ∈ {1.0, 2.0, 5.0, 7.0, 10.0, 15.0, 20.0, 30.0}
Typical range of values : 0.0 ≤ PercentPepper ≤ 0.0
Minimum Increment : 0.1
Recommended Increment : 1.0
Restriction : ((0.0 ≤ P ercentP epper) ∧ (P ercentP epper ≤ 100.0))
. Distribution (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . distribution.values ; VARIANT ( real )
Resulting noise distribution.
Number of elements : 513
Example

read_image(Image,’fabrik’)
disp_image(Image,WindowHandle)
sp_distribution(30,30,Dist)
add_noise_distribution(Image,ImageNoise,Dist)
disp_image(ImageNoise,WindowHandle)

Parallelization Information
SpDistribution is reentrant and processed without parallelization.
Possible Successors
AddNoiseDistribution
See also
GaussDistribution, NoiseDistributionMean, AddNoiseWhite
Alternatives
GaussDistribution, NoiseDistributionMean
Module
Foundation

3.13 Optical-Flow

[out] HImageX VectorField HImageX.OpticalFlowMg ([in] HImageX Image2,


[in] String Algorithm, [in] double SmoothingSigma,
[in] double IntegrationSigma, [in] double FlowSmoothness,
[in] double GradientConstancy, [in] VARIANT MGParamName,
[in] VARIANT MGParamValue )
void HOperatorSetX.OpticalFlowMg ([in] IHObjectX Image1,
[in] IHObjectX Image2, [out] HUntypedObjectX VectorField,
[in] VARIANT Algorithm, [in] VARIANT SmoothingSigma,
[in] VARIANT IntegrationSigma, [in] VARIANT FlowSmoothness,
[in] VARIANT GradientConstancy, [in] VARIANT MGParamName,
[in] VARIANT MGParamValue )

Compute the optical flow between two images.


OpticalFlowMg computes the optical flow between two images. The optical flow represents information about
the movement between two consecutive images of a monocular image sequence. The movement in the images can
be caused by objects that move in the world or by a movement of the camera (or both) between the acquisition of
the two images. The projection of these 3D movements into the 2D image plane is called the optical flow.
The two consecutive images of the image sequence are passed in Image1 and Image2. The computed optical
flow is returned in VectorField. The vectors in the vector field VectorField represent the movement in the
image plane between Image1 and Image2. The point in Image2 that corresponds to the point (r, c) in Image1

HALCON/COM Reference Manual, 2008-5-13


3.13. OPTICAL-FLOW 249

is given by (r0 , c0 ) = (r + u(r, c), c + v(r, c)), where u(r, c) and v(r, c) denote the value of the row and column
components of the vector field image VectorField at the point (r, c).
The parameter Algorithm allows the selection of three different algorithms for computing the optical flow. All
three algorithms are implemented by using multigrid solvers to ensure an efficient solution of the underlying partial
differential equations.
For Algorithm = ’fdrig’, the method proposed by Brox, Bruhn, Papenberg, and Weickert is used. This approach
is flow-driven, robust, isotropic, and uses a gradient constancy term.
For Algorithm = ’ddraw’, a robust variant of the method proposed by Nagel and Enkelmann is used. This
approach is data-driven, robust, anisotropic, and uses warping (in contrast to the original approach).
For Algorithm = ’clg’ the combined local-global method proposed by Bruhn, Weickert, Feddern, Kohlberger,
and Schnörr is used.
In all three algorithms, the input images can first be smoothed by a Gaussian filter with a standard deviation of
SmoothingSigma (see DerivateGauss).
All three approaches are variational approaches that compute the optical flow as the minimizer of a suitable energy
functional. In general, the energy functionals have the following form:

E(w) = ED (w) + αES (w),

where w = (u, v, 1) is the optical flow vector field to be determined (with a time step of 1 in the third coordinate).
The image sequence is regarded as a continuous function f (x), where x = (r, c, t) and (r, c) denotes the position
and t the time. Furthermore, ED (w) denotes the data term, while ES (w) denotes the smoothness term, and α is a
regularization parameter that determines the smoothness of the solution. The regularization parameter α is passed
in FlowSmoothness. While the data term encodes assumptions about the constancy of the object features in
consecutive images, e.g., the constancy of the gray values or the constancy of the first spatial derivative of the
gray values, the smoothness term encodes assumptions about the (piecewise) smoothness of the solution, i.e., the
smoothness of the vector field to be determined.
The FDRIG algorithm is based on the minimization of an energy functional that contains the following assump-
tions:
Constancy of the gray values: It is assumed that corresponding pixels in consecutive images of an image sequence
have the same gray value, i.e., that f (r + u, c + v, t + 1) = f (r, c, t). This can be written more compactly as
f (x + w) = f (x) using vector notation.
Constancy of the spatial gray value derivatives: It is assumed that corresponding pixels in consecutive images of an
image sequence additionally have have the same spatial gray value derivatives, i.e, that ∇2 f (x + u, y + v, t + 1) =
∇2 f (x, y, t) also holds, where ∇2 f = (∂x f, ∂y f ). This can be written more compactly as ∇2 f (x+w) = ∇2 f (x).
In contrast to the gray value constancy, the gradient constancy has the advantage that it is invariant to additive global
illumination changes.
Large displacements: It is assumed that large displacements, i.e., displacements larger than one pixel, occur. Under
this assumption, it makes sense to consciously abstain from using the linearization of the constancy assumptions
in the model that is typically proposed in the literature.
Statistical robustness in the data term: To reduce the influence of outliers, i.e., points that violate the constancy
assumptions, they are penalized in a statistically robust manner, i.e., the customary
√ non-robust quadratical penal-
ization ΨD (s2 ) = s2 is replaced by a linear penalization via ΨD (s2 ) = s2 + 2 , where  = 0.001 is a fixed
regularization constant.
Preservation of discontinuities in the flow field I: The solution is assumed to be piecewise smooth. While the actual
2 2
smoothness is achieved by penalizing the first
2
√ derivatives of the flow |∇2 u| + |∇2 v| , the use of a statistically
2 2
robust (linear) penalty function ΨS (s ) = s +  with  = 0.001 provides the desired preservation of edges in
the movement in the flow field to be determined. This type of smoothness term is called flow-driven and isotropic.
Taking into account all of the above assumptions, the energy functional of the FDRIG algorithm can be written as

Z  
2 2
EFDRIG (w) = |f (x + w) − f (x)| + γ |∇2 f (x + w) − ∇2 f (x)| drdc
ΨD
| {z } | {z }
gray value constancy gradient constancy
Z  
+α ΨS |∇2 u(x)|2 + |∇2 v(x)|2 drdc
| {z }
smoothness assumption

HALCON 8.0.2
250 CHAPTER 3. FILTER

Here, α is the regularization parameter passed in FlowSmoothness, while γ is the gradient constancy weight
passed in GradientConstancy. These two parameters, which constitute the model parameters of the FDRIG
algorithm, are described in more detail below.
The DDRAW algorithm is based on the minimization of an energy functional that contains the following assump-
tions:
Constancy of the gray values: It is assumed that corresponding pixels in consecutive images of an image sequence
have the same gray value, i.e., that f (x + w) = f (x).
Large displacements: It is assumed that large displacements, i.e., displacements larger than one pixel, occur. Under
this assumption, it makes sense to consciously abstain from using the linearization of the constancy assumptions
in the model that is typically proposed in the literature.
Statistical robustness in the data term: To reduce the influence of outliers, i.e., points that violate the constancy
assumptions, they are penalized in a statistically robust manner, i.e., the customary
√ non-robust quadratical penal-
ization ΨD (s2 ) = s2 is replaced by a linear penalization via ΨD (s2 ) = s2 + 2 , where  = 0.001 is a fixed
regularization constant.
Preservation of discontinuities in the flow field II: The solution is assumed to be piecewise smooth. In contrast to
the FDRIG algorithm, which allows discontinuities everywhere, the DDRAW algorithm only allows discontinuities
at the edges in the original image. Here, the local smoothness is controlled in such a way that the flow field is sharp
across image edges, while it is smooth along the image edges. This type of smoothness term is called data-driven
and anisotropic.
All assumptions of the DDRAW algorithm can be combined into the following energy functional:

Z  
2
EDDRAW (w) = ΨD |f (x + w) − f (x)| drdc
| {z }
gray value constancy
Z
∇2 u(x)> PNE (∇2 f (x)) ∇2 u(x) + ∇2 v(x)> PNE (∇2 f (x)) ∇2 v(x) drdc ,


| {z }
smoothness assumption

where PNE (∇2 f (x)) is a normalized projection matrix orthogonal to ∇2 f (x), for which

fc2 (x) + 2S −fr (x)fc (x)


 
1
PNE (∇f (x)) = .
|∇2 f (x)|2 + 22S −fr (x)fc (x) fr2 (x) + 2S

holds. This matrix ensures that the smoothness of the flow field is only assumed along the image edges. In
contrast, no assumption is made with respect to the smoothness across the image edges, resulting in the fact
that discontinuities in the solution may occur across the image edges. In this respect, S = 0.001 serves as a
regularization parameter that prevents the projection matrix PNE (∇2 f (x)) from becoming singular. In contrast to
the FDRIG algorithm, there is only one model parameter for the DDRAW algorithm: the regularization parameter
α. As mentioned above, α is described in more detail below.
As for the two approaces described above, the CLG algorithm uses certain assumptions:
Constancy of the gray values: It is assumed that corresponding pixels in consecutive images of an image sequence
have the same gray value, i.e., that f (x + w) = f (x).
Small displacements: In contrast to the two approaches above, it is assumed that only small displacements can
occur, i.e., displacements in the order of a few pixels. This facilitates a linearization of the constancy assumptions
in the model, and leads to the approximation f (x) + ∇3 f (x)> w(x) = f (x), i.e., ∇3 f (x)> w(x) = 0 should
hold. Here, ∇3 f (x) denotes the gradient in the spatial as well as the temporal domain.
Local constancy of the solution: Furthermore, it is assumed that the flow field to be computed is locally constant.
This facilitates the integration of the image data in the data term over the respective neighborhood of each pixel.
This, in turn, increases the robustness of the algorithm against noise. Mathematically, this can be achieved by
reformulating the quadratic data term as (∇3 f (x)> w(x))2 = w(x)> ∇3 f (x)∇3 f (x)> w(x). By performing a
local Gaussian-weighted integration over a neighborhood specified by the ρ (passed in IntegrationSigma),
the following data term is obtained: w(x)> Gρ ∗(∇3 f (x)∇3 f (x)> ) w(x). Here, Gρ ∗. . . denotes a convolution of
the 3 × 3 matrix ∇3 f (x)∇3 f (x)> with a Gaussian filter with a standard deviation of ρ (see DerivateGauss).
General smoothness of the flow field: Finally, the solution is assumed to be smooth everywhere in the image. This
particular type of smoothness term is called homogeneous.

HALCON/COM Reference Manual, 2008-5-13


3.13. OPTICAL-FLOW 251

All of the above assumptions can be combined into the following energy functional:
Z Z
w(x)> Gρ ∗ (∇3 f (x)∇3 f (x)> ) w(x) drdc + α |∇2 u(x)|2 + |∇2 v(x)|2 drdc ,
 
ECLG (w) =
| {z } | {z }
gray value constancy smoothness assumption

The corresponding model parameters are the regularization parameter α as well as the integration scale ρ (passed
in IntegrationSigma), which determines the size of the neighborhood over which to integrate the data term.
These two parameters are described in more detail below.
To compute the optical flow vector field for two consecutive images of an image sequence with the FDRIG,
DDRAW, or CLG algorithm, the solution that best fulfills the assumptions of the respective algorithm must be
determined. From a mathematical point of view, this means that a minimization of the above energy functionals
should be performed. For the FDRIG and DDRAW algorithms, so called coarse-to-fine warping strategies play an
important role in this minimization, because they enable the calculation of large displacements. Thus, they are a
suitable means to handle the omission of the linearization of the constancy assumptions numerically in these two
approaches.
To calculate large displacements, coarse-to-fine warping strategies use two concepts that are closely interlocked:
The successive refinement of the problem (coarse-to-fine) and the successive compensation of the current image
pair by already computed displacements (warping). Algorithmically, such coarse-to-fine warping strategies can be
described as follows:
1. First, both images of the current image pair are zoomed down to a very coarse resolution level.
2. Then, the optical flow vector field is computed on this coarse resolution.
3. The vector field is required on the next resolution level: It is applied there to the second image of the image
sequence, i.e., the problem on the finer resolution level is compensated by the already computed optical flow field.
This step is also known as warping.
4. The modified problem (difference problem) is now solved on the finer resolution level, i.e., the optical flow
vector field is computed there.
5. The steps 3-4 are repeated until the finest resolution level is reached.
6. The final result is computed by adding up the vector fields from all resolution levels.
This incremental computation of the optical flow vector field has the following advantage: While the coarse-to-fine
strategy ensures that the displacements on the finest resolution level are very small, the warping strategy ensures
that the displacements remain small for the incremental displacements (optical flow vector fields of the difference
problems). Since small displacements can be computed much more accurately than larger displacements, the
accuracy of the results typically increases significantly by using such a coarse-to-fine warping strategy. However,
instead of having to solve a single correspondence problem, an entire hierarchy of these problems must now be
solved. For the CLG algorithm, such a coarse-to-fine warping strategy is unnecessary since the model already
assumes small displacements.
The maximum number of resolution levels (warping levels), the resolution ratio between two consecutive resolution
levels, as well as the finest resolution level can be specified for the FDRIG as well as the DDRAW algorithm.
Details can be found below.
The minimization of functionals is mathematically very closely related to the minimization of functions: Like
the fact that the zero crossing of the first derivative is a necessary condition for the minimum of a function, the
fulfillment of the so called Euler-Lagrange equations is a necessary condition for the minimizing function of a
functional (the minimizing function corresponds to the desired optical flow vector field in this case). The Euler-
Lagrange equations are partial differential equations. By discretizing these Euler-Lagrange equations using finite
differences, large sparse nonlinear equation systems result for the FDRIG and DDRAW algorithms. Because
coarse-to-fine warping strategies are used, such an equation system must be solved for each resolution level, i.e.,
for each warping level. For the CLG algorithm, a single sparse linear equation system must be solved.
To ensure that the above nonlinear equation systems can be solved efficiently, the FDRIG and DDRAW use bidi-
rectional multigrid methods. From a numerical point of view, these strategies are among the fastest methods for
solving large linear and nonlinear equation systems. In contrast to conventional nonhierarchical iterative methods,
e.g., the different linear and nonlinear Gauss-Seidel variants, the multigrid methods have the advantage that correc-
tions to the solution can be determined efficiently on coarser resolution levels. This, in turn, leads to a significantly
faster convergence. The basic idea of multigrid methods additionally consists of hierarchically computing these
correction steps, i.e., the computation of the error on a coarser resolution level itself uses the same strategy and

HALCON 8.0.2
252 CHAPTER 3. FILTER

efficiently computes its error (i.e., the error of the error) by correction steps on an even coarser resolution level.
Depending on whether one or two error correction steps are performed per cycle, a so called V or W cycle is
obtained. The corresponding strategies for stepping through the resolution hierarchy are as follows for two to four
resolution levels:

Bidirectional multigrid algorithm

Fine
V-Cycles W-Cycles
1 u u u u u u u u u u u u
AAs A s s As s AAs A s s s As s s
2 A  A

A A  A

s As s As A
s As s s As s s
 A 
3 A
AAs AAsAA
s AsAAs
4

Coarse

Here, iterations on the original problem are denoted by large markers, while small markers denote iterations on
error correction problems.
Algorithmically, a correction cycle can be described as follows:
1. In the first step, several (few) iterations using an interative linear or nonlinear basic solver are performed (e.g.,
a variant of the Gauss-Seidel solver). This step is called pre-relaxation step.
2. In the second step, the current error is computed to correct the current solution (the solution after step 1).
For efficiency reasons, the error is calculated on a coarser resolution level. This step, which can be performed
iteratively several times, is called coarse grid correction step.
3. In a final step, again several (few) iterations using the interative linear or nonlinear basic solver of step 1 are
performed. This step is called post-relaxation step.
In addition, the solution can be initialized in a hierarchical manner. Starting from a very coarse variant of the
original (non)linear equation system, the solution is successively refined. To do so, interpolated solutions of
coarser variants of the equation system are used as the initialization of the next finer variant. On each resolution
level itself, the V or W cycles described above are used to efficiently solve the (non)linear equation system on that
resolution level. The corresponding multigrid methods are called full multigrid methods in the literature. The full
multigrid algorithm can be visualized as follows:

Full multigrid algorithm

Fine 4→3 3→2 2→1


i w1 w2 i w1 w2 i w1 w2
1 u u u
2 u u uA s s sA s s s
A  A
u u uA s s sA s s s As s s As s s As s s As s s
A A 
3 A A
4 u u u As A

A A s s A
AA s s A
AA s s A
AAA s s A
AA s AAs As
A As As
A

Coarse

This example represents a full multigrid algorithm that uses two W correction cycles per resolution level of the
hierarchical initialization. The interpolation steps of the solution from one resolution level to the next arew denoted
by i and the two W correction cycles by w1 and w2 . Iterations on the original problem are denoted by large markers,
while small markers denote iterations on error correction problems.
In the multigrid implementation of the FDRIG, DDRAW, and CLG algorithm, the following parameters can be
set: whether a hierarchical initialization is performed; the number of coarse grid correction steps; the maximum
number of correction levels (resolution levels); the number of pre-relaxation steps; the number of post-relaxation
steps. These parameters are described in more detail below.
The basic solver for the FDRIG algorithm is a point-coupled fixed-point variant of the linear Gauss-Seidel algo-
rithm. The basic solver for the DDRAW algorithm is an alternating line-coupled fixed-point variant of the same
type. The number of fixed-point steps can be specified for both algorithms with a further parameter. The basic
solver for the CLG algorithm is a point-coupled linear Gauss-Seidel algorithm. The transfer of the data between
the different resolution levels is performed by area-based interpolation and area-based averaging, respectively.

HALCON/COM Reference Manual, 2008-5-13


3.13. OPTICAL-FLOW 253

After the algorithms have been described, the effects of the individual parameters are discussed in the following.
The input images, along with their domains (regions of interest) are passed in Image1 and Image2. The com-
putation of the optical flow vector field VectorField is performed on the smallest surrounding rectangle of the
intersection of the domains of Image1 and Image2. The domain of VectorField is the intersection of the
two domains. Hence, by specifying reduced domains for Image1 and Image2, the processing can be focused
and runtime can potentially be saved. It should be noted, however, that all methods compute a global solution of
the optical flow. In particular, it follows that the solution on a reduced domain need not (and cannot) be identical
to the resolution on the full domain restricted to the reduced domain.
SmoothingSigma specifies the standard deviation of the Gaussian kernel that is used to smooth both input
images. The larger the value of SmoothingSigma, the larger the low-pass effect of the Gaussian kernel, i.e., the
smoother the preprocessed image. Usually, SmoothingSigma = 0.8 is a suitable choice. However, other values
in the interval [0, 2] are also possible. Larger standard deviations should only be considered if the input images are
very noisy. It should be noted that larger values of SmoothingSigma lead to slightly longer execution times.
IntegrationSigma specifies the standard deviation ρ of the Gaussian kernel Gρ that is used for the local
integration of the neighborhood information of the data term. This parameter is used only in the CLG algorithm and
has no effect on the other two algorithms. Usually, IntegrationSigma = 1.0 is a suitable choice. However,
other values in the interval [0, 3] are also possible. Larger standard deviations should only be considered if the
input images are very noisy. It should be noted that larger values of IntegrationSigma lead to slightly longer
execution times.
FlowSmoothness specifies the weight α of the smoothness term with respect to the data term. The larger the
value of FlowSmoothness, the smoother the computed optical flow field. It should be noted that choosing
FlowSmoothness too small can lead to unusable results, even though statistically robust penalty functions are
used, in particular if the warping strategy needs to predict too much information outside of the image. For byte
images with a gray value range of [0, 255], values of FlowSmoothness around 20 for the flow-driven FDRIG
algorithm and around 1000 for the data-driven DDRAW algorithm and the homogeneous CLG algorithm typically
yield good results.
GradientConstancy specifies the weight γ of the gradient constancy with respect to the gray value constancy.
This parameter is used only in the FDRIG algorithm. For the other two algorithms, it does not influence the results.
For byte images with a gray value range of [0, 255], a value of GradientConstancy = 5 is typically a good
choice, since then both constancy assumptions are used to the same extent. For large changes in illumination, how-
ever, significantly larger values of GradientConstancy may be necessary to achieve good results. It should be
noted that for large values of the gradient constancy weight the smoothness parameter FlowSmoothness must
also be chosen larger.
The parameters of the multigrid solver and for the coarse-to-fine warping strategy can be specified with the
generic parameters MGParamName and MGParamValue. Usually, it suffices to use one of the four default
parameter sets via MGParamName = ’default_parameters’ and MGParamValue = ’very_accurate’, ’accurate’,
’fast_accurate’, or ’fast’. The default parameter sets are described below. If the parameters should be speci-
fied individually, MGParamName and MGParamValue must be set to tuples of the same length. The values
corresponding to the parameters specified in MGParamName must be specified at the corresponding position in
MGParamValue.
MGParamName = ’warp_zoom_factor’ can be used to specify the resolution ratio between two consecutive warp-
ing levels in the coarse-to-fine warping hierarchy. ’warp_zoom_factor’ must be selected from the open interval
(0, 1). For performance reasons, ’warp_zoom_factor’ is typically set to 0.5, i.e., the number of pixels is halved in
each direction for each coarser warping level. This leads to an increase of 33% in the calculations that need to be
performed with respect to an algorithm that does not use warping. Values for ’warp_zoom_factor’ close to 1 can
lead to slightly better results. However, they require a disproportionately larger computation time, e.g., 426% for
’warp_zoom_factor’ = 0.9.
MGParamName = ’warp_levels’ can be used to restrict the warping hierarchy to a maximum number of levels.
For ’warp_levels’ = 0, the largest possible number of levels is used. If the image size does not allow to use
the specified number of levels (taking the resolution ratio ’warp_zoom_factor’ into account), the largest possible
number of levels is used. Usually, ’warp_levels’ should be set to 0.
MGParamName = ’warp_last_level’ can be used to specify the number of warping levels for which the flow
increment should no longer be computed. Usually, ’warp_last_level’ is set to 1 or 2, i.e., a flow increment is
computed for each warping level, or the finest warping level is skipped in the computation. Since in the latter case
the computation is performed on an image of half the resolution of the original image, the gained computation
time can be used to compute a more accurate solution, e.g., by using a full multigrid algorithm with additional
iterations. The more accurate solution is then interpolated to the full resolution.

HALCON 8.0.2
254 CHAPTER 3. FILTER

The three parameters that specify the coarse-to-fine warping strategy are only used in the FDRIG and DDRAW
algorithms. They are ignored for the CLG algorithm.
MGParamName = ’mg_solver’ can be used to specify the general multigrid strategy for solving the (non)linear
equation system (in each warping level). For ’mg_solver’ = ’multigrid’, a normal multigrid algorithm (without
coarse-to-fine initialization) is used, while for ’mg_solver’ = ’full_multigrid’ a full multigrid algorithm (with
coarse-to-fine initialization) is used. Since a resolution reduction of 0.5 is used between two consecutive levels of
the coarse-to-fine initialization (in contrast to the resolution reduction in the warping strategy, this value is hard-
coded into the algorithm), the use of a full multigrid algorithm results in an increase of the computation time by
approximately 33% with respect to the normal multigrid algorithm. Using ’mg_solver’ to ’full_multigrid’ typically
yields numerically more accurate results than ’mg_solver’ = ’multigrid’.
MGParamName = ’mg_cycle_type’ can be used to specify whether a V or W correction cycle is used per multigrid
level. Since a resolution reduction of 0.5 is used between two consecutive levels of the respective correction cycle,
using a W cycle instead of a V cycle increases the computation time by approximately 50%. Using ’mg_cycle_type’
= ’w’ typically yields numerically more accurate results than ’mg_cycle_type’ = ’v’.
MGParamName = ’mg_levels’ can be used to restrict the multigrid hierarchy for the coarse-to-fine initialization
as well as for the actual V or W correction cycles. For ’mg_levels’ = 0, the largest possible number of levels is
used. If the image size does not allow to use the specified number of levels, the largest possible number of levels
is used. Usually, ’mg_levels’ should be set to 0.
MGParamName = ’mg_cycles’ can be used to specify the total number of V or W correction cycles that are being
performed. If a full multigrid algorithm is used, ’mg_cycles’ refers to each level of the coarse-to-fine initialization.
Usually, one or two cycles are sufficient to yield a sufficiently accurate solution of the equation system. Typically,
the larger ’mg_cycles’, the more accurate the numerical results. This parameter enters almost linearly into the
computation time, i.e., doubling the number of cycles leads approximately to twice the computation time.
MGParamName = ’mg_pre_relax’ can be used to specify the number of iterations that are performed on each
level of the V or W correction cycles using the iterative basic solver before the actual error correction is performed.
Usually, one or two pre-relaxation steps are sufficient. Typically, the larger ’mg_pre_relax’, the more accurate the
numerical results.
MGParamName = ’mg_post_relax’ can be used to specify the number of iterations that are performed on each
level of the V or W correction cycles using the iterative basic solver after the actual error correction is performed.
Usually, one or two post-relaxation steps are sufficient. Typically, the larger ’mg_post_relax’, the more accurate
the numerical results.
Like when increasing the number of correction cycles, increasing the number of pre- and post-relaxation steps
increases the computation time asymptotically linearly. However, no additional restriction and prolongation oper-
ations (zooming down and up of the error correction images) are performed. Consequently, a moderate increase in
the number of relaxation steps only leads to a slight increase in the computation times.
MGParamName = ’mg_inner_iter’ can be used to specify the number of iterations to solve the linear equation
systems in each fixed-point iteration of the nonlinear basic solver. Usually, one iteration is sufficient to achieve a
sufficient convergence speed of the multigrid algorithm. The increase in computation time is slightly smaller than
for the increase in the relaxation steps. This parameter only influences the FDRIG and DDRAW algorithms since
for the CLG algorithm no nonlinear equation system needs to be solved.
As described above, usually it is sufficient to use one of the default parameter sets for the parameters described
above by using MGParamName = ’default_parameters’ and MGParamValue = ’very_accurate’, ’accurate’,
’fast_accurate’, or ’fast’. If necessary, individual parameters can be modified after the default parameter set has
been chosen by specifying a subset of the above parameters and corresponding values after ’default_parameters’ in
MGParamName and MGParamValue (e.g., MGParamName = [’default_parameters’,’warp_zoom_factor’] and
MGParamValue = [’accurate’,0.6]).
The default parameter sets use the following values for the above parameters:
’default_parameters’ = ’very_accurate’: ’warp_zoom_factor’ = 0.5, ’warp_levels’ = 0, ’warp_last_level’ = 1,
’mg_solver’ = ’full_multigrid’, ’mg_cycle_type’ = ’w’, ’mg_levels’ = 0, ’mg_cycles’ = 1, ’mg_pre_relax’ = 2,
’mg_post_relax’ = 2, ’mg_inner_iter’ = 1.
’default_parameters’ = ’accurate’: ’warp_zoom_factor’ = 0.5, ’warp_levels’ = 0, ’warp_last_level’ = 1,
’mg_solver’ = ’multigrid’, ’mg_cycle_type’ = ’v’, ’mg_levels’ = 0, ’mg_cycles’ = 1, ’mg_pre_relax’ = 1,
’mg_post_relax’ = 1, ’mg_inner_iter’ = 1.
’default_parameters’ = ’fast_accurate’: ’warp_zoom_factor’ = 0.5, ’warp_levels’ = 0, ’warp_last_level’ = 2,
’mg_solver’ = ’full_multigrid’, ’mg_cycle_type’ = ’w’, ’mg_levels’ = 0, ’mg_cycles’ = 1, ’mg_pre_relax’ = 2,
’mg_post_relax’ = 2, ’mg_inner_iter’ = 1.

HALCON/COM Reference Manual, 2008-5-13


3.13. OPTICAL-FLOW 255

’default_parameters’ = ’fast’: ’warp_zoom_factor’ = 0.5, ’warp_levels’ = 0, ’warp_last_level’ = 2, ’mg_solver’


= ’multigrid’, ’mg_cycle_type’ = ’v’, ’mg_levels’ = 0, ’mg_cycles’ = 1, ’mg_pre_relax’ = 1, ’mg_post_relax’ =
1, ’mg_inner_iter’ = 1.
It should be noted that for the CLG algorithm the two modes ’fast_accurate’ and ’fast’ are identical to the modes
’very_accurate’ and ’accurate’ since the CLG algorithm does not use a coarse-to-fine warping strategy.
Parameter
. Image1 (input iconic) . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte, uint2, real )
Input image 1.
. Image2 (input iconic) . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte, uint2, real )
Input image 2.
. VectorField (output iconic) . . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX ( vector_field )
Optical flow.
. Algorithm (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Algorithm for computing the optical flow.
Default Value : ’fdrig’
List of values : Algorithm ∈ {’fdrig’, ’ddraw’, ’clg’}
. SmoothingSigma (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Standard deviation for initial Gaussian smoothing.
Default Value : 0.8
Suggested values : SmoothingSigma ∈ {0.0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.8, 2.0}
Restriction : (SmoothingSigma ≥ 0.0)
. IntegrationSigma (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Standard deviation of the integration filter.
Default Value : 1.0
Suggested values : IntegrationSigma ∈ {0.0, 0.2, 0.4, 0.6, 0.8, 1.0, 1.2, 1.4, 1.6, 1.8, 2.0, 2.2, 2.4, 2.6,
2.8, 3.0}
Restriction : (IntegrationSigma ≥ 0.0)
. FlowSmoothness (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Weight of the smoothing term relative to the data term.
Default Value : 20
Suggested values : FlowSmoothness ∈ {10, 20, 30, 50, 70, 100, 200, 300, 500, 700, 1000, 1500, 2000}
Restriction : (F lowSmoothness ≥ 0.0)
. GradientConstancy (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Weight of the gradient constancy relative to the gray value constancy.
Default Value : 5
Suggested values : GradientConstancy ∈ {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 30, 40, 50, 70, 100}
Restriction : (GradientConstancy ≥ 0.0)
. MGParamName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . attribute.name(-array) ; VARIANT ( string )
Parameter name(s) for the multigrid algorithm.
Default Value : ’default_parameters’
List of values : MGParamName ∈ {’default_parameters’, ’mg_solver’, ’mg_cycle_type’, ’mg_levels’,
’mg_cycles’, ’mg_pre_relax’, ’mg_post_relax’, ’mg_inner_iter’, ’warp_levels’, ’warp_zoom_factor’,
’warp_last_level’}
. MGParamValue (input control) . . . . . . . . . . . . . . . attribute.value(-array) ; VARIANT ( string, real, integer )
Parameter value(s) for the multigrid algorithm.
Default Value : ’accurate’
Suggested values : MGParamValue ∈ {’very_accurate’, ’accurate’, ’fast_accurate’, ’fast’, ’multigrid’,
’full_multigrid’, ’v’, ’w’, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7,
0.8, 0.9}
Example

grab_image (Image1, FGHandle)


while (true)
grab_image (Image2, FGHandle)
optical_flow_mg (Image1, Image2, VectorField, ’fdrig’, 0.8, 1, 10,
5, ’default_parameters’, ’accurate’)

HALCON 8.0.2
256 CHAPTER 3. FILTER

threshold (VectorField, Region, 1, 10000)


copy_obj (Image2, Image1, 1, 1)
endwhile

Result
If the parameter values are correct, the operator OpticalFlowMg returns the value TRUE. If the input is empty
(no input images are available) the behavior can be set via SetSystem(’noObjectResult’,<Result>).
If necessary, an exception handling is raised.
Parallelization Information
OpticalFlowMg is reentrant and automatically parallelized (on tuple level).
Possible Successors
Threshold, VectorFieldLength
See also
UnwarpImageVectorField
References
T. Brox, A. Bruhn, N. Papenberg, and J. Weickert: High accuracy optic flow estimation based on a theory for
warping. In T. Pajdla and J. Matas, editors, Computer Vision - ECCV 2004, volume 3024 of Lecture Notes in
Computer Science, pages 25–36. Springer, Berlin, 2004.
A. Bruhn, J. Weickert, C. Feddern, T. Kohlberger, and C. Schnörr: Variational optical flow computation in real-
time. IEEE Transactions on Image Processing, 14(5):608-615, May 2005.
H.-H. Nagel and W. Enkelmann: An investigation of smoothness constraints for the estimation of displacement
vector fields from image sequences. IEEE Transactions on Pattern Analysis and Machine Intelligence, 8(5):565-
593, September 1986.
Ulrich Trottenberg, Cornelis Oosterlee, Anton Schüller: Multigrid. Academic Press, Inc., San Diego, 2000.
Module
Foundation

[out] HImageX ImageUnwarped HImageX.UnwarpImageVectorField


([in] HImageX VectorField )
void HOperatorSetX.UnwarpImageVectorField ([in] IHObjectX Image,
[in] IHObjectX VectorField, [out] HUntypedObjectX ImageUnwarped )

Unwarp an image using a vector field.


UnwarpImageVectorField unwarps the image Image using the vector field VectorField and returns the
unwarped image in ImageUnwarped. The vector field is typically determined with OpticalFlowMg. Hence,
UnwarpImageVectorField can be used to unwarp the second input image of OpticalFlowMg to the first
input image. It should be noted that because of the above sematics the vector field image represents an inverse
transformation from the destination image of the vector field to the source image.
Parameter
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte, uint2, real )
Input image
. VectorField (input iconic) . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( vector_field )
Input vector field
. ImageUnwarped (output iconic) . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, uint2, real )
Unwarped image.
Example

optical_flow_mg (Image1, Image2, VectorField, ’fdrig’, 0.8, 1, 20,


5, ’default_parameters’, ’accurate’)
unwarp_image_vector_field (Image2, VectorField, ImageUnwarped)

HALCON/COM Reference Manual, 2008-5-13


3.14. POINTS 257

Result
If the parameter values are correct, the operator UnwarpImageVectorField returns the value TRUE.
If the input is empty (no input images are available) the behavior can be set via SetSystem
(’noObjectResult’,<Result>). If necessary, an exception handling is raised.
Parallelization Information
UnwarpImageVectorField is reentrant and automatically parallelized (on domain level, tuple level).
Possible Predecessors
OpticalFlowMg
Module
Foundation

HImageX.VectorFieldLength ([in] String Mode )


[out] HImageX Length
void HOperatorSetX.VectorFieldLength ([in] IHObjectX VectorField,
[out] HUntypedObjectX Length, [in] VARIANT Mode )

Compute the length of the vectors of a vector field.


VectorFieldLength compute the length of the vectors of the vector field VectorField and returns them
in Length. The parameter Mode can be used to specify how the lengths are computed. For Mode = ’length’,
the Euclidean length of the vectors is computed. For Mode = ’squared_length’, the square of the length of the
vectors is computed. This avoids having to compute a square root internally, which is a costly operation on many
processors, and hence saves runtime on these processors.
Parameter
. VectorField (input iconic) . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( vector_field )
Input vector field
. Length (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX ( real )
Length of the vectors of the vector field.
. Mode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Mode for computing the length of the vectors.
Default Value : ’length’
List of values : Mode ∈ {’length’, ’squared_length’}
Result
If the parameter values are correct, the operator VectorFieldLength returns the value TRUE.
If the input is empty (no input images are available) the behavior can be set via SetSystem
(’noObjectResult’,<Result>). If necessary, an exception handling is raised.
Parallelization Information
VectorFieldLength is reentrant and automatically parallelized (on domain level, tuple level).
Possible Predecessors
OpticalFlowMg
Possible Successors
Threshold
Module
Foundation

3.14 Points
[out] HImageX ImageCorner HImageX.CornerResponse ([in] long Size,
[in] double Weight )
void HOperatorSetX.CornerResponse ([in] IHObjectX Image,
[out] HUntypedObjectX ImageCorner, [in] VARIANT Size, [in] VARIANT Weight )

Searching corners in images.

HALCON 8.0.2
258 CHAPTER 3. FILTER

The operator CornerResponse extracts gray value corners in an image. The formula for the calculation of the
response is:

2
R(x, y) = A(x, y) · B(x, y) − C 2 (x, y) − W eight · (A(x, y) + B(x, y))
A(x, y) = W (u, v) ∗ (∇x I(x, y))2
B(x, y) = W (u, v) ∗ (∇y I(x, y))2
C(c, y) = W (u, v) ∗ (∇x I(x, y)∇y I(x, y))

where I is the input image and R the output image of the filter. The operator GaussImage is used for smoothing
(W ), the operator SobelAmp is used for calculating the derivative (∇).
The corner response function is invariant with regard to rotation. In order to achieve a suitable dependency of the
function R(x, y) on the local gradient, the parameter Weight must be set to 0.04. With this, only gray value
corners will return positive values for R(x, y), while straight edges will receive negative values. The output image
type is identical to the input image type. Therefore, the negative output values are set to 0 if byte images are
used as input images. If this is not desired, the input image should be converted into a real or int2 image with
ConvertImageType.
Parameter

. Image (input iconic) . . . . . . . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, int2, real )


Input image.
. ImageCorner (output iconic) . . . . . . multichannel-image-array ; HImageX / HUntypedObjectX ( byte,
int2, real )
Result of the filtering.
Number of elements : (ImageCorner = Image)
. Size (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Desired filtersize of the graymask.
Default Value : 3
List of values : Size ∈ {3, 5, 7, 9, 11}
. Weight (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Weighting.
Default Value : 0.04
Typical range of values : 0.0 ≤ Weight ≤ 0.0
Minimum Increment : 0.001
Recommended Increment : 0.01
Parallelization Information
CornerResponse is reentrant and automatically parallelized (on tuple level, channel level, domain level).
Possible Successors
LocalMax, Threshold
See also
GaussImage, SobelAmp, ConvertImageType
References
C.G. Harris, M.J. Stephens, “A combined corner and edge detector”’; Proc. of the 4th Alvey Vision Conference;
August 1988; pp. 147-152.
H. Breit, “Bestimmung der Kameraeigenbewegung und Gewinnung von Tiefendaten aus monokularen Bildfol-
gen”; Diplomarbeit am Lehrstuhl f"ur Nachrichtentechnik der TU M"unchen; 30. September 1990.
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


3.14. POINTS 259

[out] HImageX DotImage HImageX.DotsImage ([in] long Diameter,


[in] String FilterType, [in] long PixelShift )
void HOperatorSetX.DotsImage ([in] IHObjectX Image,
[out] HUntypedObjectX DotImage, [in] VARIANT Diameter,
[in] VARIANT FilterType, [in] VARIANT PixelShift )

Enhance circular dots in an image.


DotsImage enhances circular dots of diameter Diameter in the input image Image. Hence, DotsImage is
especially suited for the segmentation of dot prints, e.g., in OCR applications. The enhancement is performed by
using matched filters with filter masks that are tuned for a particular dot size. For example, for Diameter = 5
the filter mask is given by:
 
−21 −21 −21

 −21 16 16 16 −21 

 −21 16 16 16 16 16 −21 
1  −21

16 16 16 16 16 −21 
336 
 −21

 16 16 16 16 16 −21 

 −21 16 16 16 −21 
−21 −21 −21

The parameter FilterType selects whether dark, light, or all dots in the image should be enhanced. The
PixelShift can be used either to increase the contrast of the output image (PixelShift > 0) or to dampen
the values in extremly bright areas that would be cut off otherwise (PixelShift = −1).
Parameter

. Image (input iconic) . . . . . . . . . . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, uint2 )


Input image.
. DotImage (output iconic) . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX ( byte, uint2 )
Output image.
. Diameter (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Diameter of the dots to be enhanced.
Default Value : 5
List of values : Diameter ∈ {3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23}
. FilterType (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Enhance dark, light, or all dots.
Default Value : ’light’
List of values : FilterType ∈ {’dark’, ’light’, ’all’}
. PixelShift (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Shift of the filter response.
Default Value : 0
List of values : PixelShift ∈ {-1, 0, 1, 2}
Parallelization Information
DotsImage is reentrant and automatically parallelized (on tuple level, channel level, domain level).
Possible Successors
Threshold
Alternatives
Laplace, LaplaceOfGauss, DiffOfGauss, DerivateGauss, ConvolImage
Module
Foundation

HALCON 8.0.2
260 CHAPTER 3. FILTER

[out] VARIANT RowJunctions HImageX.PointsFoerstner


([in] VARIANT SigmaGrad, [in] VARIANT SigmaInt, [in] VARIANT SigmaPoints,
[in] VARIANT ThreshInhom, [in] double ThreshShape, [in] String Smoothing,
[in] String EliminateDoublets, [out] VARIANT ColJunctions,
[out] VARIANT CoRRJunctions, [out] VARIANT CoRCJunctions,
[out] VARIANT CoCCJunctions, [out] VARIANT RowArea, [out] VARIANT ColArea,
[out] VARIANT CoRRArea, [out] VARIANT CoRCArea, [out] VARIANT CoCCArea )
void HOperatorSetX.PointsFoerstner ([in] IHObjectX Image,
[in] VARIANT SigmaGrad, [in] VARIANT SigmaInt, [in] VARIANT SigmaPoints,
[in] VARIANT ThreshInhom, [in] VARIANT ThreshShape, [in] VARIANT Smoothing,
[in] VARIANT EliminateDoublets, [out] VARIANT RowJunctions,
[out] VARIANT ColJunctions, [out] VARIANT CoRRJunctions,
[out] VARIANT CoRCJunctions, [out] VARIANT CoCCJunctions,
[out] VARIANT RowArea, [out] VARIANT ColArea, [out] VARIANT CoRRArea,
[out] VARIANT CoRCArea, [out] VARIANT CoCCArea )

Detect points of interest using the Förstner operator.


PointsFoerstner extracts significant points from an image. Significant points are points that differ from their
neighborhood, i.e., points where the image function changes in two dimensions. These changes occur on the one
hand at the intersection of image edges (called junction points), and on the other hand at places where color or
brightness differs from the surrounding neighborhood (called area points).
The point extraction takes place in two steps: In the first step the point regions, i.e., the inhomogeneous, isotropic
regions, are extracted from the image. To do so, the smoothed matrix
 n
X n
X 
2
 Ix,c Ix,c Iy,c 
 c=1 c=1
M =S∗ X

n Xn 
 2 
Ix,c Iy,c Iy,c
c=1 c=1

is calculated, where Ix,c and Iy,c are the first derivatives of each image channel and S stands for a smoothing.
If Smoothing is ’gauss’, the derivatives are computed with Gaussian derivatives of size SigmaGrad and the
smoothing is performed by a Gaussian of size SigmaInt. If Smoothing is ’mean’, the derivatives are computed
with a 3 × 3 Sobel filter (and hence SigmaGrad is ignored) and the smoothing is performed by a SigmaInt ×
SigmaInt mean filter. Then

inhomogeneity = TraceM

is the degree of inhomogeneity in the image and

DetM
isotropy = 4 ·
(TraceM )2

is the degree of the isotropy of the texture in the image. Image points that have an inhomogeneity greater or equal to
ThreshInhom and at the same time an isotropy greater or equal to ThreshShape are subsequently examined
further.
In the second step, two optimization functions are calculated for the resulting points. Essentially, these optimiza-
tion functions average for each point the distances to the edge directions (for junction points) and the gradient
directions (for area points) within an observation window around the point. If Smoothing is ’gauss’, the aver-
aging is performed by a Gaussian of size SigmaPoints, if Smoothing is ’mean’, the averaging is performed
by a SigmaPoints × SigmaPoints mean filter. The local minima of the optimization functions determine
the extracted points. Their subpixel precise position is returned in (RowJunctions, ColJunctions) and
(RowArea, ColArea).
In addition to their position, for each extracted point the elements CoRRJunctions, CoRCJunctions, and
CoCCJunctions (and CoRRArea, CoRCArea, and CoCCArea, respectively) of the corresponding covariance
matrix are returned. This matrix facilitates conclusions about the precision of the calculated point position. To
obtain the actual values, it is necessary to estimate the amount of noise in the input image and to multiply all

HALCON/COM Reference Manual, 2008-5-13


3.14. POINTS 261

components of the covariance matrix with the variance of the noise. (To estimate the amount of noise, apply
Intensity to homgeneous image regions or PlaneDeviation to image regions, where the gray values form
a plane. In both cases the amount of noise is returned in the parameter Deviation.) This is illustrated by the example
program
%HALCONROOT%\examples\hdevelop\Filter\Points\ points_foerstner_ellipses.dev .
It lies in the nature of this operator that corners often result in two distinct points: One junction point, where the
edges of the corner actually meet, and one area point inside the corner. Such doublets will be eliminated automati-
cally, if EliminateDoublets is ’true’. To do so, each pair of one junction point and one area point is examined.
If the points lie within each others’ observation window of the optimization function, for both points the precision
of the point position is calculated and the point with the lower precision is rejected. If EliminateDoublets is
’false’, every detected point is returned.
Attention
Note that only odd values for SigmaInt and SigmaPoints are allowed, if Smoothing is ’mean’. Even
values automatically will be replaced by the next larger odd value.
Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . (multichannel-)image ; HImageX / IHObjectX ( byte, uint2, real )


Input image.
. SigmaGrad (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Amount of smoothing used for the calculation of the gradient. If Smoothing is ’mean’, SigmaGrad is
ignored.
Default Value : 1.0
Suggested values : SigmaGrad ∈ {0.7, 0.8, 0.9, 1.0, 1.2, 1.5, 2.0, 3.0}
Typical range of values : 0.7 ≤ SigmaGrad ≤ 0.7
Recommended Increment : 0.1
Restriction : (SigmaGrad > 0.0)
. SigmaInt (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Amount of smoothing used for the integration of the gradients.
Default Value : 2.0
Suggested values : SigmaInt ∈ {0.7, 0.8, 0.9, 1.0, 1.2, 1.5, 2.0, 3.0}
Typical range of values : 0.7 ≤ SigmaInt ≤ 0.7
Recommended Increment : 0.1
Restriction : (SigmaInt > 0.0)
. SigmaPoints (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Amount of smoothing used in the optimization functions.
Default Value : 3.0
Suggested values : SigmaPoints ∈ {0.7, 0.8, 0.9, 1.0, 1.2, 1.5, 2.0, 3.0}
Typical range of values : 0.7 ≤ SigmaPoints ≤ 0.7
Recommended Increment : 0.1
Restriction : ((SigmaP oints ≥ SigmaInt) ∧ (SigmaP oints > 0.6))
. ThreshInhom (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Threshold for the segmentation of inhomogeneous image areas.
Default Value : 200
Suggested values : ThreshInhom ∈ {50, 100, 200, 500, 1000}
Restriction : (T hreshInhom ≥ 0.0)
. ThreshShape (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Threshold for the segmentation of point areas.
Default Value : 0.3
Suggested values : ThreshShape ∈ {0.1, 0.2, 0.3, 0.4, 0.5, 0.7}
Typical range of values : 0.01 ≤ ThreshShape ≤ 0.01
Minimum Increment : 0.01
Recommended Increment : 0.1
Restriction : ((0.0 ≤ T hreshShape) ∧ (T hreshShape ≤ 1.0))
. Smoothing (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Used smoothing method.
Default Value : ’gauss’
List of values : Smoothing ∈ {’gauss’, ’mean’}

HALCON 8.0.2
262 CHAPTER 3. FILTER

. EliminateDoublets (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT


Elimination of multiply detected points.
Default Value : ’false’
List of values : EliminateDoublets ∈ {’false’, ’true’}
. RowJunctions (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; VARIANT ( real )
Row coordinates of the detected junction points.
. ColJunctions (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; VARIANT ( real )
Column coordinates of the detected junction points.
. CoRRJunctions (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real )
Row part of the covariance matrix of the detected junction points.
. CoRCJunctions (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real )
Mixed part of the covariance matrix of the detected junction points.
. CoCCJunctions (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real )
Column part of the covariance matrix of the detected junction points.
. RowArea (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; VARIANT ( real )
Row coordinates of the detected area points.
. ColArea (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; VARIANT ( real )
Column coordinates of the detected area points.
. CoRRArea (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real )
Row part of the covariance matrix of the detected area points.
. CoRCArea (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real )
Mixed part of the covariance matrix of the detected area points.
. CoCCArea (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real )
Column part of the covariance matrix of the detected area points.
Result
PointsFoerstner returns TRUE if all parameters are correct and no error occurs during the execution. If the
input is empty the behavior can be set via SetSystem(’noObjectResult’,<Result>). If necessary, an
exception handling is raised.
Parallelization Information
PointsFoerstner is reentrant and processed without parallelization.
Possible Successors
GenCrossContourXld, DispCross
Alternatives
PointsHarris
References
W. Förstner, E. Gülch: “A Fast Operator for Detection and Precise Location of Distinct Points, Corners and Cir-
cular features”. In Proceedings of the Intercommission Conference on Fast Processing of Photogrametric Data,
Interlaken, pp. 281-305, 1987.
W. Förstner: “Statistische Verfahren für die automatische Bildanalyse und ihre Bewertung bei der Objekterkennung
und -vermessung”. Volume 370, Series C, Deutsche Geodätische Kommission, München, 1991.
W. Förstner: “A Framework for Low Level Feature Extraction”. European Conference on Computer Vision, LNCS
802, pp. 383-394, Springer Verlag, 1994.
C. Fuchs: “Extraktion polymorpher Bildstrukturen und ihre topologische und geometrische Gruppierung”. Volume
502, Series C, Deutsche Geodätische Kommission, München, 1998.
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


3.14. POINTS 263

[out] VARIANT Row HImageX.PointsHarris ([in] double SigmaGrad,


[in] double SigmaSmooth, [in] double Alpha, [in] VARIANT Threshold,
[out] VARIANT Col )
void HOperatorSetX.PointsHarris ([in] IHObjectX Image,
[in] VARIANT SigmaGrad, [in] VARIANT SigmaSmooth, [in] VARIANT Alpha,
[in] VARIANT Threshold, [out] VARIANT Row, [out] VARIANT Col )

Detect points of interest using the Harris operator.


PointsHarris extracts points of interest from an image. The Harris operator is based upon the smoothed matrix
 n
X n
X 
2
 Ix,c Ix,c Iy,c 
 c=1 c=1
M = Gσ ∗  X  ,

n Xn
 2 
Ix,c Iy,c Iy,c
c=1 c=1

where Gσ stands for a Gaussian smoothing of size SigmaSmooth and Ix,c and Iy,c are the first derivatives of
each image channel, computed with Gaussian derivatives of size SigmaGrad. The resulting points are the positive
local extrema of

DetM − Alpha ∗ (TraceM )2 .

If necessary, they can be restricted to points with a minimum filter response of Threshold. The coordinates of
the points are calculated with subpixel accuracy.
Parameter
. Image (input iconic) . . . . . . . . . . . . . . . . . . (multichannel-)image ; HImageX / IHObjectX ( byte, uint2, real )
Input image.
. SigmaGrad (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Amount of smoothing used for the calculation of the gradient.
Default Value : 0.7
Suggested values : SigmaGrad ∈ {0.7, 0.8, 0.9, 1.0, 1.2, 1.5, 2.0, 3.0}
Typical range of values : 0.7 ≤ SigmaGrad ≤ 0.7
Recommended Increment : 0.1
Restriction : (SigmaGrad > 0.0)
. SigmaSmooth (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Amount of smoothing used for the integration of the gradients.
Default Value : 2.0
Suggested values : SigmaSmooth ∈ {0.7, 0.8, 0.9, 1.0, 1.2, 1.5, 2.0, 3.0}
Typical range of values : 0.7 ≤ SigmaSmooth ≤ 0.7
Recommended Increment : 0.1
Restriction : (SigmaSmooth > 0.0)
. Alpha (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Weight of the squared trace of the squared gradient matrix.
Default Value : 0.04
Suggested values : Alpha ∈ {0.02, 0.03, 0.04, 0.05, 0.06, 0.07, 0.08}
Typical range of values : 0.001 ≤ Alpha ≤ 0.001
Minimum Increment : 0.001
Recommended Increment : 0.01
Restriction : (Alpha > 0.0)
. Threshold (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Minimum filter response for the points.
Default Value : 0.0
Restriction : (T hreshold ≥ 0.0)
. Row (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; VARIANT ( real )
Row coordinates of the detected points.
. Col (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; VARIANT ( real )
Column coordinates of the detected points.

HALCON 8.0.2
264 CHAPTER 3. FILTER

Result
PointsHarris returns TRUE if all parameters are correct and no error occurs during the execution. If the
input is empty the behavior can be set via SetSystem(’noObjectResult’,<Result>). If necessary, an
exception handling is raised.
Parallelization Information
PointsHarris is reentrant and processed without parallelization.
Possible Successors
GenCrossContourXld
Alternatives
PointsFoerstner
References
C. Harris, M. Stephens: “A combined corner and edge detector”. Proceedings of the 4th Alvey Vision Conference,
pp. 147-151, 1988.
V. Gouet, N.Boujemaa: “Object-based queries using color points of interest”. IEEE Workshop on Content-Based
Access of Image and Video Libraries, CVPR/CBAIVL 2001, Hawaii, USA, 2001.
Module
Foundation

[out] VARIANT Row HImageX.PointsSojka ([in] long MaskSize,


[in] VARIANT SigmaW, [in] VARIANT SigmaD, [in] VARIANT MinGrad,
[in] VARIANT MinApparentness, [in] double MinAngle, [in] String Subpix,
[out] VARIANT Col )
void HOperatorSetX.PointsSojka ([in] IHObjectX Image,
[in] VARIANT MaskSize, [in] VARIANT SigmaW, [in] VARIANT SigmaD,
[in] VARIANT MinGrad, [in] VARIANT MinApparentness, [in] VARIANT MinAngle,
[in] VARIANT Subpix, [out] VARIANT Row, [out] VARIANT Col )

Find corners using the Sojka operator.


PointsSojka defines a corner as the point of intersection of two straight, non-collinear gray value edges. To
decide whether a point of the input image Image is a corner or not, a neighbourhood of MaskSize × MaskSize
points is inspected. Only those image regions that are relevant for the decision are considered. Pixels with a
magnitude of the gradient of less than MinGrad are ignored from the outset.
Furthermore, only those of the remaining points are used that belong to one of the two gray value edges that form
the corner. For this, the so called Apparentness is calculated, which is an indicator of the probability that the
examined point actually is a corner point. Essentially, it is determined by the number of relevant points and their
gradients. A point can only be accepted as a corner when its Apparentness is at least MinApparentness.
Typical values of MinApparentness should range in the region of a few multiples of MinGrad.
To calculate the Apparentness, each mask point is weighted according to two criteria: First, the influence of a
mask point is weighted with a Gaussian of size SigmaW according to its distance from the possible corner point.
SigmaW should be roughly a quarter to the half of MaskSize to obtain a reasonable proportion of the size of the
weighting function to the mask size. Secondly, the distance of the point from the (assumed) ideal gray value edge
is estimated and the point is weighted with a Gaussian of size SigmaD according to that distance. I.e., pixels that
(due to the discretization of the input image) lie farther from the ideal gray value edge have less influence on the
result than pixels with a smaller distance. Typically, it is not necessary to modify the default value 0.75 of SigmaD
.
As a further criterion, the angle is calculated, by which the gray value edges change their direction in the corner
point. A point can only be accepted as a corner when this angle is greater than MinAngle.
The position of the detected corner points is returned in (Row, Col). Row und Col are calculated with subpixel
accuracy if Subpix is ’true’. They are calculated only with pixel accuracy if Subpix is ’false’.
Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, int1, int2, uint2, int4, real )
Input image.

HALCON/COM Reference Manual, 2008-5-13


3.14. POINTS 265

. MaskSize (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT


Required filter size.
Default Value : 9
List of values : MaskSize ∈ {5, 7, 9, 11, 13}
. SigmaW (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Sigma of the weight function according to the distance to the corner candidate.
Default Value : 2.5
Suggested values : SigmaW ∈ {2.0, 2.2, 2.4, 2.5, 2.6, 2.8, 3.0}
. SigmaD (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Sigma of the weight function for the distance to the ideal gray value edge.
Default Value : 0.75
Suggested values : SigmaD ∈ {0.6, 0.7, 0.75, 0.8, 0.9, 1.0}
Restriction : ((0.6 ≤ SigmaD) ∧ (SigmaD ≤ 1.0))
. MinGrad (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Threshold for the magnitude of the gradient.
Default Value : 30.0
Suggested values : MinGrad ∈ {20.0, 15.0, 30.0, 35.0, 40.0}
. MinApparentness (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Threshold for Apparentness.
Default Value : 90.0
Suggested values : MinApparentness ∈ {30.0, 60.0, 90.0, 150.0, 300.0, 600.0, 1500.0}
. MinAngle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; double / VARIANT
Threshold for the direction change in a corner point (radians).
Default Value : 0.5
Restriction : ((0.0 ≤ M inAngle) ∧ (M inAngle ≤ pi))
. Subpix (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Subpixel precise calculation of the corner points.
Default Value : ’false’
List of values : Subpix ∈ {’false’, ’true’}
. Row (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; VARIANT ( real )
Row coordinates of the detected corner points.
. Col (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; VARIANT ( real )
Column coordinates of the detected corner points.
Result
PointsSojka returns TRUE if all parameters are correct and no error occurs during the execution. If the
input is empty the behavior can be set via SetSystem(’noObjectResult’,<Result>). If necessary, an
exception handling is raised.
Parallelization Information
PointsSojka is reentrant and processed without parallelization.
References
Eduard Sojka: “A New and Efficient Algorithm for Detecting the Corners in Digital Images”. Pattern Recognition,
Luc Van Gool (Editor), LNCS 2449, pp. 125-132, Springer Verlag, 2002.
Module
Foundation

HALCON 8.0.2
266 CHAPTER 3. FILTER

3.15 Smoothing

[out] HImageX ImageAniso HImageX.AnisotropeDiff ([in] long Percent,


[in] long Mode, [in] long Iteration, [in] long neighborhoodType )
void HOperatorSetX.AnisotropeDiff ([in] IHObjectX Image,
[out] HUntypedObjectX ImageAniso, [in] VARIANT Percent, [in] VARIANT Mode,
[in] VARIANT Iteration, [in] VARIANT neighborhoodType )

Smooth an image by edge-preserving anisotropic diffusion.


AnisotropeDiff is obsolete and is only provided for reasons of backward compatibility. New applications
should use AnisotropicDiffusion instead.
The operator AnisotropeDiff carries out an iterative, anisotropic smoothing process on the mathematical
basis of physical diffusion. In analogy to the physical diffusion process describing the concentration balance
between molecules dependent on the density gradient, the diffusion filter carries out a smoothing of the gray
values dependent on the local gray value gradients.
For iterative calculation of the gray value of a pixel the gray value differences in relation to the four or eight
neighbors, respectively, are used. These gray value differences, however, are evaluated differently, i.e., a non-
linear diffusion process is carried out.
The evaluation is carried out by using a diffusion function (two different functions were implemented, namely
Mode = 1 and/or 2), which — depending on the gradient — ensures that within homogenous regions the smoothing
is stronger than over the margins of regions so that the edges remain sharp. The diffusion function is adjusted to
the noise ratio of the image by a histogram analysis in the gradient image (according to Canny). A high value for
Percent increases the smoothing effect but blurs the edges a little more (values from 80 - 90 percent are typical).
The parameter Iteration determines the number of iterations (typically 3–7).
Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte )


Image to be smoothed.
. ImageAniso (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX ( byte )
Smoothed image.
. Percent (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
For histogram analysis; higher values increase the smoothing effect, typically: 80-90.
Default Value : 80
Suggested values : Percent ∈ {65, 70, 75, 80, 85, 90}
Typical range of values : 50 ≤ Percent ≤ 50
Minimum Increment : 1
Recommended Increment : 5
. Mode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Selection of diffusion function.
Default Value : 1
List of values : Mode ∈ {1, 2}
. Iteration (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of iterations, typical values: 3-7.
Default Value : 5
Suggested values : Iteration ∈ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Typical range of values : 1 ≤ Iteration ≤ 1
Minimum Increment : 1
Recommended Increment : 1
. neighborhoodType (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Required neighborhood type.
Default Value : 8
List of values : neighborhoodType ∈ {4, 8}
Example

read_image(Image,’fabrik’)

HALCON/COM Reference Manual, 2008-5-13


3.15. SMOOTHING 267

anisotrope_diff(Image,Aniso,80,1,5,8)
sub_image(Image,Aniso,Sub,2.0,127)
disp_image(Sub,WindowHandle).

Complexity
For each pixel: O(Iterations ∗ 18).
Result
If the parameter values are correct the operator AnisotropeDiff returns the value TRUE. The
behavior in case of empty input (no input images available) is set via the operator SetSystem
(’noObjectResult’,<Result>). If necessary an exception handling is raised.
Parallelization Information
AnisotropeDiff is reentrant and automatically parallelized (on tuple level, channel level).
Possible Predecessors
ReadImage, GrabImage
Possible Successors
Regiongrowing, Threshold, SubImage, DynThreshold, AutoThreshold
See also
SmoothImage, BinomialFilter, GaussImage, SigmaImage, RankImage, EliminateMinMax
Alternatives
SigmaImage, RankImage
References
P. Perona, J. Malik: “Scale-space and edge detection using anisotropic diffusion”, IEEE transaction on pattern
analysis and machine intelligence, Vol. 12, No. 7, July 1990.
Module
Foundation

[out] HImageX ImageAniso HImageX.AnisotropicDiffusion


([in] String Mode, [in] double Contrast, [in] double Theta,
[in] long Iterations )
void HOperatorSetX.AnisotropicDiffusion ([in] IHObjectX Image,
[out] HUntypedObjectX ImageAniso, [in] VARIANT Mode, [in] VARIANT Contrast,
[in] VARIANT Theta, [in] VARIANT Iterations )

Perform an anisotropic diffusion of an image.


The operator AnisotropicDiffusion performs an anisotropic diffusion on the input image Image accord-
ing to the model of Perona and Malik. This procedure is also referred to as nonlinear isotropic diffusion. Consid-
ering the image as a gray value function u, the algorithm is a discretization of the partial differential equation

ut = div(g(|∇u|2 , c)∇u)

with the initial value u = u0 defined by Image at a time t0 . The equation is iterated Iterations times in
time steps of length Theta, so that the output image ImageAniso contains the gray value function at the time
t0 + Iterations · Theta.
The goal of the anisotropic diffusion is the elimination of image noise in constant image patches while preserv-
ing the edges in the image. The distinction between edges and constant patches is achieved using the threshold
Contrast on the size of the gray value differences between adjacent pixels. Contrast is referred to as the
contrast parameter and abbreviated with the letter c.
The variable diffusion coefficient g can be chosen to follow different monotonically decreasing functions with
values between 0 and 1 and determines the response of the diffusion process to an edge. With the parameter Mode,
the following functions can be selected:

1
g1 (x, c) = p
1 + 2 cx2

HALCON 8.0.2
268 CHAPTER 3. FILTER

Choosing the function g1 by setting Mode to ’parabolic’ guarantees that the associated differential equation is
parabolic, so that a well-posedness theory exists for the problem and the procedure is stable for an arbitrary step
size Theta. In this case however, there remains a slight diffusion even across edges of a height larger than c.

1
g2 (x, c) =
1 + cx2

The choice of ’perona-malik’ for Mode, as used in the publication of Perona and Malik, does not possess the
theoretical properties of g1 , but in practice it has proved to be sufficiently stable and is thus widely used. The
theoretical instability results in a slight sharpening of strong edges.

c8
g3 (x, c) = 1 − exp(−C )
x4

The function g3 with the constant C = 3.31488, proposed by Weickert, and selectable by setting Mode to ’weick-
ert’ is an improvement of g2 with respect to edge sharpening. The transition between smoothing and sharpening
happens very abruptly at x = c2 .
Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte, uint2, real )


Input image.
. ImageAniso (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX
Output image.
. Mode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Diffusion coefficient as a function of the edge amplitude.
Default Value : ’weickert’
List of values : Mode ∈ {’weickert’, ’perona-malik’, ’parabolic’}
. Contrast (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Contrast parameter.
Default Value : 5.0
Suggested values : Contrast ∈ {2.0, 5.0, 10.0, 20.0, 50.0, 100.0}
Restriction : (Contrast > 0)
. Theta (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Time step.
Default Value : 1.0
Suggested values : Theta ∈ {0.5, 1.0, 3.0}
Restriction : (T heta > 0)
. Iterations (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of iterations.
Default Value : 10
Suggested values : Iterations ∈ {1, 3, 10, 100, 500}
Restriction : (Iterations ≥ 1)
Parallelization Information
AnisotropicDiffusion is reentrant and automatically parallelized (on tuple level).
References
J. Weickert; “’Anisotropic Diffusion in Image Processing’; PhD Thesis; Fachbereich Mathematik, Universität
Kaiserslautern; 1996.
P. Perona, J. Malik; “Scale-space and edge detection using anisotropic diffusion”; Transactions on Pattern Analysis
and Machine Intelligence 12(7), pp. 629-639; IEEE; 1990.
G. Aubert, P. Kornprobst; “Mathematical Problems in Image Processing”; Applied Mathematical Sciences 147;
Springer, New York; 2002.
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


3.15. SMOOTHING 269

[out] HImageX ImageBinomial HImageX.BinomialFilter ([in] long MaskWidth,


[in] long MaskHeight )
void HOperatorSetX.BinomialFilter ([in] IHObjectX Image,
[out] HUntypedObjectX ImageBinomial, [in] VARIANT MaskWidth,
[in] VARIANT MaskHeight )

Smooth an image using the binomial filter.


BinomialFilter smooths the image Image using a binomial filter with a mask size of MaskWidth ×
MaskHeight pixels and returns the smoothed image in ImageBinomial. The binomial filter is a very good
approximation of a Gaussian filter that can be implemented extremely efficiently using only integer operations.
Hence, BinomialFilter is very fast. Let m = MaskHeight and n = MaskWidth. Then, the filter
coefficients bij are given by binomial coefficients
 
l l!
=
k k!(l − k)!

as follows:
  
1 m−1 n−1
bij =
2n+m−2 i j

Here, i = 0, . . . , m − 1 and√
j = 0, . . . , n − 1. The binomial filter performs approximately the same smoothing as
a Gaussian filter with σ = n − 1/2, where for simplicity it is assumed that m = n. In detail, the relationship
between n and σ is:
n σ
3 0.7523
5 1.0317
7 1.2505
9 1.4365
11 1.6010
13 1.7502
15 1.8876
17 2.0157
19 2.1361
21 2.2501
23 2.3586
25 2.4623
27 2.5618
29 2.6576
31 2.7500
33 2.8395
35 2.9262
37 3.0104
If different values are chosen for MaskHeight and MaskWidth, the above relation between n and σ still holds
and refers to the amount of smoothing in the row and column directions.
Parameter

. Image (input iconic) . . . . . . . . . . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, uint2 )


Input image.
. ImageBinomial (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX (
byte, uint2 )
Smoothed image.
. MaskWidth (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Filter width.
Default Value : 5
List of values : MaskWidth ∈ {1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37}

HALCON 8.0.2
270 CHAPTER 3. FILTER

. MaskHeight (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT


Filter height.
Default Value : 5
List of values : MaskHeight ∈ {1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37}
Result
If the parameter values are correct the operator BinomialFilter returns the value TRUE. The
behavior in case of empty input (no input images available) is set via the operator SetSystem
(’noObjectResult’,<Result>). If necessary an exception handling is raised.
Parallelization Information
BinomialFilter is reentrant and automatically parallelized (on tuple level, channel level, domain level).
Possible Predecessors
ReadImage, GrabImage
Possible Successors
Regiongrowing, Threshold, SubImage, DynThreshold, AutoThreshold
See also
MeanImage, AnisotropicDiffusion, SigmaImage, GenLowpass
Alternatives
GaussImage, SmoothImage, DerivateGauss, IsotropicDiffusion
Module
Foundation

[out] HImageX FilteredImage HImageX.EliminateMinMax


([in] long MaskWidth, [in] long MaskHeight, [in] double Gap, [in] long Mode )
void HOperatorSetX.EliminateMinMax ([in] IHObjectX Image,
[out] HUntypedObjectX FilteredImage, [in] VARIANT MaskWidth,
[in] VARIANT MaskHeight, [in] VARIANT Gap, [in] VARIANT Mode )

Smooth an image in the spatial domain to suppress noise.


EliminateMinMax smooths an image by replacing gray values with neighboring mean values, or local min-
ima/maxima. In order to prevent edges and lines from being smoothed, only those gray values that represent local
minima or maxima are replaced (if there is a line or edge within an image there will be at least one neighboring
pixel with a comparable gray value). Gap controls the strictness of replacment: Only gray values that exceed all
other values within their local neighborhood more than Gap and all values that fall below their neighboring more
than Gap are replaced: E(x, y) represents a N × M sized rectangular neighborhood of an pixel at position (x, y),
containing all pixels within the neighborhood except the pixel itself;

• if grayvalue(x, y) ≥ Gap + maximum(E(x, y)) then replacement;


• else if grayvalue(x, y) + Gap ≤ minimum(E(x, y)) then replacement;
• else adopt grayvalue(x, y) without change;

Mode specifies how to perform the new value in case of a replacement.


Mode = 1 → replace a local maximum with next minor local maximum and replace a local minimum with
next bigger local minimum
Mode = 2 → replace with mean value of all pixels within the local neighborhood (including the replaced
pixel)
Mode = 3 → replace with median value of all pixels within the local neighborhood (including the replaced
pixel (this is default and used if Mode has got any other value than 1 or 2)
MaskWidth and MaskHeight specifiy the width and height of the rectangular neighborhood. Border treatment:
Pixels outside the image border are not considered (e.g.: With a local 3 × 3-mask the neighborhood of a pixel at
(0, 0) reduces to the pixels at (1, 0), (0, 1) and (1, 1)).
Attention
EliminateMinMax only can work on byte images (HALCON image type BYTE_IMAGE). If MaskWidth or
MaskHeight is an even number, it is replaced by the next higher odd number (this allows the unique extraction
of the center of the filter mask). Width/height of the mask may not exceed the image width/height.

HALCON/COM Reference Manual, 2008-5-13


3.15. SMOOTHING 271

Parameter
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . (multichannel-)image ; HImageX / IHObjectX ( byte, uint2 )
Image to smooth.
. FilteredImage (output iconic) . . . (multichannel-)image ; HImageX / HUntypedObjectX ( byte, uint2 )
Smoothed image.
. MaskWidth (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; long / VARIANT
Width of filter mask.
Default Value : 3
Suggested values : MaskWidth ∈ {3, 5, 7, 9}
Typical range of values : 3 ≤ MaskWidth ≤ 3
Minimum Increment : 2
Recommended Increment : 2
Restriction : odd
. MaskHeight (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; long / VARIANT
Height of filter mask.
Default Value : 3
Suggested values : MaskHeight ∈ {3, 5, 7, 9}
Typical range of values : 3 ≤ MaskHeight ≤ 3
Minimum Increment : 2
Recommended Increment : 2
Restriction : odd
. Gap (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Gap between local maximum/minimum and all other gray values of the neighborhood.
Default Value : 1.0
Suggested values : Gap ∈ {1.0, 2.0, 5.0, 10.0}
. Mode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Replacement rule (1 = next minimum/maximum, 2 = average, 3 =median).
Default Value : 3
List of values : Mode ∈ {1, 2, 3}
Result
EliminateMinMax returns TRUE if all parameters are correct. If the input is empty EliminateMinMax
returns with an error message.
Parallelization Information
EliminateMinMax is reentrant and automatically parallelized (on tuple level, channel level, domain level).
Possible Successors
WienerFilter, WienerFilterNi
See also
MeanSp, MeanImage, MedianImage, MedianWeighted, BinomialFilter, GaussImage,
SmoothImage
References
M. Imme:“A Noise Peak Elimination Filter”; S. 204-211 in CVGIP Graphical Models and Image Processing, Vol.
53, No. 2, March 1991
M. Lückenhaus:“Grundlagen des Wiener-Filters und seine Anwendung in der Bildanalyse”; Diplomarbeit; Tech-
nische Universität München, Institut für Informatik; Lehrstuhl Prof. Radig; 1995.
Module
Foundation

[out] HImageX ImageFillSP HImageX.EliminateSp ([in] long MaskWidth,


[in] long MaskHeight, [in] long MinThresh, [in] long MaxThresh )
void HOperatorSetX.EliminateSp ([in] IHObjectX Image,
[out] HUntypedObjectX ImageFillSP, [in] VARIANT MaskWidth,
[in] VARIANT MaskHeight, [in] VARIANT MinThresh, [in] VARIANT MaxThresh )

Replace values outside of thresholds with average value.

HALCON 8.0.2
272 CHAPTER 3. FILTER

The operator EliminateSp replaces all gray values outside the indicated gray value intervals (MinThresh to
MaxThresh) with the neighboring mean values. Only those neighboring pixels which also fall within the gray
value interval are used for averaging. If no such pixel is present in the vicinity the original gray value is used. The
gray values in the input image falling within the gray value interval are also adopted without change.
Attention
If even values instead of odd values are given for MaskHeight or MaskWidth, the routine uses the next larger
odd values instead (this way the center of the filter mask is always explicitly determined).
Parameter
. Image (input iconic) . . . . . . . . . . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, uint2 )
Input image.
. ImageFillSP (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX (
byte, uint2 )
Smoothed image.
. MaskWidth (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; long / VARIANT
Width of filter mask.
Default Value : 3
Suggested values : MaskWidth ∈ {3, 5, 7, 9, 11}
Typical range of values : 3 ≤ MaskWidth ≤ 3(lin)
Minimum Increment : 2
Recommended Increment : 2
Restriction : odd
. MaskHeight (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; long / VARIANT
Height of filter mask.
Default Value : 3
Suggested values : MaskHeight ∈ {3, 5, 7, 9, 11}
Typical range of values : 3 ≤ MaskHeight ≤ 3(lin)
Minimum Increment : 2
Recommended Increment : 2
Restriction : odd
. MinThresh (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Minimum gray value.
Default Value : 1
Suggested values : MinThresh ∈ {1, 5, 7, 9, 11, 15, 23, 31, 43, 61, 101}
. MaxThresh (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Maximum gray value.
Default Value : 254
Suggested values : MaxThresh ∈ {5, 7, 9, 11, 15, 23, 31, 43, 61, 101, 200, 230, 250, 254}
Restriction : (M inT hresh ≤ M axT hresh)
Example

read_image(Image,’mreut’)
disp_image(Image,WindowHandle)
eliminate_sp(Image,ImageMeansp,3,3,101,201)
disp_image(ImageMeansp,WindowHandle).

Parallelization Information
EliminateSp is reentrant and automatically parallelized (on tuple level, channel level, domain level).
Possible Successors
DispImage
See also
BinomialFilter, GaussImage, SmoothImage, AnisotropicDiffusion, SigmaImage,
EliminateMinMax
Alternatives
MeanSp, MeanImage, MedianImage, EliminateMinMax
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


3.15. SMOOTHING 273

HImageX.FillInterlace ([in] String Mode )


[out] HImageX ImageFilled
void HOperatorSetX.FillInterlace ([in] IHObjectX ImageCamera,
[out] HUntypedObjectX ImageFilled, [in] VARIANT Mode )

Interpolate 2 video half images.


The operator FillInterlace calculates an interpolated full image or removes odd/even lines from a video
image composed of two half images. If an image is recorded with a video camera it consists of two half images
recorded at different times but stored in one image in the digital form. This can lead to several errors in further
processing. In order to reduce these errors the video image is modified. Every second line is re-calculated or
removed. The parameter Mode determines whether this must be done for even (’even’, ’rmeven’) or odd (’odd’,
’rmodd’) line numbers. If you choose ’even’ or ’odd’ the gray values in the generated lines are calculated as mean
values from the direct neighbors above or below the current pixel, respectively. If you choose ’rmeven’ or ’rmodd’
the even or odd lines numbers are removed (in that case the resulting image is only half as high as the input image).
The value ’switch’ for Mode cause the odd and even lines to be exchanged.
Parameter
. ImageCamera (input iconic) . . . . . . . . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte )
Gray image consisting of two half images.
. ImageFilled (output iconic) . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX ( byte )
Full image with interpolated/removed lines.
. Mode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Instruction whether even or odd lines should be replaced/removed.
Default Value : ’odd’
List of values : Mode ∈ {’odd’, ’even’, ’rmodd’, ’rmeven’, ’switch’}
Example

read_image(Image,’video_bild’)
fill_interlace(Image,New,’odd’)
sobel_amp(New,Sobel,’sum_abs’,3).

Complexity
For each pixel: O(2).
Result
If the parameter values are correct the operator FillInterlace returns the value TRUE. The be-
havior in case of empty input (no input images available) is set via the operator SetSystem
(’noObjectResult’,<Result>). If necessary an exception handling is raised.
Parallelization Information
FillInterlace is reentrant and automatically parallelized (on tuple level, channel level, domain level).
Possible Predecessors
ReadImage, GrabImage
Possible Successors
SobelAmp, EdgesImage, Regiongrowing, DiffOfGauss, Threshold, DynThreshold,
AutoThreshold, MeanImage, BinomialFilter, GaussImage, AnisotropicDiffusion,
SigmaImage, MedianImage
See also
MedianImage, BinomialFilter, GaussImage, CropPart
Module
Foundation

HImageX.GaussImage ([in] long Size )


[out] HImageX ImageGauss
void HOperatorSetX.GaussImage ([in] IHObjectX Image,
[out] HUntypedObjectX ImageGauss, [in] VARIANT Size )

Smooth using discrete gauss functions.

HALCON 8.0.2
274 CHAPTER 3. FILTER

The operator GaussImage smoothes images using the discrete Gaussian. The smoothing effect increases with
increasing filter size. The following filter sizes (Size) are supported (the sigma value of the gauss function is
indicated in brackets):

3 (0.65)
5 (0.87)
7 (1.43)
9 (1.88)
11 (2.31)

For border treatment the gray values of the images are reflected at the image borders.
The operator BinomialFilter can be used as an alternative to GaussImage. BinomialFilter is
significantly faster than GaussImage. It should be noted that the mask size in BinomialFilter does not
lead to the same amount of smoothing as the mask size in GaussImage. Corresponding mask sizes can be
determined based on the respective values of the Gaussian smoothing parameter sigma.
Parameter

. Image (input iconic) . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, int2, uint2, int4 )
Image to be smoothed.
. ImageGauss (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX ( byte,
int2, uint2, int4 )
Filtered image.
. Size (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Required filter size.
Default Value : 5
List of values : Size ∈ {3, 5, 7, 9, 11}
Example

gauss_image(Input,Gauss,7)
regiongrowing(Gauss,Segments,7,7,5,100).

Complexity
For each pixel: O(Size ∗ 2).
Result
If the parameter values are correct the operator GaussImage returns the value TRUE. The be-
havior in case of empty input (no input images available) is set via the operator SetSystem
(’noObjectResult’,<Result>). If necessary an exception handling is raised.
Parallelization Information
GaussImage is reentrant and automatically parallelized (on tuple level, channel level, domain level).
Possible Predecessors
ReadImage, GrabImage
Possible Successors
Regiongrowing, Threshold, SubImage, DynThreshold, AutoThreshold
See also
MeanImage, AnisotropicDiffusion, SigmaImage, GenLowpass
Alternatives
BinomialFilter, SmoothImage, DerivateGauss, IsotropicDiffusion
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


3.15. SMOOTHING 275

[out] long Size HMiscX.InfoSmooth ([in] String Filter, [in] double Alpha,
[out] VARIANT Coeffs )
void HOperatorSetX.InfoSmooth ([in] VARIANT Filter, [in] VARIANT Alpha,
[out] VARIANT Size, [out] VARIANT Coeffs )

Information on smoothing filter SmoothImage.


The operator InfoSmooth returns an estimation of the width of the smoothing filters used in routine
SmoothImage. For this purpose the underlying continuous impulse answers of Filter are scanned until a
filter coefficient is smaller than five percent of the maximum coefficient (at the origin). Alpha is the filter param-
eter (see SmoothImage). Currently four filters are supported (parameter Filter):

’deriche1’, ’deriche2’, ’shen’ und ’gauss’.

The gauss filter was conventionally implemented with filter masks (the other three are recursive filters). In the case
of the gauss filter the filter coefficients (of the one-dimensional impulse answer f (n) with n ≥ 0) are returned in
Coeffs in addition to the filter size.
Parameter

. Filter (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT


Name of required filter.
Default Value : ’deriche2’
List of values : Filter ∈ {’deriche1’, ’deriche2’, ’shen’, ’gauss’}
. Alpha (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Filter parameter: small values effect strong smoothing (reversed in case of ’gauss’).
Default Value : 0.5
Suggested values : Alpha ∈ {0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 4.0, 5.0, 7.0, 10.0}
Typical range of values : 0.01 ≤ Alpha ≤ 0.01
Minimum Increment : 0.01
Recommended Increment : 0.1
Restriction : (Alpha > 0.0)
. Size (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Width of filter is approx. size x size pixels.
. Coeffs (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
In case of gauss filter: coefficients of the “positive” half of the 1D impulse answer.
Example

info_smooth(’deriche2’,0.5,Size,Coeffs)
smooth_image(Input,Smooth,’deriche2’,7).

Result
If the parameter values are correct the operator InfoSmooth returns the value TRUE. Otherwise an exception
handling is raised.
Parallelization Information
InfoSmooth is reentrant and processed without parallelization.
Possible Predecessors
ReadImage
Possible Successors
SmoothImage
See also
SmoothImage
Module
Foundation

HALCON 8.0.2
276 CHAPTER 3. FILTER

[out] HImageX SmoothedImage HImageX.IsotropicDiffusion


([in] double Sigma, [in] long Iterations )
void HOperatorSetX.IsotropicDiffusion ([in] IHObjectX Image,
[out] HUntypedObjectX SmoothedImage, [in] VARIANT Sigma,
[in] VARIANT Iterations )

Perform an isotropic diffusion of an image.


The operator IsotropicDiffusion performs an isotropic diffusion of the input image Image. This cor-
responds to a convolution of the image matrix with a Gaussian mask of standard deviation Sigma. If the pa-
rameter Iterations is set to 0, such a convolution is performed explicitly. For input images with a full ROI,
IsotropicDiffusion returns the same results as the operator DerivateGauss when choosing ’none’ for
its parameter Component. If the gray value matrix is larger than the ROI of Image the two operators differ
since DerivateGauss takes the gray values outside of the ROI into account, while IsotropicDiffusion
mirrors the values at the boundary of the ROI in any case. The computational complexity increases linearly with
the value of Sigma.
If Iterations has a positive value the smoothing process is considered as an application of the heat equation

ut = ∆u

on the gray value function u with the initial value u = u0 defined by the gray values of Image at a time t0 . This
equation is then solved up to a time t0 + 12 Sigma2 , which is equivalent to the above convolution, using an iterative
procedure for parabolic partial differential equations. The computational complexity is proportional to the value
of Iterations and independent of Sigma in this case. For small values of Iterations, the computational
accuracy is very low, however. For this reason, choosing Iterations < 3 is not recommended.
For smaller values of Sigma, the convolution implementation is typically the faster method. Since the runtime of
the partial differential equation solver only depends on the number of iterations and not on the value of Sigma, it
is typically faster for large values of Sigma if few iterations are chosen (e.g., Iterations = 3 ).
Parameter
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte, uint2, real )
Input image.
. SmoothedImage (output iconic) . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX
Output image.
. Sigma (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Standard deviation of the Gauss distribution.
Default Value : 1.0
Suggested values : Sigma ∈ {0.1, 0.5, 1.0, 3.0, 10.0, 20.0, 50.0}
Restriction : (Sigma > 0)
. Iterations (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of iterations.
Default Value : 10
Suggested values : Iterations ∈ {0, 3, 10, 100, 500}
Restriction : (Iterations ≥ 0)
Parallelization Information
IsotropicDiffusion is reentrant and automatically parallelized (on tuple level).
Module
Foundation

[out] HImageX ImageMean HImageX.MeanImage ([in] long MaskWidth,


[in] long MaskHeight )
void HOperatorSetX.MeanImage ([in] IHObjectX Image,
[out] HUntypedObjectX ImageMean, [in] VARIANT MaskWidth,
[in] VARIANT MaskHeight )

Smooth by averaging.

HALCON/COM Reference Manual, 2008-5-13


3.15. SMOOTHING 277

The operator MeanImage carries out a linear smoothing with the gray values of all input images (Image). The
filter matrix consists of ones (evaluated equally) and has the size MaskHeight × MaskWidth. The result of the
convolution is divided by MaskHeight × MaskWidth. For border treatment the gray values are reflected at the
image edges.
For MeanImage special optimizations are implemented that use SIMD technology. The actual application
of these special optimizations is controlled by the system parameter ’mmx_enable’ (see SetSystem). If
’mmx_enable’ is set to ’true’ (and the SIMD instruction set is available), the internal calculations are performed
using SIMD technology. Note that SIMD technology performs best on large, compact input regions. Depending on
the input region and the capabilities of the hardware the execution of MeanImage might even take significantly
more time with SIMD technology than without.
At any rate, it is advantageous for the performance of MeanImage to choose the input region of Image such that
any border treatment is avoided.
Attention
If even values instead of odd values are given for MaskHeight or MaskWidth, the routine uses the next larger
odd values instead (this way the center of the filter mask is always explicitly determined).
Parameter
. Image (input iconic) . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, int2, uint2, int4,
real, vector_field )
Image to be smoothed.
. ImageMean (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX ( byte,
int2, uint2, int4, real, vector_field )
Smoothed image.
. MaskWidth (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; long / VARIANT
Width of filter mask.
Default Value : 9
Suggested values : MaskWidth ∈ {3, 5, 7, 9, 11, 15, 23, 31, 43, 61, 101}
Typical range of values : 1 ≤ MaskWidth ≤ 1
Minimum Increment : 2
Recommended Increment : 2
Restriction : odd
. MaskHeight (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; long / VARIANT
Height of filter mask.
Default Value : 9
Suggested values : MaskHeight ∈ {3, 5, 7, 9, 11, 15, 23, 31, 43, 61, 101}
Typical range of values : 1 ≤ MaskHeight ≤ 1
Minimum Increment : 2
Recommended Increment : 2
Restriction : odd
Example

read_image(Image,’fabrik’)
mean_image(Image,Mean,3,3)
disp_image(Mean,WindowHandle).

Complexity
For each pixel: O(15).
Result
If the parameter values are correct the operator MeanImage returns the value TRUE. The be-
havior in case of empty input (no input images available) is set via the operator SetSystem
(’noObjectResult’,<Result>). If necessary an exception handling is raised.
Parallelization Information
MeanImage is reentrant and automatically parallelized (on tuple level, channel level, domain level).
Possible Predecessors
ReduceDomain, Rectangle1Domain

HALCON 8.0.2
278 CHAPTER 3. FILTER

Possible Successors
DynThreshold, Regiongrowing
See also
AnisotropicDiffusion, SigmaImage, ConvolImage, GenLowpass
Alternatives
BinomialFilter, GaussImage, SmoothImage
Module
Foundation

HImageX.MeanN ( )
[out] HImageX ImageMean
void HOperatorSetX.MeanN ([in] IHObjectX Image,
[out] HUntypedObjectX ImageMean )

Average gray values over several channels.


The operator MeanN generates the pixel-by-pixel mean value of all channels . For each coordinate point the sum
of all gray values at this coordinate is calculated. The result is the mean of the gray values (sum divided by the
number of channels). The output image has one channel.
Parameter

. Image (input iconic) . . . . multichannel-image-array ; HImageX / IHObjectX ( byte, int4, uint2, int4, real )
Multichannel gray image.
. ImageMean (output iconic) . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, int4, uint2, int4,
real )
Result of averaging.
Parallelization Information
MeanN is reentrant and automatically parallelized (on tuple level, domain level).
Possible Predecessors
Compose2, Compose3, Compose4, AddChannels
Possible Successors
DispImage
See also
CountChannels
Module
Foundation

[out] HImageX ImageSPMean HImageX.MeanSp ([in] long MaskWidth,


[in] long MaskHeight, [in] long MinThresh, [in] long MaxThresh )
void HOperatorSetX.MeanSp ([in] IHObjectX Image,
[out] HUntypedObjectX ImageSPMean, [in] VARIANT MaskWidth,
[in] VARIANT MaskHeight, [in] VARIANT MinThresh, [in] VARIANT MaxThresh )

Suppress salt and pepper noise.


The operator MeanSp carries out a smoothing by averaging the values. Only the gray values within the interval
from MinThresh to MaxThresh are averaged. Gray values which are too light or too dark are ignored during
summation. If no gray value lies within the default interval during summation the original gray value is adopted.
If the thresholds are set at 0 or 255, respectively, the operator MeanSp behaves like MeanImage except for the
running time.
The operator MeanSp is used to suppress extreme gray values (salt and pepper noise = white and black dots).
Attention
If even values instead of odd values are given for MaskHeight or MaskWidth, the routine uses the next larger
odd values instead (this way the center of the filter mask is always explicitly determined).

HALCON/COM Reference Manual, 2008-5-13


3.15. SMOOTHING 279

Parameter

. Image (input iconic) . . . . . . . . . . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, uint2 )


Input image.
. ImageSPMean (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX (
byte, uint2 )
Smoothed image.
. MaskWidth (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; long / VARIANT
Width of filter mask.
Default Value : 3
Suggested values : MaskWidth ∈ {3, 5, 7, 9, 11}
Typical range of values : 3 ≤ MaskWidth ≤ 3(lin)
Minimum Increment : 2
Recommended Increment : 2
Restriction : odd
. MaskHeight (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; long / VARIANT
Height of filter mask.
Default Value : 3
Suggested values : MaskHeight ∈ {3, 5, 7, 9, 11}
Typical range of values : 3 ≤ MaskHeight ≤ 3(lin)
Minimum Increment : 2
Recommended Increment : 2
Restriction : odd
. MinThresh (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Minimum gray value.
Default Value : 1
Suggested values : MinThresh ∈ {1, 5, 7, 9, 11, 15, 23, 31, 43, 61, 101}
. MaxThresh (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Maximum gray value.
Default Value : 254
Suggested values : MaxThresh ∈ {5, 7, 9, 11, 15, 23, 31, 43, 61, 101, 200, 230, 250, 254}
Restriction : (M inT hresh ≤ M axT hresh)
Example

read_image(Image,’mreut’)
disp_image(Image,WindowHandle)
mean_sp(Image,ImageMeansp,3,3,101,201)
disp_image(ImageMeansp,WindowHandle).

Parallelization Information
MeanSp is reentrant and automatically parallelized (on tuple level, channel level, domain level).
Possible Successors
DispImage
See also
AnisotropicDiffusion, SigmaImage, BinomialFilter, GaussImage, SmoothImage,
EliminateMinMax
Alternatives
MeanImage, MedianImage, MedianSeparate, EliminateMinMax
Module
Foundation

HALCON 8.0.2
280 CHAPTER 3. FILTER

[out] HImageX ImageMedian HImageX.MedianImage ([in] String MaskType,


[in] long Radius, [in] VARIANT Margin )
void HOperatorSetX.MedianImage ([in] IHObjectX Image,
[out] HUntypedObjectX ImageMedian, [in] VARIANT MaskType,
[in] VARIANT Radius, [in] VARIANT Margin )

Median filtering with different rank masks.


The operator MedianImage carries out a non-linear smoothing of the gray values of all input images (Image).
The shift mask (MaskType) is transmitted in the form of an object (more precisely: its region). Several border
treatments can be chosen for filtering (Margin):

gray value Pixels outside of the image edges are assumued


to be constant (with the indicated gray value).
’continued’ Continuation of edge pixels.
’cyclic’ Cyclic continuation of image edges.
’mirrored’ Reflection of pixels at the image edges.

The indicated mask (= region of the mask image) is put over the image to be filtered in such a way that the center
of the mask touches all pixels of the objects once. For each of these pixels all neighboring pixels covered by the
mask are sorted in an ascending sequence according to their gray values. Thus, each of these sorted gray value
sequences contains exactly as many gray values as the mask has pixels. From these sequences the median is
selected and entered as resulting gray value at the corresponding output image.
Parameter
. Image (input iconic) . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, int2, uint2, int4,
real )
Image to be filtered.
. ImageMedian (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX (
byte, int2, uint2, int4, real )
Median filtered image.
. MaskType (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Type of median mask.
Default Value : ’circle’
List of values : MaskType ∈ {’circle’, ’rectangle’}
. Radius (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Radius of median mask.
Default Value : 1
Suggested values : Radius ∈ {1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 15, 19, 25, 31, 39, 47, 59}
Typical range of values : 1 ≤ Radius ≤ 1
Minimum Increment : 1
Recommended Increment : 2
. Margin (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( integer, real, string )
Border treatment.
Default Value : ’mirrored’
Suggested values : Margin ∈ {’mirrored’, ’cyclic’, ’continued’, 0, 30, 60, 90, 120, 150, 180, 210, 240, 255}
Example

read_image(Image,’fabrik’)
median_image(Image,Median,’circle’,3,’continued’)
disp_image(MedianWeighted,WindowHandle).

√ Complexity
For each pixel: O( F ∗ 5) with F = area of MaskType.
Result
If the parameter values are correct the operator MedianImage returns the value TRUE. The be-
havior in case of empty input (no input images available) is set via the operator SetSystem
(’noObjectResult’,<Result>). If necessary an exception handling is raised.

HALCON/COM Reference Manual, 2008-5-13


3.15. SMOOTHING 281

Parallelization Information
MedianImage is reentrant and automatically parallelized (on tuple level, channel level, domain level).
Possible Predecessors
ReadImage
Possible Successors
Threshold, DynThreshold, Regiongrowing
See also
GenCircle, GenRectangle1, GrayErosionRect, GrayDilationRect
Alternatives
RankImage
References
R. Haralick, L. Shapiro; “Computer and Robot Vision”; Addison-Wesley, 1992, Seite 318-319
Module
Foundation

[out] HImageX ImageSMedian HImageX.MedianSeparate ([in] long MaskWidth,


[in] long MaskHeight, [in] VARIANT Margin )
void HOperatorSetX.MedianSeparate ([in] IHObjectX Image,
[out] HUntypedObjectX ImageSMedian, [in] VARIANT MaskWidth,
[in] VARIANT MaskHeight, [in] VARIANT Margin )

Separated median filtering with rectangle masks.


The operator MedianSeparate carries out a variation of the median filtering: First two auxiliary images are
created. The first one originates from a median filtering with a horizontal mask with a height of one pixel and the
width MaskWidth followed by filtering with a mask with the height MaskHeight. The second auxiliary image
is created by filtering with the same masks, but with a reversed sequence of the operation: first the vertical, then
the horizontal mask. The output image results from averaging the two auxiliary images pixel by pixel.
The operator MedianSeparate is clearly faster than the normal operator MedianImage because both masks
are one pixel wide, facilitating a very effecient processing. The runtime is practically independent of the size of
the mask. For example, the operator MedianSeparate can be well used after texture filters, where large masks
are needed.
The filter can also be used several times in a row in order to enhance the smoothing.
Parameter
. Image (input iconic) . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, int2, uint2, int4,
real )
Image to be filtered.
. ImageSMedian (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX (
byte, int2, uint2, int4, real )
Median filtered image.
. MaskWidth (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; long / VARIANT
Width of rank mask.
Default Value : 25
Suggested values : MaskWidth ∈ {1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 27, 43, 51, 67, 91, 121, 151}
Typical range of values : 1 ≤ MaskWidth ≤ 1
Minimum Increment : 2
Recommended Increment : 2
. MaskHeight (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; long / VARIANT
Height of rank mask.
Default Value : 25
Suggested values : MaskHeight ∈ {1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 27, 43, 51, 67, 91, 121, 151}
Typical range of values : 1 ≤ MaskHeight ≤ 1
Minimum Increment : 2
Recommended Increment : 2

HALCON 8.0.2
282 CHAPTER 3. FILTER

. Margin (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( integer, real, string )


Border treatment.
Default Value : ’mirrored’
Suggested values : Margin ∈ {’mirrored’, ’cyclic’, ’continued’, 0, 30, 60, 90, 120, 150, 180, 210, 240, 255}
Example

read_image(Image,’fabrik’)
median_separate(Image,MedianSeparate,5,5,3)
disp_image(MedianSeparate,WindowHandle).

Complexity
For each pixel: O(40).
Parallelization Information
MedianSeparate is reentrant and automatically parallelized (on tuple level, channel level, domain level).
Possible Predecessors
TextureLaws, SobelAmp, DeviationImage
Possible Successors
LearnNdimNorm, LearnNdimBox, MedianSeparate, Regiongrowing, AutoThreshold
See also
RankImage
Alternatives
MedianImage
References
R. Haralick, L. Shapiro; “Computer and Robot Vision”; Addison-Wesley, 1992, Seite 319
Module
Foundation

[out] HImageX ImageWMedian HImageX.MedianWeighted ([in] String MaskType,


[in] long MaskSize )
void HOperatorSetX.MedianWeighted ([in] IHObjectX Image,
[out] HUntypedObjectX ImageWMedian, [in] VARIANT MaskType,
[in] VARIANT MaskSize )

Weighted median filtering with different rank masks.


The operator MedianWeighted calculates the median of the gray values within a local environment. In
contrast to MedianImage, which uses all gray values within the environment exactly once, the operator
MedianWeighted weights all gray values several times depending on their position. A gray value is received
into the field to be sorted several times according to its weighting. The following masks are available:

’gauss’ (MaskSize = 3)
1 2 1
2 4 2
1 2 1
’inner’ (MaskSize = 3)
1 1 1
1 3 1
1 1 1

The operator MedianWeighted means that, contrary to MedianImage, gray value corners remain.

HALCON/COM Reference Manual, 2008-5-13


3.15. SMOOTHING 283

Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, int2 )


Image to be filtered.
. ImageWMedian (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX (
byte, int2 )
Median filtered image.
. MaskType (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Type of median mask.
Default Value : ’inner’
List of values : MaskType ∈ {’inner’, ’gauss’}
. MaskSize (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
mask size.
Default Value : 3
List of values : MaskSize ∈ {3}
Example

read_image(Image,’fabrik’)
median_weighted(Image,MedianWeighted,’gauss’,3)
disp_image(MedianWeighted,WindowHandle).

Complexity
For each pixel: O(F ∗ log F ) with F = area of MaskType.
Parallelization Information
MedianWeighted is reentrant and automatically parallelized (on tuple level, channel level, domain level).
Possible Predecessors
ReadImage
Possible Successors
Threshold, DynThreshold, Regiongrowing
Alternatives
MedianImage, TrimmedMean, SigmaImage
References
R. Haralick, L. Shapiro; “Computer and Robot Vision”; Addison-Wesley, 1992, Seite 319
Module
Foundation

[out] HImageX ImageMidrange HImageX.MidrangeImage ([in] HRegionX Mask,


[in] VARIANT Margin )
void HOperatorSetX.MidrangeImage ([in] IHObjectX Image,
[in] IHObjectX Mask, [out] HUntypedObjectX ImageMidrange,
[in] VARIANT Margin )

Calculate the average of maximum and minimum inside any mask.


The operator MidrangeImage forms the average of maximum and minimum inside the indicated mask in the
whole image. Several border treatments (Margin) can be chosen for filtering:

gray value Pixels outside of the image edges are assumued


to be constant (with the indicated gray value).
’continued’ Continuation of edge pixels.
’cyclic’ Cyclic continuation of image edges.
’mirrored’ Reflection of pixels at the image edges.

HALCON 8.0.2
284 CHAPTER 3. FILTER

The indicated mask (= region of the mask image) is put over the image to be filtered in such a way that the center
of the mask touches all pixels once.
Parameter

. Image (input iconic) . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, int2, uint2, int4,
real )
Image to be filtered.
. Mask (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX ( byte )
Region serving as filter mask.
. ImageMidrange (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX (
byte, int2, uint2, int4, real )
Filtered output image.
. Margin (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( integer, real, string )
Border treatment.
Default Value : ’mirrored’
Suggested values : Margin ∈ {’mirrored’, ’cyclic’, ’continued’, 0, 30, 60, 90, 120, 150, 180, 210, 240, 255}
Example

read_image(Image,’fabrik’)
draw_region(Region,WindowHandle)
midrange_image(Image,Region,Midrange,’mirrored’)
disp_image(Midrange,WindowHandle).

√ Complexity
For each pixel: O( F ∗ 5) with F = area of Mask.
Result
If the parameter values are correct the operator MidrangeImage returns the value TRUE. The be-
havior in case of empty input (no input images available) is set via the operator SetSystem
(’noObjectResult’,<Result>). If necessary an exception handling is raised.
Parallelization Information
MidrangeImage is reentrant and automatically parallelized (on tuple level, channel level, domain level).
Possible Predecessors
ReadImage, DrawRegion, GenCircle, GenRectangle1
Possible Successors
Threshold, DynThreshold, Regiongrowing
See also
GenCircle, GenRectangle1, GrayErosionRect, GrayDilationRect, GrayRangeRect
Alternatives
SigmaImage
References
R. Haralick, L. Shapiro; “Computer and Robot Vision”; Addison-Wesley, 1992, Seite 319
Module
Foundation

[out] HImageX ImageRank HImageX.RankImage ([in] HRegionX Mask,


[in] long Rank, [in] VARIANT Margin )
void HOperatorSetX.RankImage ([in] IHObjectX Image,
[in] IHObjectX Mask, [out] HUntypedObjectX ImageRank, [in] VARIANT Rank,
[in] VARIANT Margin )

Smooth an image with an arbitrary rank mask.

HALCON/COM Reference Manual, 2008-5-13


3.15. SMOOTHING 285

The operator RankImage carries out a non-linear smoothing of the gray values of all input images (Image). The
filter mask (Mask) is transmitted as a region. In contrast to many other filters you can choose an arbitrary shape,
e.g., by using operators like GenCircle or DrawRegion. The position of the mask region has no influence on
the result; the center of gravity of the region is used as the reference point of the filter mask.
The specified mask is moved over the image to be filtered in such a way that the reference point of the mask touches
all pixels once. At each position a histogram is calculated from the gray values of all pixels covered by the mask.
By specifying Rank = 1 the lowest (= darkest) gray value appearing in the histogram is selected and entered as
resulting gray value in the output image ImageRank; if Rank corresponds to the number of pixels of the filter
mask, i.e., its area, the brightest gray value is selected. This behavior is idential to the erosion/dilation operators in
gray morphology ( GrayErosion, GrayDilation). If you use a rank that is equal to half of the pixels of the
filter mask you get the same behavior as for the the median filter ( MedianImage).
You can use RankImage to eliminate noise, to eliminate structures with a given orientation (use
GenRectangle2 to create the mask region), or as an advanced gray morphologic operator that is more ro-
bust against noise. In this case you will not use 1 or the mask area as rank values, but a slightly higher or lower
value, respectively.
Several border treatments can be chosen for filtering (Margin):

gray value Pixels outside of the image edges are assumued


to be constant (with the indicated gray value).
’continued’ Continuation of edge pixels.
’cyclic’ Cyclic continuation of image edges.
’mirrored’ Reflection of pixels at the image edges.

Parameter
. Image (input iconic) . . . . multichannel-image-array ; HImageX / IHObjectX ( byte, int2, uint2, int4, real )
Image to be filtered.
. Mask (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX ( byte )
Region serving as filter mask.
. ImageRank (output iconic) . . . . . . multichannel-image-array ; HImageX / HUntypedObjectX ( byte, int2,
uint2, int4, real )
Filtered image.
. Rank (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Rank of the output gray value in the sorted sequence of input gray values inside the filter mask. Typical value
(median): area(mask) / 2.
Default Value : 5
Suggested values : Rank ∈ {1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31}
Typical range of values : 1 ≤ Rank ≤ 1
Minimum Increment : 1
Recommended Increment : 2
. Margin (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( integer, real, string )
Border treatment.
Default Value : ’mirrored’
Suggested values : Margin ∈ {’mirrored’, ’cyclic’, ’continued’, 0, 30, 60, 90, 120, 150, 180, 210, 240, 255}
Example

read_image(Image,’fabrik’)
draw_region(Region,WindowHandle)
rank_image(Image,Region,ImageRank,5,’mirrored’)
disp_image(ImageRank,WindowHandle).

√ Complexity
For each pixel: O( F ∗ 5) with F = area of Mask.
Result
If the parameter values are correct the operator RankImage returns the value TRUE. The be-
havior in case of empty input (no input images available) is set via the operator SetSystem
(’noObjectResult’,<Result>). If necessary an exception handling is raised.

HALCON 8.0.2
286 CHAPTER 3. FILTER

Parallelization Information
RankImage is reentrant and automatically parallelized (on tuple level, channel level, domain level).
Possible Predecessors
ReadImage, DrawRegion, GenCircle, GenRectangle1
Possible Successors
Threshold, DynThreshold, Regiongrowing
See also
GenCircle, GenRectangle1, GrayErosionRect, GrayDilationRect
Alternatives
SigmaImage
References
R. Haralick, L. Shapiro; “Computer and Robot Vision”; Addison-Wesley, 1992, Seite 318-320
Module
Foundation

[out] HImageX ImageSigma HImageX.SigmaImage ([in] long MaskHeight,


[in] long MaskWidth, [in] long Sigma )
void HOperatorSetX.SigmaImage ([in] IHObjectX Image,
[out] HUntypedObjectX ImageSigma, [in] VARIANT MaskHeight,
[in] VARIANT MaskWidth, [in] VARIANT Sigma )

Non-linear smoothing with the sigma filter.


The operator SigmaImage carries out a non-linear smoothing of the gray values of all input images (Image).
All pixels are checked in a rectangular window (MaskHeight × MaskWidth). All pixels of the window which
differ from the current pixel by less than Sigma are used for calculating the new pixel, which is the average of the
chosen pixels. If all differences are larger than Sigma the gray value is adapted unchanged.
Attention
If even values instead of odd values are given for MaskHeight or MaskWidth, the routine uses the next larger
odd values instead (this way the center of the filter mask is always explicitly determined).
Parameter

. Image (input iconic) . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, cyclic, int1, int2,
uint2, int4, real )
Image to be smoothed.
. ImageSigma (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX ( byte,
cyclic, int1, int2, uint2, int4, real )
Smoothed image.
. MaskHeight (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; long / VARIANT
Height of the mask (number of lines).
Default Value : 5
Suggested values : MaskHeight ∈ {3, 5, 7, 9, 11, 13, 15}
Typical range of values : 3 ≤ MaskHeight ≤ 3
Minimum Increment : 2
Recommended Increment : 2
Restriction : odd
. MaskWidth (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; long / VARIANT
Width of the mask (number of columns).
Default Value : 5
Suggested values : MaskWidth ∈ {3, 5, 7, 9, 11, 13, 15}
Typical range of values : 3 ≤ MaskWidth ≤ 3
Minimum Increment : 2
Recommended Increment : 2
Restriction : odd

HALCON/COM Reference Manual, 2008-5-13


3.15. SMOOTHING 287

. Sigma (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT


Max. deviation to the average.
Default Value : 3
Suggested values : Sigma ∈ {3, 5, 7, 9, 11, 20, 30, 50}
Typical range of values : 0 ≤ Sigma ≤ 0
Minimum Increment : 1
Recommended Increment : 2
Example

read_image(Image,’fabrik’)
sigma_image(Image,ImageSigma,5,5,3)
disp_image(ImageSigma,WindowHandle).

Complexity
For each pixel: O(MaskHeight× MaskWidth).
Result
If the parameter values are correct the operator SigmaImage returns the value TRUE. The be-
havior in case of empty input (no input images available) is set via the operator SetSystem
(’noObjectResult’,<Result>). If necessary an exception handling is raised.
Parallelization Information
SigmaImage is reentrant and automatically parallelized (on tuple level, channel level, domain level).
Possible Predecessors
ReadImage
Possible Successors
Threshold, DynThreshold, Regiongrowing
See also
SmoothImage, BinomialFilter, GaussImage, MeanImage
Alternatives
AnisotropicDiffusion, RankImage
References
R. Haralick, L. Shapiro; “Computer and Robot Vision”; Addison-Wesley, 1992, Seite 325
Module
Foundation

[out] HImageX ImageSmooth HImageX.SmoothImage ([in] String Filter,


[in] double Alpha )
void HOperatorSetX.SmoothImage ([in] IHObjectX Image,
[out] HUntypedObjectX ImageSmooth, [in] VARIANT Filter, [in] VARIANT Alpha )

Smooth an image using recursive filters.


SmoothImage smooths gray images using recursive filters originally developed by Deriche and Shen and using
the non-recursive Gaussian filter. The following filters can be choosen via the parameter Filter:

’deriche1’, ’deriche2’, ’shen’ und ’gauss’.

The “filter width” (i.e., the range of the filter and thereby result of the filter) can be of any size. In the case that the
Deriche or Shen is choosen it decreases by increasing the filter parameter Alpha and increases in the case of the
Gauss filter (and Alpha corresponds to the standard deviation of the Gaussian function). An approximation of the
appropiate size of the filterwidth Alpha is performed by the operator InfoSmooth.
Non-recursive filters like the Gaussian filter are often implemented using filter-masks. In this case the runtime
of the operator increases with increasing size of the filter mask. The runtime of the recursive filters remains
constant; except the border treatment becomes a little bit more time consuming. The Gaussian filter becomes slow

HALCON 8.0.2
288 CHAPTER 3. FILTER

in comparison to the recursive ones but is in contrast to them isotropic (the filter ’deriche2’ is only weakly direction
sensitive). A comparable result of the smoothing is achieved by choosing the following values for the parameter:

Alpha(0 deriche10 )
Alpha(0 deriche20 ) =
2
Alpha( deriche10 )
0
Alpha(0 shen0 ) =
2
1.77
Alpha(0 gauss0 ) =
Alpha(0 deriche10 )

Parameter

. Image (input iconic) . . . . . . . . . . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, uint2 )


Image to be smoothed.
. ImageSmooth (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX (
byte, uint2 )
Smoothed image.
. Filter (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Filter.
Default Value : ’deriche2’
List of values : Filter ∈ {’deriche1’, ’deriche2’, ’shen’, ’gauss’}
. Alpha (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Filterparameter: small values cause strong smoothing (vice versa by using bei ’gauss’).
Default Value : 0.5
Suggested values : Alpha ∈ {0.1, 0.2, 0.3, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 4.0, 5.0, 7.0, 10.0}
Typical range of values : 0.01 ≤ Alpha ≤ 0.01
Minimum Increment : 0.01
Recommended Increment : 0.1
Restriction : (Alpha > 0)
Example

info_smooth(’deriche2’,0.5,Size,Coeffs)
smooth_image(Input,Smooth,’deriche2’,7)

Result
If the parameter values are correct the operator SmoothImage returns the value TRUE. The be-
havior in case of empty input (no input images available) is set via the operator SetSystem
(’noObjectResult’,<Result>). If necessary an exception handling is raised.
Parallelization Information
SmoothImage is reentrant and automatically parallelized (on tuple level, channel level).
Possible Predecessors
ReadImage
Possible Successors
Threshold, DynThreshold, Regiongrowing
See also
InfoSmooth, MedianImage, SigmaImage, AnisotropicDiffusion
Alternatives
BinomialFilter, GaussImage, MeanImage, DerivateGauss, IsotropicDiffusion
References
R.Deriche: “Fast Algorithms for Low-Level Vision”; IEEE Transactions on Pattern Analysis and Machine Intelli-
gence; PAMI-12, no. 1; S. 78-87; 1990.
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


3.15. SMOOTHING 289

[out] HImageX ImageTMean HImageX.TrimmedMean ([in] HRegionX Mask,


[in] long Number, [in] VARIANT Margin )
void HOperatorSetX.TrimmedMean ([in] IHObjectX Image,
[in] IHObjectX Mask, [out] HUntypedObjectX ImageTMean, [in] VARIANT Number,
[in] VARIANT Margin )

Smooth an image with an arbitrary rank mask.


The operator TrimmedMean carries out a non-linear smoothing of the gray values of all input images (Image).
The filter mask (Mask) is passed in the form of a region. The average of Number gray values located near the
median is calculated. Several border treatments can be chosen for filtering (Margin):

gray value Pixels outside of the image edges are assumued


to be constant (with the indicated gray value).
’continued’ Continuation of edge pixels.
’cyclic’ Cyclic continuation of image edges.
’mirrored’ Reflection of pixels at the image edges.

The indicated mask (= region of the mask image) is put over the image to be filtered in such a way that the center
of the mask touches all pixels once. For each of these pixels all neighboring pixels covered by the mask are sorted
in an ascending sequence according to their gray values. Thus, each of these sorted gray value sequences contains
exactly as many gray values as the mask has pixels. If F is the area of the mask the average of these sequences is
calculated as follows: The first (F - Number)/2 gray values are ignored. Then the following Number gray values
are summed up and divided by Number. Again the remaining (F - Number)/2 gray values are ignored.
Parameter
. Image (input iconic) . . . . multichannel-image-array ; HImageX / IHObjectX ( byte, int2, uint2, int4, real )
Image to be filtered.
. Mask (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
Image whose region serves as filter mask.
. ImageTMean (output iconic) . . . . . . multichannel-image-array ; HImageX / HUntypedObjectX ( byte,
int2, uint2, int4, real )
Filtered output image.
. Number (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of averaged pixels. Typical value: Surface(Mask) / 2.
Default Value : 5
Suggested values : Number ∈ {1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31}
Typical range of values : 1 ≤ Number ≤ 1
Minimum Increment : 1
Recommended Increment : 2
. Margin (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( integer, real, string )
Border treatment.
Default Value : ’mirrored’
Suggested values : Margin ∈ {’mirrored’, ’cyclic’, ’continued’, 0, 30, 60, 90, 120, 150, 180, 210, 240, 255}
Example

read_image(Image,’fabrik’)
draw_region(Region,WindowHandle)
trimmed_mean(Image,Region,TrimmedMean,5,’mirrored’)
disp_image(TrimmedMean,WindowHandle).

Result
If the parameter values are correct the operator TrimmedMean returns the value TRUE. The be-
havior in case of empty input (no input images available) is set via the operator SetSystem
(’noObjectResult’,<Result>). If necessary an exception handling is raised.
Parallelization Information
TrimmedMean is reentrant and automatically parallelized (on tuple level, channel level, domain level).

HALCON 8.0.2
290 CHAPTER 3. FILTER

Possible Predecessors
ReadImage, DrawRegion, GenCircle, GenRectangle1
Possible Successors
Threshold, DynThreshold, Regiongrowing
See also
GenCircle, GenRectangle1, GrayErosionRect, GrayDilationRect
Alternatives
SigmaImage, MedianWeighted, MedianImage
References
R. Haralick, L. Shapiro; “Computer and Robot Vision”; Addison-Wesley, 1992, Seite 320
Module
Foundation

3.16 Texture
[out] HImageX ImageDeviation HImageX.DeviationImage ([in] long Width,
[in] long Height )
void HOperatorSetX.DeviationImage ([in] IHObjectX Image,
[out] HUntypedObjectX ImageDeviation, [in] VARIANT Width,
[in] VARIANT Height )

Calculate the standard deviation of gray values within rectangular windows.


DeviationImage calculates the standard deviation of gray values in the image Image within a rectangular
mask of size (Height, Width). The resulting image is returned in ImageDeviation. To better use the range
of gray values available in the output image, the result is multiplied by 2. If the parameters Height and Width
are even, they are changed to the next larger odd value. At the image borders the gray values are mirrored.
Parameter
. Image (input iconic) . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, int4, real, int2,
uint2 )
Image for which the standard deviation is to be calculated.
. ImageDeviation (output iconic) . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, int4, real,
int2, uint2 )
Image containing the standard deviation.
. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; long / VARIANT
Width of the mask in which the standard deviation is calculated.
Default Value : 11
List of values : Width ∈ {3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25}
Restriction : (W idth ∧ odd)
. Height (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; long / VARIANT
Height of the mask in which the standard deviation is calculated.
Default Value : 11
List of values : Height ∈ {3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25}
Restriction : (Height ∧ odd)
Example

read_image(Image,’fabrik’)
disp_image(Image,WindowHandle)
deviation_image(Image,Deviation,9,9)
disp_image(Deviation,WindowHandle).

Result
DeviationImage returns TRUE if all parameters are correct. If the input is empty the behaviour can be set via
SetSystem(’noObjectResult’,<Result>). If necessary, an exception handling is raised.

HALCON/COM Reference Manual, 2008-5-13


3.16. TEXTURE 291

Parallelization Information
DeviationImage is reentrant and automatically parallelized (on tuple level, channel level, domain level).
Possible Successors
DispImage
See also
ConvolImage, TextureLaws, Intensity
Alternatives
EntropyImage, EntropyGray
Module
Foundation

[out] HImageX ImageEntropy HImageX.EntropyImage ([in] long Width,


[in] long Height )
void HOperatorSetX.EntropyImage ([in] IHObjectX Image,
[out] HUntypedObjectX ImageEntropy, [in] VARIANT Width, [in] VARIANT Height )

Calculate the entropy of gray values within a rectangular window.


EntropyImage calculates the entropy of gray values in the image Image within a rectangular mask of size
(Height, Width). The resulting image is returned in ImageEntropy, in which the entropy is multiplied by
32. If the parameters Height and Width are even, they are changed to the next larger odd value. At the image
borders the gray values are mirrored.
Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte )


Image for which the entropy is to be calculated.
. ImageEntropy (output iconic) . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX ( byte )
Entropy image.
. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; long / VARIANT
Width of the mask in which the entropy is calculated.
Default Value : 9
Suggested values : Width ∈ {3, 5, 7, 9, 11, 13, 15}
List of values : Width ∈ {3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25}
Restriction : (W idth ∧ odd)
. Height (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; long / VARIANT
Height of the mask in which the entropy is calculated.
Default Value : 9
Suggested values : Height ∈ {3, 5, 7, 9, 11, 13, 15}
List of values : Height ∈ {3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25}
Restriction : (Height ∧ odd)
Example

read_image(Image,’fabrik’)
disp_image(Image,WindowHandle)
entropy_image(Image,Entropy1,9,9)
disp_image(Entropy1,WindowHandle).

Result
EntropyImage returns TRUE if all parameters are correct. If the input is empty the behaviour can be set via
SetSystem(’noObjectResult’,<Result>). If necessary, an exception handling is raised.
Parallelization Information
EntropyImage is reentrant and automatically parallelized (on tuple level, channel level, domain level).
Possible Successors
DispImage

HALCON 8.0.2
292 CHAPTER 3. FILTER

See also
EnergyGabor, EntropyGray
Alternatives
EntropyGray
Module
Foundation

[out] HImageX ImageTexture HImageX.TextureLaws ([in] String FilterTypes,


[in] long Shift, [in] long FilterSize )
void HOperatorSetX.TextureLaws ([in] IHObjectX Image,
[out] HUntypedObjectX ImageTexture, [in] VARIANT FilterTypes,
[in] VARIANT Shift, [in] VARIANT FilterSize )

Filter an image using a Laws texture filter.


TextureLaws applies a texture transformations (according to Laws) to an image. This is done by convolving
the input image with a special filter mask. The filters are:
9 different 3x3 matrices obtainable from the following three vectors:

l = [ 1 2 1]
e = [−1 0 1]
s = [−1 2 −1]

25 different 5x5 matrices obtainable from the following five vectors:

l = [ 1 4 6 4 1]
e = [−1 −2 0 2 1]
s = [−1 0 2 0 −1]
r = [ 1 −4 6 −4 1]
w = [−1 2 0 −2 1]

36 different 7x7 matrices obtainable from the following six vectors:

l = [ 1 6 15 20 15 6 1]
e = [−1 −4 −5 0 5 4 1]
s = [−1 −2 1 4 1 −2 −1]
r = [−1 −2 −1 4 −1 −2 −1]
w = [−1 0 3 0 −3 0 1]
o = [−1 6 −15 20 −15 6 −1]

For most of the filters the resulting gray values must be modified by a Shift. This makes the different textures in
the output image more comparable to each other, provided suitable filters are used.
The name of the filter is composed of the letters of the two vectors used, where the first letter denotes convolution
in the column direction while the second letter denotes convolution in the row direction.
Parameter
. Image (input iconic) . . . . . . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, int2, uint2 )
Images to which the texture transformation is to be applied.
. ImageTexture (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX (
byte, int2, uint2 )
Texture images.
. FilterTypes (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Desired filters (name or number).
Default Value : ’el’
Suggested values : FilterTypes ∈ {’ll’, ’le’, ’ls’, ’lr’, ’lw’, ’lo’, ’el’, ’ee’, ’es’, ’er’, ’ew’, ’eo’, ’sl’, ’se’,
’ss’, ’sr’, ’sw’, ’so’, ’rl’, ’re’, ’rs’, ’rr’, ’rw’, ’ro’, ’wl’, ’we’, ’ws’, ’wr’, ’ww’, ’wo’, ’ol’, ’oe’, ’os’, ’or’, ’ow’,
’oo’}

HALCON/COM Reference Manual, 2008-5-13


3.16. TEXTURE 293

. Shift (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT


Shift to reduce the gray value dynamics.
Default Value : 2
List of values : Shift ∈ {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
. FilterSize (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Size of the filter kernel.
Default Value : 5
List of values : FilterSize ∈ {3, 5, 7}
Example

/* Two-dimensional pixel classification */


read_image(Image,’combine’)
open_window(0,0,-1,-1,’root’,’visible’,’’,WindowHandle)
disp_image(Image,WindowHandle)
texture_laws(Image,Texture1,’es’,2,5)
texture_laws(Image,Texture2,’le’,2,5)
mean_image(Texture1,H1,51,51)
mean_image(Texture2,H2,51,51)
fwrite_string(FileId,’mark desired image section’)
fnew_line(FileId)
set_color(WindowHandle,’green’)
draw_region(Region,WindowHandle)
reduce_domain(H1,Region,Foreground1)
reduce_domain(H2,Region,Foreground2)
histo_2dim(Region,Foreground1,Foreground2,Histo)
threshold(Histo,Characteristic_area,1,1000000)
set_color(WindowHandle,’blue’)
disp_region(Characteristic_area,WindowHandle)
class_2dim_sup(H1,H2,Characteristic_area,Seg,4,5)
set_color(WindowHandle,’red’)
disp_region(Seg,WindowHandle).

Result
TextureLaws returns TRUE if all parameters are correct. If the input is empty the behaviour can be set via
SetSystem(’noObjectResult’,<Result>). If necessary, an exception handling is raised.
Parallelization Information
TextureLaws is reentrant and automatically parallelized (on tuple level, channel level, domain level).
Possible Successors
MeanImage, BinomialFilter, GaussImage, MedianImage, Histo2Dim, LearnNdimNorm,
LearnNdimBox, Threshold
See also
Class2DimSup, ClassNdimNorm
Alternatives
ConvolImage
References
Laws, K.I. “Textured image segmentation”; Ph.D. dissertation, Dept. of Engineering, Univ. Southern California,
1980
Module
Foundation

HALCON 8.0.2
294 CHAPTER 3. FILTER

3.17 Wiener-Filter
void HImageX.GenPsfDefocus ([in] long PSFwidth, [in] long PSFheight,
[in] double Blurring )
void HOperatorSetX.GenPsfDefocus ([out] HUntypedObjectX Psf,
[in] VARIANT PSFwidth, [in] VARIANT PSFheight, [in] VARIANT Blurring )

Generate an impulse response of an uniform out-of-focus blurring.


GenPsfDefocus generates an impulse response (spatial domain) of an uniform out-of-focus blurring and writes
it into an image of HALCON image type ’real’. Blurring specifies the extent of blurring by defining the "‘blur
radius"’ (out-of-focus blurring maps each image pixel on a small circle with a radius of Blurring - specified
in "‘number of pixels"’). If specified less than zero, the absolute value of Blurring is used. The result image
of GenPsfDefocus encloses an spatial domain impulse response of the specified blurring. Its representation
presumes the origin in the upper left corner. This results in the following disposition of an N xM sized image:
• first rectangle ("‘upper left"’): (image coordinates xb = 0..(N/2) − 1, yb = 0..(M/2) − 1)
- conforms to the fourth quadrant of the Cartesian coordinate system, encloses values of the impulse response
at position x = 0..N/2 and y = 0.. − M/2
• second rectangle ("‘upper right"’): (image coordinates xb = N/2..N − 1, yb = 0..(M/2) − 1)
- conforms to the third quadrant of the Cartesian coordinate system, encloses values of the impulse response
at position x = −N/2.. − 1 and y = −1.. − M/2
• third rectangle ("‘lower left"’): (image coordinates xb = 0..(N/2) − 1, yb = M/2..M − 1)
- conforms to the first quadrant of the Cartesian coordinate system, encloses values of the impulse response
at position x = 1..N/2 and y = M/2..0
• fourth rectangle ("‘lower right"’): (image coordinates xb = N/2..N − 1, yb = M/2..M − 1)
- conforms to the second quadrant of the Cartesian coordinate system, encloses values of the impulse response
at position x = −N/2.. − 1 und y = M/2..1
This representation conforms to that of the impulse response parameter of the HALCON-operator
WienerFilter. So one can use GenPsfDefocus to generate an impulse response for Wiener filtering.
Parameter
. Psf (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / HUntypedObjectX ( real )
Impulse response of uniform out-of-focus blurring.
. PSFwidth (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Width of result image.
Default Value : 256
Suggested values : PSFwidth ∈ {128, 256, 512, 1024}
. PSFheight (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Height of result image.
Default Value : 256
Suggested values : PSFheight ∈ {128, 256, 512, 1024}
. Blurring (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Degree of Blurring.
Default Value : 5.0
Suggested values : Blurring ∈ {1.0, 5.0, 10.0, 15.0, 18.0}
Result
GenPsfDefocus returns TRUE if all parameters are correct.
Parallelization Information
GenPsfDefocus is reentrant and processed without parallelization.
Possible Predecessors
SimulateMotion, GenPsfMotion
Possible Successors
SimulateDefocus, WienerFilter, WienerFilterNi
See also
SimulateDefocus, GenPsfMotion, SimulateMotion, WienerFilter, WienerFilterNi

HALCON/COM Reference Manual, 2008-5-13


3.17. WIENER-FILTER 295

References
Reginald L. Lagendijk, Jan Biemond: Iterative Identification and Restoration of Images, Kluwer Academic Pub-
lishers Boston/Dordrecht/London, 1991
M. L"uckenhaus:"‘Grundlagen des Wiener-Filters und seine Anwendung in der Bildanalyse"’; Diplomarbeit; Tech-
nische Universit"at M"unchen, Institut f"ur Informatik; Lehrstuhl Prof. Radig; 1995.
Module
Foundation

void HImageX.GenPsfMotion ([in] long PSFwidth, [in] long PSFheight,


[in] double Blurring, [in] long Angle, [in] long Type )
void HOperatorSetX.GenPsfMotion ([out] HUntypedObjectX Psf,
[in] VARIANT PSFwidth, [in] VARIANT PSFheight, [in] VARIANT Blurring,
[in] VARIANT Angle, [in] VARIANT Type )

Generate an impulse response of a (linearly) motion blurring.


GenPsfMotion generates an impulse response (spatial domain) of a blurring caused by a relative motion between
the object and the camera during exposure. The generated impulse response is output into an image of HALCON
image type ’real’. PSFwidth and PSFheight define the width and height of the output image. The blurring
motion moves along an even. Angle fixes its direction by specifying the angle between the motion direction and
the x-axis (anticlockwise, measured in degrees). To specify different velocity behaviour five PSF prototypes can
be generated. Type switches between the following prototypes:

1. reverse ramp (crude model for acceleration)


2. reverse trapezoid (crude model for high acceleration)
3. square pulse (exact model for constant velocity), this is default
4. forward trapezoid (crude model for deceleration)
5. forward ramp (crude model for high deceleration)

The blurring affects all part of the image uniformly. Blurring controls the extent of blurring. It specifies the
number of pixels (lying one after another) that are affetcetd by the blurring. This number is determined by velocity
of the motion and exposure time. If Blurring is a negative number, an adequate blurring in reverse direction
is simulated. If Angle is a negative number, it is interpreted clockwise. If Angle exceeds 360 or falls below
-360, it is transformed modulo(360) in an adequate number between [0..360] resp. [−360..0]. The result image
of GenPsfMotion encloses an spatial domain impulse response of the specified blurring. Its representation
presumes the origin in the upper left corner. This results in the following disposition of an N xM sized image:
• first rectangle ("‘upper left"’): (image coordinates xb = 0..(N/2) − 1, yb = 0..(M/2) − 1)
- conforms to the fourth quadrant of the Cartesian coordinate system, encloses values of the impulse response
at position x = 0..N/2 and y = 0.. − M/2
• second rectangle ("‘upper right"’): (image coordinates xb = N/2..N − 1, yb = 0..(M/2) − 1)
- conforms to the third quadrant of the Cartesian coordinate system, encloses values of the impulse response
at position x = −N/2.. − 1 and y = −1.. − M/2
• third rectangle ("‘lower left"’): (image coordinates xb = 0..(N/2) − 1, yb = M/2..M − 1)
- conforms to the first quadrant of the Cartesian coordinate system, encloses values of the impulse response
at position x = 1..N/2 and y = M/2..0
• fourth rectangle ("‘lower right"’): (image coordinates xb = N/2..N − 1, yb = M/2..M − 1)
- conforms to the second quadrant of the Cartesian coordinate system, encloses values of the impulse response
at position x = −N/2.. − 1 und y = M/2..1
This representation conforms to that of the impulse response parameter of the HALCON-operator
WienerFilter. So one can use GenPsfMotion to generate an impulse response for Wiener filtering a
motion blurred image.

HALCON 8.0.2
296 CHAPTER 3. FILTER

Parameter

. Psf (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / HUntypedObjectX ( real )


Impulse response of motion-blur.
. PSFwidth (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Width of impulse response image.
Default Value : 256
Suggested values : PSFwidth ∈ {128, 256, 512, 1024}
. PSFheight (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Height of impulse response image.
Default Value : 256
Suggested values : PSFheight ∈ {128, 256, 512, 1024}
. Blurring (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Degree of motion-blur.
Default Value : 20.0
Suggested values : Blurring ∈ {5.0, 10.0, 20.0, 30.0, 40.0}
. Angle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Angle between direction of motion and x-axis (anticlockwise).
Default Value : 0
Suggested values : Angle ∈ {0, 45, 90, 180, 270}
. Type (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
PSF prototype resp. type of motion.
Default Value : 3
List of values : Type ∈ {1, 2, 3, 4, 5}
Result
GenPsfMotion returns TRUE if all parameters are correct.
Parallelization Information
GenPsfMotion is reentrant and processed without parallelization.
Possible Predecessors
GenPsfMotion, SimulateDefocus, GenPsfDefocus
Possible Successors
SimulateMotion, WienerFilter, WienerFilterNi
See also
SimulateMotion, SimulateDefocus, GenPsfDefocus, WienerFilter, WienerFilterNi
References
Anil K. Jain:Fundamentals of Digital Image Processing, Prentice-Hall International Inc., Englewood Cliffs, New
Jersey, 1989
M. L"uckenhaus:"‘Grundlagen des Wiener-Filters und seine Anwendung in der Bildanalyse"’; Diplomarbeit; Tech-
nische Universit"at M"unchen, Institut f"ur Informatik; Lehrstuhl Prof. Radig; 1995.
Kha-Chye Tan, Hock Lim, B. T. G. Tan:"‘Restoration of Real-World Motion-Blurred Images"’;S. 291-299 in:
CVGIP Graphical Models and Image Processing, Vol. 53, No. 3, May 1991
Module
Foundation

[out] HImageX DefocusedImage HImageX.SimulateDefocus


([in] double Blurring )
void HOperatorSetX.SimulateDefocus ([in] IHObjectX Image,
[out] HUntypedObjectX DefocusedImage, [in] VARIANT Blurring )

Simulate an uniform out-of-focus blurring of an image.


SimulateDefocus simulates out-of-focus blurring of an image. All parts of the image are blurred uniformly.
Blurring specifies the extent of blurring by defining the "‘blur radius"’ (out-of-focus blurring maps each image
pixel on a small circle with a radius of Blurring - specified in "‘number of pixels"’). If specified less than null,

HALCON/COM Reference Manual, 2008-5-13


3.17. WIENER-FILTER 297

the absolute value of Blurring is used. Simulation of blurring is done by a convolution of the image with a
blurring specific impulse response. The convolution is realized by multiplication in the Fourier domain.
Parameter

. Image (input iconic) . . . . . . image ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2, uint2, int4,
real )
Image to blur.
. DefocusedImage (output iconic) . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / HUntypedObjectX ( real )
Blurred image.
. Blurring (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Degree of blurring.
Default Value : 5.0
Suggested values : Blurring ∈ {1.0, 5.0, 10.0, 15.0, 18.0}
Result
SimulateDefocus returns TRUE if all parameters are correct. If the input is empty SimulateDefocus
returns with an error message.
Parallelization Information
SimulateDefocus is reentrant and processed without parallelization.
Possible Predecessors
GenPsfDefocus, SimulateMotion, GenPsfMotion
Possible Successors
WienerFilter, WienerFilterNi
See also
GenPsfDefocus, SimulateMotion, GenPsfMotion
References
Reginald L. Lagendijk, Jan Biemond: Iterative Identification and Restoration of Images, Kluwer Academic Pub-
lishers Boston/Dordrecht/London, 1991
M. L"uckenhaus:"‘Grundlagen des Wiener-Filters und seine Anwendung in der Bildanalyse"’; Diplomarbeit; Tech-
nische Universit"at M"unchen, Institut f"ur Informatik; Lehrstuhl Prof. Radig; 1995.
Module
Foundation

[out] HImageX MovedImage HImageX.SimulateMotion ([in] double Blurring,


[in] long Angle, [in] long Type )
void HOperatorSetX.SimulateMotion ([in] IHObjectX Image,
[out] HUntypedObjectX MovedImage, [in] VARIANT Blurring, [in] VARIANT Angle,
[in] VARIANT Type )

Simulation of (linearly) motion blur.


SimulateMotion simulates blurring caused by a relative motion between the object and the camera during
exposure. The simulated motion moves along an even. Angle fixes its direction by specifying the angle between
the motion direction and the x-axis (anticlockwise, measured in degrees). Simulation is done by a convolution of
the image with a blurring specific impulse response. The convolution is realized by multiplication in the Fourier
domain. SimulateMotion offers five prototypes of impulse responses conforming to different acceleration
behaviours. Type allows to choose one of the following PSF prototypes:

1. reverse ramp (crude model for acceleration)


2. reverse trapezoid (crude model for high acceleration)
3. square pulse (exact model for constant velocity), this is default
4. forward trapezoid (crude model for deceleration)
5. forward ramp (crude model for high deceleration)

HALCON 8.0.2
298 CHAPTER 3. FILTER

The simulated blurring affects all part of the image uniformly. Blurring controls the extent of blurring. It
specifies the number of pixels (lying one after another) that are affetcetd by the blurring. This number is determined
by velocity of the motion and exposure time. If Blurring is a negative number, an adequate blurring in reverse
direction is simulated. If Angle is a negative number, it is interpreted clockwise. If Angle exceeds 360 or falls
below -360, it is transformed modulo(360) in an adequate number between [0..360] resp. [−360..0].
Parameter
. Image (input iconic) . . . . . . image ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2, uint2, int4,
real )
image to be blurred.
. MovedImage (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / HUntypedObjectX ( real )
motion blurred image.
. Blurring (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
extent of blurring.
Default Value : 20.0
Suggested values : Blurring ∈ {5.0, 10.0, 20.0, 30.0, 40.0}
. Angle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Angle between direction of motion and x-axis (anticlockwise).
Default Value : 0
Suggested values : Angle ∈ {0, 45, 90, 180, 270}
. Type (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
impulse response of motion blur.
Default Value : 3
List of values : Type ∈ {1, 2, 3, 4, 5}
Result
SimulateMotion returns TRUE if all parameters are correct. If the input is empty SimulateMotion returns
with an error message.
Parallelization Information
SimulateMotion is reentrant and processed without parallelization.
Possible Predecessors
GenPsfMotion, GenPsfMotion
Possible Successors
SimulateDefocus, WienerFilter, WienerFilterNi
See also
GenPsfMotion, SimulateDefocus, GenPsfDefocus
References
Anil K. Jain:Fundamentals of Digital Image Processing, Prentice-Hall International Inc., Englewood Cliffs, New
Jersey, 1989
M. L"uckenhaus:"‘Grundlagen des Wiener-Filters und seine Anwendung in der Bildanalyse"’; Diplomarbeit; Tech-
nische Universit"at M"unchen, Institut f"ur Informatik; Lehrstuhl Prof. Radig; 1995.
Kha-Chye Tan, Hock Lim, B. T. G. Tan:"‘Restoration of Real-World Motion-Blurred Images"’;S. 291-299 in:
CVGIP Graphical Models and Image Processing, Vol. 53, No. 3, May 1991
Module
Foundation

[out] HImageX RestoredImage HImageX.WienerFilter ([in] HImageX Psf,


[in] HImageX FilteredImage )
void HOperatorSetX.WienerFilter ([in] IHObjectX Image,
[in] IHObjectX Psf, [in] IHObjectX FilteredImage,
[out] HUntypedObjectX RestoredImage )

Image restoration by Wiener filtering.


WienerFilter produces an estimate of the original image (= image without noise and blurring) by minimizing
the mean square error between estimated and original image. WienerFilter can be used to restore images

HALCON/COM Reference Manual, 2008-5-13


3.17. WIENER-FILTER 299

corrupted by noise and/or blurring (e.g. motion blur, atmospheric turbulence or out-of-focus blur). Method and
realisation of this restoration technique bases on the following model: The corrupted image is interpreted as the
output of a (disturbed) linear system. Functionality of a linear system is determined by its specific impuls response.
So the convolution of original image and impulse response results in the corrupted image. The specific impulse
response describes image acquisition and the occured degradations. In the presence of additive noise an additional
noise term must be considered. So the corrupted image can be modeled as the result of
[convolution(impulse_response, original_image)] + noise_term
The noise term encloses two different terms describing image-dependent and image-independent noise. According
to this model, two terms must be known for restoration by Wiener filtering:

1. degradation-specific impulse response


2. noise term

So WienerFilter needs a smoothed version of the input image to estimate the power spectral density of
noise and original image. One can use one of the smoothing HALCON-filters (e.g. EliminateMinMax)to
get this version. WienerFilter needs further the impulse response that describes the specific degradation.
This impulse response (represented in spatial domain) must fit into an image of HALCON image type ’real’.
There exist two HALCON-operators for generation of an impulse response for motion blur and out-of-focus (see
GenPsfMotion, GenPsfDefocus). The representation of the impulse response presumes the origin in the
upper left corner. This results in the following disposition of an N xM sized image:

• first rectangle ("‘upper left"’): (image coordinates xb = 0..(N/2) − 1, yb = 0..(M/2) − 1)


- conforms to the fourth quadrant of the Cartesian coordinate system, encloses values of the impulse response
at position x = 0..N/2 and y = 0.. − M/2
• second rectangle ("‘upper right"’): (image coordinates xb = N/2..N − 1, yb = 0..(M/2) − 1)
- conforms to the third quadrant of the Cartesian coordinate system, encloses values of the impulse response
at position x = −N/2.. − 1 and y = −1.. − M/2
• third rectangle ("‘lower left"’): (image coordinates xb = 0..(N/2) − 1, yb = M/2..M − 1)
- conforms to the first quadrant of the Cartesian coordinate system, encloses values of the impulse response
at position x = 1..N/2 and y = M/2..0
• fourth rectangle ("‘lower right"’): (image coordinates xb = N/2..N − 1, yb = M/2..M − 1)
- conforms to the second quadrant of the Cartesian coordinate system, encloses values of the impulse response
at position x = −N/2.. − 1 und y = M/2..1

WienerFilter works as follows:

• estimation of the power spectrum density of the original image by using the smoothed version of the corrupted
image,
• estimation of the power spectrum density of each pixel by subtracting smoothed version from unsmoothed
version,
• building the Wiener filter kernel with the quotient of power spectrum densities of noise and original image
and with the impulse response,
• processing the convolution of image and Wiener filter frequency response.

The result image has got image type ’real’.


Attention
Psf must be of image type ’real’ and conform to Image and FilteredImage in image width and height.
Parameter

. Image (input iconic) . . . . . . image ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2, uint2, int4,
real )
Corrupted image.
. Psf (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( real )
impulse response (PSF) of degradation (in spatial domain).
. FilteredImage (input iconic) . . . . . . image ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2,
uint2, int4, real )
Smoothed version of corrupted image.

HALCON 8.0.2
300 CHAPTER 3. FILTER

. RestoredImage (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / HUntypedObjectX ( real )


Restored image.
Result
WienerFilter returns TRUE if all parameters are correct. If the input is empty WienerFilter returns with
an error message.
Parallelization Information
WienerFilter is reentrant and processed without parallelization.
Possible Predecessors
GenPsfMotion, SimulateMotion, SimulateDefocus, GenPsfDefocus
See also
SimulateMotion, GenPsfMotion, SimulateDefocus, GenPsfDefocus
Alternatives
WienerFilterNi
References
M. L"uckenhaus:"‘Grundlagen des Wiener-Filters und seine Anwendung in der Bildanalyse"’; Diplomarbeit; Tech-
nische Universit"at M"unchen, Institut f"ur Informatik; Lehrstuhl Prof. Radig; 1995
Azriel Rosenfeld, Avinash C. Kak: Digital Picture Processing, Computer Science and Aplied Mathematics, Aca-
demic Press New York/San Francisco/London 1982
Module
Foundation

[out] HImageX RestoredImage HImageX.WienerFilterNi ([in] HImageX Psf,


[in] HRegionX NoiseRegion, [in] long MaskWidth, [in] long MaskHeight )
void HOperatorSetX.WienerFilterNi ([in] IHObjectX Image,
[in] IHObjectX Psf, [in] IHObjectX NoiseRegion,
[out] HUntypedObjectX RestoredImage, [in] VARIANT MaskWidth,
[in] VARIANT MaskHeight )

Image restoration by Wiener filtering.


WienerFilterNi (ni = noise-estimation integrated) produces an estimate of the original image (= im-
age without noise and blurring) by minimizing the mean square error between estimated and original image.
WienerFilter can be used to restore images corrupted by noise and/or blurring (e.g. motion blur, atmospheric
turbulence or out-of-focus blur). Method and realisation of this restoration technique bases on the following model:
The corrupted image is interpreted as the output of a (disturbed) linear system. Functionality of a linear system is
determined by its specific impuls response. So the convolution of original image and impulse response results in
the corrupted image. The specific impulse response describes image acquisition and the occured degradations. In
the presence of additive noise an additional noise term must be considered. So the corrupted image can be modeled
as the result of
[convolution(impulse_response, original_image)] + noise_term
The noise term encloses two different terms describing image-dependent and image-independent noise. According
to this model, two terms must be known for restoration by Wiener filtering:

1. degradation-specific impulse response


2. noise term

WienerFilterNi estimates the noise term as follows: The user defines a region that is suitable for noise
estimation within the image (homogeneous as possible, as edges or textures aggravate noise estimation). After
smoothing within this region by an (unweighted) median filter and subtracting smoothed version from unsmoothed,
the average noise amplitude of the region is processed within WienerFilterNi. This amplitude together with
the average gray value within the region allows estimating the quotient of the power spectral densities of noise and
original image (in contrast to WienerFilter WienerFilterNi assumes a rather constant quotient within
the whole image). The user can define width and height of the rectangular (median-)filter mask to influence the
noise estimation (MaskWidth, MaskHeight). WienerFilterNi needs further the impulse response that
describes the specific degradation. This impulse response (represented in spatial domain) must fit into an image

HALCON/COM Reference Manual, 2008-5-13


3.17. WIENER-FILTER 301

of HALCON image type ’real’. There exist two HALCON-operators for generation of an impulse response for
motion blur and out-of-focus (see GenPsfMotion, GenPsfDefocus). The representation of the impulse
response presumes the origin in the upper left corner. This results in the following disposition of an N xM sized
image:
• first rectangle ("‘upper left"’): (image coordinates xb = 0..(N/2) − 1, yb = 0..(M/2) − 1)
- conforms to the fourth quadrant of the Cartesian coordinate system, encloses values of the impulse response
at position x = 0..N/2 and y = 0.. − M/2
• second rectangle ("‘upper right"’): (image coordinates xb = N/2..N − 1, yb = 0..(M/2) − 1)
- conforms to the third quadrant of the Cartesian coordinate system, encloses values of the impulse response
at position x = −N/2.. − 1 and y = −1.. − M/2
• third rectangle ("‘lower left"’): (image coordinates xb = 0..(N/2) − 1, yb = M/2..M − 1)
- conforms to the first quadrant of the Cartesian coordinate system, encloses values of the impulse response
at position x = 1..N/2 and y = M/2..0
• fourth rectangle ("‘lower right"’): (image coordinates xb = N/2..N − 1, yb = M/2..M − 1)
- conforms to the second quadrant of the Cartesian coordinate system, encloses values of the impulse response
at position x = −N/2.. − 1 und y = M/2..1
WienerFilter works as follows:

• estimating the quotient of the power spectrum densities of noise and original image,
• building the Wiener filter kernel with the quotient of power spectrum densities of noise and original image
and with the impulse response,
• processing the convolution of image and Wiener filter frequency response.

The result image has got image type ’real’.


Attention
Psf must be of image type ’real’ and conform to Image in width and height. The Region used for noise estimation
must lie completely within the image. If MaskWidth or MaskHeight is an even number, it is replaced by the
next higher odd number (this allows the unique extraction of the center of the filter mask). Width/height of the
mask may not exceed the image width/height or be less than null.
Parameter
. Image (input iconic) . . . . . . image ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2, uint2, int4,
real )
Corrupted image.
. Psf (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( real )
impulse response (PSF) of degradation (in spatial domain).
. NoiseRegion (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
Region for noise estimation.
. RestoredImage (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / HUntypedObjectX ( real )
Restored image.
. MaskWidth (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Width of filter mask.
Default Value : 3
Suggested values : MaskWidth ∈ {3, 5, 7, 9}
Typical range of values : 0 ≤ MaskWidth ≤ 0
. MaskHeight (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Height of filter mask.
Default Value : 3
Suggested values : MaskHeight ∈ {3, 5, 7, 9}
Typical range of values : 0 ≤ MaskHeight ≤ 0
Result
WienerFilterNi returns TRUE if all parameters are correct. If the input is empty WienerFilterNi returns
with an error message.
Parallelization Information
WienerFilterNi is reentrant and processed without parallelization.

HALCON 8.0.2
302 CHAPTER 3. FILTER

Possible Predecessors
GenPsfMotion, SimulateMotion, SimulateDefocus, GenPsfDefocus
See also
SimulateMotion, GenPsfMotion, SimulateDefocus, GenPsfDefocus
Alternatives
WienerFilter
References
M. L"uckenhaus:"‘Grundlagen des Wiener-Filters und seine Anwendung in der Bildanalyse"’; Diplomarbeit; Tech-
nische Universit"at M"unchen, Institut f"ur Informatik; Lehrstuhl Prof. Radig; 1995
Azriel Rosenfeld, Avinash C. Kak: Digital Picture Processing, Computer Science and Aplied Mathematics, Aca-
demic Press New York/San Francisco/London 1982
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


Chapter 4

Graphics

4.1 Drawing

[out] HRegionX DestinationRegion HRegionX.DragRegion1


([in] HWindowX WindowHandle )
[out] HRegionX DestinationRegion HWindowX.DragRegion1
([in] HRegionX SourceRegion )
void HOperatorSetX.DragRegion1 ([in] IHObjectX SourceRegion,
[out] HUntypedObjectX DestinationRegion, [in] VARIANT WindowHandle )

Interactive moving of a region.


DragRegion1 is used to move a region on the display by mouse. Calling DragRegion1 turns the region visible
as soon as the left mouse button is pressed. Therefore the region’s edges are displayed only. As representation
mode the mode ’not’ (see SetDraw) is used during procedure’s permanence. During the movement the cursor
resides in the region’s barycenter. If you move the mouse with pressed left mouse button, the depicted region
follows - delayed - this movement. If you press the right mouse button you terminate DragRegion1. The
depicted region disappears from the display. Output is a region which corresponds to the last position on the
display. You may pass even several regions at once. Procedure AffineTransImage moves the gray values.
Attention
Gray values of regions are not moved. With moving the input region it is not sure whether the gray values of the
output regions are filled reasonable. This may occur if the gray values of the input regions do not comprise the
whole image.
Parameter

. SourceRegion (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX


Regions to move.
. DestinationRegion (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX
Moved Regions.
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window identifier.
Example

draw_region(Obj,WindowHandle)
drag_region1(Obj,New,WindowHandle)
disp_region(New,WindowHandle)
position(Obj,_,Row1,Column1,_,_,_,_)
position(New,_,Row2,Column2,_,_,_,_)
disp_arrow(WindowHandle,Row1,Column1,Row2,Column2,1.0)
fwrite_string([’Transformation: (’,Row2-Row1,’,’,Column2-Column1,’)’])
fnew_line().

303
304 CHAPTER 4. GRAPHICS

Result
DragRegion1 returns TRUE, if a region is entered, the window is valid and the needed drawing mode (see
SetInsert) is available. If necessary, an exception handling is raised. You may determine the behavior after an
empty input with SetSystem(::’noObjectResult’,<Result>:).
Parallelization Information
DragRegion1 is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow
Possible Successors
ReduceDomain, DispRegion, SetColored, SetLineWidth, SetDraw, SetInsert
See also
SetInsert, SetDraw, AffineTransImage
Alternatives
GetMposition, MoveRegion
Module
Foundation

[out] HRegionX DestinationRegion HRegionX.DragRegion2


([in] HWindowX WindowHandle, [in] long Row, [in] long Column )
[out] HRegionX DestinationRegion HWindowX.DragRegion2
([in] HRegionX SourceRegion, [in] long Row, [in] long Column )
void HOperatorSetX.DragRegion2 ([in] IHObjectX SourceRegion,
[out] HUntypedObjectX DestinationRegion, [in] VARIANT WindowHandle,
[in] VARIANT Row, [in] VARIANT Column )

Interactive movement of a region with fixpoint specification.


You use DragRegion2 to move a region on the display by mouse. It corresponds to the procedure
DragRegion1 with the difference, that the position of the mouse cursor can be determined.
Attention
Gray values of the regions are not moved. With moving the input region it is not sure whether the gray values of
the output regions are filled reasonable. This may occur if the gray values of the input regions do not comprise the
whole image.
Parameter
. SourceRegion (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
Regions to move.
. DestinationRegion (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX
Moved regions.
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window identifier.
. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; long / VARIANT
Row index of the reference point.
Default Value : 100
Suggested values : Row ∈ {0, 64, 128, 256, 512}
Typical range of values : 0 ≤ Row ≤ 0
. Column (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; long / VARIANT
Column index of the reference point.
Default Value : 100
Suggested values : Column ∈ {0, 64, 128, 256, 512}
Typical range of values : 0 ≤ Column ≤ 0
Result
DragRegion2 returns TRUE, if a region is entered, the window is valid and the needed drawing mode (see
SetInsert) is available. If necessary, an exception handling is raised. You may determine the behavior after an
empty input with SetSystem(::’noObjectResult’,<Result>:).

HALCON/COM Reference Manual, 2008-5-13


4.1. DRAWING 305

Parallelization Information
DragRegion2 is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow
Possible Successors
ReduceDomain, DispRegion, SetColored, SetLineWidth, SetDraw, SetInsert,
AffineTransImage
See also
SetInsert, SetDraw, AffineTransImage
Alternatives
GetMposition, MoveRegion, DragRegion1, DragRegion3
Module
Foundation

[out] HRegionX DestinationRegion HRegionX.DragRegion3


([in] HRegionX MaskRegion, [in] HWindowX WindowHandle, [in] long Row,
[in] long Column )
[out] HRegionX DestinationRegion HWindowX.DragRegion3
([in] HRegionX SourceRegion, [in] HRegionX MaskRegion, [in] long Row,
[in] long Column )
void HOperatorSetX.DragRegion3 ([in] IHObjectX SourceRegion,
[in] IHObjectX MaskRegion, [out] HUntypedObjectX DestinationRegion,
[in] VARIANT WindowHandle, [in] VARIANT Row, [in] VARIANT Column )

Interactive movement of a region with restriction of positions.


You use DragRegion3 to move a region on the display by mouse. It corresponds to the procedure
DragRegion2 with the enhancement, that all points are specified which can be entered by mouse. If you
move the mouse outside of this area (MaskRegion), the region on the point with the smallest distance inside
MaskRegion will be displayed.
Attention
The region’s gray values are not moved. With moving the input region it is not sure whether the gray values of
the output regions are filled reasonable. This may occur if the gray values of the input regions do not comprise the
whole image.
Parameter

. SourceRegion (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX


Regions to move.
. MaskRegion (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
Points on which it is allowed for a region to move.
. DestinationRegion (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX
Moved regions.
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window identifier.
. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; long / VARIANT
Row index of the reference point.
Default Value : 100
Suggested values : Row ∈ {0, 64, 128, 256, 512}
Typical range of values : 0 ≤ Row ≤ 0
. Column (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; long / VARIANT
Column index of the reference point.
Default Value : 100
Suggested values : Column ∈ {0, 64, 128, 256, 512}
Typical range of values : 0 ≤ Column ≤ 0

HALCON 8.0.2
306 CHAPTER 4. GRAPHICS

Result
DragRegion3 returns TRUE, if a region is entered, if the window is valid and the needed drawing mode (see
SetInsert) is available. If necessary, an exception handling is raised. You may determine the behavior after an
empty input with SetSystem(::’noObjectResult’,<Result>:).
Parallelization Information
DragRegion3 is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow, GetMposition
Possible Successors
ReduceDomain, DispRegion, SetColored, SetLineWidth, SetDraw, SetInsert,
AffineTransImage
See also
SetInsert, SetDraw, AffineTransImage
Alternatives
GetMposition, MoveRegion, DragRegion1, DragRegion2
Module
Foundation

[out] double Row HWindowX.DrawCircle ([out] double Column,


[out] double Radius )
void HOperatorSetX.DrawCircle ([in] VARIANT WindowHandle,
[out] VARIANT Row, [out] VARIANT Column, [out] VARIANT Radius )

Interactive drawing of a circle.


DrawCircle produces the parameter for a circle created interactive by the user in the window.
To create a circle you have to press the mouse button at the location which is used as the center of that circle. While
keeping the mouse button pressed, the Radius’s length can be modified through moving the mouse. After another
mouse click in the created circle center you can move it. A clicking close to the circular arc you can modify the
Radius of the circle. Pressing the right mousebutton terminates the procedure. After terminating the procedure
the circle is not visible in the window any longer.
Parameter
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window identifier.
. Row (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . circle.center.y ; double / VARIANT
Barycenter’s row index.
. Column (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . circle.center.x ; double / VARIANT
Barycenter’s column index.
. Radius (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . circle.radius ; double / VARIANT
Circle’s radius.
Example

read_image(Image,’affe’)
draw_circle(WindowHandle,Row,Column,Radius)
gen_circle(Circle,Row,Column,Radius,)
reduce_domain(Image,Circle,GrayCircle)
disp_image(GrayCircle,WindowHandle).

Result
DrawCircle returns TRUE if the window is valid and the needed drawing mode (see SetInsert) is available.
If necessary, an exception handling is raised.
Parallelization Information
DrawCircle is reentrant, local, and processed without parallelization.

HALCON/COM Reference Manual, 2008-5-13


4.1. DRAWING 307

Possible Predecessors
OpenWindow
Possible Successors
ReduceDomain, DispRegion, SetColored, SetLineWidth, SetDraw, SetInsert
See also
GenCircle, DrawRectangle1, DrawRectangle2, DrawPolygon, SetInsert
Alternatives
DrawCircleMod, DrawEllipse, DrawRegion
Module
Foundation

[out] double Row HWindowX.DrawCircleMod ([in] double RowIn,


[in] double ColumnIn, [in] double RadiusIn, [out] double Column,
[out] double Radius )
void HOperatorSetX.DrawCircleMod ([in] VARIANT WindowHandle,
[in] VARIANT RowIn, [in] VARIANT ColumnIn, [in] VARIANT RadiusIn,
[out] VARIANT Row, [out] VARIANT Column, [out] VARIANT Radius )

Interactive drawing of a circle.


DrawCircleMod produces the parameter for a circle created interactive by the user in the window.
To create a circle are expected the coordinates RowIn and ColumnIn of the center of a circle with radius
RadiusIn. After another mouse click in the created circle center you can move it. A clicking close to the
circular arc you can modify the Radius of the circle. Pressing the right mousebutton terminates the procedure.
After terminating the procedure the circle is not visible in the window any longer.
Parameter
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window identifier.
. RowIn (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . circle.center.y ; double / VARIANT
Row index of the center.
. ColumnIn (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . circle.center.x ; double / VARIANT
Column index of the center.
. RadiusIn (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . circle.radius1 ; double / VARIANT
Radius of the circle.
. Row (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . circle.center.y ; double / VARIANT
Barycenter’s row index.
. Column (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . circle.center.x ; double / VARIANT
Barycenter’s column index.
. Radius (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . circle.radius ; double / VARIANT
Circle’s radius.
Example

read_image(Image,’affe’)
draw_circle_mod(WindowHandle,20,20,15,Row,Column,Radius)
gen_circle(Circle,Row,Column,Radius,)
reduce_domain(Image,Circle,GrayCircle)
disp_image(GrayCircle,WindowHandle).

Result
DrawCircleMod returns TRUE if the window is valid and the needed drawing mode (see SetInsert) is
available. If necessary, an exception handling is raised.
Parallelization Information
DrawCircleMod is reentrant, local, and processed without parallelization.

HALCON 8.0.2
308 CHAPTER 4. GRAPHICS

Possible Predecessors
OpenWindow
Possible Successors
ReduceDomain, DispRegion, SetColored, SetLineWidth, SetDraw, SetInsert
See also
GenCircle, DrawRectangle1, DrawRectangle2, DrawPolygon, SetInsert
Alternatives
DrawCircle, DrawEllipse, DrawRegion
Module
Foundation

[out] double Row HWindowX.DrawEllipse ([out] double Column,


[out] double Phi, [out] double Radius1, [out] double Radius2 )
void HOperatorSetX.DrawEllipse ([in] VARIANT WindowHandle,
[out] VARIANT Row, [out] VARIANT Column, [out] VARIANT Phi,
[out] VARIANT Radius1, [out] VARIANT Radius2 )

Interactive drawing of an ellipse.


DrawEllipse returns the parameter for any orientated ellipse, which has been created interactively by the user
in the window.
The created ellipse is described by its center, its two half axes and the angle between the first half axis and the
horizontal coordinate axis.
To create an ellipse you have to determine the center of the ellipse with the left mouse button. Keeping the button
pressed determines the length (Radius1) and the orientation (Phi) of the first half axis. In doing so a temporary
default length for the second half axis is assumed, which may be modified afterwards on demand. After another
mouse click in the center of the created ellipse you can move it. A mouse click close to a vertex “grips” it to
modify the length of the appropriate half axis. You may modify the orientation only, if a vertex of the first half axis
is gripped.
Pressing the right mouse button terminates the procedure. After terminating the procedure the ellipse is not visible
in the window any longer.
Parameter
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window identifier.
. Row (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ellipse.center.y ; double / VARIANT
Row index of the center.
. Column (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ellipse.center.x ; double / VARIANT
Column index of the center.
. Phi (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ellipse.angle.rad ; double / VARIANT
Orientation of the first half axis in radians.
. Radius1 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ellipse.radius1 ; double / VARIANT
First half axis.
. Radius2 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ellipse.radius2 ; double / VARIANT
Second half axis.
Example

read_image(Image,’affe’)
draw_ellipse(WindowHandle,Row,Column,Phi,Radius1,Radius2)
gen_ellipse(Ellipse,Row,Column,Phi,Radius1,Radius2)
reduce_domain(Image,Ellipse,GrayEllipse)
sobel_amp(GrayEllipse,Sobel,’sum_abs’,3)
disp_image(Sobel,WindowHandle).

HALCON/COM Reference Manual, 2008-5-13


4.1. DRAWING 309

Result
DrawEllipse returns TRUE, if the window is valid and the needed drawing mode (see SetInsert) is avail-
able. If necessary, an exception handling is raised.
Parallelization Information
DrawEllipse is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow
Possible Successors
ReduceDomain, DispRegion, SetColored, SetLineWidth, SetDraw, SetInsert
See also
GenEllipse, DrawRectangle1, DrawRectangle2, DrawPolygon, SetInsert
Alternatives
DrawEllipseMod, DrawCircle, DrawRegion
Module
Foundation

[out] double Row HWindowX.DrawEllipseMod ([in] double RowIn,


[in] double ColumnIn, [in] double PhiIn, [in] double Radius1In,
[in] double Radius2In, [out] double Column, [out] double Phi,
[out] double Radius1, [out] double Radius2 )
void HOperatorSetX.DrawEllipseMod ([in] VARIANT WindowHandle,
[in] VARIANT RowIn, [in] VARIANT ColumnIn, [in] VARIANT PhiIn,
[in] VARIANT Radius1In, [in] VARIANT Radius2In, [out] VARIANT Row,
[out] VARIANT Column, [out] VARIANT Phi, [out] VARIANT Radius1,
[out] VARIANT Radius2 )

Interactive drawing of an ellipse.


DrawEllipseMod returns the parameter for any orientated ellipse, which has been created interactively by the
user in the window.
The created ellipse is described by its center, its two half axes and the angle between the first half axis and the
horizontal coordinate axis.
To create an ellipse are expected the parameters RowIn, ColumnIn,PhiIn,Radius1In,Radius2In. Keep-
ing the button pressed determines the length (Radius1) and the orientation (Phi) of the first half axis. In doing
so a temporary default length for the second half axis is assumed, which may be modified afterwards on demand.
After another mouse click in the center of the created ellipse you can move it. A mouse click close to a vertex
“grips” it to modify the length of the appropriate half axis. You may modify the orientation only, if a vertex of the
first half axis is gripped.
Pressing the right mouse button terminates the procedure. After terminating the procedure the ellipse is not visible
in the window any longer.
Parameter

. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT


Window identifier.
. RowIn (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ellipse.center.y ; double / VARIANT
Row index of the barycenter.
. ColumnIn (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ellipse.center.x ; double / VARIANT
Column index of the barycenter.
. PhiIn (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ellipse.angle.rad ; double / VARIANT
Orientation of the bigger half axis in radians.
. Radius1In (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ellipse.radius1 ; double / VARIANT
Bigger half axis.
. Radius2In (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ellipse.radius1 ; double / VARIANT
Smaller half axis.

HALCON 8.0.2
310 CHAPTER 4. GRAPHICS

. Row (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ellipse.center.y ; double / VARIANT


Row index of the center.
. Column (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ellipse.center.x ; double / VARIANT
Column index of the center.
. Phi (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ellipse.angle.rad ; double / VARIANT
Orientation of the first half axis in radians.
. Radius1 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ellipse.radius1 ; double / VARIANT
First half axis.
. Radius2 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ellipse.radius2 ; double / VARIANT
Second half axis.
Example

read_image(Image,’affe’)
draw_ellipse_mod(WindowHandle,RowIn,ColumnIn,PhiIn,Radius1In,Radius2In,Row,Column,Phi,Ra
gen_ellipse(Ellipse,Row,Column,Phi,Radius1,Radius2)
reduce_domain(Image,Ellipse,GrayEllipse)
sobel_amp(GrayEllipse,Sobel,’sum_abs’,3)
disp_image(Sobel,WindowHandle).

Result
DrawEllipseMod returns TRUE, if the window is valid and the needed drawing mode (see SetInsert) is
available. If necessary, an exception handling is raised.
Parallelization Information
DrawEllipseMod is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow
Possible Successors
ReduceDomain, DispRegion, SetColored, SetLineWidth, SetDraw, SetInsert
See also
GenEllipse, DrawRectangle1, DrawRectangle2, DrawPolygon, SetInsert
Alternatives
DrawEllipse, DrawCircle, DrawRegion
Module
Foundation

[out] double Row1 HWindowX.DrawLine ([out] double Column1,


[out] double Row2, [out] double Column2 )
void HOperatorSetX.DrawLine ([in] VARIANT WindowHandle,
[out] VARIANT Row1, [out] VARIANT Column1, [out] VARIANT Row2,
[out] VARIANT Column2 )

Draw a line.
DrawLine returns the parameter for a line, which has been created interactively by the user in the window.
To create a line you have to press the left mouse button determining a start point of the line. While keeping the
button pressed you may “drag” the line in any direction. After another mouse click in the middle of the created
line you can move it. If you click on one end point of the created line, you may move this point. Pressing the right
mousebutton terminates the procedure.
After terminating the procedure the line is not visible in the window any longer.

HALCON/COM Reference Manual, 2008-5-13


4.1. DRAWING 311

Parameter
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window identifier.
. Row1 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.begin.y ; double / VARIANT
Row index of the first point of the line.
. Column1 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.begin.x ; double / VARIANT
Column index of the first point of the line.
. Row2 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.end.y ; double / VARIANT
Row index of the second point of the line.
. Column2 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.end.x ; double / VARIANT
Column index of the second point of the line.
Example

get_system(’width’,Width)
get_system(’height’,Height)
set_part(WindowHandle,0,0,Width-1,Height-1)
read_image(Image,’affe’)
disp_image(Image,WindowHandle)
draw_line(WindowHandle,Row1,Column1,Row2,Column2)
set_part(WindowHandle,Row1,Column1,Row2,Column2)
disp_image(Image,WindowHandle)
fwrite_string([’Clipping = (’,Row1,’,’,Column1,’)’])
fwrite_string([’,(’,Row2,’,’,Column2,’)’])
fnew_line().

Result
DrawLine returns TRUE, if the window is valid and the needed drawing mode (see SetInsert) is available.
If necessary, an exception handling is raised.
Parallelization Information
DrawLine is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow
Possible Successors
ReduceDomain, DispLine, SetColored, SetLineWidth, SetDraw, SetInsert
See also
DrawLineMod, GenRectangle1, DrawCircle, DrawEllipse, SetInsert
Module
Foundation

[out] double Row1 HWindowX.DrawLineMod ([in] double Row1In,


[in] double Column1In, [in] double Row2In, [in] double Column2In,
[out] double Column1, [out] double Row2, [out] double Column2 )
void HOperatorSetX.DrawLineMod ([in] VARIANT WindowHandle,
[in] VARIANT Row1In, [in] VARIANT Column1In, [in] VARIANT Row2In,
[in] VARIANT Column2In, [out] VARIANT Row1, [out] VARIANT Column1,
[out] VARIANT Row2, [out] VARIANT Column2 )

Draw a line.
DrawLineMod returns the parameter for a line, which has been created interactively by the user in the window.
To create a line are expected the coordinates of the start point Row1In, Column1In and of the end point
Row2In,Column2In. If you click on one end point of the created line, you may move this point. After an-
other mouse click in the middle of the created line you can move it.
Pressing the right mousebutton terminates the procedure.

HALCON 8.0.2
312 CHAPTER 4. GRAPHICS

After terminating the procedure the line is not visible in the window any longer.
Parameter

. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT


Window identifier.
. Row1In (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.begin.y ; double / VARIANT
Row index of the first point of the line.
. Column1In (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.begin.x ; double / VARIANT
Column index of the first point of the line.
. Row2In (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.end.y ; double / VARIANT
Row index of the second point of the line.
. Column2In (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.end.x ; double / VARIANT
Column index of the second point of the line.
. Row1 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.begin.y ; double / VARIANT
Row index of the first point of the line.
. Column1 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.begin.x ; double / VARIANT
Column index of the first point of the line.
. Row2 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.end.y ; double / VARIANT
Row index of the second point of the line.
. Column2 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.end.x ; double / VARIANT
Column index of the second point of the line.
Example

get_system(’width’,Width)
get_system(’height’,Height)
set_part(WindowHandle,0,0,Width-1,Height-1)
read_image(Image,’affe’)
disp_image(Image,WindowHandle)
draw_line_mod(WindowHandle,10,20,55,124,Row1,Column1,Row2,Column2)
set_part(WindowHandle,Row1,Column1,Row2,Column2)
disp_image(Image,WindowHandle)
fwrite_string([’Clipping = (’,Row1,’,’,Column1,’)’])
fwrite_string([’,(’,Row2,’,’,Column2,’)’])
fnew_line().

Result
DrawLineMod returns TRUE, if the window is valid and the needed drawing mode is available. If necessary, an
exception handling is raised.
Parallelization Information
DrawLineMod is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow
Possible Successors
ReduceDomain, DispLine, SetColored, SetLineWidth, SetDraw, SetInsert
See also
GenCircle, DrawRectangle1, DrawRectangle2
Alternatives
DrawLine, DrawEllipse, DrawRegion
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


4.1. DRAWING 313

void HXLDContX.DrawNurbs ([in] HWindowX WindowHandle,


[in] String Rotate, [in] String Move, [in] String Scale,
[in] String KeepRatio, [in] long Degree, [out] VARIANT Rows,
[out] VARIANT Cols, [out] VARIANT Weights )
[out] HXLDContX ContOut HWindowX.DrawNurbs ([in] String Rotate,
[in] String Move, [in] String Scale, [in] String KeepRatio, [in] long Degree,
[out] VARIANT Rows, [out] VARIANT Cols, [out] VARIANT Weights )
void HOperatorSetX.DrawNurbs ([out] HUntypedObjectX ContOut,
[in] VARIANT WindowHandle, [in] VARIANT Rotate, [in] VARIANT Move,
[in] VARIANT Scale, [in] VARIANT KeepRatio, [in] VARIANT Degree,
[out] VARIANT Rows, [out] VARIANT Cols, [out] VARIANT Weights )

Interactive drawing of a NURBS curve.


DrawNurbs returns the contour ContOut and control information (Rows, Cols, and Weights) of
a NURBS curve of degree Degree, which has been created interactively by the user in the win-
dow WindowHandle. For additional information concerning NURBS curves, see the documentation of
GenContourNurbsXld. To use the control information Rows, Cols, and Weights in a subsequent call
to the operator GenContourNurbsXld, the knot vector Knots should be set to ’auto’.
The NURBS curve is created and manipulated by the means of its control polygon. By contrast, using the operator
DrawNurbsInterp, it is possible to create a NURBS curve that interpolates points specified by the user. Di-
rectly after calling DrawNurbs, you can add control points by clicking with the left mouse button in the window
at the desired positions.
When there are three control points or more, the first and the last point will be marked with an additional square.
By clicking on them you can close the curve or open it again. You delete the point appended last by pressing the
Ctrl key.
As soon as the number of control points exceeds Degree, the NURBS curve given by the specified control polygon
and weight vector is displayed in addition to the control polygon.
The control point which was handled last is surrounded by a circle representing its weight. By simply dragging the
circle you can increase or decrease the weight of this control point.
Existing control points can be moved by dragging them with the mouse. Further new points on the control polygon
(to refine the control polygon) can be inserted by a left click on the desired position on the control polygon.
By pressing the Shift key, you can switch into the transformation mode. In this mode you can rotate, move, and
scale the contour as a whole, but only if you set the parameters Rotate, Move, and Scale, respectively, to true.
Instead of the pick points and the control polygon, 3 symbols are displayed with the contour: a cross in the middle
and an arrow to the right if Rotate is set to true, and a double-headed arrow to the upper right if Scale is set to
true.
You can

• move the curve by clicking the left mouse button on the cross in the center and then dragging it to the new
position,
• rotate it by clicking with the left mouse button on the arrow and then dragging it, till the curve has the right
direction, and
• scale it by dragging the double arrow. To keep the ratio the parameter KeepRatio has to be set to true.

By pressing the Shift key again you can switch back to the edit mode. Pressing the right mouse button terminates
the procedure.
The appearance of the curve while drawing is determined by the line width, size, and color set via the operators
SetColor, SetColored, SetLineWidth, and SetLineStyle. The control polygon and all handles are
displayed in the second color set by SetColor or SetColored. Their line width is fixed to 1 and their line
style is fixed to a drawn-through line.

HALCON 8.0.2
314 CHAPTER 4. GRAPHICS

Parameter

. ContOut (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xld_cont ; HXLDContX / HUntypedObjectX


Contour approximating the NURBS curve.
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window identifier.
. Rotate (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Enable rotation?
Default Value : ’true’
List of values : Rotate ∈ {’true’, ’false’}
. Move (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Enable moving?
Default Value : ’true’
List of values : Move ∈ {’true’, ’false’}
. Scale (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Enable scaling?
Default Value : ’true’
List of values : Scale ∈ {’true’, ’false’}
. KeepRatio (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Keep ratio while scaling?
Default Value : ’true’
List of values : KeepRatio ∈ {’true’, ’false’}
. Degree (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
The degree p of the NURBS curve. Reasonable values are 3 to 25.
Default Value : 3
Suggested values : Degree ∈ {2, 3, 4, 5}
Restriction : (Degree ≥ 2)
. Rows (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . coordinates.y ; VARIANT
Row coordinates of the control polygon.
. Cols (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . coordinates.x ; VARIANT
Columns coordinates of the control polygon.
. Weights (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT
Weight vector.
Result
DrawNurbs returns TRUE, if the window is valid. If necessary, an exception handling is raised.
Parallelization Information
DrawNurbs is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow
Possible Successors
SetColored, SetLineWidth, SetDraw, SetInsert
See also
DrawNurbsMod, DrawNurbsInterp, GenContourNurbsXld
Alternatives
DrawXld, DrawNurbsInterp
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


4.1. DRAWING 315

void HXLDContX.DrawNurbsInterp ([in] HWindowX WindowHandle,


[in] String Rotate, [in] String Move, [in] String Scale,
[in] String KeepRatio, [in] long Degree, [out] VARIANT ControlRows,
[out] VARIANT ControlCols, [out] VARIANT Knots, [out] VARIANT Rows,
[out] VARIANT Cols, [out] VARIANT Tangents )
[out] HXLDContX ContOut HWindowX.DrawNurbsInterp ([in] String Rotate,
[in] String Move, [in] String Scale, [in] String KeepRatio, [in] long Degree,
[out] VARIANT ControlRows, [out] VARIANT ControlCols, [out] VARIANT Knots,
[out] VARIANT Rows, [out] VARIANT Cols, [out] VARIANT Tangents )
void HOperatorSetX.DrawNurbsInterp ([out] HUntypedObjectX ContOut,
[in] VARIANT WindowHandle, [in] VARIANT Rotate, [in] VARIANT Move,
[in] VARIANT Scale, [in] VARIANT KeepRatio, [in] VARIANT Degree,
[out] VARIANT ControlRows, [out] VARIANT ControlCols, [out] VARIANT Knots,
[out] VARIANT Rows, [out] VARIANT Cols, [out] VARIANT Tangents )

Interactive drawing of a NURBS curve using interpolation.


DrawNurbsInterp returns the contour ContOut of a NURBS curve of degree Degree, which has been
created interactively by the user in the window WindowHandle using interpolation. That means, that the user
specifies a set of points and the operator computes the parameters of a NURBS curve that includes this points. By
contrast, using the Operator DrawNurbs it is possible to create a NURBS curve by drawing its control polygon.
In addition to ContOut, the control information of the curve (ControlRows, ControlCols, and Knots), the
interpolation points (Rows, Cols) specified by the user and the tangents at the first and the last point (Tangents)
are returned. Tangents consists of four values. The first two values correspond to the y (row) and the x (column)
value of the tangent at the start of the curve and the second two values to the tangent at the end of the curve,
respectively.
The weight vector is not returned because it consists of equal entries. As a consequence, one can use ’auto’ as
weight vector if the control information is used in a subsequent call to the operator GenContourNurbsXld.
For more information on NURBS see the documentation of GenContourNurbsXld.
Directly after calling DrawNurbsInterp, you can add interpolation points by clicking with the left mouse
button in the window at the desired positions. If enough points are specified (at least Degree − 1), a NURBS
curve that goes through all specified points (in the order of their generation) is computed and displayed.
When there are three points or more, the first and the last point will be marked with an additional square. By
clicking on them you can close the curve or open it again. You delete the point appended last by pressing the Ctrl
key.
The tangents (i.e. the first derivative of the curve) of the first and the last point are displayed as lines. They can be
modified by dragging their ends using the mouse.
Existing points can be moved by dragging them with the mouse. Further new points on the curve can be inserted
by a left click on the desired position on the curve.
By pressing the Shift key, you can switch into the transformation mode. In this mode you can rotate, move, and
scale the curve as a whole, but only if you set the parameters Rotate, Move, and Scale, respectively, to true.
Instead of the pick points and the two tangents, 3 symbols are displayed with the curve: a cross in the middle and
an arrow to the right if Rotate is set to true, and a double-headed arrow to the upper right if Scale is set to true.
You can
• move the curve by clicking the left mouse button on the cross in the center and then dragging it to the new
position,
• rotate it by clicking with the left mouse button on the arrow and then dragging it, till the curve has the right
direction, and
• scale it by dragging the double arrow. To keep the ratio, the parameter KeepRatio has to be set to true.
By pressing the Shift key again you can switch back to the edit mode. Pressing the right mouse button terminates
the procedure.
The appearance of the curve while drawing is determined by the line width, size, and color set via the operators
SetColor, SetColored, SetLineWidth, and SetLineStyle. The tangents and all handles are dis-
played in the second color set by SetColor or SetColored. Their line width is fixed to 1 and their line style
is fixed to a drawn-through line.

HALCON 8.0.2
316 CHAPTER 4. GRAPHICS

Attention
In contrast to DrawNurbs, each point specified by the user influences the whole curve. Thus, if one point is
moved, the whole curve can and will change. To minimize this effects, it is recommended to use a small degree
(3-5) and to place the points such that they are approximately equally spaced. In general, uneven degrees will
perform slightly better than even degrees.
Parameter
. ContOut (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xld_cont ; HXLDContX / HUntypedObjectX
Contour of the curve.
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window identifier.
. Rotate (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Enable rotation?
Default Value : ’true’
List of values : Rotate ∈ {’true’, ’false’}
. Move (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Enable moving?
Default Value : ’true’
List of values : Move ∈ {’true’, ’false’}
. Scale (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Enable scaling?
Default Value : ’true’
List of values : Scale ∈ {’true’, ’false’}
. KeepRatio (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Keep ratio while scaling?
Default Value : ’true’
List of values : KeepRatio ∈ {’true’, ’false’}
. Degree (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
The degree p of the NURBS curve. Reasonable values are 3 to 5.
Default Value : 3
Suggested values : Degree ∈ {2, 3, 4, 5}
Restriction : ((Degree ≥ 2) ∧ (Degree ≤ 9))
. ControlRows (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . coordinates.y ; VARIANT
Row coordinates of the control polygon.
. ControlCols (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . coordinates.x ; VARIANT
Column coordinates of the control polygon.
. Knots (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT
Knot vector.
. Rows (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . coordinates.y ; VARIANT
Row coordinates of the points specified by the user.
. Cols (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . coordinates.x ; VARIANT
Column coordinates of the points specified by the user.
. Tangents (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT
Tangents specified by the user.
Result
DrawNurbsInterp returns TRUE, if the window is valid. If necessary, an exception handling is raised.
Parallelization Information
DrawNurbsInterp is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow
Possible Successors
SetColored, SetLineWidth, SetDraw, SetInsert
See also
DrawNurbsInterpMod, DrawNurbs, GenContourNurbsXld
Alternatives
DrawXld, DrawNurbs

HALCON/COM Reference Manual, 2008-5-13


4.1. DRAWING 317

Module
Foundation

void HXLDContX.DrawNurbsInterpMod ([in] HWindowX WindowHandle,


[in] String Rotate, [in] String Move, [in] String Scale,
[in] String KeepRatio, [in] String Edit, [in] long Degree,
[in] VARIANT RowsIn, [in] VARIANT ColsIn, [in] VARIANT TangentsIn,
[out] VARIANT ControlRows, [out] VARIANT ControlCols, [out] VARIANT Knots,
[out] VARIANT Rows, [out] VARIANT Cols, [out] VARIANT Tangents )
[out] HXLDContX ContOut HWindowX.DrawNurbsInterpMod
([in] String Rotate, [in] String Move, [in] String Scale,
[in] String KeepRatio, [in] String Edit, [in] long Degree,
[in] VARIANT RowsIn, [in] VARIANT ColsIn, [in] VARIANT TangentsIn,
[out] VARIANT ControlRows, [out] VARIANT ControlCols, [out] VARIANT Knots,
[out] VARIANT Rows, [out] VARIANT Cols, [out] VARIANT Tangents )
void HOperatorSetX.DrawNurbsInterpMod ([out] HUntypedObjectX ContOut,
[in] VARIANT WindowHandle, [in] VARIANT Rotate, [in] VARIANT Move,
[in] VARIANT Scale, [in] VARIANT KeepRatio, [in] VARIANT Edit,
[in] VARIANT Degree, [in] VARIANT RowsIn, [in] VARIANT ColsIn,
[in] VARIANT TangentsIn, [out] VARIANT ControlRows,
[out] VARIANT ControlCols, [out] VARIANT Knots, [out] VARIANT Rows,
[out] VARIANT Cols, [out] VARIANT Tangents )

Interactive modification of a NURBS curve using interpolation.


DrawNurbsInterpMod returns the contour ContOut of a NURBS curve of degree Degree, which has been
modified interactively by the user in the window WindowHandle.
In addition to ContOut the control information of the curve (ControlRows, ControlCols, and Knots), the
interpolation points (Rows, Cols) specified by the user and the tangents at the first and the last point (Tangents)
are returned. Tangents consists of four values. The first two values correspond to the y (row) and the x (column)
value of the tangent at the start of the curve and the second two values to the tangent at the end of the curve,
respectively.
The weight vector is not returned because it consists of equal entries. As a consequence one can use ’auto’ as
weight vector, if the control information is used in a subsequent call to the operator GenContourNurbsXld.
For more information on NURBS see the documentation of GenContourNurbsXld.
The input curve is specified by the interpolation points (RowsIn, ColsIn), its degree Degree and the tangents
TangentsIn, such that DrawNurbsInterpMod can be applied to the output data of DrawNurbsInterp.
You can modify the curve in two ways: by editing the interpolation points, e.g., by inserting or moving points, or
by transforming the curve as a whole, e.g., by rotating moving or scaling it. Note that you can only edit the curve
if Edit is set to true. Similarly, you can only rotate, move or scale it if Rotate, Move, and Scale, respectively,
are set to true.
DrawNurbsInterpMod starts in the transformation mode. In this mode, the curve is displayed together with 3
symbols: a cross in the middle and an arrow to the right if Rotate is set to true, and a double-headed arrow to
the upper right if Scale is set to true. To switch into the edit mode, press the Shift key; by pressing it again, you
can switch back into the transformation mode.
Transformation Mode
• To move the curve, click with the left mouse button on the cross in the center and then drag it to the new
position, i.e., keep the mouse button pressed while moving the mouse.
• To rotate it, click with the left mouse button on the arrow and then drag it, till the curve has the right direction.
• Scaling is achieved by dragging the double arrow. To keep the ratio, the parameter KeepRatio has to be
set to true.
Edit Mode
In this mode, the curve is displayed together with its interpolation points and the start and end tangent. Start and
end point are marked by an additional square. You can perform the following modifications:

HALCON 8.0.2
318 CHAPTER 4. GRAPHICS

• To append new points, click with the left mouse button in the window and a new point is added at this position.
• You can delete the point appended last by pressing the Ctrl key.
• To move a point, drag it with the mouse.
• To insert a point on the curve, click on the desired position on the curve.
• To close respectively open the curve, click on the first or on the last point.

Pressing the right mouse button terminates the procedure.


The appearance of the curve while drawing is determined by the line width, size and color set via the operators
SetColor, SetColored, SetLineWidth, and SetLineStyle. The tangents and all handles are dis-
played in the second color set by SetColor or SetColored. Their line width is fixed to 1 and their line style
is fixed to a drawn-through line.
Attention
In contrast to DrawNurbs, each point specified by the user influences the whole curve. Thus, if one point is
moved, the whole curve can and will change. To minimize this effects, it is recommended to use a small degree
(3-5) and to place the points such that they are approximately equally spaced. In general, uneven degrees will
perform slightly better than even degrees.
Parameter

. ContOut (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xld_cont ; HXLDContX / HUntypedObjectX


Contour of the modified curve.
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window identifier.
. Rotate (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Enable rotation?
Default Value : ’true’
List of values : Rotate ∈ {’true’, ’false’}
. Move (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Enable moving?
Default Value : ’true’
List of values : Move ∈ {’true’, ’false’}
. Scale (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Enable scaling?
Default Value : ’true’
List of values : Scale ∈ {’true’, ’false’}
. KeepRatio (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Keep ratio while scaling?
Default Value : ’true’
List of values : KeepRatio ∈ {’true’, ’false’}
. Edit (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Enable editing?
Default Value : ’true’
List of values : Edit ∈ {’true’, ’false’}
. Degree (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
The degree p of the NURBS curve. Reasonable values are 3 to 5.
Default Value : 3
Suggested values : Degree ∈ {2, 3, 4, 5}
Restriction : ((Degree ≥ 2) ∧ (Degree ≤ 9))
. RowsIn (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . coordinates.y ; VARIANT
Row coordinates of the input interpolation points.
. ColsIn (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . coordinates.x ; VARIANT
Column coordinates of the input interpolation points.
. TangentsIn (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT
Input tangents.
. ControlRows (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . coordinates.y ; VARIANT
Row coordinates of the control polygon.

HALCON/COM Reference Manual, 2008-5-13


4.1. DRAWING 319

. ControlCols (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . coordinates.x ; VARIANT


Column coordinates of the control polygon.
. Knots (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT
Knot vector.
. Rows (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . coordinates.y ; VARIANT
Row coordinates of the points specified by the user.
. Cols (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . coordinates.x ; VARIANT
Column coordinates of the points specified by the user.
. Tangents (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT
Tangents specified by the user.
Result
DrawNurbsInterpMod returns TRUE, if the window is valid. If necessary, an exception handling is raised.
Parallelization Information
DrawNurbsInterpMod is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow
Possible Successors
SetColored, SetLineWidth, SetDraw, SetInsert
See also
DrawNurbsInterp, GenContourNurbsXld
Alternatives
DrawXldMod, DrawNurbsMod
Module
Foundation

void HXLDContX.DrawNurbsMod ([in] HWindowX WindowHandle,


[in] String Rotate, [in] String Move, [in] String Scale,
[in] String KeepRatio, [in] String Edit, [in] long Degree,
[in] VARIANT RowsIn, [in] VARIANT ColsIn, [in] VARIANT WeightsIn,
[out] VARIANT Rows, [out] VARIANT Cols, [out] VARIANT Weights )
[out] HXLDContX ContOut HWindowX.DrawNurbsMod ([in] String Rotate,
[in] String Move, [in] String Scale, [in] String KeepRatio, [in] String Edit,
[in] long Degree, [in] VARIANT RowsIn, [in] VARIANT ColsIn,
[in] VARIANT WeightsIn, [out] VARIANT Rows, [out] VARIANT Cols,
[out] VARIANT Weights )
void HOperatorSetX.DrawNurbsMod ([out] HUntypedObjectX ContOut,
[in] VARIANT WindowHandle, [in] VARIANT Rotate, [in] VARIANT Move,
[in] VARIANT Scale, [in] VARIANT KeepRatio, [in] VARIANT Edit,
[in] VARIANT Degree, [in] VARIANT RowsIn, [in] VARIANT ColsIn,
[in] VARIANT WeightsIn, [out] VARIANT Rows, [out] VARIANT Cols,
[out] VARIANT Weights )

Interactive modification of a NURBS curve.


DrawNurbsMod returns the contour ContOut and control information (Rows, Cols, and Weights)
of a NURBS curve of degree Degree, which has been interactively modified by the user in the win-
dow WindowHandle. For additional information concerning NURBS curves, see the documentation of
GenContourNurbsXld. To use the control information Rows, Cols, and Weights in a subsequent call
to the operator GenContourNurbsXld, the knot vector Knots should be set to ’auto’.
The input NURBS curve is specified by its control polygon (RowsIn, ColsIn), its weight vector WeightsIn
and its degree Degree. The knot vector is assumed to be uniform (i.e. ’auto’ in GenContourNurbsXld).
You can modify the curve in two ways: by editing the control polygon, e.g., by inserting or moving control points,
or by transforming the contour as a whole, e.g., by rotating moving or scaling it. Note that you can only edit the

HALCON 8.0.2
320 CHAPTER 4. GRAPHICS

control polygon if Edit is set to true. Similarly, you can only rotate, move or scale it if Rotate, Move, and
Scale, respectively, are set to true.
DrawNurbsMod starts in the transformation mode. In this mode, the curve is displayed together with 3 symbols:
a cross in the middle and an arrow to the right if Rotate is set to true, and a double-headed arrow to the upper
right if Scale is set to true. To switch into the edit mode, press the Shift key; by pressing it again, you can switch
back into the transformation mode.
Transformation Mode

• To move the curve, click with the left mouse button on the cross in the center and then drag it to the new
position, i.e., keep the mouse button pressed while moving the mouse.
• To rotate it, click with the left mouse button on the arrow and then drag it, till the curve has the right direction.
• Scaling is achieved by dragging the double arrow. To keep the ratio, the parameter KeepRatio has to be
set to true.

Edit Mode
In this mode, the curve is displayed together with its control polygon. Start and end point are marked by an
additional square and the point which was handled last is surrounded by a circle representing its weight. You can
perform the following modifications:

• To append control points, click with the left mouse button in the window and a new point is added at this
position.
• You can delete the point appended last by pressing the Ctrl key.
• To move a point, drag it with the mouse.
• To insert a point on the control polygon, click on the desired position on the polygon.
• To close respectively open the curve, click on the first or on the last control point.
• You can modify the weight of a control point by first clicking on the point itself (if it is not already the point
which was modified or created last) and then dragging the circle around the point.

Pressing the right mouse button terminates the procedure.


The appearance of the curve while drawing is determined by the line width, size and color set via the operators
SetColor, SetColored, SetLineWidth, and SetLineStyle. The control polygon and all handles are
displayed in the second color set by SetColor or SetColored. Their line width is fixed to 1 and their line
style is fixed to a drawn-through line.
Parameter

. ContOut (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .xld_cont ; HXLDContX / HUntypedObjectX


Contour of the modified curve.
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window identifier.
. Rotate (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Enable rotation?
Default Value : ’true’
List of values : Rotate ∈ {’true’, ’false’}
. Move (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Enable moving?
Default Value : ’true’
List of values : Move ∈ {’true’, ’false’}
. Scale (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Enable scaling?
Default Value : ’true’
List of values : Scale ∈ {’true’, ’false’}
. KeepRatio (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Keep ratio while scaling?
Default Value : ’true’
List of values : KeepRatio ∈ {’true’, ’false’}

HALCON/COM Reference Manual, 2008-5-13


4.1. DRAWING 321

. Edit (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT


Enable editing?
Default Value : ’true’
List of values : Edit ∈ {’true’, ’false’}
. Degree (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
The degree p of the NURBS curve. Reasonable values are 3 to 25.
Default Value : 3
Suggested values : Degree ∈ {2, 3, 4, 5}
Restriction : (Degree ≥ 2)
. RowsIn (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . coordinates.y ; VARIANT
Row coordinates of the input control polygon.
. ColsIn (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . coordinates.x ; VARIANT
Column coordinates of the input control polygon.
. WeightsIn (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT
Input weight vector.
. Rows (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . coordinates.y ; VARIANT
Row coordinates of the control polygon.
. Cols (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . coordinates.x ; VARIANT
Columns coordinates of the control polygon.
. Weights (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT
Weight vector.
Result
DrawNurbsMod returns TRUE, if the window is valid. If necessary, an exception handling is raised.
Parallelization Information
DrawNurbsMod is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow
Possible Successors
SetColored, SetLineWidth, SetDraw, SetInsert
See also
DrawNurbs, DrawNurbsInterp, GenContourNurbsXld
Alternatives
DrawNurbsInterpMod, DrawXldMod
Module
Foundation

HWindowX.DrawPoint ([out] double Column )


[out] double Row
void HOperatorSetX.DrawPoint ([in] VARIANT WindowHandle,
[out] VARIANT Row, [out] VARIANT Column )

Draw a point.
DrawPoint returns the parameter for a point, which has been created interactively by the user in the window.
To create a point you have to press the left mouse button. While keeping the button pressed you may “drag” the
point in any direction. Pressing the right mousebutton terminates the procedure.
After terminating the procedure the point is not visible in the window any longer.
Parameter
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window identifier.
. Row (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; double / VARIANT
Row index of the point.
. Column (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; double / VARIANT
Column index of the point.

HALCON 8.0.2
322 CHAPTER 4. GRAPHICS

Example

get_system(’width’,Width)
get_system(’height’,Height)
set_part(WindowHandle,0,0,Width-1,Height-1)
read_image(Image,’affe’)
disp_image(Image,WindowHandle)
draw_point(WindowHandle,Row1,Column1)
disp_line(WindowHandle,Row1-2,Column1,Row1+2,Column1)
disp_line(WindowHandle,Row1,Column1-2,Row1,Column1+2)
disp_image(Image,WindowHandle)
fwrite_string([’Clipping = (’,Row1,’,’,Column1,’)’])
fnew_line().

Result
DrawPoint returns TRUE, if the window is valid and the needed drawing mode is available. If necessary, an
exception handling is raised.
Parallelization Information
DrawPoint is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow
Possible Successors
ReduceDomain, DispLine, SetColored, SetLineWidth, SetDraw, SetInsert
See also
DrawPointMod, DrawCircle, DrawEllipse, SetInsert
Module
Foundation

[out] double Row HWindowX.DrawPointMod ([in] double RowIn,


[in] double ColumnIn, [out] double Column )
void HOperatorSetX.DrawPointMod ([in] VARIANT WindowHandle,
[in] VARIANT RowIn, [in] VARIANT ColumnIn, [out] VARIANT Row,
[out] VARIANT Column )

Draw a point.
DrawPointMod returns the parameter for a point, which has been created interactively by the user in the window.
To create a point are expected the coordinates RowIn and ColumnIn. While keeping the button pressed you may
“drag” the point in any direction. Pressing the right mousebutton terminates the procedure.
After terminating the procedure the point is not visible in the window any longer.
Parameter

. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT


Window identifier.
. RowIn (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .point.y ; double / VARIANT
Row index of the point.
. ColumnIn (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; double / VARIANT
Column index of the point.
. Row (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; double / VARIANT
Row index of the point.
. Column (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; double / VARIANT
Column index of the point.

HALCON/COM Reference Manual, 2008-5-13


4.1. DRAWING 323

Example

get_system(’width’,Width)
get_system(’height’,Height)
set_part(WindowHandle,0,0,Width-1,Height-1)
read_image(Image,’affe’)
disp_image(Image,WindowHandle)
draw_point_mod(WindowHandle,Row1,Column1)
disp_line(WindowHandle,Row1-2,Column1,Row1+2,Column1)
disp_line(WindowHandle,Row1,Column1-2,Row1,Column1+2)
disp_image(Image,WindowHandle)
fwrite_string([’Clipping = (’,Row1,’,’,Column1,’)’])
fnew_line().

Result
DrawPointMod returns TRUE, if the window is valid and the needed drawing mode is available. If necessary,
an exception handling is raised.
Parallelization Information
DrawPointMod is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow
Possible Successors
ReduceDomain, DispLine, SetColored, SetLineWidth, SetDraw, SetInsert
See also
DrawPoint, DrawCircle, DrawEllipse, SetInsert
Module
Foundation

[out] HRegionX PolygonRegion HWindowX.DrawPolygon ( )


void HRegionX.DrawPolygon ([in] HWindowX WindowHandle )
void HOperatorSetX.DrawPolygon ([out] HUntypedObjectX PolygonRegion,
[in] VARIANT WindowHandle )

Interactive drawing of a polygon row.


DrawPolygon produces an image. The region of that image spans exactly the imagepoints entered interactively
by mouse clicks (gray values remain undefined).
Painting in the output window happens while pressing the left mouse button. Releasing the left mouse button and
repressing it at another position effects drawing a line between these two points. Pressing the right mouse button
terminates the input. Painting uses that color which has been set by SetColor, SetRgb, etc. .
To put gray values on the created PolygonRegion for further processing, you may use the procedure
ReduceDomain.
Attention
The painted contour is not closed automatically, in particular it is not “filled up” either.
Output object’s gray values are not defined.
Parameter

. PolygonRegion (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX


Region, which encompasses all painted points.
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window identifier.

HALCON 8.0.2
324 CHAPTER 4. GRAPHICS

Example

draw_polygon(Polygon,WindowHandle)
shape_trans(Polygon,Filled,’convex’)
disp_region(Filled,WindowHandle).

Result
If the window is valid, DrawPolygon returns TRUE. If necessary, an exception handling is raised.
Parallelization Information
DrawPolygon is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow
Possible Successors
ReduceDomain, DispRegion, SetColored, SetLineWidth, SetDraw
See also
ReduceDomain, FillUp, SetColor
Alternatives
DrawRegion, DrawCircle, DrawRectangle1, DrawRectangle2, Boundary
Module
Foundation

[out] double Row1 HWindowX.DrawRectangle1 ([out] double Column1,


[out] double Row2, [out] double Column2 )
void HOperatorSetX.DrawRectangle1 ([in] VARIANT WindowHandle,
[out] VARIANT Row1, [out] VARIANT Column1, [out] VARIANT Row2,
[out] VARIANT Column2 )

Draw a rectangle parallel to the coordinate axis.


DrawRectangle1 returns the parameter for a rectangle parallel to the coordinate axes, which has been created
interactively by the user in the window.
To create a rectangle you have to press the left mouse button determining a corner of the rectangle. While keeping
the button pressed you may “drag” the rectangle in any direction. After another mouse click in the middle of the
created rectangle you can move it. A click close to one side “grips” it to modify the rectangle’s dimension in
perpendicular direction to this side. If you click on one corner of the created rectangle, you may move this corner.
Pressing the right mousebutton terminates the procedure.
After terminating the procedure the rectangle is not visible in the window any longer.
Parameter

. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT


Window identifier.
. Row1 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.origin.y ; double / VARIANT
Row index of the left upper corner.
. Column1 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.origin.x ; double / VARIANT
Column index of the left upper corner.
. Row2 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.corner.y ; double / VARIANT
Row index of the right lower corner.
. Column2 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.corner.x ; double / VARIANT
Column index of the right lower corner.
Example

get_system(’width’,Width)
get_system(’height’,Height)

HALCON/COM Reference Manual, 2008-5-13


4.1. DRAWING 325

set_part(WindowHandle,0,0,Width-1,Height-1)
read_image(Image,’affe’)
disp_image(Image,WindowHandle)
draw_rectangle1(WindowHandle,Row1,Column1,Row2,Column2)
set_part(WindowHandle,Row1,Column1,Row2,Column2)
disp_image(Image,WindowHandle)
fwrite_string([’Clipping = (’,Row1,’,’,Column1,’)’])
fwrite_string([’,(’,Row2,’,’,Column2,’)’])
fnew_line().

Result
DrawRectangle1 returns TRUE, if the window is valid and the needed drawing mode (see SetInsert) is
available. If necessary, an exception handling is raised.
Parallelization Information
DrawRectangle1 is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow
Possible Successors
ReduceDomain, DispRegion, SetColored, SetLineWidth, SetDraw, SetInsert
See also
GenRectangle1, DrawCircle, DrawEllipse, SetInsert
Alternatives
DrawRectangle1Mod, DrawRectangle2, DrawRegion
Module
Foundation

[out] double Row1 HWindowX.DrawRectangle1Mod ([in] double Row1In,


[in] double Column1In, [in] double Row2In, [in] double Column2In,
[out] double Column1, [out] double Row2, [out] double Column2 )
void HOperatorSetX.DrawRectangle1Mod ([in] VARIANT WindowHandle,
[in] VARIANT Row1In, [in] VARIANT Column1In, [in] VARIANT Row2In,
[in] VARIANT Column2In, [out] VARIANT Row1, [out] VARIANT Column1,
[out] VARIANT Row2, [out] VARIANT Column2 )

Draw a rectangle parallel to the coordinate axis.


DrawRectangle1Mod returns the parameter for a rectangle parallel to the coordinate axes, which has been
created interactively by the user in the window.
To create a rectangle are expected the parameters Row1In, Column1In,Row2In und Column2In. After a
mouse click in the middle of the created rectangle you can move it. A click close to one side “grips” it to modify
the rectangle’s dimension in perpendicular direction to this side. If you click on one corner of the created rectangle,
you may move this corner. Pressing the right mousebutton terminates the procedure.
After terminating the procedure the rectangle is not visible in the window any longer.
Parameter
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window identifier.
. Row1In (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.origin.y ; double / VARIANT
Row index of the left upper corner.
. Column1In (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.origin.x ; double / VARIANT
Column index of the left upper corner.
. Row2In (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.corner.y ; double / VARIANT
Row index of the right lower corner.
. Column2In (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.corner.x ; double / VARIANT
Column index of the right lower corner.

HALCON 8.0.2
326 CHAPTER 4. GRAPHICS

. Row1 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.origin.y ; double / VARIANT


Row index of the left upper corner.
. Column1 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.origin.x ; double / VARIANT
Column index of the left upper corner.
. Row2 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.corner.y ; double / VARIANT
Row index of the right lower corner.
. Column2 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.corner.x ; double / VARIANT
Column index of the right lower corner.
Example

get_system(’width’,Width)
get_system(’height’,Height)
set_part(WindowHandle,0,0,Width-1,Height-1)
read_image(Image,’affe’)
disp_image(Image,WindowHandle)
draw_rectangle1_mod(WindowHandle,Row1In,Column1In,Row2In,Column2In,Row1,Column1,Row2,Col
set_part(WindowHandle,Row1,Column1,Row2,Column2)
disp_image(Image,WindowHandle)
fwrite_string([’Clipping = (’,Row1,’,’,Column1,’)’])
fwrite_string([’,(’,Row2,’,’,Column2,’)’])
fnew_line().

Result
DrawRectangle1Mod returns TRUE, if the window is valid and the needed drawing mode (see SetInsert)
is available. If necessary, an exception handling is raised.
Parallelization Information
DrawRectangle1Mod is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow
Possible Successors
ReduceDomain, DispRegion, SetColored, SetLineWidth, SetDraw, SetInsert
See also
GenRectangle1, DrawCircle, DrawEllipse, SetInsert
Alternatives
DrawRectangle1, DrawRectangle2, DrawRegion
Module
Foundation

[out] double Row HWindowX.DrawRectangle2 ([out] double Column,


[out] double Phi, [out] double Length1, [out] double Length2 )
void HOperatorSetX.DrawRectangle2 ([in] VARIANT WindowHandle,
[out] VARIANT Row, [out] VARIANT Column, [out] VARIANT Phi,
[out] VARIANT Length1, [out] VARIANT Length2 )

Interactive drawing of any orientated rectangle.


DrawRectangle2 returns the parameter for any orientated rectangle, which has been created interactively by
the user in the window.
The created rectangle is described by its center, its two half axes and the angle between the first half axis and the
horizontal coordinate axis.
To create a rectangle you have to press the left mouse button for the center of the rectangle. While keeping the
button pressed you may dimension the length (Length1) and the orientation (Phi) of the first half axis. In doing
so a temporary default length for the second half axis is assumed, which may be modified afterwards on demand.
After another mouse click in the middle of the created rectangle, you can move it. A click close to one side “grips”

HALCON/COM Reference Manual, 2008-5-13


4.1. DRAWING 327

it to modify the rectangle’s dimension in perpendicular direction to this side. You only can modify the orientation,
if you grip a side perpendicular to the first half axis. Pressing the right mouse button terminates the procedure.
After terminating the procedure the rectangle is not visible in the window any longer.
Parameter
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window identifier.
. Row (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle2.center.y ; double / VARIANT
Row index of the barycenter.
. Column (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle2.center.x ; double / VARIANT
Column index of the barycenter.
. Phi (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle2.angle.rad ; double / VARIANT
Orientation of the bigger half axis in radians.
. Length1 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle2.hwidth ; double / VARIANT
Bigger half axis.
. Length2 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle2.hheight ; double / VARIANT
Smaller half axis.
Result
DrawRectangle2 returns TRUE, if the window is valid and the needed drawing mode (see SetInsert) is
available. If necessary, an exception handling is raised.
Parallelization Information
DrawRectangle2 is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow
Possible Successors
ReduceDomain, DispRegion, SetColored, SetLineWidth, SetDraw, SetInsert
See also
GenRectangle2, DrawCircle, DrawEllipse, SetInsert
Alternatives
DrawRectangle2Mod, DrawRectangle1, DrawRegion
Module
Foundation

[out] double Row HWindowX.DrawRectangle2Mod ([in] double RowIn,


[in] double ColumnIn, [in] double PhiIn, [in] double Length1In,
[in] double Length2In, [out] double Column, [out] double Phi,
[out] double Length1, [out] double Length2 )
void HOperatorSetX.DrawRectangle2Mod ([in] VARIANT WindowHandle,
[in] VARIANT RowIn, [in] VARIANT ColumnIn, [in] VARIANT PhiIn,
[in] VARIANT Length1In, [in] VARIANT Length2In, [out] VARIANT Row,
[out] VARIANT Column, [out] VARIANT Phi, [out] VARIANT Length1,
[out] VARIANT Length2 )

Interactive drawing of any orientated rectangle.


DrawRectangle2Mod returns the parameter for any orientated rectangle, which has been created interactively
by the user in the window.
The created rectangle is described by its center, its two half axes and the angle between the first half axis and the
horizontal coordinate axis.
To create a rectangle are expected the parameters RowIn, ColumnIn,PhiIn,Length1In,Length2In. A
click close to one side “grips” it to modify the rectangle’s dimension in perpendicular direction (Length2) to this
side. You only can modify the orientation (Phi), if you grip a side perpendicular to the first half axis. After another
mouse click in the middle of the created rectangle, you can move it. Pressing the right mouse button terminates
the procedure.

HALCON 8.0.2
328 CHAPTER 4. GRAPHICS

After terminating the procedure the rectangle is not visible in the window any longer.
Parameter

. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT


Window identifier.
. RowIn (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle2.center.y ; double / VARIANT
Row index of the barycenter.
. ColumnIn (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle2.center.x ; double / VARIANT
Column index of the barycenter.
. PhiIn (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle2.angle.rad ; double / VARIANT
Orientation of the bigger half axis in radians.
. Length1In (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle2.hwidth ; double / VARIANT
Bigger half axis.
. Length2In (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle2.hheight ; double / VARIANT
Smaller half axis.
. Row (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle2.center.y ; double / VARIANT
Row index of the barycenter.
. Column (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle2.center.x ; double / VARIANT
Column index of the barycenter.
. Phi (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle2.angle.rad ; double / VARIANT
Orientation of the bigger half axis in radians.
. Length1 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle2.hwidth ; double / VARIANT
Bigger half axis.
. Length2 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle2.hheight ; double / VARIANT
Smaller half axis.
Result
DrawRectangle2Mod returns TRUE, if the window is valid and the needed drawing mode (see SetInsert)
is available. If necessary, an exception handling is raised.
Parallelization Information
DrawRectangle2Mod is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow
Possible Successors
ReduceDomain, DispRegion, SetColored, SetLineWidth, SetDraw, SetInsert
See also
GenRectangle2, DrawCircle, DrawEllipse, SetInsert
Alternatives
DrawRectangle2, DrawRectangle1, DrawRectangle2, DrawRegion
Module
Foundation

HWindowX.DrawRegion ( )
[out] HRegionX Region
void HRegionX.DrawRegion ([in] HWindowX WindowHandle )
void HOperatorSetX.DrawRegion ([out] HUntypedObjectX Region,
[in] VARIANT WindowHandle )

Interactive drawing of a closed region.


DrawRegion produces an image. The region of that image spans exactly the image region entered interactively
by mouse clicks (gray values remain undefined). Painting happens in the output window while keeping the left
mouse button pressed. The left mouse button even operates by clicking in the output window; through this a line
between the previous clicked points is drawn. Clicking the right mouse button terminates input and closes the
outline. Subsequently the image is “filled up”. Also it contains the whole image area enclosed by the mouse.

HALCON/COM Reference Manual, 2008-5-13


4.1. DRAWING 329

Painting uses that color which has been set by SetColor, SetRgb, etc. .
Attention
The output object’s gray values are not defined.
Parameter
. Region (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX
Interactive created region.
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window identifier.
Example

read_image(Image,’fabrik’)
disp_image(Image,WindowHandle)
draw_region(Region,WindowHandle)
reduce_domain(Image,Region,New)
regiongrowing(New,Segmente,5,5,6,50)
set_colored(WindowHandle,12)
disp_region(Segmente,WindowHandle).

Result
If the window is valid, DrawRegion returns TRUE. If necessary, an exception handling is raised.
Parallelization Information
DrawRegion is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow
Possible Successors
ReduceDomain, DispRegion, SetColored, SetLineWidth, SetDraw
See also
DrawPolygon, ReduceDomain, FillUp, SetColor
Alternatives
DrawCircle, DrawEllipse, DrawRectangle1, DrawRectangle2
Module
Foundation

void HXLDContX.DrawXld ([in] HWindowX WindowHandle, [in] String Rotate,


[in] String Move, [in] String Scale, [in] String KeepRatio )
[out] HXLDContX ContOut HWindowX.DrawXld ([in] String Rotate,
[in] String Move, [in] String Scale, [in] String KeepRatio )
void HOperatorSetX.DrawXld ([out] HUntypedObjectX ContOut,
[in] VARIANT WindowHandle, [in] VARIANT Rotate, [in] VARIANT Move,
[in] VARIANT Scale, [in] VARIANT KeepRatio )

Interactive drawing of a contour.


DrawXld returns a contour, which has been created interactively by the user in the window.
Directly after calling DrawXld you can add contour points by clicking with the left mouse button in the window
at the desired positions. You delete the point appended last by pressing the Ctrl key. As soon as you add three
contour points, 5 so-called pick points are displayed, one in the middle and 4 at the corners of the surrounding
rectangle. By clicking on a pick point you can close the contour or open it again. If the contour is closed, the pick
points are displayed in form of squares, otherwise they are shaped like a ’u’.
If the contour is closed you can
• move contour points by clicking with the left mouse button on a point marked by a rectangle and keep the
mouse button pressed while moving the mouse,

HALCON 8.0.2
330 CHAPTER 4. GRAPHICS

• insert contour points by clicking with the left mouse button in the vicinity of a line and then move the mouse
to the position where you want the new point to be placed, and
• delete contour points by selecting the point which should be deleted with the left mouse button and then press
the Ctrl key.

By pressing the Shift key, you can switch into the transformation mode. In this mode you can rotate, move, and
scale the contour as a whole, but only if you set the parameters Rotate, Move, and Scale, respectively, to true.
Instead of the pick points, 3 symbols are displayed with the contour: a cross in the middle and an arrow to the right
if Rotate is set to true, and a double-headed arrow to the upper right if Scale is set to true.
You can

• move the contour by clicking the left mouse button on the cross in the center and then dragging it to the new
position,
• rotate it by clicking with the left mouse button on the arrow and then dragging it, till the contour has the right
direction, and
• scale it by dragging the double arrow. To keep the ratio the parameter KeepRatio has to be set to true.

Pressing the right mouse button terminates the procedure.


Parameter

. ContOut (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xld_cont ; HXLDContX / HUntypedObjectX


Modified contour.
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window identifier.
. Rotate (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Enable rotation?
Default Value : ’true’
List of values : Rotate ∈ {’true’, ’false’}
. Move (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Enable moving?
Default Value : ’true’
List of values : Move ∈ {’true’, ’false’}
. Scale (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Enable scaling?
Default Value : ’true’
List of values : Scale ∈ {’true’, ’false’}
. KeepRatio (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Keep ratio while scaling?
Default Value : ’true’
List of values : KeepRatio ∈ {’true’, ’false’}
Result
DrawXld returns TRUE, if the window is valid and the needed drawing mode (see SetInsert) is available. If
necessary, an exception handling is raised.
Parallelization Information
DrawXld is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow
Possible Successors
ReduceDomain, DispRegion, SetColored, SetLineWidth, SetDraw, SetInsert
See also
GenRectangle2, DrawCircle, DrawEllipse, SetInsert
Alternatives
DrawRectangle2, DrawRectangle1, DrawRectangle2, DrawRegion
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


4.1. DRAWING 331

[out] HXLDContX ContOut HXLDContX.DrawXldMod


([in] HWindowX WindowHandle, [in] String Rotate, [in] String Move,
[in] String Scale, [in] String KeepRatio, [in] String Edit )
[out] HXLDContX ContOut HWindowX.DrawXldMod ([in] HXLDContX ContIn,
[in] String Rotate, [in] String Move, [in] String Scale,
[in] String KeepRatio, [in] String Edit )
void HOperatorSetX.DrawXldMod ([in] IHObjectX ContIn,
[out] HUntypedObjectX ContOut, [in] VARIANT WindowHandle,
[in] VARIANT Rotate, [in] VARIANT Move, [in] VARIANT Scale,
[in] VARIANT KeepRatio, [in] VARIANT Edit )

Interactive modification of a contour.


DrawXldMod returns a contour, which has been interactively modified by the user in the window.
You can modify the contour in two ways: by editing the contour itself, e.g., by inserting or moving contour points,
or by transforming the contour as a whole, e.g., by rotating moving or scaling it. Note that you can only edit a
contour if Edit is set to true. Similarly, you can only rotate, move or scale it if Rotate, Move, and Scale,
respectively, are set to true.
DrawXldMod starts in the transformation mode. In this mode, the contour is displayed together with 3 symbols:
a cross in the middle and an arrow to the right if Rotate is set to true, and a double-headed arrow to the upper
right if Scale is set to true. To switch into the edit mode, press the Shift key; by pressing it again, you can switch
back into the transformation mode.
Transformation Mode
• To move the contour, click with the left mouse button on the cross in the center and then drag it to the new
position´, i.e., keep the mouse button pressed while moving the mouse.
• To rotate it, click with the left mouse button on the arrow and then drag it, till the contour has the right
direction.
• Scaling is achieved by dragging the double arrow. To keep the ratio the parameter KeepRatio has to be set
to true.
Edit Mode In this mode, the contour is display together with 5 pick points, which are located in the middle and
at the corners of the surrounding rectangle. If the contour is closed, the pick points are displayed as squares,
otherwise shaped like a ’u’. By clicking on a pick point, you can close an open contour and vice versa. Depending
on the state of the contour, you can perform different modifications. Open contours (pick points shaped like a ’u’)
• To append points, click with the left mouse button in the window and a new point is added at this position.
• You can delete the point appended last by pressing the Ctrl key.
• To move or insert points, you must first close the contour by clicking on one of the pick points.
Closed contours (square pick points)
• To move a point, click with the left mouse button on a point marked by a rectangle and then drag it to the
new position.
• To insert a point, click with the left mouse button in the vicinity of a line and then move the mouse to the
position where you want the new point to be placed.
• To delete a point, select the point which should be deleted with the left mouse button and then press the Ctrl
key.
Pressing the right mouse button terminates the procedure.
Parameter
. ContIn (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xld_cont ; HXLDContX / IHObjectX
Input contour.
. ContOut (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .xld_cont ; HXLDContX / HUntypedObjectX
Modified contour.
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window identifier.

HALCON 8.0.2
332 CHAPTER 4. GRAPHICS

. Rotate (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT


Enable rotation?
Default Value : ’true’
List of values : Rotate ∈ {’true’, ’false’}
. Move (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Enable moving?
Default Value : ’true’
List of values : Move ∈ {’true’, ’false’}
. Scale (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Enable scaling?
Default Value : ’true’
List of values : Scale ∈ {’true’, ’false’}
. KeepRatio (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Keep ratio while scaling?
Default Value : ’true’
List of values : KeepRatio ∈ {’true’, ’false’}
. Edit (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Enable editing?
Default Value : ’true’
List of values : Edit ∈ {’true’, ’false’}
Result
DrawXldMod returns TRUE, if the window is valid and the needed drawing mode (see SetInsert) is available.
If necessary, an exception handling is raised.
Parallelization Information
DrawXldMod is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow
Possible Successors
ReduceDomain, DispRegion, SetColored, SetLineWidth, SetDraw, SetInsert
See also
GenRectangle2, DrawCircle, DrawEllipse, SetInsert
Alternatives
DrawRectangle2, DrawRectangle1, DrawRectangle2, DrawRegion
Module
Foundation

4.2 Gnuplot

void HOperatorSetX.GnuplotClose ([in] VARIANT GnuplotFileID )

Close all open gnuplot files or terminate an active gnuplot sub-process.


GnuplotClose closes all gnuplot files opened by GnuplotOpenFile or terminates the gnuplot sub-process
created with GnuplotOpenPipe. In the latter case, all temporary files used to display images and control values
are deleted. This means that GnuplotClose must be called after such a plot sequence. GnuplotFileID is
the identifier of the corresponding gnuplot output stream.
Parameter
. GnuplotFileID (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . gnuplot_id ; HGnuplotX / VARIANT
Identifier for the gnuplot output stream.
Result
GnuplotClose returns TRUE if GnuplotFileID is a valid gnuplot output stream. Otherwise, an exception
handling is raised.
Parallelization Information
GnuplotClose is processed completely exclusively without parallelization.

HALCON/COM Reference Manual, 2008-5-13


4.2. GNUPLOT 333

Possible Predecessors
GnuplotOpenPipe, GnuplotOpenFile, GnuplotPlotImage
See also
GnuplotOpenPipe, GnuplotOpenFile, GnuplotPlotImage
Module
Foundation

void HGnuplotX.GnuplotOpenFile ([in] String FileName )


void HOperatorSetX.GnuplotOpenFile ([in] VARIANT FileName,
[out] VARIANT GnuplotFileID )

Open a gnuplot file for visualization of images and control values.


GnuplotOpenFile allows the output of images and control values in a format which can be later
processed by gnuplot. The parameter FileName determines the base-name of the files to be created
by calls to GnuplotPlotImage. GnuplotOpenFile generates a gnuplot control file with the
name <FileName>.gp, in which the respective plot commands are written. Each image plotted by
GnuplotPlotImage (or control values plotted by GnuplotPlotCtrl) creates a data file with the name
<FileName>.dat.<Number>, where Number is the number of the plot in the current sequence. The gener-
ated control file can later be edited to create the desired effect. After the last plot GnuplotClose has to be
called in order to close all open files. The corresponding identifier for the gnuplot output stream is returned in
GnuplotFileID.
Parameter
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.read ; String / VARIANT
Base name for control and data files.
. GnuplotFileID (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . gnuplot_id ; HGnuplotX / VARIANT
Identifier for the gnuplot output stream.
Result
GnuplotOpenFile returns the value TRUE if the control file could be opened. Otherwise, an exception han-
dling is raised.
Parallelization Information
GnuplotOpenFile is processed completely exclusively without parallelization.
Possible Successors
GnuplotPlotImage, GnuplotClose
See also
GnuplotOpenPipe, GnuplotClose, GnuplotPlotImage
Alternatives
GnuplotOpenPipe
Module
Foundation

void HGnuplotX.GnuplotOpenPipe ( )
void HOperatorSetX.GnuplotOpenPipe ([out] VARIANT GnuplotFileID )

Open a pipe to a gnuplot process for visualization of images and control values.
GnuplotOpenPipe opens a pipe to a gnuplot sub-process with which subsequently images can be visualized
as 3D-plots ( GnuplotPlotImage) or control values can be visualized as 2D-plots ( GnuplotPlotCtrl).
The sub-process must be terminated after displaying the last plot by calling GnuplotClose. The corresponding
identifier for the gnuplot output stream is returned in GnuplotFileID.
Attention
GnuplotOpenPipe is only implemented for Unix because gnuplot for Windows (wgnuplot) cannot be con-
trolled by an external process.

HALCON 8.0.2
334 CHAPTER 4. GRAPHICS

Parameter
. GnuplotFileID (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . gnuplot_id ; HGnuplotX / VARIANT
Identifier for the gnuplot output stream.
Result
GnuplotOpenPipe returns the value TRUE if the sub-process could be created. Otherwise, an exception han-
dling is raised.
Parallelization Information
GnuplotOpenPipe is processed completely exclusively without parallelization.
Possible Successors
GnuplotPlotImage, GnuplotPlotCtrl, GnuplotClose
Alternatives
GnuplotOpenFile
Module
Foundation

void HGnuplotX.GnuplotPlotCtrl ([in] VARIANT Values )


void HOperatorSetX.GnuplotPlotCtrl ([in] VARIANT GnuplotFileID,
[in] VARIANT Values )

Plot control values using gnuplot.


GnuplotPlotCtrl displays a tuple of control values using gnuplot. If there is an active gnuplot sub-process
(started with GnuplotOpenPipe), the image is displayed in a gnuplot window. Otherwise, the image is
output to a file, which can be later read by gnuplot. In both cases the gnuplot output stream is identified by
GnuplotFileID.
Parameter
. GnuplotFileID (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . gnuplot_id ; HGnuplotX / VARIANT
Identifier for the gnuplot output stream.
. Values (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Control values to be plotted (y-values).
Result
GnuplotPlotCtrl returns the value if GnuplotFileID is a valid gnuplot output stream, if the data file for
the current plot could be opened, and if only integer or floating point values were passed. Otherwise, an exception
handling is raised.
Parallelization Information
GnuplotPlotCtrl is processed completely exclusively without parallelization.
Possible Predecessors
GnuplotOpenPipe, GnuplotOpenFile
Possible Successors
GnuplotClose
See also
GnuplotOpenPipe, GnuplotOpenFile, GnuplotClose
Module
Foundation

void HFunction1dX.GnuplotPlotFunct1D ([in] long GnuplotFileID )


void HGnuplotX.GnuplotPlotFunct1D ([in] HFunction1dX Function )
void HOperatorSetX.GnuplotPlotFunct1D ([in] VARIANT GnuplotFileID,
[in] VARIANT Function )

Plot a function using gnuplot.

HALCON/COM Reference Manual, 2008-5-13


4.2. GNUPLOT 335

GnuplotPlotCtrl displays a function of control values using gnuplot. If there is an active gnuplot sub-process
(started with GnuplotOpenPipe), the image is displayed in a gnuplot window. Otherwise, the image is
output to a file, which can be later read by gnuplot. In both cases the gnuplot output stream is identified by
GnuplotFileID.
Parameter
. GnuplotFileID (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . gnuplot_id ; long / HGnuplotX / VARIANT
Identifier for the gnuplot output stream.
. Function (input control) . . . . . . . . . . . . . . . . . . . . function_1d ; HFunction1dX / VARIANT ( real, integer )
Function to be plotted.
Result
GnuplotPlotCtrl returns TRUE if GnuplotFileID is a valid gnuplot output stream, and if the data file for
the current plot could be opened. Otherwise, an exception handling is raised.
Parallelization Information
GnuplotPlotFunct1D is processed completely exclusively without parallelization.
Possible Predecessors
GnuplotOpenPipe, GnuplotOpenFile
Possible Successors
GnuplotClose
See also
GnuplotOpenPipe, GnuplotOpenFile, GnuplotClose
Alternatives
GnuplotPlotCtrl
Module
Foundation

void HImageX.GnuplotPlotImage ([in] long GnuplotFileID,


[in] long SamplesX, [in] long SamplesY, [in] VARIANT ViewRotX,
[in] VARIANT ViewRotZ, [in] String Hidden3D )
void HGnuplotX.GnuplotPlotImage ([in] HImageX Image,
[in] long SamplesX, [in] long SamplesY, [in] VARIANT ViewRotX,
[in] VARIANT ViewRotZ, [in] String Hidden3D )
void HOperatorSetX.GnuplotPlotImage ([in] IHObjectX Image,
[in] VARIANT GnuplotFileID, [in] VARIANT SamplesX, [in] VARIANT SamplesY,
[in] VARIANT ViewRotX, [in] VARIANT ViewRotZ, [in] VARIANT Hidden3D )

Visualize images using gnuplot.


GnuplotPlotImage displays an image as a 3D-plot using gnuplot. If there is an active gnuplot sub-process
(started with GnuplotOpenPipe), the image is displayed in a gnuplot window. Otherwise, the image is
output to a file, which can be later read by gnuplot. In both cases the gnuplot output stream is identified by
GnuplotFileID. The parameters SamplesX and SamplesY determine the number of data points in the x-
and y-direction, respectively, which gnuplot should use to display the image. They are the equivalent of the gnuplot
variables samples and isosamples. The parameters ViewRotX und ViewRotZ determine the rotation of the plot
with respect to the viewer. ViewRotX is the rotation of the coordinate system about the x-axis, while ViewRotZ
is the rotation of the plot about the z-axis. These two parameters correspond directly to the first two parameters
of the ’set view’ command in gnuplot. The parameter Hidden3D determines whether hidden surfaces should be
removed. This is equivalent to the ’set hidden3d’ command in gnuplot. If a single image is passed to the operator,
it is displayed in a separate plot. If multiple images are passed, they are displayed in the same plot.
Parameter
. Image (input iconic) . . . . . . image ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2, uint2, int4,
real )
Image to be plotted.
. GnuplotFileID (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . gnuplot_id ; long / HGnuplotX / VARIANT
Identifier for the gnuplot output stream.

HALCON 8.0.2
336 CHAPTER 4. GRAPHICS

. SamplesX (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT


Number of samples in the x-direction.
Default Value : 64
Typical range of values : 2 ≤ SamplesX ≤ 2
Restriction : (SamplesX ≥ 2)
. SamplesY (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of samples in the y-direction.
Default Value : 64
Typical range of values : 2 ≤ SamplesY ≤ 2
Restriction : (SamplesY ≥ 2)
. ViewRotX (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Rotation of the plot about the x-axis.
Default Value : 60
Typical range of values : 0 ≤ ViewRotX ≤ 0
Minimum Increment : 0.01
Recommended Increment : 10
Restriction : ((0 ≤ V iewRotX) ∧ (V iewRotX ≤ 180))
. ViewRotZ (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Rotation of the plot about the z-axis.
Default Value : 30
Typical range of values : 0 ≤ ViewRotZ ≤ 0
Minimum Increment : 0.01
Recommended Increment : 10
Restriction : ((0 ≤ V iewRotZ) ∧ (V iewRotZ ≤ 360))
. Hidden3D (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Plot the image with hidden surfaces removed.
Default Value : ’hidden3d’
List of values : Hidden3D ∈ {’hidden3d’, ’nohidden3d’}
Result
GnuplotPlotImage returns the value if GnuplotFileID is a valid gnuplot output stream, and if the data
file for the current plot could be opened. Otherwise, an exception handling is raised.
Parallelization Information
GnuplotPlotImage is processed completely exclusively without parallelization.
Possible Predecessors
GnuplotOpenPipe, GnuplotOpenFile
Possible Successors
GnuplotClose
See also
GnuplotOpenPipe, GnuplotOpenFile, GnuplotClose
Module
Foundation

4.3 LUT
void HWindowX.DispLut ([in] long Row, [in] long Column, [in] long Scale )
void HOperatorSetX.DispLut ([in] VARIANT WindowHandle, [in] VARIANT Row,
[in] VARIANT Column, [in] VARIANT Scale )

Graphical view of the look-up-table (lut).


DispLut displays a graphical view of the look-up-table (lut) in the valid window. A look-up-table defines the
transformation of image gray values to colors/gray levels on the screen. On most systems this can be modified.
DispLut creates a graphical view of the table assigned to the output window with the logical window number
WindowHandle and displays it for every basic color (red, green, blue). Row and Column define the position
of the centre of the graphic. Scale allows scaling of the graphic, whereas 1 means displaying all 256 values, 2

HALCON/COM Reference Manual, 2008-5-13


4.3. LUT 337

means displaying 128 values, 3 means displaying only 64 values, etc. Tables for monochrome-representations are
displayed in the currently set color (see SetColor, SetRgb, etc.). Tables for displaying "‘false colors"’ are
viewed with red, green and blue for each color component.
Attention
DrawLut can only be used on hardware supporting look-up-tables for the output.
Parameter
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window identifier.
. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; long / VARIANT
Row of centre of the graphic.
Default Value : 128
Typical range of values : 0 ≤ Row ≤ 0
. Column (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; long / VARIANT
Column of centre of the graphic.
Default Value : 128
Typical range of values : 0 ≤ Column ≤ 0
. Scale (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Scaling of the graphic.
Default Value : 1
List of values : Scale ∈ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Typical range of values : 0 ≤ Scale ≤ 0
Example

set_lut(WindowHandle,’color’)
disp_lut(WindowHandle,256,256,1)
get_mbutton(WindowHandle,_,_,_)
set_lut(WindowHandle,’sqrt’)
disp_lut(WindowHandle,128,128,2).

Result
DispLut returns TRUE if the hardware supports a look-up-table, the window is valid and the parameters are
correct. Otherwise an exception handling is raised.
Parallelization Information
DispLut is reentrant, local, and processed without parallelization.
Possible Predecessors
SetLut
See also
OpenWindow, OpenTextwindow, DrawLut, SetLut, SetFix, SetPixel, WriteLut, GetLut,
SetColor
Module
Foundation

void HWindowX.DrawLut ( )
void HOperatorSetX.DrawLut ([in] VARIANT WindowHandle )

Manipulate look-up-table (lut) interactively.


DrawLut allows interactive manipulation of the look-up-table of the device currently displaying the output win-
dow.
By pressing and holding down the left mouse button one can change (from "‘left to right"’) the red-, green- and
blue-intensity displayed in a 2 dimensional diagram with the gray values on the x-axis. The left mouse button
also is used for choosing the color channel that should be changed. As an alternative, one can map pure gray
levels (gray "‘color channel"’) to the gray values on the x-axis. The right mouse button is used for terminating
the change-process. The modified look-up-table can be saved by WriteLut and reloaded later by SetLut.

HALCON 8.0.2
338 CHAPTER 4. GRAPHICS

GetLut succeeding DrawLut returns directly the RGB tuple of the look-up-table. These are suitable as input of
SetLut.
Attention
DrawLut can only be used on hardware supporting look-up-tables for the output and allow dynamic changing of
the tables.
Parameter

. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT


Window identifier.
Example

read_image(Image,’fabrik’)
disp_image(Image,WindowHandle)
draw_lut(WindowHandle)
write_lut(WindowHandle,’my_lut’).
...
read_image(Image,’fabrik’)
set_lut(WindowHandle,’my_lut’).

Result
DrawLut returns TRUE if the window is valid. Otherwise an exception handling is raised.
Parallelization Information
DrawLut is reentrant, local, and processed without parallelization.
Possible Successors
SetLutStyle, SetLut, WriteLut, DispLut
See also
WriteLut, SetLut, GetLut, DispLut
Alternatives
SetFix, SetRgb
Module
Foundation

HWindowX.GetFixedLut ( )
[out] String Mode
void HOperatorSetX.GetFixedLut ([in] VARIANT WindowHandle,
[out] VARIANT Mode )

Get fixing of "‘look-up-table"’ (lut) for "‘real color images"’


Parameter

. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT


Window identifier.
. Mode (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Mode of fixing.
Default Value : ’true’
List of values : Mode ∈ {’true’, ’false’}
Parallelization Information
GetFixedLut is reentrant, local, and processed without parallelization.
Possible Successors
SetFixedLut
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


4.3. LUT 339

HWindowX.GetLut ( )
[out] VARIANT LookUpTable
void HOperatorSetX.GetLut ([in] VARIANT WindowHandle,
[out] VARIANT LookUpTable )

Get current look-up-table (lut).


GetLut returns the name or the values of the look-up-table (lut) of the window, currently used by DispImage
(or indirectly by DispRegion, etc.) for output. To set a look-up-table use SetLut. If the current table is a
system table without any modification ( by SetFix ), the name of the table is returned. If it is a modified table,
a table read from a file or a table for output with pseudo real colors, the RGB-values of the table are returned.
Attention

Parameter

. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT


Window identifier.
. LookUpTable (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( integer, string )
Name of look-up-table or tuple of RGB-values.
Result
GetLut returns TRUE if the window is valid. Otherwise an exception handling is raised.
Parallelization Information
GetLut is reentrant, local, and processed without parallelization.
Possible Successors
DrawLut, SetLut
See also
SetLut, DrawLut
Alternatives
SetFix, GetPixel
Module
Foundation

[out] double Hue HWindowX.GetLutStyle ([out] double Saturation,


[out] double Intensity )
void HOperatorSetX.GetLutStyle ([in] VARIANT WindowHandle,
[out] VARIANT Hue, [out] VARIANT Saturation, [out] VARIANT Intensity )

Get modification parameters of look-up-table (lut).


GetLutStyle returns the values that were set with SetLutStyle. Default is:

Hue: 0.0
Saturation 1.0
Intensity 1.0

Parameter

. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT


Window identifier.
. Hue (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Modification of color value.
. Saturation (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Modification of saturation.
. Intensity (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Modification of intensity.

HALCON 8.0.2
340 CHAPTER 4. GRAPHICS

Result
GetLutStyle returns TRUE if the window is valid and the parameter is correct. Otherwise an exception han-
dling is raised.
Parallelization Information
GetLutStyle is reentrant, local, and processed without parallelization.
Possible Successors
SetLutStyle, SetLut
See also
SetLutStyle
Module
Foundation

[out] VARIANT LookUpTable HWindowX.QueryLut ( )


void HOperatorSetX.QueryLut ([in] VARIANT WindowHandle,
[out] VARIANT LookUpTable )

Query all available look-up-tables (lut).


QueryLut returns the names of all look-up-tables available on the current used device. These tables can be set
with SetLut. An table named ’default’ is always available.
Attention

Parameter
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window identifier.
. LookUpTable (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( string )
Names of look-up-tables.
Result
QueryLut returns TRUE if a window is valid. Otherwise an exception handling is raised.
Parallelization Information
QueryLut is reentrant, local, and processed without parallelization.
Possible Successors
SetLutStyle, SetLut, WriteLut, DispLut
See also
SetLut
Module
Foundation

void HWindowX.SetFixedLut ([in] String Mode )


void HOperatorSetX.SetFixedLut ([in] VARIANT WindowHandle,
[in] VARIANT Mode )

Fix "‘look-up-table"’ (lut) for "‘real color images"’.


Parameter
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window identifier.
. Mode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Mode of fixing.
Default Value : ’true’
List of values : Mode ∈ {’true’, ’false’}

HALCON/COM Reference Manual, 2008-5-13


4.3. LUT 341

Parallelization Information
SetFixedLut is reentrant, local, and processed without parallelization.
Possible Predecessors
GetFixedLut
Module
Foundation

void HWindowX.SetLut ([in] VARIANT LookUpTable )


void HOperatorSetX.SetLut ([in] VARIANT WindowHandle,
[in] VARIANT LookUpTable )

Set "‘look-up-table"’ (lut).


SetLut sets look-up-table of the device (monitor) displaying the output window. A look-up-table defines the
transformation of a "‘gray value"’ within an image into a gray value or color on the screen. It describes the screen
gray value/color as a combination of red, green and blue for any image gray value (0..255) (so it is a ’table’ to
’look up’ the screen gray value/color for each image gray value: look-up-table). Transformation into screen-colors
is performed in real-time at every time the screen is displayed new (typically this happens about 60 - 70 times per
second). So it is possible to change the llok-up-table to get a new look of images or regions. Please remind that
not all machines support changing the look-up-table (e.g. monochrome resp. real color).
Look-up-tables within HALCON (and on a machine that supports 256 colors) are diposed into three areas:

S: system area resp. user area,


G: graphic colors,
B: image data.

Colors in S descend from applications that were active before starting HALCON and should not get lost. Graphic
colors in G are used for operators such as DispRegion, DispCircle etc. and are set unique within all
look-up-tables. An output in a graphic color has always got the same (color-)look, even if different look-up-tables
are used. SetColor and SetRgb set graphic colors. Gray values resp. colors in B are used by DispImage
to display an image. They can change according to the current look-up-table. There exist two exceptions to this
concept:

• SetGray allows setting of colors of the area B for operators such as DispRegion,
• SetFix that allows modification of graphic colors.

For common monitors only one look-up-table can be loaded per screen. Whereas SetLut can be activated
separately for each window. There is the following solution for this problem: It will always be activated the
look-up-table that is assigned to the "‘active window"’ (a window is set into the state "‘active"’ by the window
manager).
look-up-table can also be used with truecolor displays. In this case the look-up-table will be simulated in software.
This means, that the look-up-table will be used each time an image is displayed.
WindowsNT specific: if the graphiccard is used in mode different from truecolor, you must display the image after
setting the look-up-taple.
QueryLut lists the names of all look-up-tables. They differ from each other in the area used for gray values.
Within this area the following behaiviour is defined:
gray value tables (1-7 image levels)
’default’: Only the two basic colors (generally black and white) are used.
color tables (Real color, static gray value steps)
’default’: Table proposed by the hardware.
gray value tables (256 colors)
’default’: As ’linear’.

HALCON 8.0.2
342 CHAPTER 4. GRAPHICS

’linear’: Linear increasing of gray values from 0 (black) to 255 (white).


’inverse’: Inverse function of ’linear’.
’sqr’: Gray values increase according to square function.
’inv_sqr’: Inverse function of ’sqr’.
’cube’: Gray values increase according to cubic function.
’inv_cube’: Inverse function of ’cube’.
’sqrt’: Gray values increase according to square-root function.
’inv_sqrt’: Inverse Function of ’sqrt’.
’cubic_root’: Gray values increase according to cubic-root function.
’inv_cubic_root’: Inverse Function of ’cubic_root’.

color tables (256 colors)

’color1’: Linear transition from red via green to blue.


’color2’: Smooth transition from yellow via red, blue to green.
’color3’: Smooth transition from yellow via red, blue, green, red to blue.
’color4’: Smooth transition from yellow via red to blue.
’three’: Displaying the three colors red, green and blue.
’six’: Displaying the six basic colors yellow, red, magenta, blue, cyan and green.
’twelve’: Displaying 12 colors.
’twenty_four’: Displaying 24 colors.
’rainbow’: Displaying the spectral colors from red via green to blue.
’temperature’: Temperature table from black via red, yellow to white.
’change1’: Color changement after every pixel within the table alternating the six basic colors.
’change2’: Fivefold color changement from green via red to blue.
’change3’: Threefold color changement from green via red to blue.

A look-up-table can be read from a file. Every line of such a file must contain three numbers in the range of 0 to
255, with the first number describing the amount of red, the second the amount of green and the third the amount
of blue of the represented display color. The number of lines can vary. The first line contains information for the
first gray value and the last line for the last value. If there are less lines than gray values, the available information
values are distributed over the whole interval. If there are more lines than gray values, a number of (uniformly
distributed) lines is ignored. The file-name must conform to "‘LookUpTable.lut"’. Within the parameter the
name is specified without file extension. HALCON will search for the file in the current directory and after that in
a specified directory ( see SetSystem(::’lutDir’,<Pfad>:) ). It is also possible to call SetLut with
a tuple of RGB-Values. These will be set directly. The number of parameter values must conform to the number
of pixels currently used within the look-up-table.
Attention
SetLut can only be used with monitors supporting 256 gray levels/colors.
Parameter

. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT


Window identifier.
. LookUpTable (input control) . . . . . . . . . . . . . . . . . . . . . . filename.read(-array) ; VARIANT ( integer, string )
Name of look-up-table, values of look-up-table (RGB) or file name.
Default Value : ’default’
Suggested values : LookUpTable ∈ {’default’, ’linear’, ’inverse’, ’sqr’, ’inv_sqr’, ’cube’, ’inv_cube’, ’sqrt’,
’inv_sqrt’, ’cubic_root’, ’inv_cubic_root’, ’color1’, ’color2’, ’color3’, ’color4’, ’three’, ’six’, ’twelve’,
’twenty_four’, ’rainbow’, ’temperature’, ’cyclic_gray’, ’cyclic_temperature’, ’hsi’, ’change1’, ’change2’,
’change3’}

HALCON/COM Reference Manual, 2008-5-13


4.3. LUT 343

Example

read_image(Image,’affe’)
query_lut(WindowHandle,LUTs)
for(1,|LUTs|,i)
set_lut(WindowHandle,LUTs[i])
fwrite_string([’current table ’,LUTs[i]])
fnew_line()
get_mbutton(WindowHandle,_,_,_)
loop().

Result
SetLut returns TRUE if the hardware supports a look-up-table and the parameter is correct. Otherwise an excep-
tion handling is raised.
Parallelization Information
SetLut is reentrant, local, and processed without parallelization.
Possible Predecessors
QueryLut, DrawLut, GetLut
Possible Successors
WriteLut
See also
GetLut, QueryLut, DrawLut, SetFix, SetColor, SetRgb, SetHsi, WriteLut
Alternatives
DrawLut, SetFix, SetPixel
Module
Foundation

void HWindowX.SetLutStyle ([in] double Hue, [in] double Saturation,


[in] double Intensity )
void HOperatorSetX.SetLutStyle ([in] VARIANT WindowHandle,
[in] VARIANT Hue, [in] VARIANT Saturation, [in] VARIANT Intensity )

Changing the look-up-table (lut).


SetLutStyle changes the look-up-table (lut) of the device displaying the valid output window. It has got three
parameters:

Hue: Rotation of color space, Hue = 1.9 conforms to a one-time rotation of the color space. No changement: Hue
= 0.0 Complement colors: Hue = 0.5
Saturation: Changement of saturation, No changement: Saturation = 1.0 Gray value image: Saturation = 0.0
Intensity: Changement of intensity, No changement: Intensity = 1.0 Black image: Intensity = 0.0

Changement affects only the part of an look-up-table that is used for diplaying images. The parameter of modifi-
cation remain until the next call of SetLutStyle. Calling SetLut has got no effect on these parameters.
Parameter

. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT


Window identifier.
. Hue (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Modification of color value.
Default Value : 0.0
Typical range of values : 0.0 ≤ Hue ≤ 0.0
Restriction : ((0.0 ≤ Hue) ∧ (Hue ≤ 1.0))

HALCON 8.0.2
344 CHAPTER 4. GRAPHICS

. Saturation (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT


Modification of saturation.
Default Value : 1.5
Restriction : (0.0 ≤ Saturation)
. Intensity (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Modification of intensity.
Default Value : 1.5
Restriction : (0.0 ≤ Intensity)
Example

read_image(Image,’affe’)
set_lut(WindowHandle,’color’)
repeat(:::) >
get_mbutton(WindowHandle,Row,Column,Button)
eval(Row/300.0,Saturation)
eval(Column/512.0,Hue)
set_lut_style(WindowHandle,Hue,Saturation,1.0)
until(Button = 1).

Result
SetLutStyle returns TRUE if the window is valid and the parameter is correct. Otherwise an exception han-
dling is raised.
Parallelization Information
SetLutStyle is reentrant, local, and processed without parallelization.
Possible Predecessors
GetLutStyle
Possible Successors
SetLut
See also
GetLutStyle
Alternatives
SetLut, ScaleImage
Module
Foundation

void HWindowX.WriteLut ([in] String FileName )


void HOperatorSetX.WriteLut ([in] VARIANT WindowHandle,
[in] VARIANT FileName )

Write look-up-table (lut) as file.


WriteLut saves the look-up-table (resp. the part of it that is relevant for displaying image gray values) of the
valid output window into a file named ’FileName.lut’. It can be read again later with SetLut.
Attention
WriteLut is only suitable for systems using 256 colors.
Parameter

. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT


Window identifier.
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.write ; String / VARIANT
File name (of file containing the look-up-table).
Default Value : /tmp/lut

HALCON/COM Reference Manual, 2008-5-13


4.4. MOUSE 345

Example

read_image(Image,’affe’)
disp_image(Image,WindowHandle)
draw_lut(WindowHandle)
write_lut(WindowHandle,’test_lut’).

Result
WriteLut returns TRUE if the window with the required properties (256 colors) is valid and the parameter (file
name) is correct. Otherwise an exception handling is raised.
Parallelization Information
WriteLut is reentrant, local, and processed without parallelization.
Possible Predecessors
DrawLut, SetLut
See also
SetLut, DrawLut, SetPixel, GetPixel
Module
Foundation

4.4 Mouse
[out] long Row HWindowX.GetMbutton ([out] long Column,
[out] long Button )
void HOperatorSetX.GetMbutton ([in] VARIANT WindowHandle,
[out] VARIANT Row, [out] VARIANT Column, [out] VARIANT Button )

Wait until a mouse button is pressed.


GetMbutton returns the coordinates of the mouse pointer in the output window and the mouse button pressed
(Button):

1: Left button,
2: Middle button,
4: Right button.

The operator waits until a button is pressed in the output window. If more than one button is pressed, the sum of
the individual buttons’ values is returned. The origin of the coordinate system is located in the left upper corner
of the window. The row coordinates increase towards the bottom, while the column coordinates increase towards
the right. For graphics windows, the coordinates of the lower right corner are (image height-1,image width-1)
(see OpenWindow, ResetObjDb), while for text windows they are (window height-1,window width-1) (see
OpenTextwindow).
Attention
GetMbutton only returns if a mouse button is pressed in the window.
Parameter

. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT


Window identifier.
. Row (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; long / VARIANT
Row coordinate of the mouse position in the window.
. Column (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; long / VARIANT
Column coordinate of the mouse position in the window.
. Button (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Mouse button(s) pressed.

HALCON 8.0.2
346 CHAPTER 4. GRAPHICS

Result
GetMbutton returns the value TRUE.
Parallelization Information
GetMbutton is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow, OpenTextwindow
See also
OpenWindow, OpenTextwindow
Alternatives
GetMposition
Module
Foundation

[out] long Row HWindowX.GetMposition ([out] long Column,


[out] long Button )
void HOperatorSetX.GetMposition ([in] VARIANT WindowHandle,
[out] VARIANT Row, [out] VARIANT Column, [out] VARIANT Button )

Query the mouse position.


GetMposition returns the coordinates of the mouse pointer in the output window and the mouse button pressed.
These values are returned regardless of the state of the mouse buttons (pressed or not pressed). If more than one
button is pressed, the sum of the individual buttons’ values is returned. The possible values for Button are:

0: No button,
1: Left button,
2: Middle button,
4: Right button.

The origin of the coordinate system is located in the left upper corner of the window. The row coordinates increase
towards the bottom, while the column coordinates increase towards the right. For graphics windows, the coordi-
nates of the lower right corner are (image height-1,image width-1) (see OpenWindow, ResetObjDb), while
for text windows they are (window height-1,window width-1) (see OpenTextwindow).
Attention
GetMposition fails (returns FAIL) if the mouse pointer is not located within the window. In this case, no values
are returned.
Parameter
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window identifier.
. Row (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; long / VARIANT
Row coordinate of the mouse position in the window.
. Column (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; long / VARIANT
Column coordinate of the mouse position in the window.
. Button (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Mouse button(s) pressed or 0.
Result
GetMposition returns the value TRUE. If the mouse pointer is not located within the window, FAIL is returned.
Parallelization Information
GetMposition is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow, OpenTextwindow
See also
OpenWindow, OpenTextwindow

HALCON/COM Reference Manual, 2008-5-13


4.4. MOUSE 347

Alternatives
GetMbutton
Module
Foundation

HWindowX.GetMshape ( )
[out] String Cursor
void HOperatorSetX.GetMshape ([in] VARIANT WindowHandle,
[out] VARIANT Cursor )

Query the current mouse pointer shape.


GetMshape returns the name of the pointer shape set for the window. The mouse pointer shape can be used in
the operator SetMshape.
Parameter

. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT


Window identifier.
. Cursor (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Mouse pointer name.
Result
GetMshape returns the value TRUE.
Parallelization Information
GetMshape is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow, OpenTextwindow, QueryMshape
Possible Successors
SetMshape
See also
SetMshape, QueryMshape
Module
Foundation

HWindowX.QueryMshape ( )
[out] VARIANT ShapeNames
void HOperatorSetX.QueryMshape ([in] VARIANT WindowHandle,
[out] VARIANT ShapeNames )

Query all available mouse pointer shapes.


QueryMshape returns the names of all available mouse pointer shapes for the window. These can be used in the
operator SetMshape. If no mouse pointers are available, the empty tuple is returned.
Parameter

. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT


Window identifier.
. ShapeNames (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( string )
Available mouse pointer names.
Result
QueryMshape returns the value TRUE.
Parallelization Information
QueryMshape is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow, OpenTextwindow, GetMshape

HALCON 8.0.2
348 CHAPTER 4. GRAPHICS

Possible Successors
SetMshape
See also
SetMshape, GetMshape
Module
Foundation

void HWindowX.SetMshape ([in] String Cursor )


void HOperatorSetX.SetMshape ([in] VARIANT WindowHandle,
[in] VARIANT Cursor )

Set the current mouse pointer shape.


SetMshape sets the shape of the mouse pointer for the window. A list of the names of all available mouse
pointer shapes can be obtained by calling QueryMshape. The mouse pointer shape given by Cursor is used if
the mouse pointer enters the window, irrespective of which window is the output window at present.
Parameter

. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT


Window identifier.
. Cursor (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Mouse pointer name.
Default Value : ’arrow’
Result
SetMshape returns the value TRUE if the mouse pointer shape Cursor is defined for this window. Otherwise,
an exception handling is raised.
Parallelization Information
SetMshape is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow, OpenTextwindow, QueryMshape, GetMshape
See also
GetMshape, QueryMshape
Module
Foundation

4.5 Output

void HWindowX.DispArc ([in] VARIANT CenterRow, [in] VARIANT CenterCol,


[in] VARIANT Angle, [in] VARIANT BeginRow, [in] VARIANT BeginCol )
void HOperatorSetX.DispArc ([in] VARIANT WindowHandle,
[in] VARIANT CenterRow, [in] VARIANT CenterCol, [in] VARIANT Angle,
[in] VARIANT BeginRow, [in] VARIANT BeginCol )

Displays circular arcs in a window.


DispArc displays one or several circular arcs in the output window. An arc is described by its center point
(CenterRow,CenterCol), the angle between start and end of the arc (Angle in radians) and the first point of
the arc (BeginRow,BeginCol). The arc is displayed in clockwise direction. The parameters for output can be
determined - as with the output of regions - with the procedures SetColor, SetGray, SetDraw, etc. It is
possible to draw several arcs with one call by using tupel parameters. For the use of colors with several arcs, see
SetColor.
Attention
The center point has to be within the window. The radius of the arc has be at least 2 pixel.

HALCON/COM Reference Manual, 2008-5-13


4.5. OUTPUT 349

Parameter

. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT


Window identifier.
. CenterRow (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . arc.center.y ; VARIANT ( integer, real )
Row coordinate of center point.
Default Value : 64
Suggested values : CenterRow ∈ {0, 64, 128, 256}
Typical range of values : 0 ≤ CenterRow ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 1
. CenterCol (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . arc.center.x ; VARIANT ( integer, real )
Column coordinate of center point.
Default Value : 64
Suggested values : CenterCol ∈ {0, 64, 128, 256}
Typical range of values : 0 ≤ CenterCol ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 1
. Angle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . arc.angle.rad ; VARIANT ( integer, real )
Angle between start and end of the arc (in radians).
Default Value : 3.1415926
Suggested values : Angle ∈ {0.0, 0.785398, 1.570796, 3.1415926, 6.283185}
Typical range of values : 0.0 ≤ Angle ≤ 0.0(lin)
Minimum Increment : 0.01
Recommended Increment : 0.1
Restriction : (Angle > 0.0)
. BeginRow (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . arc.begin.y(-array) ; VARIANT ( integer, real )
Row coordinate of the start of the arc.
Default Value : 32
Suggested values : BeginRow ∈ {0, 64, 128, 256}
Typical range of values : 0 ≤ BeginRow ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 1
. BeginCol (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . arc.begin.x(-array) ; VARIANT ( integer, real )
Column coordinate of the start of the arc.
Default Value : 32
Suggested values : BeginCol ∈ {0, 64, 128, 256}
Typical range of values : 0 ≤ BeginCol ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 1
Example

open_window(0,0,-1,-1,’root’,’visible’,’’,WindowHandle)
set_draw(WindowHandle,’fill’)
set_color(WindowHandle,’white’)
set_insert(WindowHandle,’not’)
Row = 100
Column = 100
disp_arc(WindowHandle,Row,Column,3.14,Row+10,Column+10)
close_window(WindowHandle).

Result
DispArc returns TRUE.
Parallelization Information
DispArc is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow, SetDraw, SetColor, SetColored, SetLineWidth, SetRgb, SetHsi

HALCON 8.0.2
350 CHAPTER 4. GRAPHICS

See also
OpenWindow, OpenTextwindow, SetColor, SetDraw, SetRgb, SetHsi
Alternatives
DispCircle, DispEllipse, DispRegion, GenCircle, GenEllipse
Module
Foundation

void HWindowX.DispArrow ([in] VARIANT Row1, [in] VARIANT Column1,


[in] VARIANT Row2, [in] VARIANT Column2, [in] VARIANT Size )
void HOperatorSetX.DispArrow ([in] VARIANT WindowHandle,
[in] VARIANT Row1, [in] VARIANT Column1, [in] VARIANT Row2,
[in] VARIANT Column2, [in] VARIANT Size )

Displays arrows in a window.


DispArrow displays one or several arrows in the output window. An arrow is described by the coordinates of
the start (Row1,Column1) and the end (Row2,Column2). An arrowhead is displayed at the end of the arrow.
The size of the arrowhead is specified by the parameter Size. If the arrow consists of just one point (start =
end) nothing is displayed. The procedures used to control the display of regions (e.g. SetDraw, SetColor,
SetLineWidth) can also be used with arrows. Several arrows can be displayed with one call by using tuple
parameters. For the use of colors with several arcs, see SetColor.
Attention
The start and the end of the arrows must fall within the window.
Parameter

. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT


Window identifier.
. Row1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.begin.y(-array) ; VARIANT ( integer, real )
Row index of the start.
Default Value : 10.0
Suggested values : Row1 ∈ {0.0, 64.0, 128.0, 256.0}
Typical range of values : 0.0 ≤ Row1 ≤ 0.0(lin)
Minimum Increment : 1.0
Recommended Increment : 1.0
. Column1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.begin.x(-array) ; VARIANT ( integer, real )
Column index of the start.
Default Value : 10.0
Suggested values : Column1 ∈ {0.0, 64.0, 128.0, 256.0}
Typical range of values : 0.0 ≤ Column1 ≤ 0.0(lin)
Minimum Increment : 1.0
Recommended Increment : 1.0
. Row2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.end.y(-array) ; VARIANT ( integer, real )
Row index of the end.
Default Value : 118.0
Suggested values : Row2 ∈ {0.0, 64.0, 128.0, 256.0}
Typical range of values : 0.0 ≤ Row2 ≤ 0.0(lin)
Minimum Increment : 1.0
Recommended Increment : 1.0
. Column2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.end.x(-array) ; VARIANT ( integer, real )
Column index of the end.
Default Value : 118.0
Suggested values : Column2 ∈ {0.0, 64.0, 128.0, 256.0}
Typical range of values : 0.0 ≤ Column2 ≤ 0.0(lin)
Minimum Increment : 1.0
Recommended Increment : 1.0

HALCON/COM Reference Manual, 2008-5-13


4.5. OUTPUT 351

. Size (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )


Size of the arrowhead.
Default Value : 1.0
Suggested values : Size ∈ {1.0, 2.0, 3.0, 5.0}
Typical range of values : 0.0 ≤ Size ≤ 0.0(lin)
Minimum Increment : 1.0
Recommended Increment : 1.0
Restriction : (Size > 0.0)
Example

set_color(WindowHandle,[’red’,’green’])
disp_arrow(WindowHandle,[10,10],[10,10],[118,110],[118,118],1.0).

Result
DispArrow returns TRUE.
Parallelization Information
DispArrow is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow, SetDraw, SetColor, SetColored, SetLineWidth, SetRgb, SetHsi
See also
OpenWindow, OpenTextwindow, SetColor, SetDraw, SetLineWidth
Alternatives
DispLine, GenRegionPolygon, DispRegion
Module
Foundation

void HImageX.DispChannel ([in] HWindowX WindowHandle,


[in] VARIANT Channel )
void HWindowX.DispChannel ([in] HImageX MultichannelImage,
[in] VARIANT Channel )
void HOperatorSetX.DispChannel ([in] IHObjectX MultichannelImage,
[in] VARIANT WindowHandle, [in] VARIANT Channel )

Displays images with several channels.


DispChannel displays an image in the output window. It is possible to display several images with one call. In
this case the images are displayed one after another. If the definition domains of the images overlap only the last
image is visible. The parameter Channel defines the number of the channel that is displayed. For RGB-images
the three color channels have to be used within a tuple parameter. For more information see DispImage.
Parameter

. MultichannelImage (input iconic) . . . . . . image(-array) ; HImageX / IHObjectX ( byte, direction,


cyclic, int1, int2, uint2, int4, real, complex,
vector_field )
Multichannel images to be displayed.
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window identifier.
. Channel (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Number of channel or the numbers of the RGB-channels
Default Value : 1
List of values : Channel ∈ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Example

HALCON 8.0.2
352 CHAPTER 4. GRAPHICS

/* Tranformation from rgb to gray */


read_image(Image,’patras’)
disp_color(Image,WindowHandle)
rgb1_to_gray(Image,GrayImage)
disp_image(GrayImage,WindowHandle).

Result
If the used images contain valid values and a correct output mode is set, DispChannel returns TRUE. Otherwise
an exception handling is raised.
Parallelization Information
DispChannel is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow, SetRgb, SetLut, SetHsi
See also
OpenWindow, OpenTextwindow, ResetObjDb, SetLut, DrawLut, DumpWindow
Alternatives
DispImage, DispColor
Module
Foundation

void HWindowX.DispCircle ([in] VARIANT Row, [in] VARIANT Column,


[in] VARIANT Radius )
void HOperatorSetX.DispCircle ([in] VARIANT WindowHandle,
[in] VARIANT Row, [in] VARIANT Column, [in] VARIANT Radius )

Displays circles in a window.


DispCircle displays one or several circles in the output window. A circle is described by the center (Row,
Column) and the radius Radius. If the used coordinates are not within the window the circle is clipped accord-
ingly.
The procedures used to control the display of regions (e.g. SetDraw, SetGray, SetDraw) can also be used
with circles. Several circles can be displayed with one call by using tuple parameters. For the use of colors with
several circles, see SetColor.
Attention
The center of the circle must be within the window.
Parameter

. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT


Window identifier.
. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . circle.center.y(-array) ; VARIANT ( integer, real )
Row index of the center.
Default Value : 64
Suggested values : Row ∈ {0, 64, 128, 256}
Typical range of values : 0 ≤ Row ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 1
. Column (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . circle.center.x(-array) ; VARIANT ( integer, real )
Column index of the center.
Default Value : 64
Suggested values : Column ∈ {0, 64, 128, 256}
Typical range of values : 0 ≤ Column ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 1

HALCON/COM Reference Manual, 2008-5-13


4.5. OUTPUT 353

. Radius (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . circle.radius(-array) ; VARIANT ( integer, real )


Radius of the circle.
Default Value : 64
Suggested values : Radius ∈ {0, 64, 128, 256}
Typical range of values : 0 ≤ Radius ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 1
Restriction : (Radius > 0.0)
Example

open_window(0,0,-1,-1,’root’,’visible’,’’,WindowHandle)
set_draw(WindowHandle,’fill’)
set_color(WindowHandle,’white’)
set_insert(WindowHandle,’not’)
repeat()
get_mbutton(WindowHandle,Row,Column,Button)
disp_circle(WindowHandle,Row,Column,(Row + Column) mod 50)
until(Button = 1)
close_window(WindowHandle).

Result
DispCircle returns TRUE.
Parallelization Information
DispCircle is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow, SetDraw, SetColor, SetColored, SetLineWidth, SetRgb, SetHsi
See also
OpenWindow, OpenTextwindow, SetColor, SetDraw, SetRgb, SetHsi
Alternatives
DispEllipse, DispRegion, GenCircle, GenEllipse
Module
Foundation

void HImageX.DispColor ([in] HWindowX WindowHandle )


void HWindowX.DispColor ([in] HImageX ColorImage )
void HOperatorSetX.DispColor ([in] IHObjectX ColorImage,
[in] VARIANT WindowHandle )

Displays a color (RGB) image


DispColor displays the three channels of a color image in the output window. The channels are ordered in the
sequence (red,green,blue). DispColor can be simulated by DispChannel.
Attention
Due to the restricted number of available colors the color appearance is usually different from the original.
Parameter
. ColorImage (input iconic) . . . . . . image ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2,
uint2, int4, real, complex, vector_field )
Color image to display.
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window identifier.
Result
If the used image contains valid values and a correct output mode is set, DispColor returns TRUE. Otherwise
an exception handling is raised.

HALCON 8.0.2
354 CHAPTER 4. GRAPHICS

Parallelization Information
DispColor is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow, SetRgb, SetLut, SetHsi
See also
DispImage, OpenWindow, OpenTextwindow, ResetObjDb, SetLut, DrawLut, DumpWindow
Alternatives
DispChannel, DispObj
Module
Foundation

void HWindowX.DispCross ([in] VARIANT Row, [in] VARIANT Column,


[in] double Size, [in] double Angle )
void HOperatorSetX.DispCross ([in] VARIANT WindowHandle,
[in] VARIANT Row, [in] VARIANT Column, [in] VARIANT Size, [in] VARIANT Angle )

Displays crosses in a window.


DispCross displays one or several crosses in the output window. A cross is described by the coordinates of
the center point (Row,Column), the length of its bars Size and the orientation Angle. The procedures used to
control the display of regions (e.g. SetColor, SetGray, SetDraw, SetLineWidth) can also be used
with crosses. Several crosses can be displayed with one call by using tuple parameters. For the use of colors with
several crosses, see SetColor.
Parameter
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window identifier.
. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . coordinates.y(-array) ; VARIANT ( real )
Row coordinate of the center.
Default Value : 32
Suggested values : Row ∈ {0, 64, 128, 256, 511}
. Column (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . coordinates.x(-array) ; VARIANT ( real )
Column coordinate of the center.
Default Value : 32
Suggested values : Column ∈ {0, 64, 128, 256, 511}
. Size (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Length of the bars.
Default Value : 6.0
Suggested values : Size ∈ {4.0, 6.0, 8.0, 10.0}
. Angle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; double / VARIANT
Orientation.
Default Value : 0.0
Suggested values : Angle ∈ {0.0, 0.78539816339744830961566084581988}
Result
DispCross returns TRUE.
Parallelization Information
DispCross is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow, SetRgb, SetLut, SetHsi, SetDraw, SetColor, SetColored, SetLineWidth
See also
OpenWindow, OpenTextwindow, SetColor, SetRgb, SetHsi, SetInsert, SetLineWidth
Alternatives
DispArrow, DispRectangle1, DispRectangle2, DispCircle
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


4.5. OUTPUT 355

void HWindowX.DispDistribution ([in] VARIANT Distribution,


[in] long Row, [in] long Column, [in] long Scale )
void HOperatorSetX.DispDistribution ([in] VARIANT WindowHandle,
[in] VARIANT Distribution, [in] VARIANT Row, [in] VARIANT Column,
[in] VARIANT Scale )

Displays a noise distribution.


DispDistribution displays a distribution in the window. The parameters are the same as in SetPaint
(WindowHandle,’histogram’) or GenRegionHisto. Noise distributions can be generated with opera-
tions like GaussDistribution or NoiseDistributionMean.
Parameter

. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT


Window identifier.
. Distribution (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Gray value distribution (513 values).
. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; long / VARIANT
Row index of center.
Default Value : 256
Suggested values : Row ∈ {0, 64, 128, 256}
Typical range of values : 0 ≤ Row ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 10
. Column (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; long / VARIANT
Column index of center.
Default Value : 256
Suggested values : Column ∈ {0, 64, 128, 256}
Typical range of values : 0 ≤ Column ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 10
. Scale (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Size of display.
Default Value : 1
Suggested values : Scale ∈ {1, 2, 3, 4, 5, 6}
Example

open_window(0,0,-1,-1,’root’,’visible’,’’,WindowHandle)
set_draw(WindowHandle,’fill’)
set_color(WindowHandle,’white’)
set_insert(WindowHandle,’not’)
read_image(Image,’affe’)
draw_region(Region,WindowHandle)
noise_distribution_mean(Region,Image,21,Distribution)
disp_distribution (WindowHandle,Distribution,100,100,3).

Parallelization Information
DispDistribution is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow, SetDraw, SetColor, SetColored, SetLineWidth, SetRgb, SetHsi,
NoiseDistributionMean, GaussDistribution
See also
GenRegionHisto, SetPaint, GaussDistribution, NoiseDistributionMean
Module
Foundation

HALCON 8.0.2
356 CHAPTER 4. GRAPHICS

void HWindowX.DispEllipse ([in] VARIANT CenterRow,


[in] VARIANT CenterCol, [in] VARIANT Phi, [in] VARIANT Radius1,
[in] VARIANT Radius2 )
void HOperatorSetX.DispEllipse ([in] VARIANT WindowHandle,
[in] VARIANT CenterRow, [in] VARIANT CenterCol, [in] VARIANT Phi,
[in] VARIANT Radius1, [in] VARIANT Radius2 )

Displays ellipses.
DispEllipse displays one or several ellipses in the output window. An ellipse is described by the center
(CenterRow, CenterCol), the orientation Phi (in radians) and the radii of the major and the minor axis
(Radius1 and Radius2).
The procedures used to control the display of regions (e.g. SetDraw, SetGray, SetDraw) can also be used
with ellipses. Several ellipses can be displayed with one call by using tuple parameters. For the use of colors with
several ellipses, see SetColor.
Attention
The center of the ellipse must be within the window.
Parameter

. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT


Window identifier.
. CenterRow (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ellipse.center.y(-array) ; VARIANT ( integer )
Row index of center.
Default Value : 64
Suggested values : CenterRow ∈ {0, 64, 128, 256}
Typical range of values : 0 ≤ CenterRow ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 10
. CenterCol (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ellipse.center.x(-array) ; VARIANT ( integer )
Column index of center.
Default Value : 64
Suggested values : CenterCol ∈ {0, 64, 128, 256}
Typical range of values : 0 ≤ CenterCol ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 10
. Phi (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ellipse.angle.rad(-array) ; VARIANT ( integer, real )
Orientation of the ellipse in radians
Default Value : 0.0
Suggested values : Phi ∈ {0.0, 0.785398, 1.570796, 3.1415926, 6.283185}
Typical range of values : 0.0 ≤ Phi ≤ 0.0(lin)
Minimum Increment : 0.01
Recommended Increment : 0.1
. Radius1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . ellipse.radius1(-array) ; VARIANT ( integer, real )
Radius of major axis.
Default Value : 24.0
Suggested values : Radius1 ∈ {0.0, 64.0, 128.0, 256.0}
Typical range of values : 0.0 ≤ Radius1 ≤ 0.0(lin)
Minimum Increment : 1.0
Recommended Increment : 10.0
. Radius2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . ellipse.radius2(-array) ; VARIANT ( integer, real )
Radius of minor axis.
Default Value : 14.0
Suggested values : Radius2 ∈ {0.0, 64.0, 128.0, 256.0}
Typical range of values : 0.0 ≤ Radius2 ≤ 0.0(lin)
Minimum Increment : 1.0
Recommended Increment : 10.0
Example

HALCON/COM Reference Manual, 2008-5-13


4.5. OUTPUT 357

set_color(WindowHandle,’red’)
draw_region(MyRegion,WindowHandle)
elliptic_axis(MyRegionRa,Rb,Phi)
area_center(MyRegion,_,Row,Column)
disp_ellipse(WindowHandle,Row,Column,Phi,Ra,Rb).

Result
DispEllipse returns TRUE, if the parameters are correct. Otherwise an exception handling is raised.
Parallelization Information
DispEllipse is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow, SetDraw, SetColor, SetColored, SetLineWidth, SetRgb, SetHsi,
EllipticAxis, AreaCenter
See also
OpenWindow, OpenTextwindow, SetColor, SetRgb, SetHsi, SetDraw, SetLineWidth
Alternatives
DispCircle, DispRegion, GenEllipse, GenCircle
Module
Foundation

void HImageX.DispImage ([in] HWindowX WindowHandle )


void HWindowX.DispImage ([in] HImageX Image )
void HOperatorSetX.DispImage ([in] IHObjectX Image,
[in] VARIANT WindowHandle )

Displays gray value images.


DispImage displays the gray values of an image in the output window. The gray value pixels of the definition
domain ( SetComprise(::WindowHandle,’object’:)) or of the whole image ( SetComprise(::
WindowHandle,’image’:)) are used. Restriction to the definition domain is the default.
For the display of gray value images the number of gray values is usually reduced. This is due to the fact that colors
have to be reserved for the display of graphics (e.g. SetColor) and the window manager. Also depending on
the number of bitplanes on the used output device often less than 256 colors (eight bitplanes) are available. The
number of "’colors"’ actually reserved for the display of gray values can be queried by GetSystem. Before
opening the first window this value can be modified by SetSystem. For instance for 8 bitplanes 200 real gray
values are the default.
The reduction of the number of gray values does not pose problems as long as only gray value information is
displayed, humans cannot distinguish 256 different shades of gray. If certain gray values are used for the rep-
resentation of region information (which is not the style commonly used in HALCON ), confusions might be
the result, since different numerical values are displayed on the screen with the same gray value. The procedure
LabelToRegion should be used on these images in order to transform the label data into HALCON objects.
If images of type ’int2’, ’int4’, ’real’ or ’complex’ are displayed, the smallest and largest gray value is computed.
Afterwards the pixel data is rescaled according to the number of available gray values (depending on the output
device. e.g. 200). It is possible that some pixels have a very different value than the other pixels. This might lead
to the display of an (almost) completely white or black image. In order to decide if the current image is a binary
image MinMaxGray can be used. If neccessary the image can be transformed or converted by ScaleImage
and ConvertImageType before it is displayed.
Attention
If a wrong output mode was set by SetPaint, the error will be reported when DispImage is used.
Parameter

. Image (input iconic) . . . . . . image ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2, uint2, int4,
real, complex, vector_field )
Gray value image to display.

HALCON 8.0.2
358 CHAPTER 4. GRAPHICS

. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT


Window identifier.
Example

/* Output of a gray image: */


read_image(Image1,’affe’)
disp_image(Image1,WindowHandle).

Result
If the used image contains valid values and a correct output mode is set, DispImage returns TRUE. Otherwise
an exception handling is raised.
Parallelization Information
DispImage is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow, SetRgb, SetLut, SetHsi, ScaleImage, ConvertImageType, MinMaxGray
See also
OpenWindow, OpenTextwindow, ResetObjDb, SetComprise, SetPaint, SetLut, DrawLut,
PaintGray, ScaleImage, ConvertImageType, DumpWindow
Alternatives
DispObj, DispColor
Module
Foundation

void HWindowX.DispLine ([in] VARIANT Row1, [in] VARIANT Column1,


[in] VARIANT Row2, [in] VARIANT Column2 )
void HOperatorSetX.DispLine ([in] VARIANT WindowHandle,
[in] VARIANT Row1, [in] VARIANT Column1, [in] VARIANT Row2,
[in] VARIANT Column2 )

Draws lines in a window.


DispLine displays one or several lines in the output window. A line is described by the coordinates of the start
(Row1,Column1) and the coordinates of the end (Row2,Column2). The procedures used to control the display of
regions (e.g. SetColor, SetGray, SetDraw, SetLineWidth) can also be used with lines. Several lines
can be displayed with one call by using tuple parameters. For the use of colors with several lines, see SetColor.
Attention
The starting points and the ending points of the lines must be in the window.
Parameter
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window identifier.
. Row1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.begin.y(-array) ; VARIANT ( real )
Row index of the start.
Default Value : 32
Suggested values : Row1 ∈ {0, 64, 128, 256, 511}
Typical range of values : 0 ≤ Row1 ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 10
. Column1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.begin.x(-array) ; VARIANT ( real )
Column index of the start.
Default Value : 32
Suggested values : Column1 ∈ {0, 64, 128, 256, 511}
Typical range of values : 0 ≤ Column1 ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 10

HALCON/COM Reference Manual, 2008-5-13


4.5. OUTPUT 359

. Row2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.end.y(-array) ; VARIANT ( real )


Row index of end.
Default Value : 64
Suggested values : Row2 ∈ {0, 64, 128, 256, 511}
Typical range of values : 0 ≤ Row2 ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 10
. Column2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.end.x(-array) ; VARIANT ( real )
Column index of end.
Default Value : 64
Suggested values : Column2 ∈ {0, 64, 128, 256, 511}
Typical range of values : 0 ≤ Column2 ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 10
Example

/* Prozedur zur Ausgabe der Kontur eines Rechtecks: /*

disp_rectangle1_margin(WindowHandle,Row1,Column1,Row2,Column2):
disp_line(WindowHandle,Row1,Column1,Row1,Column2)
disp_line(WindowHandle,Row1,Column2,Row2,Column2)
disp_line(WindowHandle,Row2,Column2,Row2,Column1)
disp_line(WindowHandle,Row2,Column1,Row1,Column1).

Result
DispLine returns TRUE.
Parallelization Information
DispLine is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow, SetRgb, SetLut, SetHsi, SetDraw, SetColor, SetColored, SetLineWidth
See also
OpenWindow, OpenTextwindow, SetColor, SetRgb, SetHsi, SetInsert, SetLineWidth
Alternatives
DispArrow, DispRectangle1, DispRectangle2, DispRegion, GenRegionPolygon,
GenRegionPoints
Module
Foundation

void HObjectX.DispObj ([in] HWindowX WindowHandle )


void HWindowX.DispObj ([in] IHObjectX Object )
void HOperatorSetX.DispObj ([in] IHObjectX Object,
[in] VARIANT WindowHandle )

Displays image objects (image, region, XLD).


DispObj displays objects depending of their kind. DispObj is equivalent to DispImage for one channel im-
ages, equivalent to DispColor for three channel images, equivalent to DispRegion for regions and equivalent
to DispXld for XLDs.
Parameter

. Object (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . object(-array) ; IHObjectX


Image object to be displayed.
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window identifier.

HALCON 8.0.2
360 CHAPTER 4. GRAPHICS

Example

/* Output of a gray image: */


read_image(Image1,’affe’)
disp_obj(Image1,WindowHandle)
threshold(Image,Region,0,128)
disp_obj(Region,WindowHandle)

Result
If the used object is valid and a correct output mode is set, DispObj returns TRUE. Otherwise an exception
handling is raised.
Parallelization Information
DispObj is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow, SetRgb, SetLut, SetHsi, ScaleImage, ConvertImageType, MinMaxGray
See also
OpenWindow, OpenTextwindow, ResetObjDb, SetComprise, SetPaint, SetLut, DrawLut,
PaintGray, ScaleImage, ConvertImageType, DumpWindow
Alternatives
DispColor, DispImage, DispXld, DispRegion
Module
Foundation

void HWindowX.DispPolygon ([in] VARIANT Row, [in] VARIANT Column )


void HOperatorSetX.DispPolygon ([in] VARIANT WindowHandle,
[in] VARIANT Row, [in] VARIANT Column )

Displays a polyline.
DispPolygon displays a polyline with the row coordinates Row and the column coordinates Column in the
output window. The parameters Row and Column have to be provided as tuples. Straight lines are drawn between
the given points. The start and the end of the polyline are not connected.
The procedures used to control the display of regions (e.g. SetColor, SetGray, SetDraw,
SetLineWidth) can also be used with polylines.
Attention
The given coordinates must lie within the window.
Parameter
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window identifier.
. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . polygon.y ; VARIANT ( integer, real )
Row index
Default Value : [16,80,80]
Suggested values : Row ∈ {0, 64, 128, 256, 511}
Typical range of values : 0 ≤ Row ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 10
. Column (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . polygon.x ; VARIANT ( integer, real )
Column index
Default Value : [48,16,80]
Suggested values : Column ∈ {0, 64, 128, 256, 511}
Typical range of values : 0 ≤ Column ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 10

HALCON/COM Reference Manual, 2008-5-13


4.5. OUTPUT 361

Result
DispPolygon returns TRUE.
Parallelization Information
DispPolygon is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow, SetRgb, SetLut, SetHsi, SetDraw, SetColor, SetColored, SetLineWidth
See also
OpenWindow, OpenTextwindow, SetColor, SetRgb, SetHsi, SetInsert, SetLineWidth
Alternatives
DispLine, GenRegionPolygon, DispRegion
Module
Foundation

void HWindowX.DispRectangle1 ([in] VARIANT Row1, [in] VARIANT Column1,


[in] VARIANT Row2, [in] VARIANT Column2 )
void HOperatorSetX.DispRectangle1 ([in] VARIANT WindowHandle,
[in] VARIANT Row1, [in] VARIANT Column1, [in] VARIANT Row2,
[in] VARIANT Column2 )

Display of rectangles aligned to the coordinate axes.


DispRectangle1 displays one or several rectangles in the output window. A rectangle is described by the upper
left corner (Row1,Column1) and the lower right corner (Row2,Column2). If the given coordinates are not within
the boundary of the window the rectangle is clipped accordingly. The procedures used to control the display of
regions (e.g. SetColor, SetGray, SetDraw, SetLineWidth) can also be used with rectangles. Several
rectangles can be displayed with one call by using tuple parameters.
Parameter

. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT


Window identifier.
. Row1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.origin.y(-array) ; VARIANT ( integer, real )
Row index of the upper left corner.
Default Value : 16
Suggested values : Row1 ∈ {0, 64, 128, 256, 511}
Typical range of values : 0 ≤ Row1 ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 10
. Column1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.origin.x(-array) ; VARIANT ( integer, real )
Column index of the upper left corner.
Default Value : 16
Suggested values : Column1 ∈ {0, 64, 128, 256, 511}
Typical range of values : 0 ≤ Column1 ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 10
. Row2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.corner.y(-array) ; VARIANT ( integer, real )
Row index of the lower right corner.
Default Value : 48
Suggested values : Row2 ∈ {0, 64, 128, 256, 511}
Typical range of values : 0 ≤ Row2 ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 10
Restriction : (Row2 ≥ Row1)

HALCON 8.0.2
362 CHAPTER 4. GRAPHICS

. Column2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.corner.x(-array) ; VARIANT ( integer, real )


Column index of the lower right corner.
Default Value : 80
Suggested values : Column2 ∈ {0, 64, 128, 256, 511}
Typical range of values : 0 ≤ Column2 ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 10
Restriction : (Column2 ≥ Column1)
Example

set_color(WindowHandle,’green’)
draw_region(MyRegion,WindowHandle)
smallest_rectangle1(MyRegion,R1,C1,R2,C2)
disp_rectangle1(WindowHandle,R1,C1,R2,C2).

Result
DispRectangle1 returns TRUE.
Parallelization Information
DispRectangle1 is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow, SetRgb, SetLut, SetHsi, SetDraw, SetColor, SetColored, SetLineWidth
See also
OpenWindow, OpenTextwindow, SetColor, SetDraw, SetLineWidth
Alternatives
DispRectangle2, GenRectangle1, DispRegion, DispLine, SetShape
Module
Foundation

void HWindowX.DispRectangle2 ([in] VARIANT CenterRow,


[in] VARIANT CenterCol, [in] VARIANT Phi, [in] VARIANT Length1,
[in] VARIANT Length2 )
void HOperatorSetX.DispRectangle2 ([in] VARIANT WindowHandle,
[in] VARIANT CenterRow, [in] VARIANT CenterCol, [in] VARIANT Phi,
[in] VARIANT Length1, [in] VARIANT Length2 )

Displays arbitrarily oriented rectangles.


DispRectangle2 draws one or several arbitrarily oriented rectangles in the output window. A rectangle is
described by the center (CenterRow,CenterCol), the orientation Phi (in radians) and half the lengths of
the edges Length1 and Length2. The procedures used to control the display of regions (e.g. SetDraw,
SetGray, SetDraw) can also be used with rectangles. Several rectangles can be displayed with one call by
using tuple parameters. For the use of colors with several rectangles, see SetColor.
Attention
The center must lie within the window boundaries.
Parameter
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window identifier.
. CenterRow (input control) . . . . . . . . . . . . . . . . . . . . . rectangle2.center.y(-array) ; VARIANT ( integer, real )
Row index of the center.
Default Value : 48
Suggested values : CenterRow ∈ {0, 64, 128, 256, 511}
Typical range of values : 0 ≤ CenterRow ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 10

HALCON/COM Reference Manual, 2008-5-13


4.5. OUTPUT 363

. CenterCol (input control) . . . . . . . . . . . . . . . . . . . . . rectangle2.center.x(-array) ; VARIANT ( integer, real )


Column index of the center.
Default Value : 64
Suggested values : CenterCol ∈ {0, 64, 128, 256, 511}
Typical range of values : 0 ≤ CenterCol ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 10
. Phi (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle2.angle.rad(-array) ; VARIANT ( integer, real )
Orientation of rectangle in radians.
Default Value : 0.0
Suggested values : Phi ∈ {0.0, 0.785398, 1.570796, 3.1415926, 6.283185}
Typical range of values : 0.0 ≤ Phi ≤ 0.0(lin)
Minimum Increment : 0.01
Recommended Increment : 0.1
. Length1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . rectangle2.hwidth(-array) ; VARIANT ( integer, real )
Half of the length of the longer side.
Default Value : 48
Suggested values : Length1 ∈ {0, 64, 128, 256, 511}
Typical range of values : 0 ≤ Length1 ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 10
. Length2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . rectangle2.hheight(-array) ; VARIANT ( integer, real )
Half of the length of the shorter side.
Default Value : 32
Suggested values : Length2 ∈ {0, 64, 128, 256, 511}
Typical range of values : 0 ≤ Length2 ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 10
Restriction : (Length2 < Length1)
Example

set_color(WindowHandle,’green’)
draw_region(MyRegion:WindowHandle)
elliptic_axis(MyRegion,Ra,Rb,Phi)
area_center(MyRegion,_,Row,Column)
disp_rectangle2(WindowHandle,Row,Column,Phi,Ra,Rb).

Result
DispRectangle2 returns TRUE, if the parameters are correct. Otherwise an exception handling is raised.
Parallelization Information
DispRectangle2 is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow, SetRgb, SetLut, SetHsi, SetDraw, SetColor, SetColored, SetLineWidth
See also
OpenWindow, OpenTextwindow, DispRegion, SetColor, SetDraw, SetLineWidth
Alternatives
DispRegion, GenRectangle2, DispRectangle1, SetShape
Module
Foundation

HALCON 8.0.2
364 CHAPTER 4. GRAPHICS

void HRegionX.DispRegion ([in] HWindowX WindowHandle )


void HWindowX.DispRegion ([in] HRegionX DispRegions )
void HOperatorSetX.DispRegion ([in] IHObjectX DispRegions,
[in] VARIANT WindowHandle )

Displays regions in a window.


DispRegion displays the regions in DispRegions in the output window. The parameters for output can be
set with the procedures SetColor, SetGray, SetDraw, SetLineWidth, etc.
The color(s) for the display of the regions are determined with SetColor, SetRgb, SetGray or
SetColored. If more than one region is displayed and more than one color is set, the colors are assigned in
a cyclic way to the regions.
The form of the region for output can be modified by SetPaint (e.g. encompassing circle, convex hull). The
command SetDraw determines if the region is filled or only the boundary is drawn. If only the boundary is
drawn, the thickness of the boundary will be determined by SetLineWidth and the style by SetLineStyle.
Parameter

. DispRegions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Regions to display.
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window identifier.
Example

/* Output with 12 colors: */


set_colored(WindowHandle,12)
disp_region(SomeSegments,WindowHandle).

/* Symbolic representation: */
set_draw(WindowHandle,’margin’)
set_color(WindowHandle,’red’)
set_shape(WindowHandle,’ellipse’)
disp_region(SomeSegmentsWindowHandle).

/* Representation of a margin with pattern: */


set_draw(WindowHandle,’margin’)
set_color(WindowHandle,’blue’)
set_line_style(WindowHandle,[12,3])
disp_region(Segments,WindowHandle).

Result
DispRegion returns TRUE.
Parallelization Information
DispRegion is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow, SetRgb, SetLut, SetHsi, SetShape, SetLineStyle, SetInsert, SetFix,
SetDraw, SetColor, SetColored, SetLineWidth
See also
OpenWindow, OpenTextwindow, SetColor, SetColored, SetDraw, SetShape, SetPaint,
SetGray, SetRgb, SetHsi, SetPixel, SetLineWidth, SetLineStyle, SetInsert, SetFix,
PaintRegion, DumpWindow
Alternatives
DispObj, DispArrow, DispLine, DispCircle, DispRectangle1, DispRectangle2,
DispEllipse
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


4.6. PARAMETERS 365

void HXLDX.DispXld ([in] HWindowX WindowHandle )


void HWindowX.DispXld ([in] IHXLDX XLDObject )
void HOperatorSetX.DispXld ([in] IHObjectX XLDObject,
[in] VARIANT WindowHandle )

Display an XLD object.


DispXld serves to display an XLD object of arbitrary type.
Parameter

. XLDObject (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xld ; IHXLDX / IHObjectX


XLD object to display.
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window id.
Parallelization Information
DispXld is reentrant, local, and processed without parallelization.
See also
DispImage, DispRegion, DispChannel, DispColor, DispLine, DispArc
Module
Foundation

4.6 Parameters
HInfoX.GetComprise ([in] HWindowX WindowHandle )
[out] String Mode
void HOperatorSetX.GetComprise ([in] VARIANT WindowHandle,
[out] VARIANT Mode )

Get the output treatment of an image matrix.


GetComprise returns the output mode of grayvalues in the window WindowHandle that is used by
DispImage and DispColor. The output mode defines whether only the grayvalues of objects are displayed
or the whole image is displayed. The query is used for temporary mode settings, i.e., the current mode is queried,
then overwritten with ( SetComprise) and finally reset.
Attention

Parameter

. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT


Window_id.
. Mode (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Display mode for images.
Result
GetComprise returns TRUE if the window is valid. Otherwise an exception handling is raised.
Parallelization Information
GetComprise is reentrant and processed without parallelization.
Possible Successors
SetComprise, DispImage, DispImage
See also
SetComprise, DispImage, DispColor
Module
Foundation

HALCON 8.0.2
366 CHAPTER 4. GRAPHICS

HWindowX.GetDraw ( )
[out] String Mode
void HOperatorSetX.GetDraw ([in] VARIANT WindowHandle,
[out] VARIANT Mode )

Get the current region fill mode.


GetDraw returns the region fill mode of the output window. It is used by operators as DispRegion,
DispCircle, DispArrow, DispRectangle1, DispRectangle2 etc. The region fill mode is set with
SetDraw.
Attention

Parameter
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window_id.
. Mode (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Current region fill mode.
Result
GetDraw returns TRUE, if the window is valid. Otherwise an exception handling is raised.
Parallelization Information
GetDraw is reentrant and processed without parallelization.
Possible Successors
SetDraw, DispRegion
See also
SetDraw, DispRegion, SetPaint
Module
Foundation

HWindowX.GetFix ( )
[out] String Mode
void HOperatorSetX.GetFix ([in] VARIANT WindowHandle,
[out] VARIANT Mode )

Get mode of fixing of current look-up-table (lut).


Use GetFix to get mode of fixing of current look-up-table (look-up-table of valid window) set before by
SetFix.
Attention

Parameter
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window identifier.
. Mode (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Current Mode of fixing.
Result
GetFix returns TRUE if the window is valid. Otherwise an exception handling is raised.
Parallelization Information
GetFix is reentrant, local, and processed without parallelization.
Possible Successors
SetFix, SetPixel, SetRgb
See also
SetFix
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


4.6. PARAMETERS 367

[out] VARIANT Hue HWindowX.GetHsi ([out] VARIANT Saturation,


[out] VARIANT Intensity )
void HOperatorSetX.GetHsi ([in] VARIANT WindowHandle, [out] VARIANT Hue,
[out] VARIANT Saturation, [out] VARIANT Intensity )

Get the HSI coding of the current color.


GetHsi returns the output color or grayvalues, respectively, for the window, described in Hue, Saturation
and Intensity. GetHsi corresponds to the procedure GetPixel but returns the entries of the color lookup
table instead of its indices. The values returned by GetHsi can be set with SetHsi.
Attention
The values returned by GetHsi may be inaccurate due to rounding errors. They do not necessarily match the
values set with SetHsi exactly (colors are stored in RGB internally).
Parameter
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window_id.
. Hue (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Hue (color value) of the current color.
. Saturation (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Saturation of the current color.
. Intensity (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Intensity of the current color.
Result
GetHsi returns TRUE, if the window is valid. Otherwise an exception handling is raised.
Parallelization Information
GetHsi is reentrant and processed without parallelization.
Possible Successors
SetHsi, SetRgb, DispImage
See also
SetHsi, SetColor, SetRgb, TransToRgb, TransFromRgb
Module
Foundation

void HRegionX.GetIcon ([in] HWindowX WindowHandle )


[out] HRegionX Icon HWindowX.GetIcon ( )
void HOperatorSetX.GetIcon ([out] HUntypedObjectX Icon,
[in] VARIANT WindowHandle )

Query the icon for region output


GetIcon queries the icon that was set with SetIcon.
Parameter
. Icon (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX
Icon for the regions center of gravity.
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window_id.
Result
GetIcon always returns TRUE.
Parallelization Information
GetIcon is reentrant and processed without parallelization.
Possible Predecessors
SetIcon

HALCON 8.0.2
368 CHAPTER 4. GRAPHICS

Possible Successors
DispRegion
Module
Foundation

[out] String Mode HWindowX.GetInsert ( )


void HOperatorSetX.GetInsert ([in] VARIANT WindowHandle,
[out] VARIANT Mode )

Get the current display mode.


GetInsert returns the display mode of the output window. It is used by procedures like DispRegion,
DispLine, DispRectangle1, etc. The mode is set with SetInsert. Possible values for Mode can
be queried with the procedure QueryInsert.
Attention

Parameter
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window_id.
. Mode (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Display mode.
Result
GetInsert returns TRUE if the window is valid. Otherwise an exception handling is raised.
Parallelization Information
GetInsert is reentrant and processed without parallelization.
Possible Predecessors
QueryInsert
Possible Successors
SetInsert, DispImage
See also
SetInsert, QueryInsert, DispRegion, DispLine
Module
Foundation

HWindowX.GetLineApprox ( )
[out] long Approximation
void HOperatorSetX.GetLineApprox ([in] VARIANT WindowHandle,
[out] VARIANT Approximation )

Get the current approximation error for contour display.


GetLineApprox returns a parameter that controls the approximation error for region contour display in the
window. It is used by the procedure DispRegion. Approximation controls the polygon approximation
for contour display (0 ⇔ no approximation). Approximation is only important for displaying the contour of
objects, especially if a line style was set with SetLineStyle.
Attention

Parameter
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window_id.
. Approximation (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; long / VARIANT
Current approximation error for contour display.

HALCON/COM Reference Manual, 2008-5-13


4.6. PARAMETERS 369

Result
GetLineApprox returns TRUE if the window is valid. Otherwise an exception handling is raised.
Parallelization Information
GetLineApprox is reentrant and processed without parallelization.
Possible Successors
SetLineApprox, SetLineStyle, DispRegion
See also
GetRegionPolygon, SetLineApprox, SetLineStyle, DispRegion
Module
Foundation

HWindowX.GetLineStyle ( )
[out] VARIANT Style
void HOperatorSetX.GetLineStyle ([in] VARIANT WindowHandle,
[out] VARIANT Style )

Get the current graphic mode for contours.


GetLineStyle returns the display mode for contoures when displaying regions. It is used by procedures like
DispRegion, DispLine, DispPolygon, etc. Style is set with the procedure SetLineStyle. Style
is only important for displaying the contour of objects, especially if a line style was set with SetLineStyle.
Attention

Parameter

. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT


Window_id.
. Style (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Template for contour display.
Result
GetLineStyle returns TRUE if the window is valid. Otherwise an exception handling is raised.
Parallelization Information
GetLineStyle is reentrant, local, and processed without parallelization.
See also
SetLineStyle, DispRegion
Module
Foundation

HWindowX.GetLineWidth ( )
[out] long Width
void HOperatorSetX.GetLineWidth ([in] VARIANT WindowHandle,
[out] VARIANT Width )

Get the current line width for contour display.


GetLineWidth returns the line width for region display in the window. It is used by procedures like
DispRegion, DispLine, DispPolygon, etc. Width is set with the procedure SetLineWidth. Width
is only important for displaying the contour of objects.
Attention

Parameter

. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT


Window_id.

HALCON 8.0.2
370 CHAPTER 4. GRAPHICS

. Width (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT


Current line width for contour display.
Result
GetLineWidth returns TRUE if the window is valid. Otherwise an exception handling is raised.
Parallelization Information
GetLineWidth is reentrant and processed without parallelization.
Possible Successors
SetLineWidth, SetLineStyle, DispRegion
See also
SetLineWidth, DispRegion
Module
Foundation

[out] VARIANT Mode HWindowX.GetPaint ( )


void HOperatorSetX.GetPaint ([in] VARIANT WindowHandle,
[out] VARIANT Mode )

Get the current display mode for grayvalues.


GetPaint returns the display mode for grayvalues in the window. Mode is used by the procedure DispImage.
GetPaint is used for temporary changes of the grayvalue display mode. The current value is queried, then
changed (with procedure SetPaint) and finally the old value is written back. The available modes can be
viewed with the procedure QueryPaint. Mode is the name of the display mode. If a mode can be customized
with parameters, the parameter values are passed in a tuple after the mode name. The order of values is the same
as in SetPaint.
Attention

Parameter
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window_id.
. Mode (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( string, integer )
Name and parameter values of the current display mode.
Result
GetPaint returns TRUE if the window is valid. Otherwise an exception handling is raised.
Parallelization Information
GetPaint is reentrant and processed without parallelization.
Possible Predecessors
QueryPaint
Possible Successors
SetPaint, DispRegion, DispImage
See also
SetPaint, QueryPaint, DispImage
Module
Foundation

[out] long Row1 HWindowX.GetPart ([out] long Column1, [out] long Row2,
[out] long Column2 )
void HOperatorSetX.GetPart ([in] VARIANT WindowHandle,
[out] VARIANT Row1, [out] VARIANT Column1, [out] VARIANT Row2,
[out] VARIANT Column2 )

Get the image part.

HALCON/COM Reference Manual, 2008-5-13


4.6. PARAMETERS 371

GetPart returns the upper left and lower right corner of the image part shown in the window. The image part
can be changed with the procedure SetPart (Default is the whole image).
Attention

Parameter
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window_id.
. Row1 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.origin.y ; long / VARIANT
Row index of the image part’s upper left corner.
. Column1 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.origin.x ; long / VARIANT
Column index of the image part’s upper left corner.
. Row2 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.corner.y ; long / VARIANT
Row index of the image part’s lower right corner.
. Column2 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.corner.x ; long / VARIANT
Column index of the image part’s lower right corner.
Result
GetPart returns TRUE if the window is valid. Otherwise an exception handling is raised.
Parallelization Information
GetPart is reentrant and processed without parallelization.
Possible Successors
SetPart, DispRegion, DispImage
See also
SetPart, DispImage, DispRegion, DispColor
Module
Foundation

HWindowX.GetPartStyle ( )
[out] long Style
void HOperatorSetX.GetPartStyle ([in] VARIANT WindowHandle,
[out] VARIANT Style )

Get the current interpolation mode for grayvalue display.


GetPartStyle returns the interpolation mode used for displaying an image part in the window. An interpolation
takes place if the output window is larger than the image format or the image output format (see SetPart).
HALCON supports three interpolation modes:

0 no interpolation (low quality, very fast).


1 unweighted interpolation (average quality and computation time)
2 weighted interpolation (high quality, slow)

The current mode can be changed with SetPartStyle.


Attention

Parameter
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window_id.
. Style (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Interpolation mode for image display: 0 (fast, low quality) to 2 (slow, high quality).
List of values : Style ∈ {0, 1, 2}
Result
GetPartStyle returns TRUE if the window is valid. Otherwise an exception handling is raised.
Parallelization Information
GetPartStyle is reentrant and processed without parallelization.

HALCON 8.0.2
372 CHAPTER 4. GRAPHICS

Possible Successors
SetPartStyle, DispRegion, DispImage
See also
SetPartStyle, SetPart, DispImage, DispColor
Module
Foundation

HWindowX.GetPixel ( )
[out] VARIANT Pixel
void HOperatorSetX.GetPixel ([in] VARIANT WindowHandle,
[out] VARIANT Pixel )

Get the current color lookup table index.


GetPixel returns the internal coding of the output grayvalue or color, respectively, for the window. If the
output mode is set to color(s) or grayvalue(s) (see SetColor or SetGray), then the color- or grayvalues are
transformed for internal use. The internal code is then used for (physical) screen display. The transformation
depends on the mapping characteristics and the condition of the output device and can be different in different
program runs. Don’t confuse the term "‘pixel"’ with the term "‘pixel"’ in image processing (the other procedure is
GetGrayval). Here a pixel is meant to be the color loookup table index.
With GetPixel it is possible to save the output mode without knowing whether colors or grayvalues are used.
Pixel is set with the procedure SetPixel.
Attention

Parameter
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window_id.
. Pixel (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Index of the current color look-up table.
Result
GetPartStyle returns TRUE if the window is valid. Otherwise an exception handling is raised.
Parallelization Information
GetPixel is reentrant and processed without parallelization.
Possible Successors
SetPixel, DispRegion, DispImage
See also
SetPixel, SetFix
Module
Foundation

[out] VARIANT Red HWindowX.GetRgb ([out] VARIANT Green,


[out] VARIANT Blue )
void HOperatorSetX.GetRgb ([in] VARIANT WindowHandle, [out] VARIANT Red,
[out] VARIANT Green, [out] VARIANT Blue )

Get the current color in RGB-coding.


GetRgb returns the output colors or grayvalues, respectively, for the output window. They are defined by the three
color components red, green and blue.
GetRgb is like GetPixel but returns the entries of the color lookup table rather than the indices. The values
returned by GetRgb can be set with SetRgb.
Attention

HALCON/COM Reference Manual, 2008-5-13


4.6. PARAMETERS 373

Parameter

. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT


Window_id.
. Red (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
The current color’s red value.
. Green (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
The current color’s green value.
. Blue (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
The current color’s blue value.
Result
GetRgb returns TRUE if the window is valid. Otherwise an exception handling is raised.
Parallelization Information
GetRgb is reentrant and processed without parallelization.
Possible Successors
SetRgb, DispRegion, DispImage
See also
SetRgb
Module
Foundation

HWindowX.GetShape ( )
[out] String DisplayShape
void HOperatorSetX.GetShape ([in] VARIANT WindowHandle,
[out] VARIANT DisplayShape )

Get the current region output shape.


GetShape returns the shape in which regions are displayed. The available shapes can be queried with
QueryShape and then changed with SetShape.
Attention

Parameter

. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT


Window_id.
. DisplayShape (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Current region output shape.
Result
GetShape returns TRUE if the window is valid. Otherwise an exception handling is raised.
Parallelization Information
GetShape is reentrant and processed without parallelization.
Possible Predecessors
QueryShape
Possible Successors
SetShape, DispRegion
See also
SetShape, QueryShape, DispRegion
Module
Foundation

HALCON 8.0.2
374 CHAPTER 4. GRAPHICS

HWindowX.QueryAllColors ( )
[out] VARIANT Colors
void HOperatorSetX.QueryAllColors ([in] VARIANT WindowHandle,
[out] VARIANT Colors )

Query all color names.


QueryAllColors returns the names of all colors that are known to HALCON . That doesn’t mean, that these
colors are available for specific screens. On some screens there may only be a subset of colors available (see
QueryColor). Before opening the first window, SetSystem can be used to define which and how many
colors should be used. The HALCON colors are used to display regions ( DispRegion, DispPolygon,
DispCircle, etc.). They can be defined with SetColor.
Attention

Parameter
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window_id.
. Colors (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( string )
Color names.
Example

query_all_colors(WindowHandle,Colors)
<interactive selection from Colors provide ActColors> >
set_system(’graphic_colors’,ActColors)
open_window(0,0,1,1,’root’,’invisible’,"’,WindowHandle)
query_color(WindowHandle,F)
close_window(WindowHandle)
fwrite_string([’Setting Colors: ’,F]).

Result
QueryAllColors always returns TRUE
Parallelization Information
QueryAllColors is reentrant, local, and processed without parallelization.
Possible Successors
SetSystem, SetColor, DispRegion
See also
QueryColor, SetSystem, SetColor, DispRegion, OpenWindow, OpenTextwindow
Module
Foundation

HWindowX.QueryColor ( )
[out] VARIANT Colors
void HOperatorSetX.QueryColor ([in] VARIANT WindowHandle,
[out] VARIANT Colors )

Query all color names displayable in the window.


QueryColor returns the names of all colors that are usable for region output ( DispRegion, DispPolygon,
DispCircle, etc.). On a b/w screen QueryColor returns ’black’ and ’white’. These two "‘colors"’ are
displayable on any screen. In addition to ’black’ and ’white’ several grayvalues (e.g. ’dim gray’) are returned
on screens capable of grayvalues. A list of all displayable colors is returned for screens with color lookup table.
The returned tuple of colors begins with b/w, followed by the three primaries (’red’,’green’,’blue’) and several
grayvalues. Before opening the first window it is furthermore possible to define the color list with SetSystem
(::’graphicColors’,...:). QueryAllColors(::WindowHandle:Colors ) returns a list of all
available colors for the SetSystem(::’graphicColors’,...:) call. For screens with truecolor output
the same list is returned by QueryColor. The list of available colors (to HALCON ) must not be confused

HALCON/COM Reference Manual, 2008-5-13


4.6. PARAMETERS 375

with the list of displayable colors. For screens with truecolor output the available colors are only a small subset of
the displayable colors. Colors that are not directly available to HALCON can be chosen manually with SetRgb
or SetHsi. If colors are chosen that are known to HALCON but cannot be displayed, HALCON can choose a
similar color. To use this faeture, SetCheck(::’˜color’:) must be set.
Attention

Parameter

. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT


Window_id.
. Colors (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( string )
Color names.
Example

open_window(0,0,-1,-1,’root’,’invisible’,"’,WindowHandle)
query_color(WindowHandle,Colors)
close_window(WindowHandle)
fwrite_string([’Displayable colors: ’,Farben]).

Result
QueryColor returns TRUE, if the window is valid. Otherwise an exception handling is raised.
Parallelization Information
QueryColor is reentrant, local, and processed without parallelization.
Possible Successors
SetColor, DispRegion
See also
QueryAllColors, SetColor, DispRegion, OpenWindow, OpenTextwindow
Module
Foundation

[out] VARIANT PossibleNumberOfColors HInfoX.QueryColored ( )


void HOperatorSetX.QueryColored
([out] VARIANT PossibleNumberOfColors )

Query the number of colors for color output.


QueryColored returns all possible parameter values for SetColored. SetColored defines how many
colors are used for region or graphics output.
Attention

Parameter

. PossibleNumberOfColors (output control) . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )


Tuple of the possible numbers of colors.
Example

regiongrowing(Image,Seg,5,5,6,100)
query_colored(Colors)
set_colored(WindowHandle,Colors[1])
disp_region(Seg,WindowHandle).

Result
QueryColored always returns TRUE.

HALCON 8.0.2
376 CHAPTER 4. GRAPHICS

Parallelization Information
QueryColored is reentrant and processed without parallelization.
Possible Successors
SetColored, SetColor, DispRegion
See also
SetColored, SetColor
Alternatives
QueryColor
Module
Foundation

HWindowX.QueryGray ( )
[out] VARIANT Grayval
void HOperatorSetX.QueryGray ([in] VARIANT WindowHandle,
[out] VARIANT Grayval )

Query the displayable grayvalues.


QueryGray returns all grayvalues that are used for grayvalue output ( DispImage) and that can be reproduced
exactly in the window. They can be set with the SetGray call. The number of displayable grayvalues can be set
with SetSystem(::’numGray*’,...:) before opening the first window.
Attention

Parameter

. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT


Window_id.
. Grayval (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Tuple of all displayable grayvalues.
Result
QueryGray returns TRUE, if the window is valid. Otherwise an exception handling is raised.
Parallelization Information
QueryGray is reentrant, local, and processed without parallelization.
Possible Successors
SetGray, DispRegion
See also
SetGray, DispImage
Module
Foundation

HWindowX.QueryInsert ( )
[out] VARIANT Mode
void HOperatorSetX.QueryInsert ([in] VARIANT WindowHandle,
[out] VARIANT Mode )

Query the possible graphic modes.


QueryInsert returns the possible modes pixels can be displayed in the output window. New pixels may e.g.
overwrite old ones. In most of the cases there is a functional relationship between old and new values.
Possible display functions:

’copy’: overwrite displayed pixels


’xor’: display old "‘xor"’ new pixels
’complement’: complement displayed pixels

HALCON/COM Reference Manual, 2008-5-13


4.6. PARAMETERS 377

"‘copy"’ is always available.


Attention

Parameter

. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT


Window_id.
. Mode (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( string )
Display function name.
Result
QueryInsert returns TRUE, if the window is valid. Otherwise an exception handling is raised.
Parallelization Information
QueryInsert is reentrant, local, and processed without parallelization.
Possible Successors
SetInsert, DispRegion
See also
SetInsert, GetInsert
Module
Foundation

HInfoX.QueryLineWidth ([out] long Max )


[out] long Min
void HOperatorSetX.QueryLineWidth ([out] VARIANT Min,
[out] VARIANT Max )

Query the possible line widths.


QueryLineWidth returns the minimal (Min) and maximal (Max) values of widths of region border which can
be displayed. Setting of the border width is done with SetLineWidth. Border width is used by operators like
DispRegion, DispLine, DispCircle, DispRectangle1, DispRectangle2 etc. if the drawing
mode is "‘margin"’ ( SetDraw(::WindowHandle,’margin’:)).
Attention

Parameter

. Min (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT


Displayable minimum width.
. Max (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Displayable maximum width.
Result
QueryLineWidth returns TRUE if the window is valid. Otherwise an exception handling is raised.
Parallelization Information
QueryLineWidth is reentrant and processed without parallelization.
Possible Successors
GetLineWidth, SetLineWidth, SetLineStyle, DispLine
See also
DispCircle, DispLine, DispRectangle1, DispRectangle2, DispRegion, SetLineWidth,
GetLineWidth, SetLineStyle
Module
Foundation

HALCON 8.0.2
378 CHAPTER 4. GRAPHICS

HWindowX.QueryPaint ( )
[out] VARIANT Mode
void HOperatorSetX.QueryPaint ([in] VARIANT WindowHandle,
[out] VARIANT Mode )

Query the grayvalue display modes.


QueryPaint returns the names of all grayvalue display modes (e.g. ’gray’, ’3D-plot’, ’contourline’, etc.) for
the output window. These modes are used by SetPaint. QueryPaint only returns the names of the display
values, not the additional parameters that may be necessary for some modes.
Attention

Parameter

. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT


Window_id.
. Mode (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( string )
Grayvalue display mode names.
Result
QueryPaint returns TRUE if the window is valid. Otherwise an exception handling is raised.
Parallelization Information
QueryPaint is reentrant, local, and processed without parallelization.
Possible Successors
GetPaint, SetPaint, DispImage
See also
SetPaint, GetPaint, DispImage
Module
Foundation

HInfoX.QueryShape ( )
[out] VARIANT DisplayShape
void HOperatorSetX.QueryShape ([out] VARIANT DisplayShape )

Query the region display modes.


QueryShape returns the names of all region display modes (e.g. ’original’, ’circle’, ’rectangle1’, ’rectangle2’,
’ellipse’, etc.) for the window. They are used by SetShape.
Attention

Parameter

. DisplayShape (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( string )


region display mode names.
Result
QueryShape returns TRUE, if the window is valid. Otherwise an exception handling is raised.
Parallelization Information
QueryShape is reentrant and processed without parallelization.
Possible Successors
GetShape, SetShape, DispRegion
See also
SetShape, GetShape, DispRegion
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


4.6. PARAMETERS 379

void HWindowX.SetColor ([in] VARIANT Color )


void HOperatorSetX.SetColor ([in] VARIANT WindowHandle,
[in] VARIANT Color )

Set output color.


SetColor defines the colors for region output in the window. The available colors can be queried with the
procedure QueryColor. The "‘colors"’ ’black’ and ’white’ are available for all screens. If colors are used
that are not displayable on the screen, HALCON can choose a similar, displayable color of the output. For this,
SetCheck(::’˜color’:) must be called. Furthermore, the list of available colors can be set with the proce-
dure SetSystem(::’graphicColors’,...:). That must be done before opening the first output window.
If only a single color is passed, all output is in this color. If a tuple of colors is passed, the output color of regions
is modulo to the number of colors. In the example below, the first circle is displayed red, the second in green
and the third in red again. HALCON always begins output with the first color passed. Note, that the number of
output colors depends on the number of objects that are displayed in one procedure call. If only single objects are
displayed, they always appear in the first color, even if the consist of more than one connected components.
The defined colors are used until SetColor, SetPixel, SetRgb, SetHsi or SetGray is called again.
Colors are defined seperately for each window. They can only be changed for the valid window.
Color is used in procedures with region output like DispRegion, DispLine, DispRectangle1,
DispArrow etc. It is also used by procedures with grayvalue output in certain output modes (e.g. ’3D-
plot’,’histogram’, ’contourline’, etc. See SetPaint).
Attention

Parameter

. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT


Window_id.
. Color (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Output color names.
Default Value : ’white’
Suggested values : Color ∈ {’black’, ’white’, ’red’, ’green’, ’blue’, ’cyan’, ’magenta’, ’yellow’, ’dim gray’,
’gray’, ’light gray’, ’medium slate blue’, ’coral’, ’slate blue’, ’spring green’, ’orange red’, ’orange’, ’dark olive
green’, ’pink’, ’cadet blue’}
Example

set_color(WindowHandle,[’red’,’green’])
disp_circle(WindowHandle,[100,200,300],[200,300,100],[100,100,100]).

Result
SetColor returns TRUE if the window is valid and the passed colors are displayable on the screen. Otherwise
an exception handling is raised.
Parallelization Information
SetColor is reentrant, local, and processed without parallelization.
Possible Predecessors
QueryColor
Possible Successors
DispRegion
See also
GetRgb, DispRegion, SetFix, SetPaint
Alternatives
SetRgb, SetHsi
Module
Foundation

HALCON 8.0.2
380 CHAPTER 4. GRAPHICS

void HWindowX.SetColored ([in] long NumberOfColors )


void HOperatorSetX.SetColored ([in] VARIANT WindowHandle,
[in] VARIANT NumberOfColors )

Set multiple output colors.


SetColored is a shortcut for certain SetColor calls. It allows the user to display a region set in different
colors. NumberOfColors defines the number of colors that are used. Valid values for NumberOfColors
can be queried with QueryColored. Furthermore, the list of available colors can be set with the procedure
SetSystem(::’graphicColors’,...:). This must be done before opening the first output window.
Attention

Parameter

. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT


Window_id.
. NumberOfColors (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of output colors.
Default Value : 12
List of values : NumberOfColors ∈ {3, 6, 12}
Result
SetColored returns TRUE if NumberOfColors is correct and the window is valid. Otherwise an exception
handling is raised.
Parallelization Information
SetColored is reentrant, local, and processed without parallelization.
Possible Predecessors
QueryColored, SetColor
Possible Successors
DispRegion
See also
QueryColored, SetColor, DispRegion
Module
Foundation

void HWindowX.SetComprise ([in] String Mode )


void HOperatorSetX.SetComprise ([in] VARIANT WindowHandle,
[in] VARIANT Mode )

Define the image matrix output clipping.


SetComprise defines the image matrix output clipping. If Mode is set to ’object’, only grayvalues belonging to
the output object are displayed. If set to ’image’, the whole image matrix is displayed. Default is ’object’.
Attention
If Mode was set to ’image’, undefined grayvalues may be displayed. Depending on the context they are black or
can have random content. See the examples.
Parameter

. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT


Window_id.
. Mode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Clipping mode for grayvalue output.
Default Value : ’object’
List of values : Mode ∈ {’image’, ’object’}

HALCON/COM Reference Manual, 2008-5-13


4.6. PARAMETERS 381

Example

open_window(0,0,-1,-1,’root’,’visible’,"’,WindowHandle)
read_image(Image,’fabrik’)
threshold(Image,Seg,100,255)
set_system(’init_new_image’,’false’)
sobel_amp(Image,Sob,’sum_abs’,3)
disp_image(Sob,WindowHandle)
get_comprise(Mode)
fwrite_string([’Current mode for gray values: ’,Mode])
fnew_line()
set_comprise(WindowHandle,’image’)
get_mbutton(WindowHandle,_,_,_)
disp_image(Sob,WindowHandle)
fwrite_string([’Current mode for gray values: image’])
fnew_line().

Result
SetComprise returns TRUE if Mode is correct and the window is valid. Otherwise an exception handling is
raised.
Parallelization Information
SetComprise is reentrant and processed without parallelization.
Possible Predecessors
GetComprise
Possible Successors
DispImage
See also
GetComprise, DispImage, DispColor
Module
Foundation

void HWindowX.SetDraw ([in] String Mode )


void HOperatorSetX.SetDraw ([in] VARIANT WindowHandle,
[in] VARIANT Mode )

Define the region fill mode.


SetDraw defines the region fill mode. If Mode is set to ’fill’, output regions are filled, if set to ’margin’, only
contours are displayed. Setting Mode only affects the valid window. It is used by procedures with region output like
DispRegion, DispCircle, DispRectangle1, DispRectangle2, DispArrow etc. It is also used
by procedures with grayvalue output for some grayvalue output modes (e.g. ’histogram’, see SetPaint). If the
mode is ’margin’, the contour can be affected with SetLineWidth, SetLineApprox and SetLineStyle.
Attention
If the output mode is ’margin’ and the line width is more than one, objects may not be displayed.
Parameter

. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT


Window_id.
. Mode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Fill mode for region output.
Default Value : ’fill’
List of values : Mode ∈ {’fill’, ’margin’}
Result
SetDraw returns TRUE if Mode is correct and the window is valid. Otherwise an exception handling is raised.

HALCON 8.0.2
382 CHAPTER 4. GRAPHICS

Parallelization Information
SetDraw is reentrant, local, and processed without parallelization.
Possible Predecessors
GetDraw
Possible Successors
DispRegion
See also
GetDraw, DispRegion, SetPaint, DispImage, SetLineWidth, SetLineStyle
Module
Foundation

void HWindowX.SetFix ([in] String Mode )


void HOperatorSetX.SetFix ([in] VARIANT WindowHandle,
[in] VARIANT Mode )

Set fixing of "‘look-up-table"’ (lut)


Behaviour for Mode = ’true’: SetFix fixes that pixel lastly ascertained by one of the operators SetGray,
SetColor, SetHsi or SetRgb (Remark: Here a pixel is the index within the current look-up-table). To assign
a new color to a fixed pixel set a color or gray value by using SetColor, SetRgb, SetHsi or SetGray.
This makes it possible to define any color ( SetColor), any gray value ( SetGray) and any color combination
( SetRgb, SetHsi) at any position of the look-up-table.
Mode set to ’false’ reset the fixing. To modify or create a look-up-table process SetPixel, SetFix(::
WindowHandle,’true’:), SetRgb and SetFix(::WindowHandle,’false’:) one after another.
Attention
As a side effect SetFix can change colors of "‘non-HALCON windows"’.
Parameter
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window identifier.
. Mode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Mode of fixing.
Default Value : ’true’
List of values : Mode ∈ {’true’, ’false’}
Result
SetFix returns TRUE if the window is valid, the hardware supports a look-up-table and all parameters are correct.
Otherwise an exception handling is raised.
Parallelization Information
SetFix is reentrant, local, and processed without parallelization.
Possible Predecessors
GetFix
Possible Successors
SetPixel, SetRgb
See also
GetFix, SetPixel, SetRgb, SetColor, SetHsi, SetGray
Module
Foundation

void HWindowX.SetGray ([in] VARIANT GrayValues )


void HOperatorSetX.SetGray ([in] VARIANT WindowHandle,
[in] VARIANT GrayValues )

Define grayvalues for region output.

HALCON/COM Reference Manual, 2008-5-13


4.6. PARAMETERS 383

SetGray defines the grayvalues for region output. Grayvalues are defined as the range of the color
lookup table that is used for grayvalue output with DispImage in conjunction with SetPaint(::
WindowHandle,’gray’:). These entries can be modified by SetLut. So a ’grayvalue’ is the color in
which a pixel with the same value is displayed (not necessarily really gray). In general, when changing the color
lookup table with SetLut, the colors of the displayed image will change too.
If a grayvalue is needed as a color for image output (i.e. no color changes with SetLut are possible), it can be
set with SetColor(::WindowHandle,’gray’:).
If only a single grayvalue is passed, all output will take place in that grayvalue. If a tuple of grayvalues is passed,
all output will take place in grayvalues modulo the number of tuple elements. In the example below, the first circle
is displayed with grayvalue 100, the second with 200 and the third with 100 again. Every output procedure starts
with the first grayvalue. Note, that the number of output grayvalues depends on the number of objects that are
displayed in one procedure call. If only single objects are displayed, they always appear in the first grayvalue, even
if the consist of more than one connected components.
When the procedures SetGray, SetColor, SetRgb, SetHsi are called, the overwrite the existing values.
If not all grayvalues are displayable on the output device, the number range of GrayValues (0..255) is dithered
to the range of displayable grayvalues. In any case 0 is displayed as black and 255 as white. The displayable
grayvalues can be queried with the procedure QueryGray. Furthermore, the number of actually displayed
grayvalues can be changed with SetSystem(::’numGray*’,...:). This must be done before opening
the first window. With SetCheck(::’˜color’:) error messages can be suppressed if a grayvalue can’t be
displayed on the screen. In that case, a similar grayvalue is displayed.
Attention

Parameter

. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT


Window_id.
. GrayValues (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Grayvalues for region output.
Default Value : 255
Suggested values : GrayValues ∈ {0, 1, 2, 10, 16, 32, 64, 100, 120, 128, 250, 251, 252, 253, 254, 255}
Typical range of values : 0 ≤ GrayValues ≤ 0
Example

set_gray(WindowHandle,[100,200])
disp_circle(WindowHandle,[100,200,300],[200,300,100],[100,100,100]).

Parallelization Information
SetGray is reentrant, local, and processed without parallelization.
Possible Successors
DispRegion
See also
GetPixel, SetColor
Module
Foundation

void HWindowX.SetHsi ([in] VARIANT Hue, [in] VARIANT Saturation,


[in] VARIANT Intensity )
void HOperatorSetX.SetHsi ([in] VARIANT WindowHandle, [in] VARIANT Hue,
[in] VARIANT Saturation, [in] VARIANT Intensity )

Define output colors (HSI-coded).


SetHsi sets the region output color(s)/grayvalue(s) for the valid window. Colors are passed as Hue,
Saturation, and Intensity. Transformation from HSI to RGB is done with:

HALCON 8.0.2
384 CHAPTER 4. GRAPHICS

H = (2πHue)/255

I = ( 6Intensity)/255 √
M 1 = (sin (H)Saturation)/(255 √6)
M 2 = (cos (H)Saturation)/(255 2)

R = (2M 1 + I)/(4√6)
G = (−M 1 + M 2 + I)/(4√6
B = (−M 1 − M 2 + I)/(4 6)
Red = R ∗ 255
Green = G ∗ 255
Blue = B ∗ 255

If only one combination is passed, all output will take place in that color. If a tuple of colors is passed, the output
color of regions and geometric objects is modulo to the number of colors. HALCON always begins output with
the first color passed. Note, that the number of output colors depends on the number of objects that are displayed
in one procedure call. If only single objects are displayed, they always appear in the first color, even if the consist
of more than one connected components.
Selected colors are used until the next call of SetColor, SetPixel, SetRgb or SetGray. Colors are
relevant to windows, i.e. only the colors of the valid window can be set. Region output colors are used by
operatores like DispRegion, DispLine, DispRectangle1, DispRectangle2, DispArrow, etc. It
is also used by procedures with grayvalue output in certain output modes (e.g. ’3D-plot’,’histogram’, ’contourline’,
etc. See SetPaint).
Attention
The selected intensities may not be available for the selected hues. In that case, the intensities will be lowered
automatically.
Parameter
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window_id.
. Hue (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Hue for region output.
Default Value : 30
Typical range of values : 0 ≤ Hue ≤ 0
Restriction : ((0 ≤ Hue) ∧ (Hue ≤ 255))
. Saturation (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Saturation for region output.
Default Value : 255
Typical range of values : 0 ≤ Saturation ≤ 0
Restriction : ((0 ≤ Saturation) ∧ (Saturation ≤ 255))
. Intensity (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Intensity for region output.
Default Value : 84
Typical range of values : 0 ≤ Intensity ≤ 0
Restriction : ((0 ≤ Intensity) ∧ (Intensity ≤ 255))
Result
SetHsi returns TRUE if the window is valid and the output colors are displayable. Otherwise an exception
handling is raised.
Parallelization Information
SetHsi is reentrant, local, and processed without parallelization.
Possible Predecessors
GetHsi
Possible Successors
DispRegion
See also
GetHsi, GetPixel, TransFromRgb, TransToRgb, DispRegion

HALCON/COM Reference Manual, 2008-5-13


4.6. PARAMETERS 385

Module
Foundation

void HRegionX.SetIcon ([in] HWindowX WindowHandle )


void HWindowX.SetIcon ([in] HRegionX Icon )
void HOperatorSetX.SetIcon ([in] IHObjectX Icon,
[in] VARIANT WindowHandle )

Icon definition for region output.


SetIcon defines an icon for region output ( DispRegion). It is displayed in the regions center of gravity. The
use of this icon is activated with SetShape.
Parameter
. Icon (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
Icon for center of gravity.
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window_id.
Parallelization Information
SetIcon is reentrant and processed without parallelization.
Possible Predecessors
GenCircle, GenEllipse, GenRectangle1, GenRectangle2, DrawRegion
Possible Successors
SetShape, DispRegion
Module
Foundation

void HWindowX.SetInsert ([in] String Mode )


void HOperatorSetX.SetInsert ([in] VARIANT WindowHandle,
[in] VARIANT Mode )

Define the pixel output function.


SetInsert defines the function, with which pixels are displayed in the output window. It is e.g. possible for a
pixel to overwrite the old value. In most of the cases there is a functional relationship between old and new values.
The definition value is only valid for the valid window. Output procedures that honor Mode are e.g.
DispRegion, DispPolygon, DispCircle.
Possible display functions are:

’copy’: overwrite displayed pixels


’xor’: display old "xor" new pixels
’complement’: complement displayed pixels

There may not be all functions available, depending on the physical display. However, "‘copy"’ is always available.
Attention

Parameter
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window_id.
. Mode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Name of the display function.
Default Value : ’copy’
List of values : Mode ∈ {’copy’, ’xor’, ’complement’}

HALCON 8.0.2
386 CHAPTER 4. GRAPHICS

Result
SetInsert returns TRUE if the paramter is correct and the window is valid. Otherwise an exception handling is
raised.
Parallelization Information
SetInsert is reentrant, local, and processed without parallelization.
Possible Predecessors
QueryInsert, GetInsert
Possible Successors
DispRegion
See also
GetInsert, QueryInsert
Module
Foundation

void HWindowX.SetLineApprox ([in] long Approximation )


void HOperatorSetX.SetLineApprox ([in] VARIANT WindowHandle,
[in] VARIANT Approximation )

Define the approximation error for contour display.


SetLineApprox defines the approximation error for region contour display in the window. Approximation
values greater than zero cause a polygon approximation ≈ smoothing (with a maximum polygon/contour de-
viation of Approximation pixel). The approximation algorithm is the same as in GetRegionPolygon.
SetLineApprox is important for contour output via SetLineStyle.
Attention

Parameter
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window_id.
. Approximation (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Maximum deviation from the original contour.
Default Value : 0
Restriction : (Approximation ≥ 0)
Example

/* Calling */
set_line_approx(WindowHandle,Approximation)
set_draw(WindowHandle,’margin’)
disp_region(Obj,WindowHandle).

/* correspond with */
get_region_polygon(Obj,Approximation,Row,Col)
disp_polygon(WindowHandle,Row,Col).

Result
SetLineApprox returns TRUE if the parameter is correct and the window is valid. Otherwise an exception
handling is raised.
Parallelization Information
SetLineApprox is reentrant and processed without parallelization.
Possible Predecessors
GetLineApprox
Possible Successors
DispRegion

HALCON/COM Reference Manual, 2008-5-13


4.6. PARAMETERS 387

See also
GetLineApprox, SetLineStyle, SetDraw, DispRegion
Alternatives
GetRegionPolygon, DispPolygon
Module
Foundation

void HWindowX.SetLineStyle ([in] VARIANT Style )


void HOperatorSetX.SetLineStyle ([in] VARIANT WindowHandle,
[in] VARIANT Style )

Define a contour output pattern.


SetLineStyle defines the output pattern of region contours. The information is used by procedures like
DispRegion, DispLine, DispPolygon etc. The current value can be queried with GetLineStyle.
Style contains up to five pairs of values. The first value is the length of the visible contour part, the second is the
length of the invisible part. The value pairs are used cyclical for contour output.
Attention
SetLineStyle does an implicit polygon approximation (see SetLineApprox(::WindowHandle,3:)).
It is only possible to enlarge it with SetLineApprox.
Parameter

. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT


Window_id.
. Style (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Contour pattern.
Default Value : []
Example

* stroke line: X-Windows


set_line_style(WindowHandle,[20,7])
* point-stroke line: X-Windows
set_line_style(WindowHandle,[20,7,3,7])
* passing line (standard)
set_line_style(WindowHandle,[])

Result
SetLineStyle returns TRUE if the parameter is correct and the window is valid. Otherwise an exception
handling is raised.
Parallelization Information
SetLineStyle is reentrant, local, and processed without parallelization.
Possible Predecessors
GetLineStyle
Possible Successors
DispRegion
See also
GetLineStyle, SetLineApprox, DispRegion
Module
Foundation

HALCON 8.0.2
388 CHAPTER 4. GRAPHICS

void HWindowX.SetLineWidth ([in] long Width )


void HOperatorSetX.SetLineWidth ([in] VARIANT WindowHandle,
[in] VARIANT Width )

Define the line width for region contour output.


SetLineWidth defines the line width (in pixel) in which a region contour is displayed (e.g. with DispRegion,
DispLine, DispPolygon, etc.) The procedure GetLineWidth returns the current value for the window.
Some output devices may not allow to change the contour width. If it is possible for the current device, it can be
queried with QueryLineWidth.
Attention
The line width is important if the output mode was set to ’margin’ (see SetDraw). If the line width is greater
than one, regions may not always be displayed correctly.
Parameter
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window_id.
. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Line width for region output in contour mode.
Default Value : 1
Restriction : ((W idth ≥ 1) ∧ (W idth ≤ 2000))
Result
SetLineWidth returns TRUE if the parameter is correct and the window is valid. Otherwise an exception
handling is raised.
Parallelization Information
SetLineWidth is reentrant and processed without parallelization.
Possible Predecessors
QueryLineWidth, GetLineWidth
Possible Successors
DispRegion
See also
GetLineWidth, QueryLineWidth, SetDraw, DispRegion
Module
Foundation

void HWindowX.SetPaint ([in] VARIANT Mode )


void HOperatorSetX.SetPaint ([in] VARIANT WindowHandle,
[in] VARIANT Mode )

Define the grayvalue output mode.


SetPaint defines the output mode for gray value display (single- or multichannel) in the window. The mode is
used by DispObj, DispImage, and DispColor.
This page describes the different modes that can be used for gray value output. It should be noted that the mode
’default’ is the most suitable in almost all cases.
The hardware characteristics determine how gray values can be displayed. On a screen with one to seven bit planes,
only binary data can be displayed. On screens with at least eight bit planes, it is possible to display multiple gray
values. For binary displays, HALCON includes algorithms using a dithering matrix (fast, but low resolution),
minimal error (good, but slow) and thresholding. Using the thresholding algorithm, the threshold can be passed as
a second parameter (a tuple with the string ’threshold’ and the actual threshold, e.g.: [’theshold’, 100]).
Displays with eight bit planes use approximately 200 gray values for output. Of course it is still possible to use a
binary display on those displays.
A different way to display gray values is the histogram (mode: ’histogram’). This mode has two additional
parameter values: Row (second value) and column (third value). They denote row and column of the histogram

HALCON/COM Reference Manual, 2008-5-13


4.6. PARAMETERS 389

center for positioning on the screen. The scale factor (fourth value) determines the histogram size: a scale factor of
1 distinguishes 256 grayvalues, 2 distinguishes 128 gray values, 3 distinguishes 64 gray values, and so on. The four
values are passed as a tuple, e.g. [’histogram’,256,256,1]. If only the first value is passed (’histogram’), the other
values are set to defaults or the last values, respectively. For histogram computation see GrayHisto. Histogram
output honors the same parameters as procedures like DispRegion etc. (e.g. SetColor, SetDraw, etc.)
Yet another mode is the display of relative frequencies of the number of connection components ("’compo-
nent_histogram"’). For informations on computing the component histogram see ShapeHistoAll). Positioning
and resolution are exactly as in the mode ’histogram’.
In mode ’mean’, all object regions are displayed in their mean gray value.
The modes ’row’ and ’column’ allow the display of lines or columns, respecively. The position (row and column
index) is passed with the second paramter value. The third parameter value is the scale factor in percent (100
means 1 pixel per grayvalue, 50 means one pixel per two gray values).
Gray images can also be interpreted as 3d data, depending on the grayvalue. To view these 3d plots, select the
modes ’contourline’, ’3D-plot’ or ’3D-plot_hidden’.
Three-channel images are interpreted as RGB images. They can be displayed in three different modes. Two of
them can be optimized by Floyd-Steinberg dithering.
Vector field images can be viewed as ’vector_field’.
All available painting modes can be queried with QueryPaint.
Paramters for modes that need more than one parameter can be passed the following ways:

• Only the name of the mode is passed: the defaults or the most recently used values are used, respectively.
Example: SetPaint(WindowHandle,’contourline’)
• All values are passed: all output characteristics can be set. Example: SetPaint
(WindowHandle,[’contourline’,10,1])
• Only the first n values are passed: only the passed values are changed. Example: SetPaint
(WindowHandle,[’contourline’,10])
• Some of the values are replaced by an asterisk (’*’): The value of the replaced parameters is not changed.
Example: SetPaint(WindowHandle,[’contourline’,’*’,1])

If the current mode is ’default’, HALCON chooses a suitable algorithm for the output of 2- and 3-channel images.
No SetPaint call is necessary in this case.
Apart from SetPaint there are other operators that affect the output of grayvalues. The most important of
them are SetPart, SetPartStyle, SetLut and SetLutStyle. Some output modes display gray-
values using region output (e.g. ’histogram’,’contourline’,’3D-plot’, etc.). In these modes, paramters set with
SetColor, SetRgb, SetHsi, SetPixel, SetShape, SetLineWidth and SetInsert influence
grayvalue output. This can lead to unexpected results when using SetShape(’convex’) and SetPaint
(WindowHandle,’histogram’). Here the convex hull of the histogram is displayed.
Modes:

• one-channel images:
’default’ optimal display on given hardware
’gray’ grayvalue output
’mean’ mean grayvalue
’dither4_1’ binary image, dithering matrix 4x4
’dither4_2’ binary image, dithering matrix 4x4
’dither4_3’ binary image, dithering matrix 4x4
’dither8_1’ binary image, dithering matrix 8x8
’floyd_steinberg’ binary image, optimal grayvalue simulation
[’threshold’,Threshold ]
’threshold’ binary image, threshold: 128 (default)
[’threshold’,200 ] binary image, any threshold: (here: 200)
[’histogram’,Line,Column,Scale ]
’histogram’ grayvalue output as histogram.
position default: max. size, in the window center

HALCON 8.0.2
390 CHAPTER 4. GRAPHICS

[’histogram’,256,256,2 ] grayvalue output as histogram, any parameter values.


positioning: window center (here (256,256))
size: (here 2, half the max. size)
[’component_histogram’,Line,Column,Scale ]
’component_histogram’ output as histogram of the connection components.
Positioning: default
[’component_histogram’,256,256,1 ] output as histogram of the connection components.
Positioning: (here (256, 256))
Scaling: (here 1, max. size)
[’row’,Line,Scale ]
’row’ output of the grayvalue profile along the given line.
line: image center (default)
Scaling: 50
[’row’,100,20 ] output of the grayvalue profile of line 100 with a scaling of 0.2 (20
[’column’,Column,Scale ]
’column’ output of the grayvalue profile along the given column.
column: image center (default)
Scaling: 50
[’column’,100,20 ] output of the grayvalue profile of column 100 with a scaling of 0.2 (20
[’contourline’,Step,Colored ]
’contourline’ grayvalue output as contour lines: the grayvalue difference per line is defined with the
parameter ’Step’ (default: 30, i.e. max. 8 lines for 256 grayvalues). The line can be displayed in
a given color (see set_color) or in the grayvalue they represent. This behaviour is defined with the
parameter ’Colored’ (0 = color, 1 = grayvalues). Default is color.
[’contourline’,15,1 ] grayvalue output as contour lines with a step of 15 and gray output.
[’3D-plot’, Step, Colored, EyeHeight, EyeDistance, ScaleGray, LinePos, ColumnPos]
’3D-plot’ grayvalues are interpreted as 3d data: the greater the value, the ’higher’ the assumed moun-
tain. Lines with step 2 (second paramter value) are drawn along the x- and y-axes. The third pa-
rameter (Colored) determines, if the output should be in color (default) or grayvalues. To define the
projection of the 3d data, use the parameters EyeHeight and EyeDistance. The projection parameters
take values from 0 to 255. ScaleGray defines a factor, by which the grayvalues are multiplied for
’height’ interpretation (given in percent. 100EyeHeight and EyeDistance the image can be shifted
out of place. Use RowPos and ColumnPos to move the whole output. Values from -127 to 127 are
possible.
[’3D-plot’, 5, 1, 110, 160, 150, 70, -10 ] line step: 5 pixel
Colored: yes (1)
EyeHeight: 110
EyeDistance: 160
ScaleGray: 1.5 (150)
RowPos: 70 pixel down
ColumnPos: 10 pixel right
[’3D-plot_hidden’, Step, Colored, EyeHeight, EyeDistance, ScaleGray, LinePos, ColumnPos]
’3D-plot_hidden’ like ’3D-plot’, but computes hidden lines.
• Two-channel images:
’default’ output the first channel.
• Three-channel images:
’default’ output as RGB image with ’median_cut’.
’television’ color addition algorithm for RGB images: (three components necessary for DispImage).
Images are displayed via a fixed color lookup table. Fast, but non-optimal color resolution. Only recom-
mended on bright screens.
’grid_scan’ grid-scan algorithm for RGB images (three components necessary for DispImage). An op-
timized color lookup table is generated for each image. Slower than ’television’. Disadvantages: Hard
color boundaries (no dithering). Different color lookup table for every image.
’grid_scan_floyd_steinberg’ grid-scan with Floyd-Steinberg dithering for smooth color boundaries.

HALCON/COM Reference Manual, 2008-5-13


4.6. PARAMETERS 391

’median_cut’ median-cut algorithm for RGB images (three components necessary for DispImage). Sim-
ilar to grid-scan. Disadvantages: Hard color boundaries (no dithering). Different color lookup table for
every image.
’median_cut_floyd_steinberg’ median-cut algorithm with Floyd-Steinberg dithering for smooth color
boundaries.
• Vector field images:
[’vector_field’, Step, MinLengh, ScaleLength ]
’vector_field’ Output a vector field. In this mode, a circle is drawn for each vector at the position of
the pixel. Furthermore, a line segment is drawn with the current vector. The step size for drawing
the vectors, i.e., the distance between the drawn vectors, can be set with the parameter Step. Short
vectors can be suppressed with the third parameter value (MinLength). The fourth parameter value
scales the vector length. It should be noted that by setting ’vector_field’ only the internal param-
eters Step, MinLengh, and ScaleLength are changed. The current display mode is not changed.
Vector field images are always displayed as vector field, no matter which mode is selected with
SetPaint.
[’vector_field’,16,2,3 ] Output of every 16. vector, that is longer than 2 pixel. Each vector is multiplied
by 3 for output.

Attention

• Display of color images (’television’, ’grid_scan’, etc.) changes the color lookup tables.
• If a wrong color mode is set, the error message may appear not until the DispImage call.
• Grayvalue output may be influenced by region output parameters. This can yield unexpected results.

Parameter

. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT


Window_id.
. Mode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( integer, string )
Output mode. Additional parameters possible.
Default Value : ’default’
List of values : Mode ∈ {’default’, ’histogram’, ’row’, ’column’, ’contourline’, ’3D-plot’, ’3D-plot_hidden’,
’3D-plot_point’, ’vector_field’}
Example

read_image(Image,’fabrik’)
open_window(0,0,-1,-1,’root’,’visible’,"’,WindowHandle)
query_paint(WindowHandleModi)
fwrite_string([’available gray value modes: ’,Modi])
fnew_line()
disp_image(Image,WindowHandle)
get_mbutton(WindowHandle,_,_,_)
set_color(WindowHandle,’red’)
set_draw(WindowHandle,’margin’)
set_paint(WindowHandle,’histogram’)
disp_image(Image,WindowHandle)
set_color(WindowHandle,’blue’)
set_paint(WindowHandle,[’histogram’,100,100,3])
disp_image(Image,WindowHandle)
set_color(WindowHandle,’yellow’)
set_paint(WindowHandle,[’row’,100])
disp_image(Image,WindowHandle)
get_mbutton(WindowHandle,_,_,_)
clear_window(WindowHandle)
set_paint(WindowHandle,[’contourline’,10,1])
disp_image(Image,WindowHandle)

HALCON 8.0.2
392 CHAPTER 4. GRAPHICS

set_lut(WindowHandle,’color’)
get_mbutton(WindowHandle,_,_,_)
clear_window(WindowHandle)
set_part(WindowHandle,100,100,300,300)
set_paint(WindowHandle,’3D-plot’)
disp_image(Image,WindowHandle).

Result
SetPaint returns TRUE if the parameter is correct and the window is valid. Otherwise an exception handling is
raised.
Parallelization Information
SetPaint is reentrant, local, and processed without parallelization.
Possible Predecessors
QueryPaint, GetPaint
Possible Successors
DispImage
See also
GetPaint, QueryPaint, DispImage, SetShape, SetRgb, SetColor, SetGray
Module
Foundation

void HWindowX.SetPart ([in] long Row1, [in] long Column1, [in] long Row2,
[in] long Column2 )
void HOperatorSetX.SetPart ([in] VARIANT WindowHandle,
[in] VARIANT Row1, [in] VARIANT Column1, [in] VARIANT Row2,
[in] VARIANT Column2 )

Modify the displayed image part.


SetPart modifies the image part that is displayed in the window. (Row1,Column1) denotes the upper left
corner and (Row2,Column2) the lower right corner of the image part to display. The changed values are used by
grayvalue output operators ( DispImage, DispColor) as well as region output operators ( DispRegion)).
If only part of an image is displayed, it will be zoomed to full window size. The zooming interpolation method
can be set with SetPartStyle. GetPart returns the values of the image part to display.
Beside setting the image part directly, the following special modes are supported:

Row1 = Column1 = Row2 = Column2 = -1: The window size is choosen as the image part, i.e. no zooming of
the image will be performed.
Row1, Column1 > -1 and Row2 = Column2 = -1: The size of the last displayed image (in this window) is
choosen as the image part, i.e. the image can completely be displayed in the image. For this the image
will be zoomed if necessary.

Parameter
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window_id.
. Row1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.origin.y ; long / VARIANT
Row of the upper left corner of the chosen image part.
Default Value : 0
. Column1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.origin.x ; long / VARIANT
Column of the upper left corner of the chosen image part.
Default Value : 0
. Row2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.corner.y ; long / VARIANT
Row of the lower right corner of the chosen image part.
Default Value : -1
Restriction : ((Row2 ≥ Row1) ∨ (Row2 = −1))

HALCON/COM Reference Manual, 2008-5-13


4.6. PARAMETERS 393

. Column2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.corner.x ; long / VARIANT


Column of the lower right corner of the chosen image part.
Default Value : -1
Restriction : ((Column2 ≥ Column1) ∨ (Column2 = −1))
Example

get_system(’width’,,Width)
get_system(’height’,Height)
set_part(WindowHandle,0,0,Height-1,Width-1)
disp_image(Image,WindowHandle)
draw_rectangle1(WindowHandle:Row1,Column1,Row2,Column2)
set_part(WindowHandle,Row1,Column1,Row2,Column2)
disp_image(Image,WindowHandle).

Result
SetPart returns TRUE if the window is valid. Otherwise an exception handling is raised.
Parallelization Information
SetPart is reentrant and processed without parallelization.
Possible Predecessors
GetPart
Possible Successors
SetPartStyle, DispImage, DispRegion
See also
GetPart, SetPartStyle, DispRegion, DispImage, DispColor
Alternatives
AffineTransImage
Module
Foundation

void HWindowX.SetPartStyle ([in] long Style )


void HOperatorSetX.SetPartStyle ([in] VARIANT WindowHandle,
[in] VARIANT Style )

Define an interpolation method for grayvalue output.


SetPartStyle defines the interpolation method to zoom an image part which is displayed in the window.
Interpolation takes place, if the output window has different size than the image to display (e.g. after a call to
SetPart or a window resize). Three modes are supported:

0 no interpolation (low quality, very fast).


1 unweighted interpolation (medium quality and run time)
2 weighted interpolation (high quality, slow)

The current value can be queried with GetPartStyle.


Attention

Parameter
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window_id.
. Style (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Interpolation method for image output: 0 (fast, low quality) to 2 (slow, high quality).
Default Value : 0
List of values : Style ∈ {0, 1, 2}

HALCON 8.0.2
394 CHAPTER 4. GRAPHICS

Result
SetPartStyle returns TRUE if the parameter is correct and the window is valid. Otherwise an exception
handling is raised.
Parallelization Information
SetPartStyle is reentrant and processed without parallelization.
Possible Predecessors
GetPartStyle
Possible Successors
SetPart, DispImage, DispRegion
See also
GetPartStyle, SetPart, DispImage, DispColor
Alternatives
AffineTransImage
Module
Foundation

void HWindowX.SetPixel ([in] VARIANT Pixel )


void HOperatorSetX.SetPixel ([in] VARIANT WindowHandle,
[in] VARIANT Pixel )

Define a color lookup table index.


SetPixel sets pixel values: colors ( SetColor, SetRgb, etc.) and grayvalues ( SetGray) are coded together
into a number, called pixel. This ’pixel’ is an index in the color lookup table. It ranges from 0 to 1 in b/w images
and 0 to 255 color images with 8 bit planes. It is different from the ’pixel’ ("picture element") in image processing.
Therefore HALCON distinguishes between pixel and image element (or grayvalue).
The current value can be queried with GetPixel.
Attention

Parameter

. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT


Window_id.
. Pixel (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Color lookup table index.
Default Value : 128
Typical range of values : 0 ≤ Pixel ≤ 0
Result
SetPixel returns TRUE if the parameter is correct and the window is valid. Otherwise an exception handling is
raised.
Parallelization Information
SetPixel is reentrant, local, and processed without parallelization.
Possible Predecessors
GetPixel
Possible Successors
DispImage, DispRegion
See also
GetPixel, SetLut, DispRegion, DispImage, DispColor
Alternatives
SetRgb, SetColor, SetHsi
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


4.6. PARAMETERS 395

void HWindowX.SetRgb ([in] VARIANT Red, [in] VARIANT Green,


[in] VARIANT Blue )
void HOperatorSetX.SetRgb ([in] VARIANT WindowHandle, [in] VARIANT Red,
[in] VARIANT Green, [in] VARIANT Blue )

Set the color definition via RGB values.


SetRgb sets the output color(s) or the grayvalues, respectively, for region output for the window. The colors are
defined with the red, green and blue components. If only one combination is passed, all output takes place in that
color. If a tuple is passed, region output and output of geometric objects takes place modulo the passed colors.
For every call of an output procedure, output is started with the first color. If only one object is displayed per call,
it will always be displayed in the first color. This is even true for objects with multiple connection components.
If multiple objects are displayed per procedure call, multiple colors are used. The defined colors are used until
SetColor, SetPixel, SetRgb or SetGray is called again. The values are used by procedures like
DispRegion, DispLine, DispRectangle1, DispRectangle2, DispArrow, etc.
Attention
If a passed is not available, an exception handling is raised. If SetCheck(::’˜color’:) was called before,
HALCON uses a similar color and suppresses the error.
Parameter

. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT


Window_id.
. Red (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Red component of the color.
Default Value : 255
Typical range of values : 0 ≤ Red ≤ 0
Restriction : ((0 ≤ Red) ∧ (Red ≤ 255))
. Green (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Green component of the color.
Default Value : 0
Typical range of values : 0 ≤ Green ≤ 0
Restriction : ((0 ≤ Green) ∧ (Green ≤ 255))
. Blue (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Blue component of the color.
Default Value : 0
Typical range of values : 0 ≤ Blue ≤ 0
Restriction : ((0 ≤ Blue) ∧ (Blue ≤ 255))
Result
SetRgb returns TRUE if the window is valid and all passed colors are available and displayable. Otherwise an
exception handling is raised.
Parallelization Information
SetRgb is reentrant, local, and processed without parallelization.
Possible Successors
DispImage, DispRegion
See also
SetFix, DispRegion
Alternatives
SetHsi, SetColor, SetGray
Module
Foundation

HALCON 8.0.2
396 CHAPTER 4. GRAPHICS

void HWindowX.SetShape ([in] String Shape )


void HOperatorSetX.SetShape ([in] VARIANT WindowHandle,
[in] VARIANT Shape )

Define the region output shape.


SetShape defines the shape for region output. It is only valid for the window with the logical window num-
ber WindowHandle. The output shape is used by DispRegion. The available shapes can be queried with
QueryShape.
Available modes:

’original’: The shape is displayed unchanged. Nevertheless modifications via parameters like set_line_width or
set_line_approx can take place. This is also true for all other modes.
’outer_circle’: Each region is displayed by the smallest surrounding circle. (See SmallestCircle.)
’inner_circle’: Each region is displayed by the largest included circle. (See InnerCircle.)
’ellipse’: Each region is displayed by an ellipse with the same moments and orientation (See EllipticAxis.)
’rectangle1’: Each region is displayed by the smallest surrounding rectangle parallel to the coordinate axes. (See
SmallestRectangle1.)
’rectangle2’: Each region is displayed by the smallest surrounding rectangle. (See SmallestRectangle2.)
’convex’: Each region is displayed by its convex hull (See Convexity.)
’icon’ Each region is displayed by the icon set with SetIcon in the center of gravity.

Attention
Caution is advised for grayvalue output procedures with output parameter settings that use region out-
put, e.g. DispImage with SetPaint(::WindowHandle,’histogram’:) and SetShape(::
WindowHandle,’convex’:). In that case the convex hull of the grayvalue histogram is displayed.
Parameter
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window_id.
. Shape (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Region output mode.
Default Value : ’original’
List of values : Shape ∈ {’original’, ’convex’, ’outer_circle’, ’inner_circle’, ’rectangle1’, ’rectangle2’,
’ellipse’, ’icon’}
Example

read_image(Image,’fabrik’)
regiongrowing(Image,Seg,5,5,6,100)
set_colored(WindowHandle,12)
set_shape(WindowHandle,’rectangle2’)
disp_region(Seg,WindowHandle).

Result
SetShape returns TRUE if the parameter is correct and the window is valid. Otherwise an exception handling is
raised.
Parallelization Information
SetShape is reentrant and processed without parallelization.
Possible Predecessors
SetIcon, QueryShape, GetShape
Possible Successors
DispRegion
See also
GetShape, QueryShape, DispRegion
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


4.7. TEXT 397

4.7 Text
HWindowX.GetFont ( )
[out] String Font
void HOperatorSetX.GetFont ([in] VARIANT WindowHandle,
[out] VARIANT Font )

Get the current font.


GetFont queries the name of the font used in the output window. The font is used by the operators
WriteString, ReadString etc. The font is set by the operator SetFont. Text windows as well as windows
for image display use fonts. Both types of windows have a default font that can be modified with SetSystem
(’defaultFont’,Fontname) prior to opening the window. A list of all available fonts can be obtained using
QueryFont.
Parameter
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window identifier.
. Font (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Name of the current font.
Example

get_font(WindowHandle,CurrentFont)
set_font(WindowHandle,MyFont)
write_string(WindowHandle,[’The name of my Font is:’,Myfont])
new_line(WindowHandle)
set_font(WindowHandle,CurrentFont)

Result
GetFont returns TRUE.
Parallelization Information
GetFont is reentrant and processed without parallelization.
Possible Predecessors
OpenWindow, OpenTextwindow, QueryFont
Possible Successors
SetFont
See also
SetFont, QueryFont, OpenWindow, OpenTextwindow, SetSystem
Module
Foundation

[out] long Ascent HWindowX.GetStringExtents ([in] VARIANT Values,


[out] long Descent, [out] long Width, [out] long Height )
void HOperatorSetX.GetStringExtents ([in] VARIANT WindowHandle,
[in] VARIANT Values, [out] VARIANT Ascent, [out] VARIANT Descent,
[out] VARIANT Width, [out] VARIANT Height )

Get the spatial size of a string.


GetStringExtents queries width and height of the output size of a string using the font of the window. In
addition the extension above and below the current baseline for writing is returned (Ascent bzw. Descent).
The sizes are measured in the coordinate system of the window (for text windows in pixels). Using
GetStringExtents it is possible to determine text output and input independently from the used font. The
conversion from integer numbers and floating point numbers to text strings is the same as in WriteString.
Attention

HALCON 8.0.2
398 CHAPTER 4. GRAPHICS

Parameter
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window identifier.
. Values (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string, real, integer )
Values to consider.
Default Value : ’test_string’
. Ascent (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Maximum height above baseline for writing.
. Descent (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Maximum extension below baseline for writing.
. Width (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Text width.
. Height (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Text height.
Result
GetStringExtents returns TRUE if the window is valid. Otherwise an exception handling is raised.
Parallelization Information
GetStringExtents is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow, OpenTextwindow, SetFont
Possible Successors
SetTposition, WriteString, ReadString, ReadChar
See also
SetTposition, SetFont
Module
Foundation

HWindowX.GetTposition ([out] long Column )


[out] long Row
void HOperatorSetX.GetTposition ([in] VARIANT WindowHandle,
[out] VARIANT Row, [out] VARIANT Column )

Get cursor position.


GetTposition queries the current position of the text cursor in the output window. The position is measured in
the coordinate system of the window (in pixels for text windows). The next output of text in this window starts at
the cursor position. The left end of the baseline for writing the next string (not considering descenders) is placed
on this position. The position is changed by the output or input of text ( WriteString, ReadString) or by
an explicit change of position by ( SetTposition, NewLine).
Attention
If the output text does not fit completely into the window, an exception handling is raised. This can be avoided by
SetCheck(’˜text’).
Parameter
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window identifier.
. Row (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; long / VARIANT
Row index of text cursor position.
. Column (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; long / VARIANT
Column index of text cursor position.
Result
GetTposition returns TRUE if the window is valid. Otherwise an exception handling is raised.
Parallelization Information
GetTposition is reentrant, local, and processed without parallelization.

HALCON/COM Reference Manual, 2008-5-13


4.7. TEXT 399

Possible Predecessors
OpenWindow, OpenTextwindow, SetFont
Possible Successors
SetTposition, WriteString, ReadString, ReadChar
See also
NewLine, ReadString, SetTposition, WriteString, SetCheck
Module
Foundation

HWindowX.GetTshape ( )
[out] String TextCursor
void HOperatorSetX.GetTshape ([in] VARIANT WindowHandle,
[out] VARIANT TextCursor )

Get the shape of the text cursor.


GetTshape queries the shape of the text cursor for the output window. A new cursor shape is set by the operator
SetTshape.
A text cursor marks the current position for text output (which can also be invisible). It is different from the mouse
cursor (although both will be called "’cursor"’ if the context makes misconceptions impossible). The available
shapes for the text cursor can be queried with QueryTshape.
Parameter
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window identifier.
. TextCursor (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Name of the current text cursor.
Result
GetTshape returns TRUE if the window is valid. Otherwise an exception handling is raised.
Parallelization Information
GetTshape is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow, OpenTextwindow, SetFont
Possible Successors
SetTshape, SetTposition, WriteString, ReadString, ReadChar
See also
SetTshape, QueryTshape, WriteString, ReadString
Module
Foundation

void HWindowX.NewLine ( )
void HOperatorSetX.NewLine ([in] VARIANT WindowHandle )

Set the position of the text cursor to the beginning of the next line.
NewLine sets the position of the text cursor to the beginning of the next line. The new position depends on the
current font. The left end of the baseline for writing the following text string (not considering descenders) is placed
on this position.
If the next line does not fit into the window the content of the window is scrolled by the height of one line in the
upper direction. In order to reach the correct new cursor position the font used in the next line must be set before
NewLine is called. The position is changed by the output or input of text ( WriteString, ReadString) or
by an explicit change of position by ( SetTposition).

HALCON 8.0.2
400 CHAPTER 4. GRAPHICS

Parameter
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window identifier.
Result
NewLine returns TRUE if the window is valid. Otherwise an exception handling is raised.
Parallelization Information
NewLine is reentrant and processed without parallelization.
Possible Predecessors
OpenWindow, OpenTextwindow, SetFont, WriteString
See also
WriteString, SetFont
Alternatives
GetTposition, GetStringExtents, SetTposition, MoveRectangle
Module
Foundation

[out] VARIANT Font HWindowX.QueryFont ( )


void HOperatorSetX.QueryFont ([in] VARIANT WindowHandle,
[out] VARIANT Font )

Query the available fonts.


QueryFont queries the fonts available for text output in the output window. They can be set with the operator
SetFont. Fonts are used by the operators WriteString, ReadChar, ReadString and NewLine.
Attention
For different machines the available fonts may differ a lot. Therefore QueryFont will return different fonts on
different machines.
Parameter
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window identifier.
. Font (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( string )
Tuple with available font names.
Example

open_window(0,0,-1,-1,’root’,’visible’,’’,WindowHandle)
set_check(’~text’)
query_font(WindowHandle,Fontlist)
set_color(WindowHandle,’white’)
for i=0 to |Fontlist|-1 by 1
set_font(WindowHandle,Fontlist[i])
write_string(WindowHandle,Fontlist[i])
new_line(WindowHandle)
endfor

Result
QueryFont returns TRUE.
Parallelization Information
QueryFont is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow, OpenTextwindow
Possible Successors
SetFont, WriteString, ReadString, ReadChar

HALCON/COM Reference Manual, 2008-5-13


4.7. TEXT 401

See also
SetFont, WriteString, ReadString, ReadChar, NewLine
Module
Foundation

HWindowX.QueryTshape ( )
[out] VARIANT TextCursor
void HOperatorSetX.QueryTshape ([in] VARIANT WindowHandle,
[out] VARIANT TextCursor )

Query all shapes available for text cursors.


QueryTshape queries the available shapes of text cursors for the output window. The retrieved shapes can be
used by the operator SetTshape.
Parameter
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window identifier.
. TextCursor (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( string )
Names of the available text cursors.
Result
QueryTshape returns TRUE.
Parallelization Information
QueryTshape is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow, OpenTextwindow
Possible Successors
SetTshape, WriteString, ReadString
See also
SetTshape, GetShape, SetTposition, WriteString, ReadString
Module
Foundation

HWindowX.ReadChar ([out] String Code )


[out] String Char
void HOperatorSetX.ReadChar ([in] VARIANT WindowHandle,
[out] VARIANT Char, [out] VARIANT Code )

Read a character from a text window.


ReadChar reads a character from the keyboard in the input window (= output window). If the character is
printable it is returned in Char. If a control key has been pressed, this will be indicated by the value of Code.
Some important keys are recognizable by this value. Possible values are:
’character’: printable character
’left’: cursor left
’right’: cursor right
’up’: cursor up
’down’: cursor down
’insert’: insert
’none’: none of these keys
Attention
The window has to be a text window.

HALCON 8.0.2
402 CHAPTER 4. GRAPHICS

Parameter

. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT


Window identifier.
. Char (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Input character (if it is not a control character).
. Code (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Code for input character.
Result
ReadChar returns TRUE if the text window is valid. Otherwise an exception handling is raised.
Parallelization Information
ReadChar is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenTextwindow, SetFont
See also
WriteString, SetFont
Alternatives
ReadString, FreadChar, FreadString
Module
Foundation

[out] String OutString HWindowX.ReadString ([in] String InString,


[in] long Length )
void HOperatorSetX.ReadString ([in] VARIANT WindowHandle,
[in] VARIANT InString, [in] VARIANT Length, [out] VARIANT OutString )

Read a string in a text window.


ReadString reads a string with a predetermined maximum size (Length) from the keyboard in the input
window (= output window). The string is read from the current position of the text cursor using the current font.
The maximum size has to be small enough to keep the string within the right window boundary. A default string
which can be edited or simply accepted by the user may be provided. After text input the text cursor is positioned
at the end of the edited string. Commands for editing:

RETURN finish input


BACKSPACE delete the character on the left side of the cursor and move the cursor to this position.

Parameter

. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT


Window identifier.
. InString (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Default string (visible before input).
Default Value : ”
. Length (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Maximum number of characters.
Default Value : 32
Restriction : (Length > 0)
. OutString (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Read string.
Result
ReadString returns TRUE if the text window is valid and a string of maximal length fits within the right window
boundary. Otherwise an exception handling is raised.
Parallelization Information
ReadString is reentrant, local, and processed without parallelization.

HALCON/COM Reference Manual, 2008-5-13


4.7. TEXT 403

Possible Predecessors
OpenTextwindow, SetFont
See also
SetTposition, NewLine, OpenTextwindow, SetFont, SetColor
Alternatives
ReadChar, FreadString, FreadChar
Module
Foundation

void HWindowX.SetFont ([in] String Font )


void HOperatorSetX.SetFont ([in] VARIANT WindowHandle,
[in] VARIANT Font )

Set the font used for text output.


SetFont sets the font for the output window. The font is used by the operators WriteString, ReadString
etc. A default font (which can be set via SetSystem(’defaultFont’,Fontname)) is assigned when a
window is opened. The assigned font can be changed with SetFont. All available fonts can be queried with
QueryFont. Fonts are not used for file operations.
The syntax for the specification of a font (in Font) differs for UNIX and Windows environments: In Windows a
string with the following components is used:

-FontName-Height-Width-Italic-Underlined-Strikeout-Bold-CharSet-

where “Italic”, “Underlined”, “Strikeout” and “Bold” can take the values 1 and 0 to activate or de-
activate the corresponding feature. “Charset” can be used to select the character set, if it differs
from the default one. You can use the names of the defines (ANSI_CHARSET, BALTIC_CHARSET,
CHINESEBIG5_CHARSET, DEFAULT_CHARSET, EASTEUROPE_CHARSET, GB2312_CHARSET,
GREEK_CHARSET, HANGUL_CHARSET, MAC_CHARSET, OEM_CHARSET, RUSSIAN_CHARSET,
SHIFTJIS_CHARSET, SYMBOL_CHARSET, JOHAB_CHARSET, HEBREW_CHARSET, ARA-
BIC_CHARSET) or the integer value.
All parameters beside “FontName” und “Height” are optional, however it is only possible to omit parameters from
the end of the string. At the begin and end of the string a minus is required. To use the default setting, a * can be
used for the corresponding feature. Examples:

• -Arial-10-*-1-*-*-1-ANSI_CHARSET-
• -Arial-10-*-1-*-*-1-
• -Arial-10-

Please refer to the Windows documentation (Fonts and Text in the MSDN) for a detailed discussion.
On UNIX environments the Font is specified by a string with the following components:
-FOUNDRY-FAMILY_NAME-WEIGHT_NAME-SLANT-SETWIDTH_NAME-ADD_STYLE_NAME-PIXEL_SIZE
-POINT_SIZE-RESOLUTION_X-RESOLUTION_Y-SPACING-AVERAGE_WIDTH-CHARSET_REGISTRY
-CHARSET_ENCODING,
where FOUNDRY identifies the organisation that supplied the Font. The actual name of Font is given in FAM-
ILY_NAME (e.g. ’courier’). WEIGHT_NAME describes the typographic weight of the Font in human readable
form (e.g. ’medium’, ’semibold’, ’demibold’, or ’bold’). SLANT is one of the following codes:

• r for Roman
• i for Italic
• o for Oblique
• ri for Reverse Italic
• ro for Reverse Oblique

HALCON 8.0.2
404 CHAPTER 4. GRAPHICS

• ot for Other

SET_WIDTH_NAME describes the proportionate width of the font (e.g. ’normal’). ADD_STYLE_NAME iden-
tifies additional typographic style information (e.g. ’serif’ or ’sans serif’) and is empty in most cases.
The PIXEL_SIZE is the height of the Font on the screen in pixel, while POINT_SIZE is the print size the Font
was designed for. RESOLUTION_Y and RESOLUTION_X contain the vertical and horizontal Resolution of the
Font. SPACING may be one of the following three codes:

• p for Proportional,
• m for Monospaced, or
• c for CharCell.

The AVERAGE_WIDTH is the mean of the width of each character in Font. The character set encoded in Font
is described in CHARSET_REGISTRY and CHARSET_ENCODING (e.g. ISO8859-1).
An example of a valid string for Font would be
’-adobe-courier-medium-r-normal–12-120-75-75-m-70-iso8859-1’,
which is a 12px medium weighted courier font. As on Windows systems not all fields have to be specified and a *
can be used instead:
’-adobe-courier-medium-r-*–12-*-*-*-*-*-*-*’.
Please refer to "X Logical Font Description Conventions" for detailed information on individual parameters.
Attention
For different machines the available fonts may differ a lot. Therefore it is suggested to use wildcards, tables of
fonts and/or the operator QueryFont.
Parameter

. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT


Window identifier.
. Font (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Name of new font.
Example

get_system (’operating_system’, OS)


if (OS{0:2} = ’Win’)
set_font (WindowHandle, ’-Courier New-18-*-*-*-*-1-’)
else
set_font (WindowHandle, ’-*-courier-bold-r-normal--22-*-*-*-*-*-iso8859-1’)

Result
SetFont returns TRUE if the font name is correct. Otherwise an exception handling is raised.
Parallelization Information
SetFont is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow, OpenTextwindow
Possible Successors
QueryFont
See also
GetFont, QueryFont, OpenTextwindow, OpenWindow
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


4.7. TEXT 405

void HWindowX.SetTposition ([in] long Row, [in] long Column )


void HOperatorSetX.SetTposition ([in] VARIANT WindowHandle,
[in] VARIANT Row, [in] VARIANT Column )

Set the position of the text cursor.


SetTposition sets the position of the text cursor in the output window. The reference position is the upper left
corner of an upper case character.
The position is measured in the image coordinate system. The position of the text cursor can be marked, e.g., by
an underscore. The next text output in this window starts at the cursor position. The left end of the baseline for
writing the following text string (not considering descenders) is placed on this position.
The position is changed by the output or input of text ( WriteString, ReadString) or by an explicit
change of position by ( SetTposition, NewLine). In order to stop the display of the cursor, the operator
SetTshape with the parameter "’invisible"’ can be used.
Parameter

. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT


Window identifier.
. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; long / VARIANT
Row index of text cursor position.
Default Value : 24
. Column (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; long / VARIANT
Column index of text cursor position.
Default Value : 12
Result
SetTposition returns TRUE if the window is valid. Otherwise an exception handling is raised.
Parallelization Information
SetTposition is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow, OpenTextwindow
Possible Successors
SetTshape, WriteString, ReadString
See also
ReadString, SetTshape, WriteString
Alternatives
NewLine
Module
Foundation

void HWindowX.SetTshape ([in] String TextCursor )


void HOperatorSetX.SetTshape ([in] VARIANT WindowHandle,
[in] VARIANT TextCursor )

Set the shape of the text cursor.


SetTshape sets the shape and the display mode of the text cursor of the output window.
A text cursor marks the current position for text output. It is different from the mouse cursor (although both will
be called ’cursor’, if the context makes misconceptions impossible). The available shapes for the text cursor can
be queried with QueryTshape.
Parameter

. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT


Window identifier.

HALCON 8.0.2
406 CHAPTER 4. GRAPHICS

. TextCursor (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT


Name of cursor shape.
Default Value : ’invisible’
Result
GetTshape returns TRUE if the window is valid and the given cursor shape is defined for this window. Otherwise
an exception handling is raised.
Parallelization Information
SetTshape is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow, OpenTextwindow, QueryTshape, GetTshape
Possible Successors
WriteString, ReadString
See also
GetTshape, QueryTshape, WriteString, ReadString
Module
Foundation

void HWindowX.WriteString ([in] VARIANT String )


void HOperatorSetX.WriteString ([in] VARIANT WindowHandle,
[in] VARIANT String )

Print text in a window.


WriteString prints String in the output window starting at the current cursor position. The output text has
to fit within the right window boundary (the width of the string can be queried by GetStringExtents).
The font currently assigned to the window will used. The text cursor is positioned at the end of the text.
WriteString can output all three types of data used in HALCON . The conversion to a string is guided by the
following rules:

• strings are not converted.


• integer numbers are converted without any spaces before or after the number.
• floating numbers are printed (if possible) with a floating point and without an exponent.
• the resulting strings are concatenated without spaces.

For buffering of texts see SetSystem with the flag ’flush_graphic’.


Attention
If clipping at the window boundary is desired, exceptions can be switched off by SetCheck(’˜text’).
Parameter
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window identifier.
. String (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( integer, real, string )
Tuple of output values (all types).
Default Value : ’hello’
Result
WriteString returns TRUE if the window is valid and the output text fits within the current line (see
SetCheck). Otherwise an exception handling is raised.
Parallelization Information
WriteString is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow, OpenTextwindow, SetFont, GetStringExtents
See also
SetTposition, GetStringExtents, OpenTextwindow, SetFont, SetSystem, SetCheck

HALCON/COM Reference Manual, 2008-5-13


4.8. WINDOW 407

Alternatives
FwriteString
Module
Foundation

4.8 Window
void HWindowX.ClearRectangle ([in] VARIANT Row1, [in] VARIANT Column1,
[in] VARIANT Row2, [in] VARIANT Column2 )
void HOperatorSetX.ClearRectangle ([in] VARIANT WindowHandle,
[in] VARIANT Row1, [in] VARIANT Column1, [in] VARIANT Row2,
[in] VARIANT Column2 )

Delete a rectangle on the output window.


ClearRectangle deletes all entries in the rectangle which is defined through the upper left corner
(Row1,Column1) and the lower right corner (Row2,Column2). Deletion significates that the specified rectangle
is set to the background color (see OpenWindow, OpenTextwindow).
If you want to delete more than one rectangle, you may pass several rectangles, i.e., the parameters Row1,
Column1, Row2 and Column2 are tupel.
Parameter

. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT


Window identifier.
. Row1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.origin.y(-array) ; VARIANT ( integer )
Line index of upper left corner.
Default Value : 10
Typical range of values : 0 ≤ Row1 ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 1
. Column1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.origin.x(-array) ; VARIANT ( integer )
Column index of upper left corner.
Default Value : 10
Typical range of values : 0 ≤ Column1 ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 1
. Row2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.corner.y(-array) ; VARIANT ( integer )
Row index of lower right corner.
Default Value : 118
Typical range of values : 0 ≤ Row2 ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 1
Restriction : (Row2 > Row1)
. Column2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.corner.x(-array) ; VARIANT ( integer )
Column index of lower right corner.
Default Value : 118
Typical range of values : 0 ≤ Column2 ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 1
Restriction : (Column2 ≥ Column1)
Example

/* "Interaktives" Loeschen eines Rechtecks im Ausgabefenster: */


draw_rectangle1(WindowHandle,L1,C1,L2,C2)
clear_rectangle(WindowHandle,L1,C1,L2,C2).

HALCON 8.0.2
408 CHAPTER 4. GRAPHICS

Result
If an output window exists and the specified parameters are correct ClearRectangle returns TRUE. If neces-
sary an exception handling is raised.
Parallelization Information
ClearRectangle is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow, SetDraw, SetColor, SetColored, SetLineWidth, SetRgb, SetHsi,
DrawRectangle1
See also
OpenWindow, OpenTextwindow
Alternatives
ClearWindow, DispRectangle1
Module
Foundation

void HWindowX.ClearWindow ( )
void HOperatorSetX.ClearWindow ([in] VARIANT WindowHandle )

Delete an output window.


ClearWindow deletes all entries in the output window. The window (background and edge) is reset to its original
state. Parameters assigned to this window (e.g., with SetColor, SetPaint, etc.) remain unmodified.
Parameter
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window identifier.
Example

clear_window(WindowHandle).

Result
If the output window is valid ClearWindow returns TRUE. If necessary an exception handling is raised.
Parallelization Information
ClearWindow is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow, OpenTextwindow
See also
OpenWindow, OpenTextwindow
Alternatives
ClearRectangle, DispRectangle1
Module
Foundation

void HOperatorSetX.CloseWindow ([in] VARIANT WindowHandle )

Close an output window.


CloseWindow closes a window which have been opened by OpenWindow or by OpenTextwindow. Af-
terwards the output device or the window area, respectively, is ready to accept new calls of OpenWindow or
OpenTextwindow.

HALCON/COM Reference Manual, 2008-5-13


4.8. WINDOW 409

Parameter

. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT


Window identifier.
Result
If the output window is valid CloseWindow returns TRUE. If necessary an exception handling is raised.
Parallelization Information
CloseWindow is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow, OpenTextwindow
See also
OpenWindow, OpenTextwindow
Module
Foundation

void HWindowX.CopyRectangle ([in] HWindowX WindowHandleDestination,


[in] VARIANT Row1, [in] VARIANT Column1, [in] VARIANT Row2,
[in] VARIANT Column2, [in] VARIANT DestRow, [in] VARIANT DestColumn )
void HOperatorSetX.CopyRectangle ([in] VARIANT WindowHandleSource,
[in] VARIANT WindowHandleDestination, [in] VARIANT Row1,
[in] VARIANT Column1, [in] VARIANT Row2, [in] VARIANT Column2,
[in] VARIANT DestRow, [in] VARIANT DestColumn )

Copy all pixels within rectangles between output windows.


CopyRectangle copies all pixels from the specified window with the logical window
number WindowHandleSource in the specified window with the logical window number
WindowHandleDestination. It copies pixels which reside inside a rectangle which is specified by
parameters Row1, Column1, Row2 and Column2. The target position is specified through the upper left corner
of the rectangle (DestRow, DestColumn).
If you want to move more than one rectangle, you may pass them at once (in form of the tupel mode).
You may use CopyRectangle to copy edited graphics from an "‘invisible"’ window in a visible window.
Therefore a window with the option ’buffer’ is opened. The graphics is then displayed in this window and is
copied in a visible window afterwards. The advantage of this strategy is, that CopyRectangle is much more
rapid than output procedures as, e.g., DispChannel. This means a particular advantage while using demo
programs. You could even realise short "‘clips"’: you have to create for every image of a sequence a window of a
’buffer’ type and pass the data into it. Output is the image sequence whereat all buffers are copied one after another
in a visible window.
Attention
Both windows have to reside on the same computer.
Parameter

. WindowHandleSource (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT


Number of the source window.
. WindowHandleDestination (input control) . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Number of the destination window.
. Row1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.origin.y(-array) ; VARIANT ( integer )
Row index of upper left corner in the source window.
Default Value : 0
Typical range of values : 0 ≤ Row1 ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 1

HALCON 8.0.2
410 CHAPTER 4. GRAPHICS

. Column1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.origin.x(-array) ; VARIANT ( integer )


Column index of upper left corner in the source window.
Default Value : 0
Typical range of values : 0 ≤ Column1 ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 1
. Row2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.corner.y(-array) ; VARIANT ( integer )
Row index of lower right corner in the source window.
Default Value : 128
Typical range of values : 0 ≤ Row2 ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 1
Restriction : (Row2 ≥ Row1)
. Column2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.corner.x(-array) ; VARIANT ( integer )
Column index of lower right corner in the source window.
Default Value : 128
Typical range of values : 0 ≤ Column2 ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 1
Restriction : (Column2 ≥ Column1)
. DestRow (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( integer )
Row index of upper left corner in the target window.
Default Value : 0
Typical range of values : 0 ≤ DestRow ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 1
. DestColumn (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( integer )
Column index of upper left corner in the target window.
Default Value : 0
Typical range of values : 0 ≤ DestColumn ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 1
Example

read_image(Image,’affe’)
open_window(0,0,-1,-1,’root’,’buffer’,’’,WindowHandle)
disp_image(Image,WindowHandle)
open_window(0,0,-1,-1,’root’,’visible’,’’,WindowHandleDestination)
repeat()
get_mbutton(WindowHandleDestination,Row,Column,Button)
copy_rectangle(BufferID,WindowHandleDestination,20,90,120,390,Row,Column)
until(Button = 1)
close_window(WindowHandleDestination)
close_window(WindowHandle)
clear(Image).

Result
If the output window is valid and if the specified parameters are correct CloseWindow returns TRUE. If neces-
sary an exception handling is raised.
Parallelization Information
CopyRectangle is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow, OpenTextwindow
Possible Successors
CloseWindow
See also
OpenWindow, OpenTextwindow

HALCON/COM Reference Manual, 2008-5-13


4.8. WINDOW 411

Alternatives
MoveRectangle, SlideImage
Module
Foundation

void HWindowX.DumpWindow ([in] VARIANT Device, [in] String FileName )


void HOperatorSetX.DumpWindow ([in] VARIANT WindowHandle,
[in] VARIANT Device, [in] VARIANT FileName )

Write the window content to a file.


DumpWindow writes the content of the window to a file. You may continue to process this file by convenient
printers or other programs. The content of a display is prepared for each special device (Device), i.e., it is
formated in a manner, that you may print this file directly or it can be processed furthermore by a graphical
program.
To transform gray values the current color table of the window is used, i.e., the values of SetLutStyle remain
unconsidered.
Possible values for Device

’postscript’: PostScript - file.


File extension: ’.ps’
’postscript’,Width,Height: PostScript - file with specification of the output size. W idth and Height refer to the
size. In this case a tupel with three values as Device is passed.
File extension: ’.ps’
’tiff’: TIFF - file, 1 byte per pixel incl. current color table or 3 bytes per sample (dependent on VGA card),
uncompressed.
File extension: ’.tiff’
’bmp’: Windows-BMP format, RGB image, 3 bytes per pixel. The color resolution pendends on the VGA card.
File extension: ’.bmp’
’jpeg’: JPEG format, with lost of information; together with the format string the quality value determining the
compression rate can be provided: e.g., ’jpeg 30’.
File extension: ’.jpg’
’jp2’: JPEG2000 format (lossless and lossy compression); together with the format string the quality value de-
terming the compression rate can be provided (e.g. ’jp2 40’). This value corresponds to the ratio of the size
of the compressed image and the size of the uncompressed image (in percent). As lossless JPEG2000 com-
pression reduces the file size significantly already, only smaller values (typically smaller than 50) influence
the file size. Is no value provided (and only then), the image is compressed without loss.
File extension: ’.jp2’
’png’: PNG format (lossless compression); together with the format string, a compresion level between 0 and
9 can be specified, where 0 corresponds to no compression and 9 to the best possible compression. Alter-
natively, the compression can be selected with the following strings: ’best’, ’fastest’, and ’none’. Hence,
examples for correct parameters are ’png’, ’png 7’, and ’png none’.
File extension: ’.png’

Attention
Under UNIX, the graphics window must be completely visible on the root window, because otherwise the contents
of the window cannot be read due to limitations in X Windows. If larger graphical displays are to be written to a
file, the window type ’pixmap’ can be used.
Parameter

. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT


Window identifier.

HALCON 8.0.2
412 CHAPTER 4. GRAPHICS

. Device (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string, integer )


Name of the target device or of the graphic format.
Default Value : ’postscript’
List of values : Device ∈ {’postscript’, ’tiff’, ’bmp’, ’jpeg’, ’jp2’, ’png’, ’jpeg 100’, ’jpeg 80’, ’jpeg 60’,
’jpeg 40’, ’jpeg 20’, ’jp2 50’, ’jp2 40’, ’jp2 30’, ’jp2 20’, ’png best’, ’png fastest’, ’png none’}
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.write ; String / VARIANT
File name (without extension).
Default Value : ’halcon_dump’
Example

/* PostScript - Dump von Bild und eingeblendeten Regionen: */


disp_image(Image,WindowHandle)
set_colored(WindowHandle,12)
disp_region(Regions,WindowHandle)
dump_window(WindowHandle,’postscript’,’/tmp/halcon_dump’)
system_call(’lp -d ps /tmp/halcon_dump.ps’).

Result
If the appropriate window is valid and the specified parameters are correct DumpWindow returns TRUE. If
necessary an exception handling is raised.
Parallelization Information
DumpWindow is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow, SetDraw, SetColor, SetColored, SetLineWidth, OpenTextwindow, DispRegion
Possible Successors
SystemCall
See also
OpenWindow, OpenTextwindow, SetSystem, DumpWindowImage
Module
Foundation

HWindowX.DumpWindowImage ( )
[out] HImageX Image
void HImageX.DumpWindowImage ([in] HWindowX WindowHandle )
void HOperatorSetX.DumpWindowImage ([out] HUntypedObjectX Image,
[in] VARIANT WindowHandle )

Write the window content in an image object.


DumpWindowImage writes the content of the graphics window (WindowHandle) in an image (Image). To
transform gray values the current color table of the window is used, i.e., the values of SetLutStyle remain
unconsidered.
Attention
Under UNIX, the graphics window must be completely visible on the root window, because otherwise the contents
of the window cannot be read due to limitations in X Windows.
Parameter
. Image (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / HUntypedObjectX ( byte )
Saved image.
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window identifier.
Result
If the window is valid DumpWindowImage returns TRUE. If necessary an exception handling is raised.
Parallelization Information
DumpWindowImage is reentrant, local, and processed without parallelization.

HALCON/COM Reference Manual, 2008-5-13


4.8. WINDOW 413

Possible Predecessors
OpenWindow, SetDraw, SetColor, SetColored, SetLineWidth, OpenTextwindow, DispRegion
See also
OpenWindow, OpenTextwindow, SetSystem, DumpWindow
Module
Foundation

[out] long OSWindowHandle HWindowX.GetOsWindowHandle


([out] long OSDisplayHandle )
void HOperatorSetX.GetOsWindowHandle ([in] VARIANT WindowHandle,
[out] VARIANT OSWindowHandle, [out] VARIANT OSDisplayHandle )

Get the operating system window handle.


GetOsWindowHandle returns the operating system window handle of the HALCON window WindowHandle
in OSWindowHandle. Under UNIX, additionally the operating system display handle is returned in
OSDisplayHandle. The operating system window handle can be used to access the window using func-
tions from the operating system, e.g., to draw in a user-defined manner into the window. Under Windows,
OSWindowHandle can be cast to a variable of type HWND. Under UNIX systems, OSWindowHandle can
be cast into a variable of type Window, while OSDisplayHandle can be cast into a variable of type Display.
Parameter
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window identifier.
. OSWindowHandle (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Operating system window handle.
. OSDisplayHandle (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Operating system display handle (under UNIX only).
Result
If the window is valid GetOsWindowHandle returns TRUE. Otherwise, an exception handling is raised.
Parallelization Information
GetOsWindowHandle is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow, OpenTextwindow
Module
Foundation

[out] VARIANT AttributeValue HSystemX.GetWindowAttr


([in] String AttributeName )
void HOperatorSetX.GetWindowAttr ([in] VARIANT AttributeName,
[out] VARIANT AttributeValue )

Get window characteristics.


The operator GetWindowAttr can be used to read characteristics of graphics windows that were set using
SetWindowAttr. The following parameters of a window may be queried:

’border_width’ Width of the window border in pixels.


’border_color’ Color of the window border.
’background_color’ Background color of the window.
’window_title’ Name of the window in the titlebar.

HALCON 8.0.2
414 CHAPTER 4. GRAPHICS

Parameter

. AttributeName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT


Name of the attribute that should be returned.
List of values : AttributeName ∈ {’border_width’, ’border_color’, ’background_color’, ’window_title’}
. AttributeValue (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( string, integer )
Attribute value.
Result
If the parameters are correct GetWindowAttr returns TRUE. If necessary an exception handling is raised.
Parallelization Information
GetWindowAttr is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow, SetDraw, SetColor, SetColored, SetLineWidth, OpenTextwindow
See also
OpenWindow, SetWindowAttr
Module
Foundation

[out] long Row HWindowX.GetWindowExtents ([out] long Column,


[out] long Width, [out] long Height )
void HOperatorSetX.GetWindowExtents ([in] VARIANT WindowHandle,
[out] VARIANT Row, [out] VARIANT Column, [out] VARIANT Width,
[out] VARIANT Height )

Information about a window’s size and position.


GetWindowExtents returns the position of the upper left corner, as well as width and height of the output
window.
Attention
Size and position of a window may be modified by the window manager, without explicit instruction in the pro-
gram. Therefore the values which are returned by GetWindowExtents may change cause of side effects.
Parameter

. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT


Window identifier.
. Row (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.origin.y ; long / VARIANT
Row index of upper left corner of the window.
. Column (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .rectangle.origin.x ; long / VARIANT
Column index of upper left corner of the window.
. Width (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.extent.x ; long / VARIANT
Window width.
. Height (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.extent.y ; long / VARIANT
Window height.
Example

open_window(100,100,200,200,’root’,’visible’,’’,WindowHandle)
fwrite_string(’Move the window with the mouse!’)
fnew_line()
repeat()
get_mbutton(WindowHandle,_,_,Button)
get_window_extents(WindowHandle,Row,Column,Width,Height)
fwrite([’(’Row,’,’,Column,’)’])
fnew_line()
until(Button = 4).

HALCON/COM Reference Manual, 2008-5-13


4.8. WINDOW 415

Result
If the window is valid GetWindowExtents returns TRUE. If necessary an exception handling is raised.
Parallelization Information
GetWindowExtents is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow, SetDraw, SetColor, SetColored, SetLineWidth, OpenTextwindow
See also
SetWindowExtents, OpenWindow, OpenTextwindow
Module
Foundation

[out] long ImageRed HWindowX.GetWindowPointer3 ([out] long ImageGreen,


[out] long ImageBlue, [out] long Width, [out] long Height )
void HOperatorSetX.GetWindowPointer3 ([in] VARIANT WindowHandle,
[out] VARIANT ImageRed, [out] VARIANT ImageGreen, [out] VARIANT ImageBlue,
[out] VARIANT Width, [out] VARIANT Height )

Access to a window’s pixel data.


GetWindowPointer3 enables (in some window systems) the direct access to the bitmap. Result values are the
three pointers on the color extracts of a 24-bit window (ImageRed, ImageGreen, ImageBlue), as well as the
window size (Width, Height). In the language C the type of the image points is unsigned char.
Attention
GetWindowPointer3 is usable only for window type ’pixmap’.
Parameter
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window identifier.
. ImageRed (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Pointer on red channel of pixel data.
. ImageGreen (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Pointer on green channel of pixel data.
. ImageBlue (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Pointer on blue channel of pixel data.
. Width (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; long / VARIANT
Length of an image line.
. Height (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; long / VARIANT
Number of image lines.
Result
If a window of type ’pixmap’ exists and it is valid GetWindowPointer3 returns TRUE. If necessary an
exception handling is raised.
Parallelization Information
GetWindowPointer3 is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow, OpenTextwindow
See also
OpenWindow, SetWindowType
Module
Foundation

HALCON 8.0.2
416 CHAPTER 4. GRAPHICS

HWindowX.GetWindowType ( )
[out] String WindowType
void HOperatorSetX.GetWindowType ([in] VARIANT WindowHandle,
[out] VARIANT WindowType )

Get the window type.


GetWindowType determines the type or the graphical software, respectively, of the output device for the window.
You may query the available types of output devices with procedure QueryWindowType. A reasonable use for
GetWindowType might be in the field of the development of machine independent software. Possible values
are:

’X-Window’ X-Window Version 11.


’WIN32-Window’ Microsoft Windows.
’pixmap’ Windows are not shown, but managed in memory. By this means HALCON programs can be ported on
computers without a graphical display.
’PostScript’ Objects are output to a PostScript File.
’default’ Current window type.
’system_default’ Default window type for current platform.

Parameter
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT ( integer, string )
Window identifier.
Suggested values : WindowHandle ∈ {’default’, ’system_default’}
. WindowType (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Window type
Example

open_window(100,100,200,200,’root’,’visible’,’’,WindowHandle)
get_window_type(WindowHandle,WindowType)
fwrite_string([’Window type: ’,WindowType])
fnew_line().

Result
If the window is valid GetWindowType returns TRUE. If necessary an exception handling is raised.
Parallelization Information
GetWindowType is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow, OpenTextwindow
See also
QueryWindowType, SetWindowType, GetWindowPointer3, OpenWindow, OpenTextwindow
Module
Foundation

void HWindowX.MoveRectangle ([in] VARIANT Row1, [in] VARIANT Column1,


[in] VARIANT Row2, [in] VARIANT Column2, [in] VARIANT DestRow,
[in] VARIANT DestColumn )
void HOperatorSetX.MoveRectangle ([in] VARIANT WindowHandle,
[in] VARIANT Row1, [in] VARIANT Column1, [in] VARIANT Row2,
[in] VARIANT Column2, [in] VARIANT DestRow, [in] VARIANT DestColumn )

Copy inside an output window.


MoveRectangle copies all entries in the rectangle (Row1,Column1), (Row2,Column2) of the output window
to a new position inside the same window. This position is determined by the upper left corner (DestRow,

HALCON/COM Reference Manual, 2008-5-13


4.8. WINDOW 417

DestColumn). Regions of the window, which are "‘uncovered"’ through moving the rectangle, are set to the
color of the background.
If you want to move several rectangles at once, you may pass parameters in form of tupels.
Parameter

. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT


Window identifier.
. Row1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.origin.y(-array) ; VARIANT ( integer )
Row index of upper left corner of the source rectangle.
Default Value : 0
Typical range of values : 0 ≤ Row1 ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 1
. Column1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.origin.x(-array) ; VARIANT ( integer )
Column index of upper left corner of the source rectangle.
Default Value : 0
Typical range of values : 0 ≤ Column1 ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 1
. Row2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.corner.y(-array) ; VARIANT ( integer )
Row index of lower right corner of the source rectangle.
Default Value : 64
Typical range of values : 0 ≤ Row2 ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 1
. Column2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.corner.x(-array) ; VARIANT ( integer )
Column index of lower right corner of the source rectangle.
Default Value : 64
Typical range of values : 0 ≤ Column2 ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 1
. DestRow (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( integer )
Row index of upper left corner of the target position.
Default Value : 64
Typical range of values : 0 ≤ DestRow ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 1
. DestColumn (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( integer )
Column index of upper left corner of the target position.
Default Value : 64
Typical range of values : 0 ≤ DestColumn ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 1
Example

/* "Interaktives" Kopieren eines Rechtecks im Ausgabefenster: */


draw_rectangle1(WindowHandle,L1,C1,L2,C2)
get_mbutton(WindowHandle,LN,CN,Button)
move_rectangle(WindowHandle,L1,C1,L2,C2,LN,CN).

Result
If the window is valid and the specified parameters are correct MoveRectangle returns TRUE. If necessary an
exception handling is raised.
Parallelization Information
MoveRectangle is reentrant, local, and processed without parallelization.

HALCON 8.0.2
418 CHAPTER 4. GRAPHICS

Possible Predecessors
OpenWindow, OpenTextwindow
See also
OpenWindow, OpenTextwindow
Alternatives
CopyRectangle
Module
Foundation

void HWindowX.NewExternWindow ([in] long WINHWnd, [in] long WINHDC,


[in] long Row, [in] long Column, [in] long Width, [in] long Height )
void HOperatorSetX.NewExternWindow ([in] VARIANT WINHWnd,
[in] VARIANT WINHDC, [in] VARIANT Row, [in] VARIANT Column,
[in] VARIANT Width, [in] VARIANT Height, [out] VARIANT WindowHandle )

Create a virtual graphics window under Windows NT.


NewExternWindow opens a new virtual window. Virtual means that a new window will not be created, but the
window whose Windows NT handle is given in the parameter WINHWnd is used to perform output of gray value
data, regions, graphics as well as to perform textual output. Visualization parameters for the output of data can be
done either using HALCON commands or by the appropriate Windows NT commands.
Example: setting of the drawing color:

HALCON:
set\_color(WindowHandle,"green");
disp\_region(WindowHandle,region);

Windows NT:
HPEN* penold;
HPEN penGreen = CreatePen(PS\_SOLID,1,RGB(0,255,0));
pen = (HPEN*)SelectObject(WINHDC,penGreen);
disp\_region(WindowHandle,region);

Interactive operators, for example DrawRegion, DrawCircle or GetMbutton cannot be used in this
window. The following operators can be used:

• Output of gray values: SetPaint, SetComprise, ( SetLut and SetLutStyle after output)
• Regions: SetColor, SetRgb, SetHsi, SetGray, SetPixel, SetShape, SetLineWidth,
SetInsert, SetLineStyle, SetDraw
• Image part: SetPart
• Text: SetFont

You may query current set values by calling procedures like GetShape. As some parameters are specified
through the hardware (Resolution/Colors), you may query current available resources by calling operators like
QueryColor.
The parameter WINHWnd is used to pass the window handle of the Windows NT window, in which output should
be done. The parameter WINHDC is used to pass the device context of the window WINHWnd. This device context
is used in the output routines of HALCON.
The origin of the coordinate system of the window resides in the upper left corner (coordinates: (0,0)). The row
index grows downward (maximum: Height-1), the column index grows to the right (maximal: Width-1).
You may use the value -1 for parameters Width and Height. This means, that the corresponding value is chosen
automatically. In particular, this is important if the aspect ratio of the pixels is not 1.0 (see SetSystem). If one
of the two parameters is set to -1, it will be chosen through the size which results out of the aspect ratio of the
pixels. If both parameters are set to -1, they will be set to the current image format.

HALCON/COM Reference Manual, 2008-5-13


4.8. WINDOW 419

The position and size of a window may change during runtime of a program. This may be achieved by calling
SetWindowExtents, but also through external influences (window manager). For the latter case the procedure
SetWindowExtents is provided.
Opening a window causes the assignment of a default font. It is used in connection with procedures like
WriteString and you may change it by performing SetFont after calling OpenWindow. On the other hand,
you have the possibility to specify a default font by calling SetSystem(::’defaultFont’,<Fontname>:
) before opening a window (and all following windows; see also QueryFont).
You may set the color of graphics and font, which is used for output procedures like DispRegion or
DispCircle, by calling SetRgb, SetHsi, SetGray or SetPixel. Calling SetInsert specifies
how graphics is combined with the content of the image repeat memory. Thereto you may achieve by calling, e.g.,
SetInsert(::’not’:) to eliminate the font after writing text twice at the same position.
The content of the window is not saved, if other windows overlap the window. This must be done in the program
code that handles the Windows NT window in the calling program.
For graphical output ( DispImage, DispRegion, etc.) you may adjust the window by calling procedure
SetPart in order to represent a logical clipping of the image format. In particular this implies that only this
part (appropriately scaled) of images and regions is displayed. Before you close your window, you have to close
the HALCON-window.
Steps to use new_extern_window:

Creation: • Create a Windows-window.


• Call new_extern_window with the WINHWnd of the above created window.
Use: • Before drawing in the window you have to call the method set_window_dc. This ensures that the halcon
drawing routines use the right DC. After drawing call again set_window_dc, but this time with the
address of a long set to zero, this ensures that HALCON can delete the created graphic objects.
Destroy: • Call close_window.

Attention
Note that parameters as Row, Column, Width and Height are constrained through the output device, i.e., the
size of the Windows NT desktop.
Parameter

. WINHWnd (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT


Windows windowhandle of a previously created window.
Restriction : (W IN HW nd 6= 0)
. WINHDC (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Device context of WINHWnd.
Restriction : (W IN HDC 6= 0)
. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.origin.y ; long / VARIANT
Row coordinate of upper left corner.
Default Value : 0
Restriction : (Row ≥ 0)
. Column (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.origin.x ; long / VARIANT
Column coordinate of upper left corner.
Default Value : 0
Restriction : (Column ≥ 0)
. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.extent.x ; long / VARIANT
Width of the window.
Default Value : 512
Restriction : ((W idth > 0) ∨ (W idth = −1))
. Height (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.extent.y ; long / VARIANT
Height of the window.
Default Value : 512
Restriction : ((Height > 0) ∨ (Height = −1))
. WindowHandle (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window identifier.

HALCON 8.0.2
420 CHAPTER 4. GRAPHICS

Result
If the values of the specified parameters are correct NewExternWindow returns TRUE. If necessary, an excep-
tion is raised.
Parallelization Information
NewExternWindow is reentrant, local, and processed without parallelization.
Possible Predecessors
ResetObjDb
Possible Successors
SetColor, QueryWindowType, GetWindowType, SetWindowType, GetMposition,
SetTposition, SetTshape, SetWindowExtents, GetWindowExtents, QueryColor, SetCheck,
SetSystem
See also
OpenWindow, DispRegion, DispImage, DispColor, SetLut, QueryColor, SetColor, SetRgb,
SetHsi, SetPixel, SetGray, SetPart, SetPartStyle, QueryWindowType, GetWindowType,
SetWindowType, GetMposition, SetTposition, SetWindowExtents, GetWindowExtents,
SetWindowAttr, SetCheck, SetSystem
Alternatives
OpenWindow, OpenTextwindow
Module
Foundation

void HWindowX.OpenTextwindow ([in] long Row, [in] long Column,


[in] long Width, [in] long Height, [in] long BorderWidth,
[in] String BorderColor, [in] String BackgroundColor,
[in] VARIANT FatherWindow, [in] String Mode, [in] String Machine )
void HOperatorSetX.OpenTextwindow ([in] VARIANT Row,
[in] VARIANT Column, [in] VARIANT Width, [in] VARIANT Height,
[in] VARIANT BorderWidth, [in] VARIANT BorderColor,
[in] VARIANT BackgroundColor, [in] VARIANT FatherWindow, [in] VARIANT Mode,
[in] VARIANT Machine, [out] VARIANT WindowHandle )

Open a textual window.


OpenTextwindow opens a new textual window, which can be used to perform textual input and output, as well
as to perform output of images. All output ( WriteString, ReadString, DispRegion, etc.) is redirected
to this window, if the same logical window number WindowHandle is used.
Besides the mouse cursor textual windows possess also a textual cursor which indicates the current writing position
(more exactly: the lower left corner of the output string without consideration of descenders). Its position is
indicated through an underscore or another type (the indication of this position may also be disabled (= default
setting); cf. SetTshape). You may set or query the position by calling the procedures SetTposition or
GetTposition.
After you opened a textual window the position of the cursor is set to (H,0). Whereby H significates the height of
the default font less the descenders. But the cursor is not shown. Hence the output starts for writing in the upper
left corner of the window.
You may query the colors of the background and the image edges by calling QueryColor. In the same way
you may use QueryColor in a window of type ’invisible’. During output ( WriteString) you may set the
clipping of text out of the window edges by calling SetCheck(::’∼ text’:). This disables the creation of error
messages, if text passes over the edge of the window.
The origin of the coordinate system of the window resides in the upper left corner (coordinates: (0,0)). The row
index grows downward (maximal: Height-1), the column index grows to the right (maximal: Width-1).
The parameter Machine indicates the name of the computer, which has to open the window. In case of a X-
window, TCP-IP only sets the name, DEC-Net sets in addition a colon behind the name. The "‘server"’ or the
"‘screen"’, respectively, are not specified. If the empty string is passed the environment variable DISPLAY is used.
It indicates the target computer. At this the name is indicated in common syntax

HALCON/COM Reference Manual, 2008-5-13


4.8. WINDOW 421

<Host>:0.0

.
For windows of type ’X-Window’ and ’WIN32-Window’ the parameter FatherWindow can be used to de-
termine the father window for the window to be opened. In case the control ’father’ is set via SetCheck,
FatherWindow relates to the ID of a HALCON window, otherwise ( SetCheck(’∼ father’)) it relates to the ID
of an operating system window. If FatherWindow is passed the value 0 or ’root’, then under Windows and Unix
the desktop and the root window become the father window, respectively. In this case, the value of the control
’father’ (set via SetCheck) is irrelevant.
Position and size of a window may change during runtime of a program. This may be achieved by calling
SetWindowExtents, but also through external interferences (window manager). In the latter case the pro-
cedure SetWindowExtents is provided.
Opening a window causes the assignment of a called default font. It is used in connection with procedures
like WriteString and you may overwrite it by performing SetFont after calling OpenTextwindow.
On the other hand you have the possibility to specify a default font by calling SetSystem(::
’defaultFont’,<Fontname>:) before opening a window (and all following windows; see also
QueryFont).
You may set the color of the font ( WriteString, ReadString) by calling SetColor, SetRgb, SetHsi,
SetGray or SetPixel. Calling SetInsert specifies how the text or the graphics, respectively, is combined
with the content of the image repeat memory. So you may achieve by calling, e.g., SetInsert(::’not’:) to
eliminate the font after writing text twice at the same position.
Normally every output (e.g., WriteString, DispRegion, DispCircle, etc.) in a window is terminated
by a "‘flush"’. This causes the data to be fully visible on the display after termination of the output procedure. But
this is not necessary in all cases, in particular if there are permanently output tasks or there is a mouse procedure
active. Therefore it is more favorable (i.e., more rapid) to store the data until sufficient data is available. You may
stop this behavior by calling SetSystem(::’flushGraphic’,’false’:).
The content of windows is saved (in case it is supported by special driver software); i.e., it is preserved, also
if the window is hidden by other windows. But this is not necessary in all cases: If you use a textual window,
e.g., as a parent window for other windows, you may suppress the security mechanism for it and save the nec-
essary memory at the same moment. You achieve this before opening the window by calling SetSystem(::
’backingStore’,’false’:).
Difference: graphical window - textual window

• In contrast to graphical windows ( OpenWindow) you may specify more parameters (color, edge) for a
textual window while opening it.
• You may use textual windows only for input of user data ( ReadString).
• Using textual windows, the output of images, regions and graphics is "‘clipped"’ at the edges. Whereas
during the use of graphical windows the edges are "‘zoomed"’.
• The coordinate system (e.g., with GetMbutton or GetMposition) consists of display coordinates
independently of image size. The maximum coordinates are equal to the size of the window minus 1. In
contrast to this, graphical windows ( OpenWindow) use always a coordinate system, which corresponds to
the image format.

The parameter Mode specifies the mode of the window. It can have following values:

’visible’: Normal mode for textual windows: The window is created according to the parameters and all inputs
and outputs are possible.
’invisible’: Invisible windows are not displayed in the display. Parameters like Row, Column, BorderWidth,
BorderColor, BackgroundColor and FatherWindow do not have any meaning. Output to these
windows has no effect. Input ( ReadString, mouse, etc.) is not possible. You may use these windows
to query representation parameter for an output device without opening a (visible) window. General queries
are, e.g., QueryColor and GetStringExtents.
’transparent’: These windows are transparent: the window itself is not visible (edge and background), but
all the other operations are possible and all output is displayed. Parameters like BorderColor and
BackgroundColor do not have any meaning. A common use for this mode is the creation of mouse
sensitive regions.

HALCON 8.0.2
422 CHAPTER 4. GRAPHICS

’buffer’: These are also not visible windows. The output of images, regions and graphics is not visible on
the display, but is stored in memory. Parameters like Row, Column, BorderWidth, BorderColor,
BackgroundColor and FatherWindow do not have any meaning. You may use buffer windows, if you
prepare output (in the background) and copy it finally with CopyRectangle in a visible window. Another
usage might be the rapid processing of image regions during interactive manipulations. Textual input and
mouse interaction are not possible in this mode.

Attention
You have to keep in mind that parameters like Row, Column, Width and Height are restricted by the output
device. Is a father window (FatherWindow <> ’root’) specified, then the coordinates are relative to this window.
Parameter
. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.origin.y ; long / VARIANT
Row index of upper left corner.
Default Value : 0
(lin)Minimum Increment : 1
Recommended Increment : 1
Restriction : (Row ≥ 0)
. Column (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.origin.x ; long / VARIANT
Column index of upper left corner.
Default Value : 0
(lin)Minimum Increment : 1
Recommended Increment : 1
Restriction : (Column ≥ 0)
. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.extent.x ; long / VARIANT
Window’s width.
Default Value : 256
(lin)Minimum Increment : 1
Recommended Increment : 1
Restriction : (W idth > 0)
. Height (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.extent.y ; long / VARIANT
Window’s height.
Default Value : 256
(lin)Minimum Increment : 1
Recommended Increment : 1
Restriction : (Height > 0)
. BorderWidth (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Window border’s width.
Default Value : 2
(lin)Minimum Increment : 1
Recommended Increment : 1
Restriction : (BorderW idth ≥ 0)
. BorderColor (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Window border’s color.
Default Value : ’white’
. BackgroundColor (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Background color.
Default Value : ’black’
. FatherWindow (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer, string )
Logical number of the father window. For the display as father you may specify ’root’ or 0.
Default Value : 0
Restriction : (F atherW indow ≥ 0)
. Mode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Window mode.
Default Value : ’visible’
List of values : Mode ∈ {’visible’, ’invisible’, ’transparent’, ’buffer’}
. Machine (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Computer name, where the window has to be opened or empty string.
Default Value : ”

HALCON/COM Reference Manual, 2008-5-13


4.8. WINDOW 423

. WindowHandle (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT


Window identifier.
Example

open_textwindow(0,0,900,600,1,’black’,’slate blue’,’root’,’visible’,
’’WindowHandle)
open_textwindow(10,10,300,580,3,’red’,’blue’,Father,’visible’,
’’WindowHandle)
open_window(10,320,570,580,Father,’visible’,’’WindowHandle)
set_color(WindowHandle,’red’)
read_image(Image,’affe’)
disp_image(Image,WindowHandle)
repeat()
get_mposition(WindowHandle,Row,Column,Button)
get_grayval(Image,Row,Column,1,Gray)
write_string(WindowHandle,[’ Position (’,Row,’,’,Column,’) ’])
write_string(WindowHandle,[’Gray value (’,Gray,’) ’])
new_line(WindowHandle)
until(Button = 4)
close_window(WindowHandle)
clear_obj(Image).

Result
If the values of the specified parameters are correct OpenTextwindow returns TRUE. If necessary an exception
handling is raised.
Parallelization Information
OpenTextwindow is reentrant, local, and processed without parallelization.
Possible Predecessors
ResetObjDb
Possible Successors
SetColor, QueryWindowType, GetWindowType, SetWindowType, GetMposition,
SetTposition, SetTshape, SetWindowExtents, GetWindowExtents, QueryColor, SetCheck,
SetSystem
See also
WriteString, ReadString, NewLine, GetStringExtents, GetTposition, SetColor,
QueryWindowType, GetWindowType, SetWindowType, GetMposition, SetTposition,
SetTshape, SetWindowExtents, GetWindowExtents, QueryColor, SetCheck, SetSystem
Alternatives
OpenWindow
Module
Foundation

void HWindowX.OpenWindow ([in] long Row, [in] long Column,


[in] long Width, [in] long Height, [in] VARIANT FatherWindow,
[in] String Mode, [in] String Machine )
void HOperatorSetX.OpenWindow ([in] VARIANT Row, [in] VARIANT Column,
[in] VARIANT Width, [in] VARIANT Height, [in] VARIANT FatherWindow,
[in] VARIANT Mode, [in] VARIANT Machine, [out] VARIANT WindowHandle )

Open a graphics window.


OpenWindow opens a new window, which can be used to perform output of gray value data, regions, graphics as
well as to perform textual output. All output ( DispRegion, DispImage, etc.) is redirected to this window, if
the same logical window number WindowHandle is used.

HALCON 8.0.2
424 CHAPTER 4. GRAPHICS

The background of the created window is set to black in advance and it has a white border, which is 2 pixels wide
(see also SetWindowAttr(::’borderWidth’,<Breite>:).
Certain parameters used for the editing of output data are assigned to a window. These parameters are considered
during the output itself (e.g., with DispImage or DispRegion). They are not specified by an output procedure,
but by "‘configuration procedures"’. If you want to set, e.g., the color red for the output of regions, you have to
call SetColor(::WindowHandle,’red’:) before calling DispRegion. These parameters are always
set for the window with the logical window number WindowHandle and remain assigned to a window as long
as they will be overwritten. You may use the following configuration procedures:

• Output of gray values: SetPaint, SetComprise, ( SetLut and SetLutStyle after output)
• Regions: SetColor, SetRgb, SetHsi, SetGray, SetPixel, SetShape, SetLineWidth,
SetInsert, SetLineStyle, SetDraw
• Image clipping: SetPart
• Text: SetFont

You may query current set values by calling procedures like GetShape. As some parameters are specified
through the hardware (Resolution/Colors), you may query current available ressources by calling QueryColor.
The origin of the coordinate system of the window resides in the upper left corner (coordinates: (0,0)). The row
index grows downward (maximal: Height-1), the column index grows to the right (maximal: Width-1). You
have to keep in mind, that the range of the coordinate system is independent of the window size. It is specified
only through the image format (see ResetObjDb).
The parameter Machine indicates the name of the computer, which has to open the window. In case of a X-
window, TCP-IP only sets the name, DEC-Net sets in addition a colon behind the name. The "‘server"’ resp. the
"‘screen"’ are not specified. If the empty string is passed the environment variable DISPLAY is used. It indicates
the target computer. At this the name is indicated in common syntax

<Host>:0.0

.
For windows of type ’X-Window’ and ’WIN32-Window’ the parameter FatherWindow can be used to de-
termine the father window for the window to be opened. In case the control ’father’ is set via SetCheck,
FatherWindow relates to the ID of a HALCON window, otherwise ( SetCheck(’∼ father’)) it relates to the ID
of an operating system window. If FatherWindow is passed the value 0 or ’root’, then under Windows and Unix
the desktop and the root window become the father window, respectively. In this case, the value of the control
’father’ (set via SetCheck) is irrelevant.
You may use the value "‘-1"’ for parameters Width and Height. This means, that the according value has to be
specified automatically. In particular this is of importance, if the proportion of pixels is not 1.0 (see SetSystem):
Is one of the two parameters set to "‘-1"’, it will be specified through the size which results out of the proportion
of pixels. Are both parameters set to "‘-1"’, they will be set to the maximum image format, which is currently
used (further information about the currently used maximum image format can be found in the description of
GetSystem using "‘width"’ or "‘height"’).
Position and size of a window may change during runtime of a program. This may be achieved by calling
SetWindowExtents, but also through external interferences (window manager). In the latter case the pro-
cedure SetWindowExtents is provided.
Opening a window causes the assignment of a called default font. It is used in connection with proce-
dures like WriteString and you may overwrite it by performing SetFont after calling OpenWindow.
On the other hand you have the possibility to specify a default font by calling SetSystem(::
’defaultFont’,<Fontname>:) before opening a window (and all following windows; see also
QueryFont).
You may set the color of graphics and font, which is used for output procedures like DispRegion or
DispCircle, by calling SetRgb, SetHsi, SetGray or SetPixel. Calling SetInsert specifies
how graphics is combined with the content of the image repeat memory. Thereto you may achieve by calling, e.g.,
SetInsert(::’not’:) to eliminate the font after writing text twice at the same position.
Normally every output (e.g., DispImage, DispRegion, DispCircle, etc.) in a window is terminated by
a called "‘flush"’. This causes the data to be fully visible on the display after termination of the output procedure.
But this is not necessary in all cases, in particular if there are permanently output tasks or if there is a mouse

HALCON/COM Reference Manual, 2008-5-13


4.8. WINDOW 425

procedure active. Therefore it is more favorable (i.e., more rapid) to store the data until sufficient data is available.
You may stop this behavior by calling SetSystem(::’flushGraphic’,’false’:).
The content of windows is saved (in case it is supported by special driver software); i.e., it is preserved, also if
the window is hidden by other windows. But this is not necessary in all cases: If the content of a window is built
up permanently new ( CopyRectangle), you may suppress the security mechanism for that and hence you can
save the necessary memory. This is done by calling SetSystem(::’backingStore’,’false’:) before
opening a window. In doing so you save not only memory but also time to compute. This is significant for the
output of video clips (see CopyRectangle).
For graphical output ( DispImage, DispRegion, etc.) you may adjust the window by calling procedure
SetPart in order to represent a logical clipping of the image format. In particular this implicates that you
obtain this clipping (with appropriate enlargement) of images and regions only.
Difference: graphical window - textual window
• Using graphical windows the layout is not as variable as concerned to textual windows.
• You may use textual windows for the input of user data only ( ReadString).
• During the output of images, regions and graphics a "‘zooming"’ is performed using graphical windows:
Independent on size and side ratio of the window images are transformed in that way, that they are displayed
in the window by filling it completely. On the opposite side using textual windows the output does not care
about the size of the window (only if clipping is necessary).
• Using graphical windows the coordinate system of the window corresponds to the coordinate system of
the image format. Using textual windows, its coordinate system is always equal to the display coordinates
independent on image size.
The parameter Mode determines the mode of the window. It may have following values:

’visible’: Normal mode for graphical windows: The window is created according to the parameters and all input
and output are possible.
’invisible’: Invisible windows are not displayed in the display. Parameters like Row, Column and
FatherWindow do not have any meaning. Output to these windows has no effect. Input ( ReadString,
mouse, etc.) is not possible. You may use these windows to query representation parameter for an
output device without opening a (visible) window. Common queries are, e.g., QueryColor and
GetStringExtents.
’transparent’: These windows are transparent: the window itself is not visible (edge and background), but all
the other operations are possible and all output is displayed. A common use for this mode is the creation of
mouse sensitive regions.
’buffer’: These are also not visible windows. The output of images, regions and graphics is not visible on the
display, but is stored in memory. Parameters like Row, Column and FatherWindow do not have any
meaning. You may use buffer windows, if you prepare output (in the background) and copy it finally with
CopyRectangle in a visible window. Another usage might be the rapid processing of image regions
during interactive manipulations. Textual input and mouse interaction are not possible in this mode.

Attention
You may keep in mind that parameters as Row, Column, Width and Height are constrained by the output
device. If you specify a father window (FatherWindow <> ’root’) the coordinates are relative to this window.
Parameter
. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.origin.y ; long / VARIANT
Row index of upper left corner.
Default Value : 0
(lin)Minimum Increment : 1
Recommended Increment : 1
Restriction : (Row ≥ 0)
. Column (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.origin.x ; long / VARIANT
Column index of upper left corner.
Default Value : 0
(lin)Minimum Increment : 1
Recommended Increment : 1
Restriction : (Column ≥ 0)

HALCON 8.0.2
426 CHAPTER 4. GRAPHICS

. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.extent.x ; long / VARIANT


Width of the window.
Default Value : 256
(lin)Minimum Increment : 1
Recommended Increment : 1
Restriction : ((W idth > 0) ∨ (W idth = −1))
. Height (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.extent.y ; long / VARIANT
Height of the window.
Default Value : 256
(lin)Minimum Increment : 1
Recommended Increment : 1
Restriction : ((Height > 0) ∨ (Height = −1))
. FatherWindow (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer, string )
Logical number of the father window. To specify the display as father you may enter ’root’ or 0.
Default Value : 0
Restriction : (F atherW indow ≥ 0)
. Mode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Window mode.
Default Value : ’visible’
List of values : Mode ∈ {’visible’, ’invisible’, ’transparent’, ’buffer’}
. Machine (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Name of the computer on which you want to open the window. Otherwise the empty string.
Default Value : ”
. WindowHandle (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window identifier.
Example

open_window(0,0,400,-1,’root’,’visible’,’’,WindowHandle)
read_image(Image,’fabrik’)
disp_image(Image,WindowHandle)
write_string(WindowHandle,’File, fabrik.ima’)
new_line(WindowHandle)
get_mbutton(WindowHandle,_,_,_)
set_lut(WindowHandle,’temperature’)
set_color(WindowHandle,’blue’)
write_string(WindowHandle,’temperature’)
new_line(WindowHandle)
write_string(WindowHandle,’Draw Rectangle’)
new_line(WindowHandle)
draw_rectangle1(WindowHandle,Row1,Column1,Row2,Column2)
set_part(Row1,Column1,Row2,Column2)
disp_image(Image,WindowHandle)
new_line(WindowHandle).

Result
If the values of the specified parameters are correct OpenWindow returns TRUE. If necessary an exception
handling is raised.
Parallelization Information
OpenWindow is reentrant, local, and processed without parallelization.
Possible Predecessors
ResetObjDb
Possible Successors
SetColor, QueryWindowType, GetWindowType, SetWindowType, GetMposition,
SetTposition, SetTshape, SetWindowExtents, GetWindowExtents, QueryColor, SetCheck,
SetSystem
See also
DispRegion, DispImage, DispColor, SetLut, QueryColor, SetColor, SetRgb, SetHsi,

HALCON/COM Reference Manual, 2008-5-13


4.8. WINDOW 427

SetPixel, SetGray, SetPart, SetPartStyle, QueryWindowType, GetWindowType,


SetWindowType, GetMposition, SetTposition, SetWindowExtents, GetWindowExtents,
SetWindowAttr, SetCheck, SetSystem
Alternatives
OpenTextwindow
Module
Foundation

[out] VARIANT WindowTypes HInfoX.QueryWindowType ( )


[out] VARIANT WindowTypes HSystemX.QueryWindowType ( )
void HOperatorSetX.QueryWindowType ([out] VARIANT WindowTypes )
Query all available window types.
QueryWindowType returns a tupel which contains all devices or software systems, respectively, which are used
to display image objects. You may use QueryWindowType usefully while developing machine independent
programs. Possible values are:
’X-Window’ X-Window Version 11.
’pixmap’ Windows are not displayed, but managed in memory. In this manner it is possible to port HALCON
programs to computers without graphical display.
’PostScript’ Objects are output to a PostScript File.
Parameter
. WindowTypes (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( string )
Names of available window types.
Result
QueryWindowType always returns TRUE.
Parallelization Information
QueryWindowType is reentrant, local, and processed without parallelization.
Possible Predecessors
ResetObjDb
Module
Foundation

void HSystemX.SetWindowAttr ([in] String AttributeName,


[in] VARIANT AttributeValue )
void HOperatorSetX.SetWindowAttr ([in] VARIANT AttributeName,
[in] VARIANT AttributeValue )

Set window characteristics.


You may use SetWindowAttr to set specific characteristics of graphics windows. With it you may modify the
following default parameters of a window:
’border_width’ Width of the window border in pixels. Is not implemented under Windows.
’border_color’ Color of the window border. Is not implemented under Windows.
’background_color’ Background color of the window.
’window_title’ Name of the window in the titlebar.
Attention
You have to call SetWindowAttr before calling OpenWindow.

HALCON 8.0.2
428 CHAPTER 4. GRAPHICS

Parameter
. AttributeName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Name of the attribute that should be modified.
List of values : AttributeName ∈ {’border_width’, ’border_color’, ’background_color’, ’window_title’}
. AttributeValue (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( string, integer )
Value of the attribute that should be set.
List of values : AttributeValue ∈ {0, 1, 2, ’white’, ’black’, ’MyName’, ’default’}
Result
If the parameters are correct SetWindowAttr returns TRUE. If necessary an exception handling is raised.
Parallelization Information
SetWindowAttr is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow, SetDraw, SetColor, SetColored, SetLineWidth, OpenTextwindow
See also
OpenWindow, GetWindowAttr
Module
Foundation

void HWindowX.SetWindowDc ([in] long WINHDC )


void HOperatorSetX.SetWindowDc ([in] VARIANT WindowHandle,
[in] VARIANT WINHDC )

Set the device context of a virtual graphics window (Windows NT).


SetWindowDc sets the device context of a window previously opened with NewExternWindow. All output (
DispRegion, DispImage, etc.) is done in the window with this device context.
The parameter WINHDC contains the device context of the window in which HALCON should output its data. This
device context is used in all output routines of HALCON.
Attention
The window WindowHandle has to be created with NewExternWindow beforehand.
Parameter
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window identifier.
. WINHDC (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
devicecontext of WINHWnd.
Restriction : (W IN HDC 6= 0)
Example

hWnd = createWINDOW(...)
new_extern_window(hwnd, hdc, 0,0,400,-1,WindowHandle)
set_device_context(WindowHandle, hdc)
read_image(Image,’fabrik’)
disp_image(Image,WindowHandle)
write_string(WindowHandle,’File, fabrik.ima’)
new_line(WindowHandle)
get_mbutton(WindowHandle,_,_,_)
set_lut(WindowHandle,’temperature’)
set_color(WindowHandle,’blue’)
write_string(WindowHandle,’temperature’)
new_line(WindowHandle)
write_string(WindowHandle,’Draw Rectangle’)
new_line(WindowHandle)
draw_rectangle1(WindowHandle,Row1,Column1,Row2,Column2)

HALCON/COM Reference Manual, 2008-5-13


4.8. WINDOW 429

set_part(Row1,Column1,Row2,Column2)
disp_image(Image,WindowHandle)
new_line(WindowHandle).

Result
If the values of the specified parameters are correct, SetWindowDc returns TRUE. If necessary, an exception is
raised.
Parallelization Information
SetWindowDc is reentrant, local, and processed without parallelization.
Possible Predecessors
NewExternWindow
Possible Successors
DispImage, DispRegion
See also
NewExternWindow, DispRegion, DispImage, DispColor, SetLut, QueryColor, SetColor,
SetRgb, SetHsi, SetPixel, SetGray, SetPart, SetPartStyle, QueryWindowType,
GetWindowType, SetWindowType, GetMposition, SetTposition, SetWindowExtents,
GetWindowExtents, SetWindowAttr, SetCheck, SetSystem
Module
Foundation

void HWindowX.SetWindowExtents ([in] long Row, [in] long Column,


[in] long Width, [in] long Height )
void HOperatorSetX.SetWindowExtents ([in] VARIANT WindowHandle,
[in] VARIANT Row, [in] VARIANT Column, [in] VARIANT Width,
[in] VARIANT Height )

Modify position and size of a window.


SetWindowExtents positions the upper left corner of the output window at (Row,Column) and changes the
size of the window to Width and Height at the same time.
Attention
If you modify the size of a window an adaptation of the displayed date to the new format is not processed automat-
ically. This has to be done by the program in performing another output of these data.
Parameter

. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT


Window identifier.
. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.origin.y ; long / VARIANT
Row index of upper left corner in target position.
Default Value : 0
(lin)Minimum Increment : 1
Recommended Increment : 1
. Column (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.origin.x ; long / VARIANT
Column index of upper left corner in target position.
Default Value : 0
(lin)Minimum Increment : 1
Recommended Increment : 1
. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.extent.x ; long / VARIANT
Width of the window.
Default Value : 512
(lin)Minimum Increment : 1
Recommended Increment : 1

HALCON 8.0.2
430 CHAPTER 4. GRAPHICS

. Height (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.extent.y ; long / VARIANT


Height of the window.
Default Value : 512
(lin)Minimum Increment : 1
Recommended Increment : 1
Result
If the window is valid and the parameters are correct SetWindowExtents returns TRUE. If necessary an
exception handling is raised.
Parallelization Information
SetWindowExtents is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow, OpenTextwindow
See also
GetWindowExtents, OpenWindow, OpenTextwindow
Module
Foundation

void HSystemX.SetWindowType ([in] String WindowType )


void HOperatorSetX.SetWindowType ([in] VARIANT WindowType )

Specify a window type.


SetWindowType determines on which type of output device the output is going to be displayed. This speci-
fication is going to be used by procedure OpenWindow while opening the windows. You may open different
windows on different types of output devices. Therefore you have to specify the wanted type before opening. You
may request the available types of output devices by calling procedure QueryWindowType. Possible values
are:

’X-Window’ X-Window Version 11.


’WIN32-Window’ Microsoft Windows.
’pixmap’ Windows are not displayed, but managed in memory only. In this manner you may port HALCON
programs to computers without graphical display.
’PostScript’ Objects are output to a PostScript File.
’system_default’ Default for current platfrom.

A useful usage of SetWindowType could be the development of machine independent programs.


Parameter

. WindowType (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT


Name of the window type which has to be set.
Default Value : ’X-Window’
List of values : WindowType ∈ {’X-Window’, ’WIN32-Window’, ’pixmap’, ’PostScript’, ’system_default’}
Result
If the type of the output device is available, then SetWindowType returns TRUE. If necessary an exception
handling is raised.
Parallelization Information
SetWindowType is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow, OpenTextwindow
See also
OpenWindow, OpenTextwindow, QueryWindowType, GetWindowType
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


4.8. WINDOW 431

void HWindowX.SlideImage ([in] HWindowX WindowHandleSource1,


[in] HWindowX WindowHandleSource2 )
void HOperatorSetX.SlideImage ([in] VARIANT WindowHandleSource1,
[in] VARIANT WindowHandleSource2, [in] VARIANT WindowHandle )

Interactive output from two window buffers.


SlideImage divides the window horizontal in two logical areas dependent of the mouse position. The content
of the first indicated window is copied in the upper area, the content of the second window is copied in the lower
area. If you press the left mouse button you may scroll the delimitation between the two areas (you may move
the mouse outside the window, too. In doing so the position of the mouse relative to the window determines the
borderline).
Pressing the right mouse button in the window terminates the procedure SlideImage.
A useful application of procedure SlideImage might be the visualisation of the effect of a filtering operation
for an image. The output is directed to the current set window (WindowHandle).
Attention
The three windows must have the same size and have to reside on the same computer.
Parameter

. WindowHandleSource1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT


Logical window number of the "‘upper window"’.
. WindowHandleSource2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Logical window number of the "‘lower window"’.
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window identifier.
Example

read_image(Image,’fabrik’)
sobel_amp(Image,Amp,’sum_abs’,3)
open_window(0,0,-1,-1,’root’,’buffer’,’’,WindowHandle)
disp_image(Amp,WindowHandle)
sobel_dir(Image,Dir,’sum_abs’,3)
open_window(0,0,-1,-1,’root’,’buffer’,’’,WindowHandle)
disp_image(Dir,WindowHandle)
open_window(0,0,-1,-1,’root’,’visible’,’’,WindowHandle)
slide_image(Puffer1,Puffer2,WindowHandle).

Result
If the both windows exist and one of these windows is valid SlideImage returns TRUE. If necessary an excep-
tion handling is raised.
Parallelization Information
SlideImage is reentrant, local, and processed without parallelization.
Possible Predecessors
OpenWindow, OpenTextwindow
See also
OpenWindow, OpenTextwindow, MoveRectangle
Alternatives
CopyRectangle, GetMposition
Module
Foundation

HALCON 8.0.2
432 CHAPTER 4. GRAPHICS

HALCON/COM Reference Manual, 2008-5-13


Chapter 5

Image

5.1 Access
[out] VARIANT Grayval HImageX.GetGrayval ([in] VARIANT Row,
[in] VARIANT Column )
void HOperatorSetX.GetGrayval ([in] IHObjectX Image, [in] VARIANT Row,
[in] VARIANT Column, [out] VARIANT Grayval )

Access the gray values of an image object.


The parameter Grayval is a tuple of floating point numbers, or integer numbers, respectively, which returns the
gray values of several pixels of Image. The line coordinates of the pixels are in the tuple Row, the columns in
Column.
Attention
The type of the values of Grayval depends on the type of the gray values.
Gray values which do not belong to the image can also be accessed. The state of these gray values is not ascertained.
The operator GetGrayval produces quite some overhead. Typically, it is used to get single gray values of an
image (e.g., GetMposition followed by GetGrayval). It is not suitable for programming image processing
operations such as filters. In this case it is more useful to use the procedure GetImagePointer1 or to directly
use the C interface for integrating own procedures.
Parameter

. Image (input iconic) . . . . . . image ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2, uint2, int4,
real, complex )
Image whose gray value is to be accessed.
. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( integer )
Line numbers of pixels to be viewed.
Default Value : 0
Suggested values : Row ∈ {0, 64, 128, 256, 512, 1024}
Typical range of values : 0 ≤ Row ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 1
Restriction : (Row ∧ (Image < height))
. Column (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( integer )
Column numbers of pixels to be viewed.
Default Value : 0
Suggested values : Column ∈ {0, 64, 128, 256, 512, 1024}
Typical range of values : 0 ≤ Column ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 1
Restriction : (Column ∧ (Image < width))
Number of elements : (Column = Row)

433
434 CHAPTER 5. IMAGE

. Grayval (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . grayval(-array) ; VARIANT ( integer, real )


Gray values of indicated pixels.
Number of elements : (Grayval = Row)
Result
If the state of the parameters is correct the operator GetGrayval returns the value TRUE. The
behavior in case of empty input (no input images available) is set via the operator SetSystem
(’noObjectResult’,<Result>). If necessary an exception handling is raised.
Parallelization Information
GetGrayval is reentrant and processed without parallelization.
Possible Predecessors
ReadImage
See also
SetGrayval
Alternatives
GetImagePointer1
Module
Foundation

[out] long Pointer HImageX.GetImagePointer1 ([out] String Type,


[out] long Width, [out] long Height )
void HOperatorSetX.GetImagePointer1 ([in] IHObjectX Image,
[out] VARIANT Pointer, [out] VARIANT Type, [out] VARIANT Width,
[out] VARIANT Height )

Access the pointer of a channel.


The operator GetImagePointer1 returns a pointer to the first channel of the image Image. Additionally, the
image type (Type = ’byte’, ’int2’, ’uint2’, etc.) and the image size (width and height) are returned. Consequently,
a direct access to the image data in the HALCON database via the pointer is possible from the programming
language in which HALCON is used. An image is stored in HALCON linearized in row major order, i.e., line by
line.
Attention
The pointer returned by GetImagePointer1 may only be used as long as the corresponding image object
exists in the HALCON database. This is the case as long as the corresponding variable in the the programming
language in which HALCON is used is valid. If this is not observed, unexpected behavior or program crashes may
result.
If data is written to an existing image via the pointer, all image objects that reference the image are modified. If,
for example, the domain of an image is restricted via ReduceDomain, the original image object with the full
domain and the image object with the reduced domain share the same image matrix (i.e., GetImagePointer1
returns the same pointer for both images). Consequently, if one of the two images in this example is modified, both
image objects are affected. Therefore, if the pointer is used to write image data in the the programming language
in which HALCON is used, the image data should be written into an image object that has been created solely for
this purpose, e.g., using GenImage1.
Parameter

. Image (input iconic) . . . . . . image ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2, uint2, int4,
real, complex, vector_field )
Input image.
. Pointer (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pointer ; long / VARIANT
Pointer to the image data in the HALCON database.
. Type (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Type of image.
List of values : Type ∈ {’int1’, ’int2’, ’uint2’, ’int4’, ’byte’, ’real’, ’direction’, ’cyclic’, ’complex’,
’vector_field’}

HALCON/COM Reference Manual, 2008-5-13


5.1. ACCESS 435

. Width (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; long / VARIANT


Width of image.
. Height (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; long / VARIANT
Height of image.
Result
The operator GetImagePointer1 returns the value TRUE if exactly one image was passed. The
behavior in case of empty input (no input images available) is set via the operator SetSystem
(’noObjectResult’,<Result>). If necessary an exception handling is raised.
Parallelization Information
GetImagePointer1 is reentrant and processed without parallelization.
Possible Predecessors
ReadImage
See also
PaintRegion, PaintGray
Alternatives
SetGrayval, GetGrayval, GetImagePointer3
Module
Foundation

[out] long PixelPointer HImageX.GetImagePointer1Rect


([out] long Width, [out] long Height, [out] long VerticalPitch,
[out] long HorizontalBitPitch, [out] long BitsPerPixel )
void HOperatorSetX.GetImagePointer1Rect ([in] IHObjectX Image,
[out] VARIANT PixelPointer, [out] VARIANT Width, [out] VARIANT Height,
[out] VARIANT VerticalPitch, [out] VARIANT HorizontalBitPitch,
[out] VARIANT BitsPerPixel )

Access to the image data pointer and the image data inside the smallest rectangle of the domain of the input image.
The operator GetImagePointer1Rect returns the pointer PixelPointer which points to the beginning of
the image data inside the smallest rectangle of the domain of Image. VerticalPitch corresponds to the width
of the input image Image multiplied with the number of bytes per pixel (HorizontalBitPitch / 8). Width
and Height correspond to the size of the smallest rectangle of the input region. HorizontalBitPitch is the
horizontal distance (in bits) between two neighbouring pixels. BitsPerPixel is the number of used bits per
pixel. GetImagePointer1Rect is symmetrical to GenImage1Rect.
Attention
The operator GetImagePointer1Rect should only be used for entry into newly created images, since other-
wise the gray values of other images might be overwritten (see relational structure).
Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, uint2, int4 )


Input image (Himage).
. PixelPointer (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pointer ; long / VARIANT
Pointer to the image data.
. Width (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; long / VARIANT
Width of the output image.
. Height (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; long / VARIANT
Height of the output image.
. VerticalPitch (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Width(input image)*(HorizontalBitPitch/8).
. HorizontalBitPitch (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Distance between two neighbouring pixels in bits .
Default Value : 8
List of values : HorizontalBitPitch ∈ {8, 16, 32}

HALCON 8.0.2
436 CHAPTER 5. IMAGE

. BitsPerPixel (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT


Number of used bits per pixel.
Default Value : 8
List of values : BitsPerPixel ∈ {8, 16, 32}
Result
The operator GetImagePointer1Rect returns the value TRUE if exactly one image was passed.
The behavior in case of empty input (no input images available) is set via the operator SetSystem
(’noObjectResult’,<Result>). If necessary an exception handling is raised.
Parallelization Information
GetImagePointer1Rect is reentrant and processed without parallelization.
Possible Predecessors
ReadImage, GenImage1Rect
See also
PaintRegion, PaintGray, GenImage1Rect
Alternatives
SetGrayval, GetGrayval, GetImagePointer3, GetImagePointer1
Module
Foundation

[out] long PointerRed HImageX.GetImagePointer3


([out] long PointerGreen, [out] long PointerBlue, [out] String Type,
[out] long Width, [out] long Height )
void HOperatorSetX.GetImagePointer3 ([in] IHObjectX ImageRGB,
[out] VARIANT PointerRed, [out] VARIANT PointerGreen,
[out] VARIANT PointerBlue, [out] VARIANT Type, [out] VARIANT Width,
[out] VARIANT Height )

Access the pointers of a colored image.


The operator GetImagePointer3 returns a C pointer to the three channels of a colored image (ImageRGB).
Additionally the image type (Type = ’byte’, ’int2’,’float’ etc.) and the image size (Width and Height) are
returned. Consequently a direct access to the image data in the HALCON database from the HALCON host
language via the pointer is possible. An image is stored in HALCON as a vector of image lines. The three
channels must have the same pixel type and the same size.
Attention
Only one image can be passed. The operator GetImagePointer3 should only be used for entry into newly
created images, since otherwise the gray values of other images might be overwritten (see relational structure).
Parameter

. ImageRGB (input iconic) . . . . . . image ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2, uint2,
int4, real, complex, vector_field )
Input image.
. PointerRed (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pointer ; long / VARIANT
Pointer to the pixels of the first channel.
. PointerGreen (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pointer ; long / VARIANT
Pointer to the pixels of the second channel.
. PointerBlue (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pointer ; long / VARIANT
Pointer to the pixels of the third channel.
. Type (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Type of image.
List of values : Type ∈ {’int1’, ’int2’, ’uint2’, ’int4’, ’byte’, ’real’, ’direction’, ’cyclic’, ’complex’,
’vector_field’}
. Width (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; long / VARIANT
Width of image.

HALCON/COM Reference Manual, 2008-5-13


5.1. ACCESS 437

. Height (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; long / VARIANT


Height of image.
Result
The operator GetImagePointer3 returns the value TRUE if exactly one image is passed. The
behavior in case of empty input (no input images available) is set via the operator SetSystem
(’noObjectResult’,<Result>). If necessary an exception handling is raised.
Parallelization Information
GetImagePointer3 is reentrant and processed without parallelization.
Possible Predecessors
ReadImage
See also
PaintRegion, PaintGray
Alternatives
SetGrayval, GetGrayval, GetImagePointer1
Module
Foundation

[out] long MSecond HImageX.GetImageTime ([out] long Second,


[out] long Minute, [out] long Hour, [out] long Day, [out] long YDay,
[out] long Month, [out] long Year )
void HOperatorSetX.GetImageTime ([in] IHObjectX Image,
[out] VARIANT MSecond, [out] VARIANT Second, [out] VARIANT Minute,
[out] VARIANT Hour, [out] VARIANT Day, [out] VARIANT YDay,
[out] VARIANT Month, [out] VARIANT Year )

Request time at which the image was created.


The operator GetImageTime returns the time at which the image was created.
Parameter
. Image (input iconic) . . . . . . image ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2, uint2, int4,
real, complex, vector_field )
Input image.
. MSecond (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Milliseconds (0..999).
. Second (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Seconds (0..59).
. Minute (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Minutes (0..59).
. Hour (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Hours (0..11).
. Day (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Day of the month (1..31).
. YDay (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Day of the year (1..365).
. Month (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Month (1..12).
. Year (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Year (xxxx).
Result
The operator GetImageTime returns the value TRUE if exactly one image was passed. The be-
havior in case of empty input (no input images available) is set via the operator SetSystem
(’noObjectResult’,<Result>). If necessary an exception handling is raised.
Parallelization Information
GetImageTime is reentrant and processed without parallelization.

HALCON 8.0.2
438 CHAPTER 5. IMAGE

Possible Predecessors
ReadImage, GrabImage
See also
CountSeconds
Module
Foundation

5.2 Acquisition

void HMiscX.CloseAllFramegrabbers ( )
void HOperatorSetX.CloseAllFramegrabbers ( )

Close all image acquisition devices.


The operator CloseAllFramegrabbers closes all currently open image acquisition devices. It is used to cope
with deadlocks resulting from damaged image acquisition handles (in that case the use of CloseFramegrabber
is impossible).
Attention
CloseAllFramegrabbers exists solely for the purpose of implementing the “reset program” functionality in
HDevelop. CloseAllFramegrabbers must not be used in any application.
Result
If it is possible to close all image acquisition devices, the operator CloseAllFramegrabbers returns the
value TRUE. Otherwise an exception handling is raised.
Parallelization Information
CloseAllFramegrabbers is local and processed completely exclusively without parallelization.
Possible Predecessors
GrabImage, GrabImageAsync
See also
OpenFramegrabber
Module
Foundation

void HOperatorSetX.CloseFramegrabber ([in] VARIANT AcqHandle )

Close specified image acquisition device.


The operator CloseFramegrabber closes the image acquisition device specified by AcqHandle. In partic-
ular, allocated memory for data buffers is released and the image acquisition device is made available for other
processes.
Attention

Parameter

. AcqHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . framegrabber ; HFramegrabberX / VARIANT


Handle of the image acquisition device to be closed.
Result
If the specified image acquisition device could be closed, CloseFramegrabber returns the value TRUE.
Otherwise an exception handling is raised.
Parallelization Information
CloseFramegrabber is processed completely exclusively without parallelization.
Possible Predecessors
GrabImage, GrabImageAsync

HALCON/COM Reference Manual, 2008-5-13


5.2. ACQUISITION 439

See also
OpenFramegrabber
Module
Foundation

[out] VARIANT ImageRed HFramegrabberX.GetFramegrabberLut


([out] VARIANT ImageGreen, [out] VARIANT ImageBlue )
void HOperatorSetX.GetFramegrabberLut ([in] VARIANT AcqHandle,
[out] VARIANT ImageRed, [out] VARIANT ImageGreen, [out] VARIANT ImageBlue )

Query look-up table of the image acquisition device.


The operator GetFramegrabberLut queries the look-up table (LUT) of the image acquisition device specified
by AcqHandle. Note that this operation is not supported for all kinds of image acquisition devices.
Parameter
. AcqHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . framegrabber ; HFramegrabberX / VARIANT
Handle of the acquisition device to be used.
. ImageRed (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Red level of the LUT entries.
. ImageGreen (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Green level of the LUT entries.
. ImageBlue (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Blue level of the LUT entries.
Result
The operator GetFramegrabberLut returns the value TRUE if the image acquisition device is open.
Parallelization Information
GetFramegrabberLut is reentrant and processed without parallelization.
Possible Predecessors
OpenFramegrabber
Possible Successors
SetFramegrabberLut
See also
SetFramegrabberLut, OpenFramegrabber
Module
Foundation

[out] VARIANT Value HFramegrabberX.GetFramegrabberParam


([in] VARIANT Param )
void HOperatorSetX.GetFramegrabberParam ([in] VARIANT AcqHandle,
[in] VARIANT Param, [out] VARIANT Value )

Query specific parameters of a image acquisition device.


The operator GetFramegrabberParam returns specific parameter values for the image acquisition device
specified by AcqHandle. The standard parameters listed below are available for all image acquisition devices.
Additional parameters may be supported by a specific image acquisition device. A list of those parameters can be
obtained with the query ’parameter’ via InfoFramegrabber.
Standard values for Param, see OpenFramegrabber:
’name’ Name of the image acquisition interface.
’horizontal_resolution’ Horizontal resolution of the image acquisition device.
’vertical_resolution’ Vertical resolution of the image acquisition device.
’image_width’ Width of the specified image part.

HALCON 8.0.2
440 CHAPTER 5. IMAGE

’image_height’ Height of the specified image part.


’start_row’ Row coordinate of upper left corner of specified image part.
’start_column’ Column coordinate of upper left corner of specified image part.
’field’ Selected video field or full frame.
’bits_per_channel’ Number of transferred bits per pixel and image channel.
’color_space’ Color space of resulting image.
’generic’ Generic value with device-specific meaning.
’external_trigger’ External triggering (’true’ / ’false’).
’camera_type’ Type of used camera (interface-specific).
’device’ Device name of the image acquistion device.
’port’ Port the image acquisition device is connected to.
’line_in’ Camera input line of multiplexer (optional).
Attention

Parameter
. AcqHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . framegrabber ; HFramegrabberX / VARIANT
Handle of the acquisition device to be used.
. Param (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Parameter of interest.
Default Value : ’revision’
Suggested values : Param ∈ {’bits_per_channel’, ’camera_type’, ’color_space’, ’continuous_grabbing’,
’device’, ’external_trigger’, ’field’, ’generic’, ’grab_timeout’, ’horizontal_resolution’, ’image_available’,
’image_height’, ’image_width’, ’line_in’, ’name’, ’port’, ’revision’, ’start_column’, ’start_row’,
’vertical_resolution’, ’volatile’}
. Value (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string, real, integer )
Parameter value.
Result
If the image acquisition device is open and the specified parameter is supported, the operator
SetFramegrabberParam returns the value TRUE. Otherwise an exception handling is raised.
Parallelization Information
GetFramegrabberParam is reentrant and processed without parallelization.
Possible Predecessors
OpenFramegrabber, SetFramegrabberParam
Possible Successors
GrabImage, GrabData, GrabImageStart, GrabImageAsync, GrabDataAsync,
SetFramegrabberParam, CloseFramegrabber
See also
OpenFramegrabber, InfoFramegrabber, SetFramegrabberParam
Module
Foundation

void HImageX.GrabData ([out] HRegionX Region, [out] HXLDContX Contours,


[in] HFramegrabberX AcqHandle, [out] VARIANT Data )
void HRegionX.GrabData ([out] HImageX Image, [out] HXLDContX Contours,
[in] HFramegrabberX AcqHandle, [out] VARIANT Data )
[out] HImageX Image HFramegrabberX.GrabData ([out] HRegionX Region,
[out] HXLDContX Contours, [out] VARIANT Data )
void HOperatorSetX.GrabData ([out] HUntypedObjectX Image,
[out] HUntypedObjectX Region, [out] HUntypedObjectX Contours,
[in] VARIANT AcqHandle, [out] VARIANT Data )

Grab images and preprocessed image data from the specified image acquisition device.

HALCON/COM Reference Manual, 2008-5-13


5.2. ACQUISITION 441

The operator GrabData grabs images and preprocessed image data via the image acquisition device specified by
AcqHandle. The desired operational mode of the image acquisition device as well as a suitable image part can
be adjusted via the operator OpenFramegrabber. Additional interface-specific settings can be specified via
SetFramegrabberParam. Depending on the current configuration of the image acquisition device, the prepro-
cessed image data can be returned in terms of images (Image), regions (Region), XLD contours (Contours),
and control data (Data).
Attention

Parameter

. Image (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX


Grabbed image data.
. Region (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Preprocessed image regions.
. Contours (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . xld_cont(-array) ; HXLDContX / HUntypedObjectX
Preprocessed XLD contours.
. AcqHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . framegrabber ; HFramegrabberX / VARIANT
Handle of the acquisition device to be used.
. Data (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string, real, integer )
Preprocessed control data.
Example

// Select a suitable image acquisition interface name AcqName


info_framegrabber(AcqName,’port’,Information,Values)
// Choose the port P and the input line L your camera is connected to
open_framegrabber(AcqName,1,1,0,0,0,0,’default’,-1,’default’,-1.0,
’default’,’default’,’default’,P,L,AcqHandle)
// Grab and segment image
grab_data(Region,AcqHandle)
// Process Region...
close_framegrabber(AcqHandle)

Result
If the image acquisition device is open and supports the image acquisition via GrabData, the operator
GrabData returns the value TRUE. Otherwise an exception handling is raised.
Parallelization Information
GrabData is reentrant and processed without parallelization.
Possible Predecessors
OpenFramegrabber, GrabImageStart, SetFramegrabberParam
Possible Successors
GrabData, GrabDataAsync, GrabImageStart, GrabImage, GrabImageAsync,
SetFramegrabberParam, CloseFramegrabber
See also
OpenFramegrabber, InfoFramegrabber, SetFramegrabberParam
Module
Foundation

HALCON 8.0.2
442 CHAPTER 5. IMAGE

void HImageX.GrabDataAsync ([out] HRegionX Region,


[out] HXLDContX Contours, [in] HFramegrabberX AcqHandle,
[in] double MaxDelay, [out] VARIANT Data )
void HRegionX.GrabDataAsync ([out] HImageX Image,
[out] HXLDContX Contours, [in] HFramegrabberX AcqHandle,
[in] double MaxDelay, [out] VARIANT Data )
[out] HImageX Image HFramegrabberX.GrabDataAsync
([out] HRegionX Region, [out] HXLDContX Contours, [in] double MaxDelay,
[out] VARIANT Data )
void HOperatorSetX.GrabDataAsync ([out] HUntypedObjectX Image,
[out] HUntypedObjectX Region, [out] HUntypedObjectX Contours,
[in] VARIANT AcqHandle, [in] VARIANT MaxDelay, [out] VARIANT Data )

Grab images and preprocessed image data from the specified image image acquisition device and start the next
asynchronous grab.
The operator GrabData grabs images and preprocessed image data via the image acquisition device specified by
AcqHandle and starts the next asynchronous grab. The desired operational mode of the image acquisition device
as well as a suitable image part can be adjusted via the operator OpenFramegrabber. Additional interface-
specific settings can be specified via SetFramegrabberParam. The segmented image regions are returned in
Region. Depending on the current configuration of the image acquisition device, the preprocessed image data
can be returned in terms of images (Image), regions (Region), XLD contours (Contours), and control data
(Data).
The grab of the next image is finished by calling GrabDataAsync or GrabImageAsync. If more than
MaxDelay ms have passed since the asynchronous grab was started, the asynchronously grabbed image is con-
sidered as too old and a new image is grabbed. If a negative value is assigned to MaxDelay this control mechanism
is deactivated.
Please note that if you call the operators GrabImage or GrabData after GrabDataAsync, the asynchronous
grab started by GrabDataAsync is aborted and a new image is grabbed (and waited for).
Attention

Parameter
. Image (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX
Grabbed image data.
. Region (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Pre-processed image regions.
. Contours (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . xld_cont(-array) ; HXLDContX / HUntypedObjectX
Pre-processed XLD contours.
. AcqHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . framegrabber ; HFramegrabberX / VARIANT
Handle of the acquisition device to be used.
. MaxDelay (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Maximum tolerated delay between the start of the asynchronous grab and the delivery of the image [ms].
Default Value : -1.0
Suggested values : MaxDelay ∈ {-1.0, 20.0, 33.3, 40.0, 66.6, 80.0, 99.9}
. Data (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string, real, integer )
Pre-processed control data.
Example

// Select a suitable image acquisition interface name AcqName


open_framegrabber(AcqName,1,1,0,0,0,0,’default’,-1,’default’,-1.0,
’default’,’default’,’default’,-1,-1,AcqHandle)
// Grab image, segment it, and start next grab
grab_data_async(Region1,AcqHandle,-1.0)
// Process Region1...
// Finish asynchronous grab, segment this image, and start next grab

HALCON/COM Reference Manual, 2008-5-13


5.2. ACQUISITION 443

grab_data_async(Region2,AcqHandle,-1.0)
// Process Region2...
close_framegrabber(AcqHandle)

Result
If the image acquisition device is open and supports the image acquisition via GrabDataAsync, the operator
GrabDataAsync returns the value TRUE. Otherwise an exception handling is raised.
Parallelization Information
GrabDataAsync is reentrant and processed without parallelization.
Possible Predecessors
OpenFramegrabber, GrabImageStart, SetFramegrabberParam
Possible Successors
GrabDataAsync, GrabImageAsync, SetFramegrabberParam, CloseFramegrabber
See also
OpenFramegrabber, InfoFramegrabber, SetFramegrabberParam
Module
Foundation

void HImageX.GrabImage ([in] HFramegrabberX AcqHandle )


[out] HImageX Image HFramegrabberX.GrabImage ( )
void HOperatorSetX.GrabImage ([out] HUntypedObjectX Image,
[in] VARIANT AcqHandle )

Grab an image from the specified image acquisition device.


The operator GrabImage grabs an image via the image acquisition device specified by AcqHandle. The desired
operational mode of the image acquisition device as well as a suitable image part can be adjusted via the operator
OpenFramegrabber. Additional interface-specific settings can be specified via SetFramegrabberParam.
Attention

Parameter

. Image (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / HUntypedObjectX ( byte, int2 )


Grabbed image.
. AcqHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . framegrabber ; HFramegrabberX / VARIANT
Handle of the acquisition device to be used.
Example

// Select a suitable image acquisition interface name AcqName


info_framegrabber(AcqName,’port’,Information,Values)
// Choose the port P and the input line L your camera is connected to
open_framegrabber(AcqName,1,1,0,0,0,0,’default’,-1,’default’,-1.0,
’default’,’default’,’default’,P,L,AcqHandle)
grab_image(Image,AcqHandle)
close_framegrabber(AcqHandle)

Result
If the image could be acquired successfully, the operator GrabImage returns the value TRUE. Otherwise an
exception handling is raised.
Parallelization Information
GrabImage is reentrant and processed without parallelization.
Possible Predecessors
OpenFramegrabber, SetFramegrabberParam

HALCON 8.0.2
444 CHAPTER 5. IMAGE

Possible Successors
GrabImage, GrabImageStart, GrabImageAsync, CloseFramegrabber
See also
OpenFramegrabber, InfoFramegrabber, SetFramegrabberParam
Module
Foundation

void HImageX.GrabImageAsync ([in] HFramegrabberX AcqHandle,


[in] double MaxDelay )
[out] HImageX Image HFramegrabberX.GrabImageAsync
([in] double MaxDelay )
void HOperatorSetX.GrabImageAsync ([out] HUntypedObjectX Image,
[in] VARIANT AcqHandle, [in] VARIANT MaxDelay )

Grab an image from the specified image acquisition device and start the next asynchronous grab.
The operator GrabImageAsync grabs an image via the image acquisition device by AcqHandle and starts the
asynchronous grab of the next image. The desired operational mode of the image acquisition device as well as a
suitable image part can be adjusted via the operator OpenFramegrabber. Additional interface-specific settings
can be specified via SetFramegrabberParam.
The grab of the next image is finished by calling GrabImageAsync or GrabDataAsync. If more than
MaxDelay ms have passed since the asynchronous grab was started, the asynchronously grabbed image is con-
sidered as too old and a new image is grabbed. If a negative value is assigned to MaxDelay this control mechanism
is deactivated.
Please note that if you call the operators GrabImage or GrabData after GrabImageAsync, the asyn-
chronous grab started by GrabImageAsync is aborted and a new image is grabbed (and waited for).
Attention

Parameter

. Image (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / HUntypedObjectX ( byte, int2 )


Grabbed image.
. AcqHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . framegrabber ; HFramegrabberX / VARIANT
Handle of the acquisition device to be used.
. MaxDelay (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Maximum tolerated delay between the start of the asynchronous grab and the delivery of the image [ms].
Default Value : -1.0
Suggested values : MaxDelay ∈ {-1.0, 20.0, 33.3, 40.0, 66.6, 80.0, 99.9}
Example

// Select a suitable image acquisition interface name AcqName


open_framegrabber(AcqName,1,1,0,0,0,0,’default’,-1,’default’,-1.0,
’default’,’default’,’default’,-1,-1,AcqHandle)
// Grab image + start next grab
grab_image_async(Image1,AcqHandle,-1.0)
// Process Image1 ...
// Finish asynchronous grab + start next grab
grab_image_async(Image2,AcqHandle,-1.0)
// Process Image2 ...
close_framegrabber(AcqHandle)

Result
If the image acquisition device is open and supports asynchronous grabbing the operator GrabImageStart
returns the value TRUE. Otherwise an exception handling is raised.

HALCON/COM Reference Manual, 2008-5-13


5.2. ACQUISITION 445

Parallelization Information
GrabImageAsync is reentrant and processed without parallelization.
Possible Predecessors
GrabImageStart, OpenFramegrabber, SetFramegrabberParam
Possible Successors
GrabImageAsync, GrabDataAsync, SetFramegrabberParam, CloseFramegrabber
See also
GrabImageStart, OpenFramegrabber, InfoFramegrabber, SetFramegrabberParam
Module
Foundation

void HFramegrabberX.GrabImageStart ([in] double MaxDelay )


void HOperatorSetX.GrabImageStart ([in] VARIANT AcqHandle,
[in] VARIANT MaxDelay )

Start an asynchronous grab from the specified image acquisition device.


The operator GrabImageStart starts the asynchronous grab of an image via the image acquisition device
specified by AcqHandle. The desired operational mode of the image acquisition device as well as a suitable
image part can be adjusted via the operator OpenFramegrabber. Additional interface-specific settings can be
specified via SetFramegrabberParam.
The grab is finished via GrabImageAsync or GrabDataAsync. If one of those operators is called more than
MaxDelay ms later, the asynchronously grabbed image is considered as too old and a new image is grabbed. If a
negative value is assigned to MaxDelay this control mechanism is deactivated.
Please note that the operator GrabImageStart makes sense only when used together with GrabImageAsync
or GrabDataAsync. If you call the operators GrabImage or GrabData instead, the asynchronous grab
started by GrabImageStart is aborted and a new image is grabbed (and waited for).
Attention

Parameter

. AcqHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . framegrabber ; HFramegrabberX / VARIANT


Handle of the acquisition device to be used.
. MaxDelay (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Maximum tolerated delay between the start of the asynchronous grab and the delivery of the image [ms].
Default Value : -1.0
Suggested values : MaxDelay ∈ {-1.0, 20.0, 33.3, 40.0, 66.6, 80.0, 99.9}
Example

// Select a suitable image acquisition interface name AcqName


open_framegrabber(AcqName,1,1,0,0,0,0,’default’,-1,’default’,-1.0,
’default’,’default’,’default’,-1,-1,AcqHandle)
grab_image(Image1,AcqHandle)
// Start next grab
grab_image_start(AcqHandle,-1.0)
// Process Image1 ...
// Finish asynchronous grab + start next grab
grab_image_async(Image2,AcqHandle,-1.0)
// Process Image2 ...
close_framegrabber(AcqHandle)

Result
If the image acquisition device is open and supports asynchronous grabbing the operator GrabImageStart
returns the value TRUE. Otherwise an exception handling is raised.

HALCON 8.0.2
446 CHAPTER 5. IMAGE

Parallelization Information
GrabImageStart is reentrant and processed without parallelization.
Possible Predecessors
OpenFramegrabber, SetFramegrabberParam
Possible Successors
GrabImageAsync, GrabDataAsync, SetFramegrabberParam, CloseFramegrabber
See also
OpenFramegrabber, InfoFramegrabber, SetFramegrabberParam
Module
Foundation

[out] String Information HInfoX.InfoFramegrabber ([in] String Name,


[in] String Query, [out] VARIANT ValueList )
void HOperatorSetX.InfoFramegrabber ([in] VARIANT Name,
[in] VARIANT Query, [out] VARIANT Information, [out] VARIANT ValueList )

Query information about the specified image acquisition interface.


The operator InfoFramegrabber returns information about the image acquisition device Name. The de-
sired information is specified via Query. A textual description according to the selected topic is returned in
Information. If applicable, ValueList contains a list of supported values. Up to now, the following queries
are possible:

’bits_per_channel’: List of all supported values for the parameter ’BitsPerChannel’, see OpenFramegrabber.
’camera_type’: Description and list of all supported values for the parameter ’CameraType’, see
OpenFramegrabber.
’color_space’: List of all supported values for the parameter ’ColorSpace’, see OpenFramegrabber.
’defaults’: Interface-specific default values in ValueList, see OpenFramegrabber.
’device’: List of all supported values for the parameter ’Device’, see OpenFramegrabber.
’external_trigger’: List of all supported values for the parameter ’ExternalTrigger’, see OpenFramegrabber.
’field’: List of all supported values for the parameter ’Field’, see OpenFramegrabber.
’general’: General information (in Information).
’horizontal_resolution’: List of all supported values for the parameter ’HorizontalResolution’, see
OpenFramegrabber.
’image_height’: List of all supported values for the parameter ’ImageHeight’, see OpenFramegrabber.
’image_width’: List of all supported values for the parameter ’ImageWidth’, see OpenFramegrabber.
’info_boards’: Information about actually installed boards or cameras. This data is especially useful for the auto-
detect mechansim of ActivVisionTools and for the Image Acquisition Assistant in HDevelop.
’line_in’: List of all supported values for the parameter ’LineIn’, see OpenFramegrabber.
’parameters’: List of all interface-specific parameters which are accessible via SetFramegrabberParam or
GetFramegrabberParam.
’parameters_readonly’: List of all interface-specific parameters which are only accessible via
GetFramegrabberParam.
’parameters_writeonly’: List of all interface-specific parameters which are only accessible via
SetFramegrabberParam.
’port’: List of all supported values for the parameter ’Port’, see OpenFramegrabber.
’revision’: Version number of the image acquisition interface.
’start_column’: List of all supported values for the parameter ’StartColumn’, see OpenFramegrabber.
’start_row’: List of all supported values for the parameter ’StartRow’, see OpenFramegrabber.
’vertical_resolution’: List of all supported values for the parameter ’VerticalResolution’, see
OpenFramegrabber.

HALCON/COM Reference Manual, 2008-5-13


5.2. ACQUISITION 447

Please check also the directory doc/html/manuals for documentation about specific image grabber interfaces.
Attention

Parameter

. Name (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT


HALCON image acquisition interface name, i.e., name of the corresponding DLL (Windows) or shared library
(Linux/UNIX).
Default Value : ’File’
Suggested values : Name ∈ {1394IIDC, ’ABS’, ’BaumerFCAM’, ’BitFlow’, ’DahengCAM’, ’DahengFG’,
’DFG-LC’, ’DirectFile’, ’DirectShow’, ’dPict’, ’DT315x’, ’DT3162’, ’eneo’, ’eXcite’, ’FALCON’, ’File’,
’FlashBusMV’, ’FlashBusMX’, ’GigEVision’, ’Ginga++’, ’GingaDG’, ’INSPECTA’, ’INSPECTA5’,
’iPORT’, ’Leutron’, ’LinX’, ’LuCam’, ’MatrixVisionAcquire’, ’MILLite’, ’mEnableIII’, ’mEnableIV’,
’mEnableVisualApplets’, ’MultiCam’, ’Opteon’, ’p3i2’, ’p3i4’, ’PX’, ’PXC’, ’PXD’, ’PXR’, ’pylon’,
’RangerC’, ’RangerE’, ’SaperaLT’, ’SonyXCI’, ’TAG’, ’TWAIN’, ’uEye’, ’VRmUsbCam’}
. Query (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Name of the chosen query.
Default Value : ’info_boards’
List of values : Query ∈ {’defaults’, ’general’, ’info_boards’, ’parameters’, ’parameters_readonly’,
’parameters_writeonly’, ’revision’, ’bits_per_channel’, ’camera_type’, ’color_space’, ’device’,
’external_trigger’, ’field’, ’generic’, ’horizontal_resolution’, ’image_height’, ’image_width’, ’port’,
’start_column’, ’start_row’, ’vertical_resolution’}
. Information (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Textual information (according to Query).
. ValueList (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( string, integer, real )
List of values (according to Query).
Example

// Select a suitable image acquisition interface name AcqName


info_framegrabber(AcqName,’port’,Information,Values)
// Choose the port P and the input line L your camera is connected to
open_framegrabber(AcqName,1,1,0,0,0,0,’default’,-1,’default’,-1.0,
’default’,’default’,’default’,P,L,AcqHandle)
grab_image(Image,AcqHandle)
close_framegrabber(AcqHandle)

Result
If the parameter values are correct and the specified image acquistion interface is available,
InfoFramegrabber returns the value TRUE. Otherwise an exception handling is raised.
Parallelization Information
InfoFramegrabber is processed completely exclusively without parallelization.
Possible Predecessors
OpenFramegrabber
Possible Successors
OpenFramegrabber
See also
OpenFramegrabber
Module
Foundation

HALCON 8.0.2
448 CHAPTER 5. IMAGE

void HFramegrabberX.OpenFramegrabber ([in] String Name,


[in] long HorizontalResolution, [in] long VerticalResolution,
[in] long ImageWidth, [in] long ImageHeight, [in] long StartRow,
[in] long StartColumn, [in] String Field, [in] VARIANT BitsPerChannel,
[in] VARIANT ColorSpace, [in] VARIANT Generic, [in] String ExternalTrigger,
[in] VARIANT CameraType, [in] VARIANT Device, [in] VARIANT Port,
[in] VARIANT LineIn )
void HOperatorSetX.OpenFramegrabber ([in] VARIANT Name,
[in] VARIANT HorizontalResolution, [in] VARIANT VerticalResolution,
[in] VARIANT ImageWidth, [in] VARIANT ImageHeight, [in] VARIANT StartRow,
[in] VARIANT StartColumn, [in] VARIANT Field, [in] VARIANT BitsPerChannel,
[in] VARIANT ColorSpace, [in] VARIANT Generic, [in] VARIANT ExternalTrigger,
[in] VARIANT CameraType, [in] VARIANT Device, [in] VARIANT Port,
[in] VARIANT LineIn, [out] VARIANT AcqHandle )

Open and configure a image acquisition device.


The operator OpenFramegrabber opens and configures the chosen image acquisition device. During this
process, the connection to the image acquisition device is tested, the image acquisition device is locked for other
processes, and, if necessary, memory is reserved for the data buffers. The actual image grabbing is done via the
operators GrabImage, GrabData, GrabImageAsync, or GrabDataAsync. If the image acquisition
device is not needed anymore, it should be closed via the operator CloseFramegrabber, releasing it for other
processes. Some image acquisition devices allow to open several instances of the same image acquisition device
class.
For all parameters image acquisition device-specific default values can be chosen explicitly (see the pa-
rameter description below). Additional information for a specific image acquisition device is available via
InfoFramegrabber. A comprehensive documentation of all image acquistion device-specific parameters con
be found in the corresponding description file in the directory doc/html/manuals.
The meaning of the particular parameters is as follows:

HorizontalResolution, VerticalResolution Desired resolution of the image acquisition device.


ImageWidth, ImageHeight Size of the image part to be returned by GrabImage etc.
StartRow, StartColumn Upper left corner of the desired image area.
Field Desired half image (’first’, ’second’, or ’next’) or selection of a full image.
BitsPerChannel Number of bits, which are transferred from the image acquisition device per pixel and image
channel (typically 5, 8, 10, 12, or 16).
ColorSpace Output color format of the grabbed images (typically ’gray’ or ’raw’ for single-channel or ’rgb’ or
’yuv’ for three-channel images).
Generic Generic parameter with device-specific meaning which can be queried by InfoFramegrabber.
ExternalTrigger Activation of external triggering (if available).
CameraType More detailed specification of the desired image acquistion device (typically the type of the analog
video format or the name of the desired camera configuration file).
Device Device name of the image acquistion device.
Port Port the image acquistion device is connected to.
LineIn Camera input line of multiplexer (if available).

The operator OpenFramegrabber returns a handle (AcqHandle) to the opened image acquisition device.
Attention
Due to the multitude of supported image acquisition devices, OpenFramegrabber contains a large number of
parameters. However, not all parameters are needed for a specific image acquisition device.

HALCON/COM Reference Manual, 2008-5-13


5.2. ACQUISITION 449

Parameter
. Name (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
HALCON image acquisition interface name, i.e., name of the corresponding DLL (Windows) or shared library
(Linux/UNIX).
Default Value : ’File’
Suggested values : Name ∈ {1394IIDC, ’ABS’, ’BaumerFCAM’, ’BitFlow’, ’DahengCAM’, ’DahengFG’,
’DFG-LC’, ’DirectFile’, ’DirectShow’, ’dPict’, ’DT315x’, ’DT3162’, ’eneo’, ’eXcite’, ’FALCON’, ’File’,
’FlashBusMV’, ’FlashBusMX’, ’GigEVision’, ’Ginga++’, ’GingaDG’, ’INSPECTA’, ’INSPECTA5’,
’iPORT’, ’Leutron’, ’LinX’, ’LuCam’, ’MatrixVisionAcquire’, ’MILLite’, ’mEnableIII’, ’mEnableIV’,
’mEnableVisualApplets’, ’MultiCam’, ’Opteon’, ’p3i2’, ’p3i4’, ’PX’, ’PXC’, ’PXD’, ’PXR’, ’pylon’,
’RangerC’, ’RangerE’, ’SaperaLT’, ’SonyXCI’, ’TAG’, ’TWAIN’, ’uEye’, ’VRmUsbCam’}
. HorizontalResolution (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; long / VARIANT
Desired horizontal resolution of image acquisition interface (absolute value or 1 for full resolution, 2 for half
resolution, or 4 for quarter resolution).
Default Value : 1
Suggested values : HorizontalResolution ∈ {1, 2, 4, 1600, 1280, 768, 640, 384, 320, 192, 160, -1}
. VerticalResolution (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; long / VARIANT
Desired vertical resolution of image acquisition interface (absolute value or 1 for full resolution, 2 for half
resolution, or 4 for quarter resolution).
Default Value : 1
Suggested values : VerticalResolution ∈ {1, 2, 4, 1200, 1024, 576, 480, 288, 240, 144, 120, -1}
. ImageWidth (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.extent.x ; long / VARIANT
Width of desired image part (absolute value or 0 for HorizontalResolution - 2*StartColumn).
Default Value : 0
Suggested values : ImageWidth ∈ {0, -1}
. ImageHeight (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.extent.y ; long / VARIANT
Height of desired image part (absolute value or 0 for VerticalResolution - 2*StartRow).
Default Value : 0
Suggested values : ImageHeight ∈ {0, -1}
. StartRow (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.origin.y ; long / VARIANT
Line number of upper left corner of desired image part (or border height if ImageHeight = 0).
Default Value : 0
Suggested values : StartRow ∈ {0, -1}
. StartColumn (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.origin.x ; long / VARIANT
Column number of upper left corner of desired image part (or border width if ImageWidth = 0).
Default Value : 0
Suggested values : StartColumn ∈ {0, -1}
. Field (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Desired half image or full image.
Default Value : ’default’
Suggested values : Field ∈ {’first’, ’second’, ’next’, ’interlaced’, ’progressive’, ’default’}
. BitsPerChannel (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Number of transferred bits per pixel and image channel (-1: device-specific default value).
Default Value : -1
Suggested values : BitsPerChannel ∈ {5, 8, 10, 12, 14, 16, -1}
. ColorSpace (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .string(-array) ; VARIANT ( string )
Output color format of the grabbed images, typically ’gray’ or ’raw’ for single-channel or ’rgb’ or ’yuv’ for
three-channel images (’default’: device-specific default value).
Default Value : ’default’
Suggested values : ColorSpace ∈ {’gray’, ’raw’, ’rgb’, ’yuv’, ’default’}
. Generic (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string, real, integer )
Generic parameter with device-specific meaning.
Default Value : -1
. ExternalTrigger (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
External triggering.
Default Value : ’default’
List of values : ExternalTrigger ∈ {’true’, ’false’, ’default’}

HALCON 8.0.2
450 CHAPTER 5. IMAGE

. CameraType (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .string(-array) ; VARIANT ( string )


Type of used camera (’default’: device-specific default value).
Default Value : ’default’
Suggested values : CameraType ∈ {’ntsc’, ’pal’, ’auto’, ’default’}
. Device (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Device the image acquisition device is connected to (’default’: device-specific default value).
Default Value : ’default’
Suggested values : Device ∈ {’-1’, ’0’, ’1’, ’2’, ’3’, ’default’}
. Port (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Port the image acquisition device is connected to (-1: device-specific default value).
Default Value : -1
Suggested values : Port ∈ {0, 1, 2, 3, -1}
. LineIn (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Camera input line of multiplexer (-1: device-specific default value).
Default Value : -1
Suggested values : LineIn ∈ {1, 2, 3, 4, -1}
. AcqHandle (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . framegrabber ; HFramegrabberX / VARIANT
Handle of the opened image acquisition device.
Example

// Select a suitable image acquisition interface name AcqName


info_framegrabber(AcqName,’port’,Information,Values)
// Choose the port P and the input line L your camera is connected to
open_framegrabber(AcqName,1,1,0,0,0,0,’default’,-1,’default’,-1.0,
’default’,’default’,’default’,P,L,AcqHandle)
grab_image(Image,AcqHandle)
close_framegrabber(AcqHandle)

Result
If the parameter values are correct and the desired image acquisition device could be opened,
OpenFramegrabber returns the value TRUE. Otherwise an exception handling is raised.
Parallelization Information
OpenFramegrabber is processed completely exclusively without parallelization.
Possible Predecessors
InfoFramegrabber
Possible Successors
GrabImage, GrabData, GrabImageStart, GrabImageAsync, GrabDataAsync,
SetFramegrabberParam
See also
InfoFramegrabber, CloseFramegrabber, GrabImage
Module
Foundation

void HFramegrabberX.SetFramegrabberLut ([in] VARIANT ImageRed,


[in] VARIANT ImageGreen, [in] VARIANT ImageBlue )
void HOperatorSetX.SetFramegrabberLut ([in] VARIANT AcqHandle,
[in] VARIANT ImageRed, [in] VARIANT ImageGreen, [in] VARIANT ImageBlue )

Set look-up table of the image acquisition device.


The operator SetFramegrabberLut sets the look-up table (LUT) of the image acquisition device specified by
AcqHandle. Note that this operation is not supported for all kinds of image acquisition devices.

HALCON/COM Reference Manual, 2008-5-13


5.2. ACQUISITION 451

Parameter
. AcqHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . framegrabber ; HFramegrabberX / VARIANT
Handle of the acquisition device to be used.
. ImageRed (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Red level of the LUT entries.
. ImageGreen (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Green level of the LUT entries.
. ImageBlue (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Blue level of the LUT entries.
Result
The operator SetFramegrabberLut returns the value TRUE if the specified LUT is correct and the image
acquisition device is open.
Parallelization Information
SetFramegrabberLut is reentrant and processed without parallelization.
Possible Predecessors
OpenFramegrabber, GetFramegrabberLut
Possible Successors
GrabImage, GrabData, GrabImageStart, GrabImageAsync, GrabDataAsync
See also
GetFramegrabberLut, OpenFramegrabber
Module
Foundation

void HFramegrabberX.SetFramegrabberParam ([in] VARIANT Param,


[in] VARIANT Value )
void HOperatorSetX.SetFramegrabberParam ([in] VARIANT AcqHandle,
[in] VARIANT Param, [in] VARIANT Value )

Set specific parameters of a image acquistion device.


The operator SetFramegrabberParam sets specific parameters for the image acquisition device specified by
AcqHandle.
Attention

Parameter
. AcqHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . framegrabber ; HFramegrabberX / VARIANT
Handle of the acquisition device to be used.
. Param (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Parameter name.
Suggested values : Param ∈ {’color_space’, ’continuous_grabbing’, ’external_trigger’, ’grab_timeout’,
’image_height’, ’image_width’, ’port’, ’start_column’, ’start_row’, ’volatile’}
. Value (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string, real, integer )
Parameter value to be set.
Result
If the image acquisition device is open and the specified parameter / parameter value is supported, the operator
SetFramegrabberParam returns the value TRUE. Otherwise an exception handling is raised.
Parallelization Information
SetFramegrabberParam is reentrant and processed without parallelization.
Possible Predecessors
OpenFramegrabber
Possible Successors
GrabImage, GrabData, GrabImageStart, GrabImageAsync, GrabDataAsync,
GetFramegrabberParam

HALCON 8.0.2
452 CHAPTER 5. IMAGE

See also
OpenFramegrabber, InfoFramegrabber, GetFramegrabberParam
Module
Foundation

5.3 Channel
[out] HImageX Image HImageX.AccessChannel ([in] long Channel )
void HOperatorSetX.AccessChannel ([in] IHObjectX MultiChannelImage,
[out] HUntypedObjectX Image, [in] VARIANT Channel )

Access a channel of a multichannel image.


The operator AccessChannel accesses a channel of the (multichannel) input image. The result is a one-channel
image. The definition domain of the input is adopted. The channels are numbered from 1 to n. The number of
channels can be determined via the operator CountChannels.
Parameter
. MultiChannelImage (input iconic) . . . . . . multichannel-image-array ; HImageX / IHObjectX ( byte,
direction, cyclic, int1, int2,
uint2, int4, real, complex, vec-
tor_field )
Multichannel image.
. Image (output iconic) . . . . . . image ; HImageX / HUntypedObjectX ( byte, direction, cyclic, int1, int2,
uint2, int4, real, complex, vector_field )
One channel of MultiChannelImage.
. Channel (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . channel ; long / VARIANT
Index of channel to be accessed.
Default Value : 1
Suggested values : Channel ∈ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}
Parallelization Information
AccessChannel is reentrant and processed without parallelization.
Possible Predecessors
CountChannels
Possible Successors
DispImage
See also
CountChannels
Alternatives
Decompose2, Decompose3, Decompose4, Decompose5
Module
Foundation

HImageX.AppendChannel ([in] HImageX Image )


[out] HImageX ImageExtended
void HOperatorSetX.AppendChannel ([in] IHObjectX MultiChannelImage,
[in] IHObjectX Image, [out] HUntypedObjectX ImageExtended )

Append additional matrices (channels) to the image.


The operator AppendChannel appends the matrices of the image Image to the matrices of
MultiChannelImage. The result is an image containing as many matrices (channels) as
MultiChannelImage and Image combined. The definition domain of the ouptput image is calculated
as the average of the definition domains of both input images.

HALCON/COM Reference Manual, 2008-5-13


5.3. CHANNEL 453

Parameter
. MultiChannelImage (input iconic) . . . . . . image ; HImageX / IHObjectX ( byte, direction, cyclic, int1,
int2, uint2, int4, real, complex, vector_field )
Multichannel image.
. Image (input iconic) . . . . . . image ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2, uint2, int4,
real, complex, vector_field )
Image to be appended.
. ImageExtended (output iconic) . . . . . . multichannel-image-array ; HImageX / HUntypedObjectX (
byte, direction, cyclic, int1, int2,
uint2, int4, real, complex, vec-
tor_field )
Image appended by Image.
Parallelization Information
AppendChannel is reentrant and processed without parallelization.
Possible Successors
DispImage
Alternatives
Compose2, Compose3, Compose4, Compose5
Module
Foundation

HImageX.ChannelsToImage ( )
[out] HImageX MultiChannelImage
void HOperatorSetX.ChannelsToImage ([in] IHObjectX Images,
[out] HUntypedObjectX MultiChannelImage )

Convert one-channel images into a multichannel image


The operator ChannelsToImage converts several one-channel images into a multichannel image. The new
definition domain is the average of the definition domains of the input images.
Parameter
. Images (input iconic) . . . . . . image ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2, uint2, int4,
real, complex, vector_field )
One-channel images to be combined into a one-channel image.
. MultiChannelImage (output iconic) . . . . . . multichannel-image-array ; HImageX / HUntypedObjectX
( byte, direction, cyclic, int1,
int2, uint2, int4, real, complex,
vector_field )
Multichannel image.
Parallelization Information
ChannelsToImage is reentrant and processed without parallelization.
Possible Successors
CountChannels, DispImage
Module
Foundation

HImageX.Compose2 ([in] HImageX Image2 )


[out] HImageX MultiChannelImage
void HOperatorSetX.Compose2 ([in] IHObjectX Image1,
[in] IHObjectX Image2, [out] HUntypedObjectX MultiChannelImage )

Convert two images into a two-channel image.


The operator Compose2 converts 2 one-channel images into a 2-channel image. The definition domain is calcu-
lated as the intersection of the definition domains of the input images.

HALCON 8.0.2
454 CHAPTER 5. IMAGE

Parameter

. Image1 (input iconic) . . . . . . image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2,
uint2, int4, real, complex, vector_field )
Input image 1.
. Image2 (input iconic) . . . . . . image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2,
uint2, int4, real, complex, vector_field )
Input image 2.
. MultiChannelImage (output iconic) . . . . . . multichannel-image-array ; HImageX / HUntypedObjectX
( byte, direction, cyclic, int1,
int2, uint2, int4, real, complex,
vector_field )
Multichannel image.
Parallelization Information
Compose2 is reentrant and automatically parallelized (on tuple level).
Possible Successors
DispImage
See also
Decompose2
Alternatives
AppendChannel
Module
Foundation

[out] HImageX MultiChannelImage HImageX.Compose3 ([in] HImageX Image2,


[in] HImageX Image3 )
void HOperatorSetX.Compose3 ([in] IHObjectX Image1,
[in] IHObjectX Image2, [in] IHObjectX Image3,
[out] HUntypedObjectX MultiChannelImage )

Convert 3 images into a three-channel image.


The operator Compose3 converts 3 one-channel images into a 3-channel image. The definition domain is calcu-
lated as the intersection of the definition domains of the input images.
Parameter

. Image1 (input iconic) . . . . . . image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2,
uint2, int4, real, complex, vector_field )
Input image 1.
. Image2 (input iconic) . . . . . . image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2,
uint2, int4, real, complex, vector_field )
Input image 2.
. Image3 (input iconic) . . . . . . image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2,
uint2, int4, real, complex, vector_field )
Input image 3.
. MultiChannelImage (output iconic) . . . . . . multichannel-image-array ; HImageX / HUntypedObjectX
( byte, direction, cyclic, int1,
int2, uint2, int4, real, complex,
vector_field )
Multichannel image.
Parallelization Information
Compose3 is reentrant and automatically parallelized (on tuple level).
Possible Successors
DispImage

HALCON/COM Reference Manual, 2008-5-13


5.3. CHANNEL 455

See also
Decompose3
Alternatives
AppendChannel
Module
Foundation

[out] HImageX MultiChannelImage HImageX.Compose4 ([in] HImageX Image2,


[in] HImageX Image3, [in] HImageX Image4 )
void HOperatorSetX.Compose4 ([in] IHObjectX Image1,
[in] IHObjectX Image2, [in] IHObjectX Image3, [in] IHObjectX Image4,
[out] HUntypedObjectX MultiChannelImage )

Convert 4 images into a four-channel image.


The operator Compose4 converts 4 one-channel images into a 4-channel image. The definition domain is calcu-
lated as the intersection of the definition domains of the input images.
Parameter
. Image1 (input iconic) . . . . . . image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2,
uint2, int4, real, complex, vector_field )
Input image 1.
. Image2 (input iconic) . . . . . . image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2,
uint2, int4, real, complex, vector_field )
Input image 2.
. Image3 (input iconic) . . . . . . image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2,
uint2, int4, real, complex, vector_field )
Input image 3.
. Image4 (input iconic) . . . . . . image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2,
uint2, int4, real, complex, vector_field )
Input image 4.
. MultiChannelImage (output iconic) . . . . . . multichannel-image-array ; HImageX / HUntypedObjectX
( byte, direction, cyclic, int1,
int2, uint2, int4, real, complex,
vector_field )
Multichannel image.
Parallelization Information
Compose4 is reentrant and automatically parallelized (on tuple level).
Possible Successors
DispImage
See also
Decompose4
Alternatives
AppendChannel
Module
Foundation

[out] HImageX MultiChannelImage HImageX.Compose5 ([in] HImageX Image2,


[in] HImageX Image3, [in] HImageX Image4, [in] HImageX Image5 )
void HOperatorSetX.Compose5 ([in] IHObjectX Image1,
[in] IHObjectX Image2, [in] IHObjectX Image3, [in] IHObjectX Image4,
[in] IHObjectX Image5, [out] HUntypedObjectX MultiChannelImage )

Convert 5 images into a five-channel image.

HALCON 8.0.2
456 CHAPTER 5. IMAGE

The operator Compose5 converts 5 one-channel images into a 5-channel image. The definition domain is calcu-
lated as the intersection of the definition domains of the input images.
Parameter
. Image1 (input iconic) . . . . . . image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2,
uint2, int4, real, complex, vector_field )
Input image 1.
. Image2 (input iconic) . . . . . . image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2,
uint2, int4, real, complex, vector_field )
Input image 2.
. Image3 (input iconic) . . . . . . image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2,
uint2, int4, real, complex, vector_field )
Input image 3.
. Image4 (input iconic) . . . . . . image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2,
uint2, int4, real, complex, vector_field )
Input image 4.
. Image5 (input iconic) . . . . . . image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2,
uint2, int4, real, complex, vector_field )
Input image 5.
. MultiChannelImage (output iconic) . . . . . . multichannel-image-array ; HImageX / HUntypedObjectX
( byte, direction, cyclic, int1,
int2, uint2, int4, real, complex,
vector_field )
Multichannel image.
Parallelization Information
Compose5 is reentrant and automatically parallelized (on tuple level).
Possible Successors
DispImage
See also
Decompose5
Alternatives
AppendChannel
Module
Foundation

[out] HImageX MultiChannelImage HImageX.Compose6 ([in] HImageX Image2,


[in] HImageX Image3, [in] HImageX Image4, [in] HImageX Image5,
[in] HImageX Image6 )
void HOperatorSetX.Compose6 ([in] IHObjectX Image1,
[in] IHObjectX Image2, [in] IHObjectX Image3, [in] IHObjectX Image4,
[in] IHObjectX Image5, [in] IHObjectX Image6,
[out] HUntypedObjectX MultiChannelImage )

Convert 6 images into a six-channel image.


The operator Compose6 converts 6 one-channel images into a 6-channel image. The definition domain is calcu-
lated as the intersection of the definition domains of the input images.
Parameter
. Image1 (input iconic) . . . . . . image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2,
uint2, int4, real, complex, vector_field )
Input image 1.
. Image2 (input iconic) . . . . . . image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2,
uint2, int4, real, complex, vector_field )
Input image 2.

HALCON/COM Reference Manual, 2008-5-13


5.3. CHANNEL 457

. Image3 (input iconic) . . . . . . image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2,
uint2, int4, real, complex, vector_field )
Input image 3.
. Image4 (input iconic) . . . . . . image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2,
uint2, int4, real, complex, vector_field )
Input image 4.
. Image5 (input iconic) . . . . . . image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2,
uint2, int4, real, complex, vector_field )
Input image 5.
. Image6 (input iconic) . . . . . . image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2,
uint2, int4, real, complex, vector_field )
Input image 6.
. MultiChannelImage (output iconic) . . . . . . multichannel-image-array ; HImageX / HUntypedObjectX
( byte, direction, cyclic, int1,
int2, uint2, int4, real, complex,
vector_field )
Multichannel image.
Parallelization Information
Compose6 is reentrant and automatically parallelized (on tuple level).
Possible Successors
DispImage
See also
Decompose6
Alternatives
AppendChannel
Module
Foundation

[out] HImageX MultiChannelImage HImageX.Compose7 ([in] HImageX Image2,


[in] HImageX Image3, [in] HImageX Image4, [in] HImageX Image5,
[in] HImageX Image6, [in] HImageX Image7 )
void HOperatorSetX.Compose7 ([in] IHObjectX Image1,
[in] IHObjectX Image2, [in] IHObjectX Image3, [in] IHObjectX Image4,
[in] IHObjectX Image5, [in] IHObjectX Image6, [in] IHObjectX Image7,
[out] HUntypedObjectX MultiChannelImage )

Convert 7 images into a seven-channel image.


The operator Compose7 converts 7 one-channel images into a 7-channel image. The definition domain is calcu-
lated as the intersection of the definition domains of the input images.
Parameter

. Image1 (input iconic) . . . . . . image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2,
uint2, int4, real, complex, vector_field )
Input image 1.
. Image2 (input iconic) . . . . . . image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2,
uint2, int4, real, complex, vector_field )
Input image 2.
. Image3 (input iconic) . . . . . . image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2,
uint2, int4, real, complex, vector_field )
Input image 3.
. Image4 (input iconic) . . . . . . image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2,
uint2, int4, real, complex, vector_field )
Input image 4.

HALCON 8.0.2
458 CHAPTER 5. IMAGE

. Image5 (input iconic) . . . . . . image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2,
uint2, int4, real, complex, vector_field )
Input image 5.
. Image6 (input iconic) . . . . . . image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2,
uint2, int4, real, complex, vector_field )
Input image 6.
. Image7 (input iconic) . . . . . . image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2,
uint2, int4, real, complex, vector_field )
Input image 7.
. MultiChannelImage (output iconic) . . . . . . multichannel-image-array ; HImageX / HUntypedObjectX
( byte, direction, cyclic, int1,
int2, uint2, int4, real, complex,
vector_field )
Multichannel image.
Parallelization Information
Compose7 is reentrant and automatically parallelized (on tuple level).
Possible Successors
DispImage
See also
Decompose7
Alternatives
AppendChannel
Module
Foundation

[out] VARIANT Channels HImageX.CountChannels ( )


void HOperatorSetX.CountChannels ([in] IHObjectX MultiChannelImage,
[out] VARIANT Channels )

Count channels of image.


The operator CountChannels counts the number of channels of all input images.
Parameter

. MultiChannelImage (input iconic) . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX (


byte, direction, cyclic, int1,
int2, uint2, int4, real, com-
plex, vector_field )
One- or multichannel image.
. Channels (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Number of channels.
Parallelization Information
CountChannels is reentrant and processed without parallelization.
Possible Successors
AccessChannel, AppendChannel, DispImage
See also
AppendChannel, AccessChannel
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


5.3. CHANNEL 459

HImageX.Decompose2 ([out] HImageX Image2 )


[out] HImageX Image1
void HOperatorSetX.Decompose2 ([in] IHObjectX MultiChannelImage,
[out] HUntypedObjectX Image1, [out] HUntypedObjectX Image2 )

Convert a two-channel image into two images.


The operator Decompose2 converts a 2-channel image into two one-channel images with the same definition
domain.
Parameter

. MultiChannelImage (input iconic) . . . . . . multichannel-image-array ; HImageX / IHObjectX ( byte,


direction, cyclic, int1, int2,
uint2, int4, real, complex, vec-
tor_field )
Multichannel image.
. Image1 (output iconic) . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, direction, cyclic, int1,
int2, uint2, int4, real, complex, vector_field )
Output image 1.
. Image2 (output iconic) . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, direction, cyclic, int1,
int2, uint2, int4, real, complex, vector_field )
Output image 2.
Parallelization Information
Decompose2 is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
CountChannels
Possible Successors
DispImage
See also
Compose2
Alternatives
AccessChannel, ImageToChannels
Module
Foundation

[out] HImageX Image1 HImageX.Decompose3 ([out] HImageX Image2,


[out] HImageX Image3 )
void HOperatorSetX.Decompose3 ([in] IHObjectX MultiChannelImage,
[out] HUntypedObjectX Image1, [out] HUntypedObjectX Image2,
[out] HUntypedObjectX Image3 )

Convert a three-channel image into three images.


The operator Decompose3 converts a 3-channel image into three one-channel images with the same definition
domain.
Parameter

. MultiChannelImage (input iconic) . . . . . . multichannel-image-array ; HImageX / IHObjectX ( byte,


direction, cyclic, int1, int2,
uint2, int4, real, complex, vec-
tor_field )
Multichannel image.
. Image1 (output iconic) . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, direction, cyclic, int1,
int2, uint2, int4, real, complex, vector_field )
Output image 1.

HALCON 8.0.2
460 CHAPTER 5. IMAGE

. Image2 (output iconic) . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, direction, cyclic, int1,
int2, uint2, int4, real, complex, vector_field )
Output image 2.
. Image3 (output iconic) . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, direction, cyclic, int1,
int2, uint2, int4, real, complex, vector_field )
Output image 3.
Parallelization Information
Decompose3 is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
CountChannels
Possible Successors
DispImage
See also
Compose3
Alternatives
AccessChannel, ImageToChannels
Module
Foundation

[out] HImageX Image1 HImageX.Decompose4 ([out] HImageX Image2,


[out] HImageX Image3, [out] HImageX Image4 )
void HOperatorSetX.Decompose4 ([in] IHObjectX MultiChannelImage,
[out] HUntypedObjectX Image1, [out] HUntypedObjectX Image2,
[out] HUntypedObjectX Image3, [out] HUntypedObjectX Image4 )

Convert a four-channel image into four images.


The operator Decompose4 converts a 4-channel image into four one-channel images with the same definition
domain.
Parameter
. MultiChannelImage (input iconic) . . . . . . multichannel-image-array ; HImageX / IHObjectX ( byte,
direction, cyclic, int1, int2,
uint2, int4, real, complex, vec-
tor_field )
Multichannel image.
. Image1 (output iconic) . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, direction, cyclic, int1,
int2, uint2, int4, real, complex, vector_field )
Output image 1.
. Image2 (output iconic) . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, direction, cyclic, int1,
int2, uint2, int4, real, complex, vector_field )
Output image 2.
. Image3 (output iconic) . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, direction, cyclic, int1,
int2, uint2, int4, real, complex, vector_field )
Output image 3.
. Image4 (output iconic) . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, direction, cyclic, int1,
int2, uint2, int4, real, complex, vector_field )
Output image 4.
Parallelization Information
Decompose4 is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
CountChannels
Possible Successors
DispImage

HALCON/COM Reference Manual, 2008-5-13


5.3. CHANNEL 461

See also
Compose4
Alternatives
AccessChannel, ImageToChannels
Module
Foundation

[out] HImageX Image1 HImageX.Decompose5 ([out] HImageX Image2,


[out] HImageX Image3, [out] HImageX Image4, [out] HImageX Image5 )
void HOperatorSetX.Decompose5 ([in] IHObjectX MultiChannelImage,
[out] HUntypedObjectX Image1, [out] HUntypedObjectX Image2,
[out] HUntypedObjectX Image3, [out] HUntypedObjectX Image4,
[out] HUntypedObjectX Image5 )

Convert a five-channel image into five images.


The operator Decompose5 converts a 5-channel image into five one-channel images with the same definition
domain.
Parameter

. MultiChannelImage (input iconic) . . . . . . multichannel-image-array ; HImageX / IHObjectX ( byte,


direction, cyclic, int1, int2,
uint2, int4, real, complex, vec-
tor_field )
Multichannel image.
. Image1 (output iconic) . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, direction, cyclic, int1,
int2, uint2, int4, real, complex, vector_field )
Output image 1.
. Image2 (output iconic) . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, direction, cyclic, int1,
int2, uint2, int4, real, complex, vector_field )
Output image 2.
. Image3 (output iconic) . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, direction, cyclic, int1,
int2, uint2, int4, real, complex, vector_field )
Output image 3.
. Image4 (output iconic) . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, direction, cyclic, int1,
int2, uint2, int4, real, complex, vector_field )
Output image 4.
. Image5 (output iconic) . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, direction, cyclic, int1,
int2, uint2, int4, real, complex, vector_field )
Output image 5.
Parallelization Information
Decompose5 is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
CountChannels
Possible Successors
DispImage
See also
Compose5
Alternatives
AccessChannel, ImageToChannels
Module
Foundation

HALCON 8.0.2
462 CHAPTER 5. IMAGE

[out] HImageX Image1 HImageX.Decompose6 ([out] HImageX Image2,


[out] HImageX Image3, [out] HImageX Image4, [out] HImageX Image5,
[out] HImageX Image6 )
void HOperatorSetX.Decompose6 ([in] IHObjectX MultiChannelImage,
[out] HUntypedObjectX Image1, [out] HUntypedObjectX Image2,
[out] HUntypedObjectX Image3, [out] HUntypedObjectX Image4,
[out] HUntypedObjectX Image5, [out] HUntypedObjectX Image6 )

Convert a six-channel image into six images.


The operator Decompose6 converts a 6-channel image into six one-channel images with the same definition
domain.
Parameter

. MultiChannelImage (input iconic) . . . . . . multichannel-image-array ; HImageX / IHObjectX ( byte,


direction, cyclic, int1, int2,
uint2, int4, real, complex, vec-
tor_field )
Multichannel image.
. Image1 (output iconic) . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, direction, cyclic, int1,
int2, uint2, int4, real, complex, vector_field )
Output image 1.
. Image2 (output iconic) . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, direction, cyclic, int1,
int2, uint2, int4, real, complex, vector_field )
Output image 2.
. Image3 (output iconic) . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, direction, cyclic, int1,
int2, uint2, int4, real, complex, vector_field )
Output image 3.
. Image4 (output iconic) . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, direction, cyclic, int1,
int2, uint2, int4, real, complex, vector_field )
Output image 4.
. Image5 (output iconic) . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, direction, cyclic, int1,
int2, uint2, int4, real, complex, vector_field )
Output image 5.
. Image6 (output iconic) . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, direction, cyclic, int1,
int2, uint2, int4, real, complex, vector_field )
Output image 6.
Parallelization Information
Decompose6 is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
CountChannels
Possible Successors
DispImage
See also
Compose6
Alternatives
AccessChannel, ImageToChannels
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


5.3. CHANNEL 463

[out] HImageX Image1 HImageX.Decompose7 ([out] HImageX Image2,


[out] HImageX Image3, [out] HImageX Image4, [out] HImageX Image5,
[out] HImageX Image6, [out] HImageX Image7 )
void HOperatorSetX.Decompose7 ([in] IHObjectX MultiChannelImage,
[out] HUntypedObjectX Image1, [out] HUntypedObjectX Image2,
[out] HUntypedObjectX Image3, [out] HUntypedObjectX Image4,
[out] HUntypedObjectX Image5, [out] HUntypedObjectX Image6,
[out] HUntypedObjectX Image7 )

Convert a seven-channel image into seven images.


The operator Decompose7 converts a 7-channel image into seven one-channel images with the same definition
domain.
Parameter

. MultiChannelImage (input iconic) . . . . . . multichannel-image-array ; HImageX / IHObjectX ( byte,


direction, cyclic, int1, int2,
uint2, int4, real, complex, vec-
tor_field )
Multichannel image.
. Image1 (output iconic) . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, direction, cyclic, int1,
int2, uint2, int4, real, complex, vector_field )
Output image 1.
. Image2 (output iconic) . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, direction, cyclic, int1,
int2, uint2, int4, real, complex, vector_field )
Output image 2.
. Image3 (output iconic) . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, direction, cyclic, int1,
int2, uint2, int4, real, complex, vector_field )
Output image 3.
. Image4 (output iconic) . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, direction, cyclic, int1,
int2, uint2, int4, real, complex, vector_field )
Output image 4.
. Image5 (output iconic) . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, direction, cyclic, int1,
int2, uint2, int4, real, complex, vector_field )
Output image 5.
. Image6 (output iconic) . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, direction, cyclic, int1,
int2, uint2, int4, real, complex, vector_field )
Output image 6.
. Image7 (output iconic) . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, direction, cyclic, int1,
int2, uint2, int4, real, complex, vector_field )
Output image 7.
Parallelization Information
Decompose7 is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
CountChannels
Possible Successors
DispImage
See also
Compose7
Alternatives
AccessChannel, ImageToChannels
Module
Foundation

HALCON 8.0.2
464 CHAPTER 5. IMAGE

HImageX.ImageToChannels ( )
[out] HImageX Images
void HOperatorSetX.ImageToChannels ([in] IHObjectX MultiChannelImage,
[out] HUntypedObjectX Images )

Convert a multichannel image into One-channel images


The operator ImageToChannels generates a one-channel image for each channel of the multichannel image in
MultiChannelImage. The definition domains are adopted from the input image. As many images are created
as MultiChannelImage has channels.
Parameter
. MultiChannelImage (input iconic) . . . . . . multichannel-image-array ; HImageX / IHObjectX ( byte,
direction, cyclic, int1, int2,
uint2, int4, real, complex, vec-
tor_field )
Multichannel image to be decomposed.
. Images (output iconic) . . . . . . image ; HImageX / HUntypedObjectX ( byte, direction, cyclic, int1, int2,
uint2, int4, real, complex, vector_field )
Generated one-channel images.
Parallelization Information
ImageToChannels is reentrant and processed without parallelization.
Possible Predecessors
CountChannels
Possible Successors
DispImage
Alternatives
AccessChannel, Decompose2, Decompose3, Decompose4, Decompose5
Module
Foundation

5.4 Creation
HImageX.CopyImage ( )
[out] HImageX DupImage
void HOperatorSetX.CopyImage ([in] IHObjectX Image,
[out] HUntypedObjectX DupImage )

Copy an image and allocate new memory for it.


CopyImage copies the input image into a new image with the same domain as the input image. In contrast to
HALCON operators such as CopyObj, physical copies of all channels are created. This can be used, for example,
to modify the gray values of the new image (see GetImagePointer1).
Parameter
. Image (input iconic) . . . . . . (multichannel-)image ; HImageX / IHObjectX ( byte, direction, cyclic, int1,
int2, uint2, int4, real, complex, vector_field )
Image to be copied.
. DupImage (output iconic) . . . . . . (multichannel-)image ; HImageX / HUntypedObjectX ( byte, direction,
cyclic, int1, int2, uint2, int4, real, complex, vec-
tor_field )
Copied image.
Parallelization Information
CopyImage is reentrant and processed without parallelization.
Possible Predecessors
ReadImage, GenImageConst
Possible Successors
SetGrayval, GetImagePointer1

HALCON/COM Reference Manual, 2008-5-13


5.4. CREATION 465

See also
GetImagePointer1
Alternatives
SetGrayval, PaintGray, GenImageConst, GenImageProto
Module
Foundation

void HImageX.GenImage1 ([in] String Type, [in] long Width,


[in] long Height, [in] long PixelPointer )
void HOperatorSetX.GenImage1 ([out] HUntypedObjectX Image,
[in] VARIANT Type, [in] VARIANT Width, [in] VARIANT Height,
[in] VARIANT PixelPointer )

Create an image from a pointer to the pixels.


The operator GenImage1 creates an image of the size Width × Height. The pixels in PixelPointer are
stored line-sequentially. The type of the given pixels (PixelPointer) must correspond to Type. The storage
for the new image is newly created by HALCON . Thus, the storage on the PixelPointer can be released after
the call. Since the type of the parameter PixelPointer is generic (long) a cast has to be used for the call.
Attention

Parameter

. Image (output iconic) . . . . . . image ; HImageX / HUntypedObjectX ( byte, direction, cyclic, int1, int2,
uint2, int4, real )
Created image with new image matrix.
. Type (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Pixel type.
Default Value : ’byte’
List of values : Type ∈ {’byte’, ’direction’, ’cyclic’, ’int1’, ’int2’, ’uint2’, ’int4’, ’real’}
. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; long / VARIANT
Width of image.
Default Value : 512
Suggested values : Width ∈ {128, 256, 512, 1024}
Typical range of values : 1 ≤ Width ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 10
Restriction : (W idth ≥ 1)
. Height (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; long / VARIANT
Height of image.
Default Value : 512
Suggested values : Height ∈ {128, 256, 512, 1024}
Typical range of values : 1 ≤ Height ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 10
Restriction : (Height ≥ 1)
. PixelPointer (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pointer ; long / VARIANT
Pointer to first gray value.
Result
If the parameter values are correct, the operator GenImage1 returns the value TRUE. Otherwise an exception
handling is raised.
Parallelization Information
GenImage1 is reentrant and processed without parallelization.
Possible Predecessors
GenImageConst, GetImagePointer1

HALCON 8.0.2
466 CHAPTER 5. IMAGE

See also
ReduceDomain, PaintGray, PaintRegion, SetGrayval
Alternatives
GenImage3, GenImageConst, GetImagePointer1
Module
Foundation

void HImageX.GenImage1Extern ([in] String Type, [in] long Width,


[in] long Height, [in] long PixelPointer, [in] long ClearProc )
void HOperatorSetX.GenImage1Extern ([out] HUntypedObjectX Image,
[in] VARIANT Type, [in] VARIANT Width, [in] VARIANT Height,
[in] VARIANT PixelPointer, [in] VARIANT ClearProc )

Create an image from a pointer on the pixels with storage management.


The operator GenImage1Extern creates an image of the size Width × Height. The pixels in
PixelPointer are stored line-sequentially. The type of the given pixels (PixelPointer) must correspond
to Type. Since the type of the parameter PixelPointer is generic (long) a cast must be used for the call.
The memory for the new image is not newly allocated by HALCON , contrary to GenImage1, and thus is not
copied either. This means that the memory space that PixelPointer points to must be released by deleting the
object Image. This is done by the procedure ClearProc provided by the caller. This procedure must have the
following signature
void ClearProc(void* ptr);
and will be called using __cdecl calling convention when deleting Image. If the memory shall not be released
(in the case of frame grabbers or static memory) a procedure “without trunk” or the NULL-Pointer can be passed.
Analogous to the parameter PixelPointer the pointer has to be passed to the procedure by casting it to long.
Parameter
. Image (output iconic) . . . . . . image ; HImageX / HUntypedObjectX ( byte, direction, cyclic, int1, int2,
uint2, int4, real )
Created HALCON image.
. Type (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Pixel type.
Default Value : ’byte’
List of values : Type ∈ {’int1’, ’int2’, ’uint2’, ’int4’, ’byte’, ’real’, ’direction’, ’cyclic’}
. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; long / VARIANT
Width of image.
Default Value : 512
Suggested values : Width ∈ {128, 256, 512, 1024}
Typical range of values : 1 ≤ Width ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 10
Restriction : (W idth ≥ 1)
. Height (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; long / VARIANT
Height of image.
Default Value : 512
Suggested values : Height ∈ {128, 256, 512, 1024}
Typical range of values : 1 ≤ Height ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 10
Restriction : (Height ≥ 1)
. PixelPointer (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pointer ; long / VARIANT
Pointer to the first gray value.
. ClearProc (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pointer ; long / VARIANT
Pointer to the procedure re-releasing the memory of the image when deleting the object.
Default Value : 0

HALCON/COM Reference Manual, 2008-5-13


5.4. CREATION 467

Result
The operator GenImage1Extern returns the value TRUE if the parameter values are correct. Otherwise an
exception handling is raised.
Parallelization Information
GenImage1Extern is reentrant and processed without parallelization.
See also
ReduceDomain, PaintGray, PaintRegion, SetGrayval
Alternatives
GenImage1, GenImageConst, GetImagePointer1
Module
Foundation

void HImageX.GenImage1Rect ([in] long PixelPointer, [in] long Width,


[in] long Height, [in] long VerticalPitch, [in] long HorizontalBitPitch,
[in] long BitsPerPixel, [in] String DoCopy, [in] long ClearProc )
void HOperatorSetX.GenImage1Rect ([out] HUntypedObjectX Image,
[in] VARIANT PixelPointer, [in] VARIANT Width, [in] VARIANT Height,
[in] VARIANT VerticalPitch, [in] VARIANT HorizontalBitPitch,
[in] VARIANT BitsPerPixel, [in] VARIANT DoCopy, [in] VARIANT ClearProc )

Create an image with a rectangular domain from a pointer on the pixels (with storage management).
The operator GenImage1Rect creates an image of size (VerticalPitch/(HorizontalBitPitch / 8))
* Height. The pixels pointed to by PixelPointer are stored line by line. Since the type of the parameter
PixelPointer is generic (long) a cast must be used for the call. VerticalPitch determines the distance
(in bytes) between pixel m in row n and pixel m in row n+1 inside of memory. All rows of the ’input image’ have
the same vertical pitch. The width of the output image equals VerticalPitch / (HorizontalBitPitch /
8). The height of input and output image are equal. The domain of the output image Image is a rectangle of the
size Width * Height. The parameter HorizontalBitPitch is the horizontal distance (in bits) between two
neighbouring pixels. BitsPerPixel is the number of used bits per pixel.
If DoCopy is set ’true’, the image data pointed to by PixelPointer is copied and memory for the new image is
newly allocated by HALCON . Else the image data is not duplicated and the memory space that PixelPointer
points to must be released when deleting the object Image. This is done by the procedure ClearProc provided
by the caller. This procedure must have the following signature
void ClearProc(void* ptr);
and will be called using __cdecl calling convention when deleting Image. If the memory shall not be released
(in the case of frame grabbers or static memory) a procedure ”without trunk” or the NULL-pointer can be passed.
Analogously to the parameter PixelPointer the pointer has to be passed to the procedure by casting it to
long. If DoCopy is ’true’ then ClearProc is irrelevant. The operator GenImage1Rect is symmetrical to
GetImagePointer1Rect.
Parameter

. Image (output iconic) . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / HUntypedObjectX ( byte, uint2, int4 )


Created HALCON image.
. PixelPointer (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pointer ; long / VARIANT
Pointer to the first pixel.
. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; long / VARIANT
Width of the image.
Default Value : 512
Suggested values : Width ∈ {128, 256, 512, 1024}
Typical range of values : 1 ≤ Width ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 10
Restriction : (W idth ≥ 1)

HALCON 8.0.2
468 CHAPTER 5. IMAGE

. Height (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; long / VARIANT


Height of the image.
Default Value : 512
Suggested values : Height ∈ {128, 256, 512, 1024}
Typical range of values : 1 ≤ Height ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 10
Restriction : (Height ≥ 1)
. VerticalPitch (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Distance (in bytes) between pixel m in row n and pixel m in row n+1 of the ’input image’.
Restriction : (V erticalP itch ≥ (W idth · (HorizontalBitP itch/8)))
. HorizontalBitPitch (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Distance between two neighbouring pixels in bits .
Default Value : 8
List of values : HorizontalBitPitch ∈ {8, 16, 32}
. BitsPerPixel (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of used bits per pixel.
Default Value : 8
List of values : BitsPerPixel ∈ {8, 9, 10, 11, 12, 13, 14, 15, 16, 32}
Restriction : (BitsP erP ixel ≤ HorizontalBitP itch)
. DoCopy (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Copy image data.
Default Value : ’false’
Suggested values : DoCopy ∈ {’true’, ’false’}
. ClearProc (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pointer ; long / VARIANT
Pointer to the procedure releasing the memory of the image when deleting the object.
Default Value : 0
Result
The operator GenImage1Rect returns the value TRUE if the parameter values are correct. Otherwise an excep-
tion handling is raised.
Parallelization Information
GenImage1Rect is reentrant and processed without parallelization.
Possible Successors
GetImagePointer1Rect
See also
GetImagePointer1Rect
Alternatives
GenImage1, GenImage1Extern
Module
Foundation

void HImageX.GenImage3 ([in] String Type, [in] long Width,


[in] long Height, [in] long PixelPointerRed, [in] long PixelPointerGreen,
[in] long PixelPointerBlue )
void HOperatorSetX.GenImage3 ([out] HUntypedObjectX ImageRGB,
[in] VARIANT Type, [in] VARIANT Width, [in] VARIANT Height,
[in] VARIANT PixelPointerRed, [in] VARIANT PixelPointerGreen,
[in] VARIANT PixelPointerBlue )

Create an image from three pointers to the pixels (red/green/blue).


The operator GenImage3 creates a three-channel image of the size Width × Height. The pixels in
PixelPointerRed, PixelPointerGreen and PixelPointerBlue are stored line-sequentially. The
type of the given pixels (PixelPointerRed etc.) must correspond to the name of the pixels (Type). The
storage for the new image is newly created by HALCON . Thus, it can be released after the call. Since the type of
the parameters (PixelPointerRed etc.) is generic (long) a “cast” must be used for the call.

HALCON/COM Reference Manual, 2008-5-13


5.4. CREATION 469

Attention

Parameter
. ImageRGB (output iconic) . . . . . . image ; HImageX / HUntypedObjectX ( byte, direction, cyclic, int1,
int2, uint2, int4, real )
Created image with new image matrix.
. Type (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Pixel type.
Default Value : ’byte’
List of values : Type ∈ {’byte’, ’direction’, ’cyclic’, ’int1’, ’int2’, ’uint2’, ’int4’, ’real’}
. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; long / VARIANT
Width of image.
Default Value : 512
Suggested values : Width ∈ {128, 256, 512, 1024}
Typical range of values : 1 ≤ Width ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 10
. Height (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; long / VARIANT
Height of image.
Default Value : 512
Suggested values : Height ∈ {128, 256, 512, 1024}
Typical range of values : 1 ≤ Height ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 10
. PixelPointerRed (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pointer ; long / VARIANT
Pointer to first red value (channel 1).
. PixelPointerGreen (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pointer ; long / VARIANT
Pointer to first green value (channel 2).
. PixelPointerBlue (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pointer ; long / VARIANT
Pointer to first blue value (channel 3).
Result
If the parameter values are correct, the operator GenImage3 returns the value TRUE. Otherwise an exception
handling is raised.
Parallelization Information
GenImage3 is reentrant and processed without parallelization.
Possible Predecessors
GenImageConst, GetImagePointer1
Possible Successors
DispColor
See also
ReduceDomain, PaintGray, PaintRegion, SetGrayval, GetImagePointer1, Decompose3
Alternatives
GenImage1, Compose3, GenImageConst
Module
Foundation

void HImageX.GenImageConst ([in] String Type, [in] long Width,


[in] long Height )
void HOperatorSetX.GenImageConst ([out] HUntypedObjectX Image,
[in] VARIANT Type, [in] VARIANT Width, [in] VARIANT Height )

Create an image with constant gray value.


The operator GenImageConst creates an image of the indicated size. The height and width of the image are
determined by Height and Width. HALCON supports the following image types:

HALCON 8.0.2
470 CHAPTER 5. IMAGE

’byte’ 1 byte per pixel (0..255)


’int1’ 1 byte per pixel (-127..127)
’int2’ 2 bytes per pixel (-32767..32767)
’uint2’ 2 bytes per pixel (0..65535)
’int4’ 4 bytes per pixel (-2147483647..2147483647)
’real’ 4 bytes per pixel, floating point
’complex’ two matrices of the type real
’vector_field’ two matrices of type real
’dir’ 1 byte per pixel (0..180)
’cyclic’ 1 byte per pixel; cyclic arithmetics (0..255).

The default value 0 is set via the operator SetSystem(’initNewImage’,<’true’/’false’>).


Attention

Parameter

. Image (output iconic) . . . . . . image ; HImageX / HUntypedObjectX ( byte, direction, cyclic, int1, int2,
uint2, int4, real, complex, vector_field )
Created image with new image matrix.
. Type (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Pixel type.
Default Value : ’byte’
List of values : Type ∈ {’byte’, ’direction’, ’cyclic’, ’int1’, ’int2’, ’uint2’, ’int4’, ’real’, ’complex’,
’vector_field’}
. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; long / VARIANT
Width of image.
Default Value : 512
Suggested values : Width ∈ {128, 256, 512, 1024}
Typical range of values : 1 ≤ Width ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 10
Restriction : (W idth ≥ 1)
. Height (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; long / VARIANT
Height of image.
Default Value : 512
Suggested values : Height ∈ {128, 256, 512, 1024}
Typical range of values : 1 ≤ Height ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 10
Restriction : (Height ≥ 1)
Result
If the parameter values are correct, the operator GenImageConst returns the value TRUE. Otherwise an excep-
tion handling is raised.
Parallelization Information
GenImageConst is reentrant and processed without parallelization.
Possible Successors
PaintRegion, ReduceDomain, GetImagePointer1, CopyObj
See also
ReduceDomain, PaintGray, PaintRegion, SetGrayval, GetImagePointer1
Alternatives
GenImage1, GenImage3
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


5.4. CREATION 471

void HImageX.GenImageGrayRamp ([in] double Alpha, [in] double Beta,


[in] double Mean, [in] long Row, [in] long Column, [in] long Width,
[in] long Height )
void HOperatorSetX.GenImageGrayRamp
([out] HUntypedObjectX ImageGrayRamp, [in] VARIANT Alpha, [in] VARIANT Beta,
[in] VARIANT Mean, [in] VARIANT Row, [in] VARIANT Column, [in] VARIANT Width,
[in] VARIANT Height )

Create a gray value ramp.


The operator GenImageGrayRamp creates a gray value ramp according to the following equation:

ImageGrayRamp0 (r, c) = Alpha(r − Row) + Beta(c − Column) + Mean

The size of the image is determined by Width and Height The gray values are of the type byte. Gray values
outside the valid area are clipped.
Attention

Parameter

. ImageGrayRamp (output iconic) . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / HUntypedObjectX ( byte )


Created image with new image matrix.
. Alpha (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Gradient in line direction.
Default Value : 1.0
Suggested values : Alpha ∈ {-2.0, -1.0, -0.5, -0.0, 0.5, 1.0, 2.0}
Minimum Increment : 0.000001
Recommended Increment : -0.005
. Beta (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Gradient in column direction.
Default Value : 1.0
Suggested values : Beta ∈ {-2.0, -1.0, -0.5, -0.0, 0.5, 1.0, 2.0}
Minimum Increment : 0.000001
Recommended Increment : -0.005
. Mean (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Mean gray value.
Default Value : 128
Suggested values : Mean ∈ {0, 20, 40, 60, 80, 100, 120, 140, 160, 180, 200, 220, 255}
Minimum Increment : 1
Recommended Increment : 10
. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; long / VARIANT
Line index of reference point.
Default Value : 256
Suggested values : Row ∈ {128, 256, 512, 1024}
Minimum Increment : 1
Recommended Increment : 10
. Column (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; long / VARIANT
Column index of reference point.
Default Value : 256
Suggested values : Column ∈ {128, 256, 512, 1024}
Minimum Increment : 1
Recommended Increment : 10

HALCON 8.0.2
472 CHAPTER 5. IMAGE

. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; long / VARIANT


Width of image.
Default Value : 512
Suggested values : Width ∈ {128, 256, 512, 1024}
Typical range of values : 1 ≤ Width ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 10
Restriction : (W idth ≥ 1)
. Height (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; long / VARIANT
Height of image.
Default Value : 512
Suggested values : Height ∈ {128, 256, 512, 1024}
Typical range of values : 1 ≤ Height ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 10
Restriction : (Height ≥ 1)
Result
If the parameter values are correct GenImageGrayRamp returns the value TRUE. Otherwise an exception han-
dling is raised.
Parallelization Information
GenImageGrayRamp is reentrant and processed without parallelization.
Possible Predecessors
MomentsGrayPlane
Possible Successors
PaintRegion, ReduceDomain, GetImagePointer1, CopyObj
See also
ReduceDomain, PaintGray
Alternatives
GenImage1
Module
Foundation

void HImageX.GenImageInterleaved ([in] long PixelPointer,


[in] String ColorFormat, [in] long OriginalWidth, [in] long OriginalHeight,
[in] long Alignment, [in] String Type, [in] long ImageWidth,
[in] long ImageHeight, [in] long StartRow, [in] long StartColumn,
[in] long BitsPerChannel, [in] long BitShift )
void HOperatorSetX.GenImageInterleaved
([out] HUntypedObjectX ImageRGB, [in] VARIANT PixelPointer,
[in] VARIANT ColorFormat, [in] VARIANT OriginalWidth,
[in] VARIANT OriginalHeight, [in] VARIANT Alignment, [in] VARIANT Type,
[in] VARIANT ImageWidth, [in] VARIANT ImageHeight, [in] VARIANT StartRow,
[in] VARIANT StartColumn, [in] VARIANT BitsPerChannel,
[in] VARIANT BitShift )

Create a three-channel image from a pointer to the interleaved pixels.


The operator GenImageInterleaved creates a three-channel image from an input image, whose pixels are
stored line-sequentially in PixelPointer. The size of the input image has to be passed in OriginalWidth
and OriginalHeight, the format of the interleaved pixels in ColorFormat.
The output image will be sized ImageWidth × ImageHeight. Together with the coordinates of upper left
corner StartRow and StartColumn any section of the input image can be extracted. When a 0 is passed to
ImageWidth, ImageHeight, StartRow, and StartColumn, the output image will have the same dimen-
sions as the input image.

HALCON/COM Reference Manual, 2008-5-13


5.4. CREATION 473

Note that the image type Type of the output image ImageRGB has to be chosen such that the whole range of
possible color values of the input image can be represented. I.e. GenImageInterleaved does not allow to
create a byte image from an input image with ColorFormat rgb48.
When the formats rgb48, bgr48, rgbx64, and bgr64 do not use the full range of 16 bits per channel and pixel, the
number of actually used bits should be passed in BitsPerChannel. Furthermore, the pixel values of the input
image can be shifted by BitShift bits to the right.
The storage for the new image is newly created by HALCON . Thus, it can be released after the call. Since the
type of the parameters (PixelPointer) is generic (long) a “cast” must be used for the call.
Possible values for ColorFormat:

’rgb555’: 16 bit rgb triple (5 bit per pixel and channel)


’bgr555’: 16 bit bgr triple (5 bit per pixel and channel)
’rgb565’: 16 bit rgb triple (5 bit per pixel and channel, 6 bit for the green channel)
’bgr565’: 16 bit bgr triple (5 bit per pixel and channel, 6 bit for the green channel)
’rgb’: 24 bit rgb triple (8 bit per pixel and channel)
’bgr’: 24 bit bgr triple (8 bit per pixel and channel)
’rgbx’: 32 bit rgb quadruple (8 bit per pixel and channel)
’bgrx’: 32 bit bgr quadruple (8 bit per pixel and channel)
’rgb48’: 48 bit rgb triple (16 bit per pixel and channel)
’bgr48’: 48 bit bgr triple (16 bit per pixel and channel)
’rgbx64’: 64 bit rgb quadruple (16 bit per pixel and channel)
’bgrx64’: 64 bit bgr quadruple (16 bit per pixel and channel)

Attention

Parameter

. ImageRGB (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / HUntypedObjectX ( byte, uint2 )


Created image with new image matrix.
. PixelPointer (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pointer ; long / VARIANT
Pointer to interleaved pixels.
. ColorFormat (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Format of the input pixels.
Default Value : ’rgb’
List of values : ColorFormat ∈ {’rgb’, ’bgr’, ’rgbx’, ’bgrx’, ’rgb48’, ’bgr48’, ’rgbx64’, ’bgrx64’, ’rgb555’,
’bgr555’, ’rgb565’, ’bgr565’}
. OriginalWidth (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; long / VARIANT
Width of input image.
Default Value : 512
Suggested values : OriginalWidth ∈ {128, 256, 512, 1024}
(lin)Minimum Increment : 1
Recommended Increment : 10
. OriginalHeight (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; long / VARIANT
Height of input image.
Default Value : 512
Suggested values : OriginalHeight ∈ {128, 256, 512, 1024}
(lin)Minimum Increment : 1
Recommended Increment : 10
. Alignment (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Reserved.
. Type (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Pixel type of output image.
Default Value : ’byte’
List of values : Type ∈ {’byte’, ’uint2’}

HALCON 8.0.2
474 CHAPTER 5. IMAGE

. ImageWidth (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.extent.x ; long / VARIANT


Width of output image.
Default Value : 0
Suggested values : ImageWidth ∈ {128, 256, 512, 1024}
(lin)Minimum Increment : 1
Recommended Increment : 10
. ImageHeight (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.extent.y ; long / VARIANT
Height of output image.
Default Value : 0
Suggested values : ImageHeight ∈ {128, 256, 512, 1024}
(lin)Minimum Increment : 1
Recommended Increment : 10
. StartRow (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.origin.y ; long / VARIANT
Line number of upper left corner of desired image part.
Default Value : 0
Suggested values : StartRow ∈ {-1, 0}
. StartColumn (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.origin.x ; long / VARIANT
Column number of upper left corner of desired image part.
Default Value : 0
Suggested values : StartColumn ∈ {-1, 0}
. BitsPerChannel (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of used bits per pixel and channel of the output image (-1: All bits are used).
Default Value : -1
Suggested values : BitsPerChannel ∈ {5, 8, 10, 12, 16, -1}
. BitShift (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of bits that the color values of the input pixels are shifted to the right (only uint2 images).
Default Value : 0
Suggested values : BitShift ∈ {0, 2, 4, 6}
Result
If the parameter values are correct, the operator GenImageInterleaved returns the value TRUE. Otherwise
an exception handling is raised.
Parallelization Information
GenImageInterleaved is reentrant and processed without parallelization.
Possible Successors
DispColor
See also
ReduceDomain, PaintGray, PaintRegion, SetGrayval
Module
Foundation

HImageX.GenImageProto ([in] VARIANT Grayval )


[out] HImageX ImageCleared
void HOperatorSetX.GenImageProto ([in] IHObjectX Image,
[out] HUntypedObjectX ImageCleared, [in] VARIANT Grayval )

Create an image with a specified constant gray value.


GenImageProto creates an output image ImageCleared with the constant gray value Grayval.
ImageCleared has the same dimensions and pixel type as the input image Image.
Parameter
. Image (input iconic) . . . . . . image ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2, uint2, int4,
real, complex, vector_field )
Input image.
. ImageCleared (output iconic) . . . . . . image ; HImageX / HUntypedObjectX ( byte, direction, cyclic,
int1, int2, uint2, int4, real, complex, vector_field )
Image with constant gray value.

HALCON/COM Reference Manual, 2008-5-13


5.4. CREATION 475

. Grayval (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )


Gray value to be used for the output image.
Default Value : 0
Suggested values : Grayval ∈ {0, 1, 2, 5, 10, 16, 32, 64, 128, 253, 254, 255}
Result
GenImageProto returns TRUE if all parameters are correct. If necessary, an exception is raised.
Parallelization Information
GenImageProto is reentrant and processed without parallelization.
Possible Predecessors
TestObjDef
See also
GetImagePointer1
Alternatives
SetGrayval, PaintGray, GenImageConst, CopyImage
Module
Foundation

void HImageX.GenImageSurfaceFirstOrder ([in] String Type,


[in] double Alpha, [in] double Beta, [in] double Gamma, [in] double Row,
[in] double Col, [in] long Width, [in] long Height )
void HOperatorSetX.GenImageSurfaceFirstOrder
([out] HUntypedObjectX ImageSurface, [in] VARIANT Type, [in] VARIANT Alpha,
[in] VARIANT Beta, [in] VARIANT Gamma, [in] VARIANT Row, [in] VARIANT Col,
[in] VARIANT Width, [in] VARIANT Height )

Create a curved gray surface with first order polynomial.


The operator GenImageSurfaceSecondOrder creates a curved gray value surface according to the following
equation:

ImageSurface(r, c) = Alpha(r − Row) + Beta(c − Col) + Gamma

The size of the image is determined by Width and Height. The gray values are of the type Type. Gray values
outside the valid area are clipped.
Parameter

. ImageSurface (output iconic) . . . . . . . . . . . . . . image ; HImageX / HUntypedObjectX ( byte, uint2, real )


Created image with new image matrix.
. Type (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Pixel type.
Default Value : ’byte’
List of values : Type ∈ {’byte’, ’uint2’, ’real’}
. Alpha (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
First order coefficient in vertical direction.
Default Value : 1.0
Suggested values : Alpha ∈ {-2.0, -1.0, -0.5, -0.0, 0.5, 1.0, 2.0}
Minimum Increment : 0.000001
Recommended Increment : -0.005
. Beta (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
First order coefficient in horizontal direction.
Default Value : 1.0
Suggested values : Beta ∈ {-2.0, -1.0, -0.5, -0.0, 0.5, 1.0, 2.0}
Minimum Increment : 0.000001
Recommended Increment : -0.005

HALCON 8.0.2
476 CHAPTER 5. IMAGE

. Gamma (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT


Zero order coefficient
Default Value : 1.0
Suggested values : Gamma ∈ {-2.0, -1.0, -0.5, -0.0, 0.5, 1.0, 2.0}
Minimum Increment : 0.000001
Recommended Increment : -0.005
. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
line coordinate of the apex of the surface
Default Value : 256.0
Suggested values : Row ∈ {0.0, 128.0, 256.0, 512.0}
Minimum Increment : 0.000001
Recommended Increment : -0.005
. Col (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Column coordinate of the apex of the surface
Default Value : 256.0
Suggested values : Col ∈ {0.0, 128.0, 256.0, 512.0}
Minimum Increment : 0.000001
Recommended Increment : -0.005
. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; long / VARIANT
Width of image.
Default Value : 512
Suggested values : Width ∈ {128, 256, 512, 1024}
Typical range of values : 1 ≤ Width ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 10
Restriction : (W idth ≥ 1)
. Height (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; long / VARIANT
Height of image.
Default Value : 512
Suggested values : Height ∈ {128, 256, 512, 1024}
Typical range of values : 1 ≤ Height ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 10
Restriction : (Height ≥ 1)
Result
If the parameter values are correct GenImageSurfaceFirstOrder returns the value TRUE. Otherwise an
exception handling is raised.
Parallelization Information
GenImageSurfaceFirstOrder is reentrant and processed without parallelization.
Possible Predecessors
FitSurfaceFirstOrder
Possible Successors
SubImage
See also
GenImageGrayRamp, GenImageSurfaceSecondOrder
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


5.4. CREATION 477

void HImageX.GenImageSurfaceSecondOrder ([in] String Type,


[in] double Alpha, [in] double Beta, [in] double Gamma, [in] double Delta,
[in] double Epsilon, [in] double Zeta, [in] double Row, [in] double Col,
[in] long Width, [in] long Height )
void HOperatorSetX.GenImageSurfaceSecondOrder
([out] HUntypedObjectX ImageSurface, [in] VARIANT Type, [in] VARIANT Alpha,
[in] VARIANT Beta, [in] VARIANT Gamma, [in] VARIANT Delta,
[in] VARIANT Epsilon, [in] VARIANT Zeta, [in] VARIANT Row, [in] VARIANT Col,
[in] VARIANT Width, [in] VARIANT Height )

Create a curved gray surface with second order polynomial.


The operator GenImageSurfaceSecondOrder creates a curved gray value surface according to the following
equation:

ImageSurface(r, c) = Alpha(r−Row)∗∗2+Beta(c−Col)∗∗2+Gamma(r−Row)∗(c−Col)+Delta(r−Row)+Epsilon(c

The size of the image is determined by Width and Height. The gray values are of the type Type. Gray values
outside the valid area are clipped.
Parameter
. ImageSurface (output iconic) . . . . . . . . . . . . . . image ; HImageX / HUntypedObjectX ( byte, uint2, real )
Created image with new image matrix.
. Type (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Pixel type.
Default Value : ’byte’
List of values : Type ∈ {’byte’, ’uint2’, ’real’}
. Alpha (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Second order coefficient in vertical direction.
Default Value : 1.0
Suggested values : Alpha ∈ {-2.0, -1.0, -0.5, -0.0, 0.5, 1.0, 2.0}
Minimum Increment : 0.000001
Recommended Increment : -0.005
. Beta (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Second order coefficient in horizontal direction.
Default Value : 1.0
Suggested values : Beta ∈ {-2.0, -1.0, -0.5, -0.0, 0.5, 1.0, 2.0}
Minimum Increment : 0.000001
Recommended Increment : -0.005
. Gamma (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Mixed second order coefficient.
Default Value : 1.0
Suggested values : Gamma ∈ {-2.0, -1.0, -0.5, -0.0, 0.5, 1.0, 2.0}
Minimum Increment : 0.000001
Recommended Increment : -0.005
. Delta (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
First order coefficient in vertical direction.
Default Value : 1.0
Suggested values : Delta ∈ {-2.0, -1.0, -0.5, -0.0, 0.5, 1.0, 2.0}
Minimum Increment : 0.000001
Recommended Increment : -0.005
. Epsilon (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
First order coefficient in horizontal direction.
Default Value : 1.0
Suggested values : Epsilon ∈ {-2.0, -1.0, -0.5, -0.0, 0.5, 1.0, 2.0}
Minimum Increment : 0.000001
Recommended Increment : -0.005

HALCON 8.0.2
478 CHAPTER 5. IMAGE

. Zeta (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT


Zero order coefficient
Default Value : 1.0
Suggested values : Zeta ∈ {-2.0, -1.0, -0.5, -0.0, 0.5, 1.0, 2.0}
Minimum Increment : 0.000001
Recommended Increment : -0.005
. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
line coordinate of the apex of the surface
Default Value : 256.0
Suggested values : Row ∈ {0.0, 128.0, 256.0, 512.0}
Minimum Increment : 0.000001
Recommended Increment : -0.005
. Col (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Column coordinate of the apex of the surface
Default Value : 256.0
Suggested values : Col ∈ {0.0, 128.0, 256.0, 512.0}
Minimum Increment : 0.000001
Recommended Increment : -0.005
. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; long / VARIANT
Width of image.
Default Value : 512
Suggested values : Width ∈ {128, 256, 512, 1024}
Typical range of values : 1 ≤ Width ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 10
Restriction : (W idth ≥ 1)
. Height (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; long / VARIANT
Height of image.
Default Value : 512
Suggested values : Height ∈ {128, 256, 512, 1024}
Typical range of values : 1 ≤ Height ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 10
Restriction : (Height ≥ 1)
Result
If the parameter values are correct GenImageSurfaceSecondOrder returns the value TRUE. Otherwise an
exception handling is raised.
Parallelization Information
GenImageSurfaceSecondOrder is reentrant and processed without parallelization.
Possible Predecessors
FitSurfaceSecondOrder
Possible Successors
SubImage
See also
GenImageGrayRamp, GenImageSurfaceFirstOrder
Module
Foundation

[out] HImageX BinImage HRegionX.RegionToBin ([in] long ForegroundGray,


[in] long BackgroundGray, [in] long Width, [in] long Height )
void HOperatorSetX.RegionToBin ([in] IHObjectX Region,
[out] HUntypedObjectX BinImage, [in] VARIANT ForegroundGray,
[in] VARIANT BackgroundGray, [in] VARIANT Width, [in] VARIANT Height )

Convert a region into a binary byte-image.

HALCON/COM Reference Manual, 2008-5-13


5.4. CREATION 479

RegionToBin converts the input region given in Region into a byte-image and assigns a gray value of
ForegroundGray to all pixels in the region. If the input region is larger than the generated image, it is clipped
at the image borders. The background is set to BackgroundGray.
Parameter

. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Regions to be converted.
. BinImage (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / HUntypedObjectX ( byte )
Result image of dimension Width × Height containing the converted regions.
. ForegroundGray (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Gray value in which the regions are displayed.
Default Value : 255
Suggested values : ForegroundGray ∈ {0, 1, 50, 100, 128, 150, 200, 254, 255}
Typical range of values : 0 ≤ ForegroundGray ≤ 0(lin)
Recommended Increment : 1
. BackgroundGray (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Gray value in which the background is displayed.
Default Value : 0
Suggested values : BackgroundGray ∈ {0, 1, 50, 100, 128, 150, 200, 254, 255}
Typical range of values : 0 ≤ BackgroundGray ≤ 0(lin)
Recommended Increment : 1
. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; long / VARIANT
Width of the image to be generated.
Default Value : 512
Suggested values : Width ∈ {256, 512, 1024}
Typical range of values : 1 ≤ Width ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 16
Restriction : (W idth ≥ 1)
. Height (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; long / VARIANT
Height of the image to be generated.
Default Value : 512
Suggested values : Height ∈ {256, 512, 1024}
Typical range of values : 1 ≤ Height ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 16
Restriction : (Height ≥ 1)
Complexity
O(2 ∗ Height ∗ Width).
Result
RegionToBin always returns TRUE. The behavior in case of empty input (no regions given) can be set
via SetSystem(’noObjectResult’,<Result>) and the behavior in case of an empty input region via
SetSystem(’emptyRegionResult’,<Result>). If necessary, an exception handling is raised.
Parallelization Information
RegionToBin is reentrant and processed without parallelization.
Possible Predecessors
Threshold, Connection, Regiongrowing, Pouring
Possible Successors
GetGrayval
See also
GenImageProto, PaintGray
Alternatives
RegionToLabel, PaintRegion, SetGrayval
Module
Foundation

HALCON 8.0.2
480 CHAPTER 5. IMAGE

[out] HImageX ImageLabel HRegionX.RegionToLabel ([in] String Type,


[in] long Width, [in] long Height )
void HOperatorSetX.RegionToLabel ([in] IHObjectX Region,
[out] HUntypedObjectX ImageLabel, [in] VARIANT Type, [in] VARIANT Width,
[in] VARIANT Height )

Convert regions to a label image.


RegionToLabel converts the input regions into a label image according to their index (1..n), i.e., the first
region is painted with the gray value 1, the second the gray value 2, etc. Only positive gray values are used. For
byte-images the index is entered modulo 256.
Regions larger than the generated image are clipped appropriately. If regions overlap the regions with the higher
image are entered (i.e., they are painted in the order in which they are contained in the input regions). If so desired,
the regions can be made non-overlapping by calling ExpandRegion.
The background, i.e., the area not covered by any regions, is set to 0. This can be used to test in which image range
no region is present.
Parameter
. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Regions to be converted.
. ImageLabel (output iconic) . . . . . . . . . . . . . . . . . . image ; HImageX / HUntypedObjectX ( byte, int2, int4 )
Result image of dimension Width × Height containing the converted regions.
. Type (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Pixel type of the result image.
Default Value : ’int2’
List of values : Type ∈ {’byte’, ’int2’, ’int4’}
. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; long / VARIANT
Width of the image to be generated.
Default Value : 512
Suggested values : Width ∈ {64, 128, 256, 512, 1024}
Typical range of values : 1 ≤ Width ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 16
Restriction : (W idth ≥ 1)
. Height (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; long / VARIANT
Height of the image to be generated.
Default Value : 512
Suggested values : Height ∈ {64, 128, 256, 512, 1024}
Typical range of values : 1 ≤ Height ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 16
Restriction : (Height ≥ 1)
Complexity
O(2 ∗ Height ∗ Width).
Result
RegionToLabel always returns TRUE. The behavior in case of empty input (no regions given) can be set
via SetSystem(’noObjectResult’,<Result>) and the behavior in case of an empty input region via
SetSystem(’emptyRegionResult’,<Result>). If necessary, an exception handling is raised.
Parallelization Information
RegionToLabel is reentrant and processed without parallelization.
Possible Predecessors
Threshold, Regiongrowing, Connection, ExpandRegion
Possible Successors
GetGrayval, GetImagePointer1
See also
LabelToRegion

HALCON/COM Reference Manual, 2008-5-13


5.5. DOMAIN 481

Alternatives
RegionToBin, PaintRegion
Module
Foundation

[out] HImageX ImageMean HRegionX.RegionToMean ([in] HImageX Image )


HImageX.RegionToMean ([in] HRegionX Regions )
[out] HImageX ImageMean
void HOperatorSetX.RegionToMean ([in] IHObjectX Regions,
[in] IHObjectX Image, [out] HUntypedObjectX ImageMean )

Paint regions with their average gray value.


RegionToMean returns an image in which the regions Regions are painted with their average gray value based
on the image Image. This operator is mainly intended to visualize segmentation results.
Parameter
. Regions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Input regions.
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte )
original gray-value image.
. ImageMean (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / HUntypedObjectX ( byte )
Result image with painted regions.
Example

read_image(Image,’fabrik’)
region_growing(Image,Regions,3,3,6,100)
region_to_mean(Regions,Image,Disp)
disp_image(Disp,WindowHandle)
set_draw(WindowHandle,’margin’)
set_color(WindowHandle,’black’)
disp_region(Regions,WindowHandle).

Result
RegionToMean returns TRUE if all parameters are correct. If the input is empty the behavior can be set via
SetSystem(’noObjectResult’,<Result>). If necessary, an exception is raised.
Parallelization Information
RegionToMean is reentrant and processed without parallelization.
Possible Predecessors
Regiongrowing, Connection
Possible Successors
DispImage
Alternatives
PaintRegion, Intensity
Module
Foundation

5.5 Domain
HRegionX.AddChannels ([in] HImageX Image )
[out] HImageX GrayRegions
void HOperatorSetX.AddChannels ([in] IHObjectX Regions,
[in] IHObjectX Image, [out] HUntypedObjectX GrayRegions )

Add gray values to regions.

HALCON 8.0.2
482 CHAPTER 5. IMAGE

The operator AddChannels adds the gray values from Image to the regions in Regions. All channels of
Image are adopted. The definition domain is calculated as the average of the definition domain of the image with
the region. Thus the new definition domain can be a subset of the input region. The size of the matrix is not
changed.
Parameter

. Regions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Input regions (without gray values).
. Image (input iconic) . . . . . . (multichannel-)image ; HImageX / IHObjectX ( byte, direction, cyclic, int1,
int2, uint2, int4, real, complex, vector_field )
Gray image for regions.
. GrayRegions (output iconic) . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, direction,
cyclic, int1, int2, uint2, int4, real, complex, vec-
tor_field )
Regions with gray values (also gray images).
Number of elements : (Regions = GrayRegions)
Parallelization Information
AddChannels is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, GenCircle, DrawRegion
Possible Successors
Threshold, Regiongrowing, GetDomain
See also
FullDomain, GetDomain, Intersection
Alternatives
ChangeDomain, ReduceDomain
Module
Foundation

HImageX.ChangeDomain ([in] HRegionX NewDomain )


[out] HImageX ImageNew
void HOperatorSetX.ChangeDomain ([in] IHObjectX Image,
[in] IHObjectX NewDomain, [out] HUntypedObjectX ImageNew )

Change definition domain of an image.


The operator ChangeDomain uses the indicated region as the new definition domain. Unlike the operator
ReduceDomain it does not form the intersection of the previous definition domain, i.e., the size of the matrix is
not changed. This implies in particular, that the region must not exceed the image matrix, otherwise using such
inconsistent iconic objects during subsequent operations will likely lead to errors or system crashes.
Attention
Due to running time the transferred region is not checked for consistency (i.e., whether it fits with the image
matrix). Incorrect regions lead to system hang-ups during subsequent operations.
Parameter

. Image (input iconic) . . . . . . image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2,
uint2, int4, real, complex, vector_field )
Input image.
. NewDomain (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
New definition domain.
. ImageNew (output iconic) . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, direction, cyclic,
int1, int2, uint2, int4, real, complex, vector_field )
Image with new definition domain.
Parallelization Information
ChangeDomain is reentrant and automatically parallelized (on tuple level).

HALCON/COM Reference Manual, 2008-5-13


5.5. DOMAIN 483

Possible Predecessors
GetDomain
See also
FullDomain, GetDomain, Intersection
Alternatives
ReduceDomain
Module
Foundation

HImageX.FullDomain ( )
[out] HImageX ImageFull
void HOperatorSetX.FullDomain ([in] IHObjectX Image,
[out] HUntypedObjectX ImageFull )

Expand the domain of an image to maximum.


The operator FullDomain enters a rectangle with the edge length of the image as new definition domain. This
means that all pixels of the matrix are included in further operations. Thus the same definition domain is obtained
as by reading or generating an image. The size of the matrix is not changed.
Parameter
. Image (input iconic) . . . . . . image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2,
uint2, int4, real, complex, vector_field )
Input image.
. ImageFull (output iconic) . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, direction, cyclic,
int1, int2, uint2, int4, real, complex, vector_field )
Image with maximum definition domain.
Parallelization Information
FullDomain is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
GetDomain
See also
GetDomain, GenRectangle1
Alternatives
ChangeDomain, ReduceDomain
Module
Foundation

HImageX.GetDomain ( )
[out] HRegionX Domain
void HOperatorSetX.GetDomain ([in] IHObjectX Image,
[out] HUntypedObjectX Domain )

Get the domain of an image.


The operator GetDomain returns the definition domains of all input images as a region.
Parameter
. Image (input iconic) . . . . . . image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2,
uint2, int4, real, complex, vector_field )
Input images.
. Domain (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Definition domains of input images.
Parallelization Information
GetDomain is reentrant and automatically parallelized (on tuple level).

HALCON 8.0.2
484 CHAPTER 5. IMAGE

Possible Successors
ChangeDomain, ReduceDomain, FullDomain
See also
GetDomain, ChangeDomain, ReduceDomain, FullDomain
Module
Foundation

[out] HImageX ImageReduced HImageX.Rectangle1Domain ([in] long Row1,


[in] long Column1, [in] long Row2, [in] long Column2 )
void HOperatorSetX.Rectangle1Domain ([in] IHObjectX Image,
[out] HUntypedObjectX ImageReduced, [in] VARIANT Row1, [in] VARIANT Column1,
[in] VARIANT Row2, [in] VARIANT Column2 )

Reduce the domain of an image to a rectangle.


The operator Rectangle1Domain reduces the definition domain of the given image to the specified rectangle.
The old domain of the input image is ignored. The size of the matrix is not changed.
Parameter
. Image (input iconic) . . . . . . image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2,
uint2, int4, real, complex, vector_field )
Input image.
. ImageReduced (output iconic) . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, direction,
cyclic, int1, int2, uint2, int4, real, complex, vec-
tor_field )
Image with reduced definition domain.
. Row1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.origin.y ; long / VARIANT
Line index of upper left corner of image area.
Default Value : 100
Suggested values : Row1 ∈ {10, 20, 50, 100, 200, 300, 500}
Typical range of values : 0 ≤ Row1 ≤ 0
. Column1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.origin.x ; long / VARIANT
Column index of upper left corner of image area.
Default Value : 100
Suggested values : Column1 ∈ {10, 20, 50, 100, 200, 300, 500}
Typical range of values : 0 ≤ Column1 ≤ 0
. Row2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.origin.y ; long / VARIANT
Line index of lower right corner of image area.
Default Value : 200
Suggested values : Row2 ∈ {10, 20, 50, 100, 200, 300, 500}
Typical range of values : 0 ≤ Row2 ≤ 0
. Column2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.origin.x ; long / VARIANT
Column index of lower right corner of image area.
Default Value : 200
Suggested values : Column2 ∈ {10, 20, 50, 100, 200, 300, 500}
Typical range of values : 0 ≤ Column2 ≤ 0
Parallelization Information
Rectangle1Domain is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
GetDomain
See also
FullDomain, GetDomain, Intersection
Alternatives
ChangeDomain, ReduceDomain, AddChannels
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


5.6. FEATURES 485

HImageX.ReduceDomain ([in] HRegionX Region )


[out] HImageX ImageReduced
void HOperatorSetX.ReduceDomain ([in] IHObjectX Image,
[in] IHObjectX Region, [out] HUntypedObjectX ImageReduced )

Reduce the domain of an image.


The operator ReduceDomain reduces the definition domain of the given image to the indicated region. The
new definition domain is calculated as the intersection of the old definition domain with the region. Thus, the new
definition domain can be a subset of the region. The size of the matrix is not changed.
Parameter
. Image (input iconic) . . . . . . image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2,
uint2, int4, real, complex, vector_field )
Input image.
. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
New definition domain.
. ImageReduced (output iconic) . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, direction,
cyclic, int1, int2, uint2, int4, real, complex, vec-
tor_field )
Image with reduced definition domain.
Parallelization Information
ReduceDomain is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
GetDomain
See also
FullDomain, GetDomain, Intersection
Alternatives
ChangeDomain, Rectangle1Domain, AddChannels
Module
Foundation

5.6 Features
[out] VARIANT Area HRegionX.AreaCenterGray ([in] HImageX Image,
[out] VARIANT Row, [out] VARIANT Column )
[out] VARIANT Area HImageX.AreaCenterGray ([in] HRegionX Regions,
[out] VARIANT Row, [out] VARIANT Column )
void HOperatorSetX.AreaCenterGray ([in] IHObjectX Regions,
[in] IHObjectX Image, [out] VARIANT Area, [out] VARIANT Row,
[out] VARIANT Column )

Compute the area and center of gravity of a region in a gray value image.
AreaCenterGray computes the area and center of gravity of the regions Regions that have gray values which
are defined by the image Image. This operator is similar to AreaCenter, but in contrast to that operator, the
gray values of the image are taken into account while computing the area and center of gravity.
The area A of a region R in the image with the gray values g(r, c) is defined as
X
A= g(r, c).
(r,c)∈R

This means that the area is defined by the volume of the gray value function g(r, c). The center of gravity is defined
by the first two normalized moments of the gray values g(r, c), i.e., by (m1,0 , m0,1 ), where
1 X p q
mp,q = r c g(r, c).
A
(r,c)∈R

HALCON 8.0.2
486 CHAPTER 5. IMAGE

Parameter
. Regions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Region(s) to be examined.
. Image (input iconic) . . . . . . image ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2, uint2, int4,
real )
Gray value image.
. Area (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Gray value volume of the region.
. Row (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( real )
Row coordinate of the gray value center of gravity.
. Column (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( real )
Column coordinate of the gray value center of gravity.
Result
AreaCenterGray returns TRUE if all parameters are correct and no error occurs during execution. If the input
is empty the behavior can be set via SetSystem(::’noObjectResult’,<Result>:). If necessary, an
exception handling is raised.
Parallelization Information
AreaCenterGray is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection
See also
AreaCenterXld, EllipticAxisGray
Alternatives
AreaCenter
Module
Foundation

[out] VARIANT Energy HRegionX.CoocFeatureImage ([in] HImageX Image,


[in] long LdGray, [in] VARIANT Direction, [out] VARIANT Correlation,
[out] VARIANT Homogeneity, [out] VARIANT Contrast )
[out] VARIANT Energy HImageX.CoocFeatureImage ([in] HRegionX Regions,
[in] long LdGray, [in] VARIANT Direction, [out] VARIANT Correlation,
[out] VARIANT Homogeneity, [out] VARIANT Contrast )
void HOperatorSetX.CoocFeatureImage ([in] IHObjectX Regions,
[in] IHObjectX Image, [in] VARIANT LdGray, [in] VARIANT Direction,
[out] VARIANT Energy, [out] VARIANT Correlation, [out] VARIANT Homogeneity,
[out] VARIANT Contrast )

Calculate a co-occurrence matrix and derive gray value features thereof.


The call of CoocFeatureImage corresponds to the consecutive execution of the operators GenCoocMatrix
and CoocFeatureMatrix. If several direction matrices of the co-occurrence matrix are to be evaluated
consecutively, it is more efficient to generate the matrix via GenCoocMatrix and then call the operator
CoocFeatureMatrix for the resulting matrix. The parameter Direction transfers the direction of the neigh-
borhood in angle or ’mean’. In the case of ’mean’ the mean value is calculated in all four directions.
Parameter
. Regions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Region to be examined.
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte )
Corresponding gray values.
. LdGray (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of gray values to be distinguished (2LdGray ).
Default Value : 6
List of values : LdGray ∈ {1, 2, 3, 4, 5, 6, 7, 8}

HALCON/COM Reference Manual, 2008-5-13


5.6. FEATURES 487

. Direction (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer, string )


Direction in which the matrix is to be calculated.
Default Value : 0
List of values : Direction ∈ {0, 45, 90, 135, ’mean’}
. Energy (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Gray value energy.
. Correlation (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Correlation of gray values.
. Homogeneity (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Local homogeneity of gray values.
. Contrast (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Gray value contrast.
Result
The operator CoocFeatureImage returns the value TRUE if an image with defined gray values (byte) is
entered and the parameters are correct. The behavior in case of empty input (no input images available) is set
via the operator SetSystem(::’noObjectResult’,<Result>:), the behavior in case of empty region
is set via SetSystem(::’emptyRegionResult’,<Result>:). If necessary an exception handling is
raised.
Parallelization Information
CoocFeatureImage is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
GenCoocMatrix
See also
Intensity, MinMaxGray, EntropyGray, SelectGray
Alternatives
CoocFeatureMatrix
Module
Foundation

[out] double Energy HImageX.CoocFeatureMatrix


([out] double Correlation, [out] double Homogeneity, [out] double Contrast )
void HOperatorSetX.CoocFeatureMatrix ([in] IHObjectX CoocMatrix,
[out] VARIANT Energy, [out] VARIANT Correlation, [out] VARIANT Homogeneity,
[out] VARIANT Contrast )

Calculate gray value features from a co-occurrence matrix.


The procedure calculates from a co-occurence matrix (CoocMatrix) the energy (Energy), correlation
(Correlation), local homogeneity (Homogeneity) and contrast (Contrast).
The operator CoocFeatureMatrix calculates the gray value features from the part of the input matrix gen-
erated by GenCoocMatrix corresponding to the direction matrix indicated by the parameters LdGray and
Direction according to the following formulae:
Energy:
width
X
Energy = c2ij
i,j=0

(Measure for image homogeneity)


Correlation: Pwidth
i,j=0 (i − ux )(j − uy )cij
Correlation =
sx sy
(Measure for gray value dependencies)
Local homogeneity:
width
X 1
Homogeneity = cij
i,j=0
1 + (i − j)2

HALCON 8.0.2
488 CHAPTER 5. IMAGE

Contrast:
width
X
Contrast = (i − j)2 cij
i,j=0

(Measure for the size of the intensity differences)


where
width = Width of CoocMatrix
cij = Entry of co-occurrence matrix
Pwidth
ux = i,j=0 i ∗ cij
Pwidth
uy = j ∗ cij
Pi,j=0
width
s2x = 2
i,j=0 (i − ux ) ∗ cij
Pwidth
s2y = 2
i,j=0 (i − uy ) ∗ cij

Attention
The region of the input image is disregarded.
Parameter

. CoocMatrix (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( real )


Co-occurrence matrix.
. Energy (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Homogeneity of the gray values.
. Correlation (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Correlation of gray values.
. Homogeneity (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Local homogeneity of gray values.
. Contrast (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Gray value contrast.
Result
The operator CoocFeatureMatrix returns the value TRUE if an image with defined gray values is passed and
the parameters are correct. The behavior in case of empty input (no input images available) is set via the operator
SetSystem(::’noObjectResult’,<Result>:). If necessary an exception handling is raised.
Parallelization Information
CoocFeatureMatrix is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
GenCoocMatrix
See also
Intensity, MinMaxGray, EntropyGray, SelectGray
Alternatives
CoocFeatureImage
Module
Foundation

[out] VARIANT Ra HRegionX.EllipticAxisGray ([in] HImageX Image,


[out] VARIANT Rb, [out] VARIANT Phi )
[out] VARIANT Ra HImageX.EllipticAxisGray ([in] HRegionX Regions,
[out] VARIANT Rb, [out] VARIANT Phi )
void HOperatorSetX.EllipticAxisGray ([in] IHObjectX Regions,
[in] IHObjectX Image, [out] VARIANT Ra, [out] VARIANT Rb, [out] VARIANT Phi )

Compute the orientation and major axes of a region in a gray value image.
The operator EllipticAxisGray calculates the length of the axes and the orientation of the ellipse having the
“same orientation” and the “aspect ratio” as the input region. Several input regions can be passed in Regions as
tuples. The length of the major axis Ra and the minor axis Rb as well as the orientation of the major axis with

HALCON/COM Reference Manual, 2008-5-13


5.6. FEATURES 489

regard to the x-axis (Phi) are determined. The angle is returned in radians. The calculation is done analogously to
EllipticAxis. The only difference is that in EllipticAxisGray the gray value moments are used instead
of the region moments. The gray value moments are derived from the input image Image. For the definition of
the gray value moments, see AreaCenterGray.
Parameter
. Regions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Region(s) to be examined.
. Image (input iconic) . . . . . . image ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2, uint2, int4,
real )
Gray value image.
. Ra (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Major axis of the region.
. Rb (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Minor axis of the region.
. Phi (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad(-array) ; VARIANT ( real )
Angle enclosed by the major axis and the x-axis.
Result
EllipticAxisGray returns TRUE if all parameters are correct and no error occurs during execution. If the
input is empty the behavior can be set via SetSystem(::’noObjectResult’,<Result>:). If necessary,
an exception handling is raised.
Parallelization Information
EllipticAxisGray is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection
Possible Successors
GenEllipse
See also
AreaCenterGray
Alternatives
EllipticAxis
Module
Foundation

[out] VARIANT Entropy HRegionX.EntropyGray ([in] HImageX Image,


[out] VARIANT Anisotropy )
[out] VARIANT Entropy HImageX.EntropyGray ([in] HRegionX Regions,
[out] VARIANT Anisotropy )
void HOperatorSetX.EntropyGray ([in] IHObjectX Regions,
[in] IHObjectX Image, [out] VARIANT Entropy, [out] VARIANT Anisotropy )

Determine the entropy and anisotropy of images.


The operator EntropyGray creates the histogram of relative frequencies of the gray values in the input image
and calculates from these frequencies the entropy and the anisotropy coefficient for each region from Regions
according to the following formulae:
Entropy:
255
X
Entropy = − rel[i] ∗ log2 (rel[i])
0
Anisotropy coefficient:
Pk
0 rel[i] ∗ log2 (rel[i])
Anisotropy =
Entropy
where

HALCON 8.0.2
490 CHAPTER 5. IMAGE

rel[i] = Histogram of relative gray value frequencies


i = Gray value of input image (0 . . . 255)
Pk
k = Smallest possible gray value with 0 rel[i] ≥ 0.5
Parameter

. Regions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Regions where the features are to be determined.
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte )
Gray value image.
. Entropy (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Information content (entropy) of the gray values.
Restriction : ((0 ≤ Entropy) ∧ (Entropy ≤ 8))
. Anisotropy (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Measure of the symmetry of gray value distribution.
Complexity
If F is the area of the region the runtime complexity is O(F + 255).
Result
The operator EntropyGray returns the value TRUE if an image with defined gray values is entered and the
parameters are correct. The behavior in case of empty input (no input images available) is set via the opera-
tor SetSystem(::’noObjectResult’,<Result>:), the behavior in case of empty region is set via
SetSystem(::’emptyRegionResult’,<Result>:). If necessary an exception handling is raised.
Parallelization Information
EntropyGray is reentrant and automatically parallelized (on tuple level).
See also
EntropyImage, GrayHisto, GrayHistoAbs, FuzzyEntropy, FuzzyPerimeter
Alternatives
SelectGray
Module
Foundation

[out] VARIANT Sigma HImageX.EstimateNoise ([in] String Method,


[in] VARIANT Percent )
void HOperatorSetX.EstimateNoise ([in] IHObjectX Image,
[in] VARIANT Method, [in] VARIANT Percent, [out] VARIANT Sigma )

Estimate the image noise from a single image.


The operator EstimateNoise estimates the standard deviation of additive noise within the domain of the image
that is passed in Image. The standard deviation is returned in Sigma.
The operator is useful in the following use cases:

• determination of MinContrast for matching,


• determination of the amplitude for edge filters,
• camera evaluation,
• monitoring errors in camera operation (e.g., user overdrives camera gain).

To estimate the noise, one of the following four methods can be selected in Method:

• ’foerstner’: If Method is set to ’foerstner’, first for each pixel a homogeneity measure is computed based
on the first derivatives of the gray values of Image. By thresholding the homogeneity measure one obtains
the homogeneous regions in the image. The threshold is computed based on a starting value for the image
noise. The starting value is obtained by applying the method ’immerkaer’ (see below) in the first step. It
is assumed that the gray value fluctuations within the homogeneous regions are solely caused by the image
noise. Furthermore it is assumed that the image noise is Gaussian distributed. The average homogeneity

HALCON/COM Reference Manual, 2008-5-13


5.6. FEATURES 491

measure within the homogeneous regions is then used to calculate a refined estimate for the image noise.
The refined estimate leads to a new threshold for the homogeneity. The described process is iterated until the
estimated image noise remains constant between two successive iterations. Finally, the standard deviation of
the estimated image noise is returned in Sigma.
Note that in some cases the iteration falsely converges to the value 0. This happens, for example, if the gray
value histogram of the input image contains gaps that are caused either by an automatic radiometric scaling
of the camera or frame grabber, respectively, or by a manual spreading of the gray values using a scaling
factor > 1.
Also note that the result obtained by this method is independent of the value passed in Percent.
• ’immerkaer’: If Method is set to ’immerkaer’, first the following filter mask is applied to the input image:

1
−2 1
M = −2 4 −2 .
1 −2 1
The advantage of this method is that M is almost insensitive to image structure but only depends on the noise
in the image. Assuming a Gaussian distributed noise, its standard deviation is finally obtained as
r
π 1 X
Sigma = |Image ∗ M | ,
2 6N
Image

where N is the number of image pixels to which M is applied. Note that the result obtained by this method
is independent of the value passed in Percent.
• ’least_squares’: If Method is set to ’least_squares’, the fluctuations of the gray values with respect to a
locally fitted gray value plane are used to estimate the image noise. First, a homogeneity measure is computed
based on the first derivatives of the gray values of Image. Homogeneous image regions are determined by
selecting the Percent percent most homogeneous pixels in the domain of the input image, i.e., pixels with
small magnitudes of the first derivatives. For each homogeneous pixel a gray value plane is fitted to its 3 × 3
neighborhood. The differences between the gray values within the 3 × 3 neighborhood and the locally fitted
plane are used to estimate the standard deviation of the noise. Finally, the average standard deviation over all
homogeneous pixels is returned in Sigma.
• ’mean’: If Method is set to ’mean’, the noise estimation is based on the difference between the input
image and a noiseless version of the input image. First, a homogeneity measure is computed based on the
first derivatives of the gray values of Image. Homogeneous image regions are determined by selecting
the Percent percent most homogeneous pixels in the domain of the input image, i.e., pixels with small
magnitudes of the first derivatives. A mean filter is applied to the homogeneous image regions in order to
eliminate the noise. It is assumed that the difference between the input image and the thus obtained noiseless
version of the image represents the image noise. Finally, the standard deviation of the differences is returned
in Sigma. It should be noted that this method requires large connected homogenous image regions to be
able to reliably estimate the noise.

Note that the methods ’foerstner’ and ’immerkaer’ assume a Gaussian distribution of the image noise, whereas
the methods ’least_squares’ and’mean’ can be applied to images with arbitrarily distributed noise. In general, the
method ’foerstner’ returns the most accurate results while the method ’immerkaer’ shows the fastest computation.
If the image noise could not be estimated reliably, the error 3175 is raised. This may happen if the image does not
contain enough homogeneous regions, if the image was artificially created, or if the noise is not of Gaussian type.
In order to avoid this error, it might be useful in some cases to try one of the following modifications in dependence
of the estimation method that is passed in Method:

• Increase the size of the input image domain (useful for all methods).
• Increase the value of the parameter Percent (useful for methods ’least_squares’ and ’mean’).
• Use the method ’immerkaer’, instead of the methods ’foerstner’, ’least_squares’, or ’mean’. The method
’immerkaer’ does not rely on the existence of homogeneous image regions, and hence is almost always
applicable.

HALCON 8.0.2
492 CHAPTER 5. IMAGE

Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte, uint2 )


Input image.
. Method (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Method to estimate the image noise.
Default Value : ’foerstner’
List of values : Method ∈ {’foerstner’, ’immerkaer’, ’least_squares’, ’mean’}
. Percent (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Percentage of used image points.
Default Value : 20
Suggested values : Percent ∈ {1, 2, 5, 7, 10, 15, 20, 30, 40, 50}
Restriction : ((0 < P ercent) ∧ (P ercent ≤ 50.))
. Sigma (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Standard deviation of the image noise.
Restriction : (Sigma ≥ 0)
Example

read_image (Image, ’combine’)


estimate_noise (ImageNoise, ’foerstner’, 20, SigmaFoerstner)
estimate_noise (ImageNoise, ’immerkaer’, 20, SigmaImmerkaer)
estimate_noise (ImageNoise, ’least_squares’, 20, SigmaLeastSquares)
estimate_noise (ImageNoise, ’mean’, 20, SigmaMean)

Result
If the parameters are valid, the operator EstimateNoise returns the value TRUE. If necessary an exception is
raised. If the image noise could not be estimated reliably, the error 3175 is raised.
Parallelization Information
EstimateNoise is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
GrabImage, GrabImageAsync, ReadImage, ReduceDomain
Possible Successors
BinomialFilter, GaussImage, MeanImage, SmoothImage
See also
GaussDistribution, AddNoiseDistribution
Alternatives
NoiseDistributionMean, Intensity, MinMaxGray
References
W. Förstner: "‘Image Preprocessing for Feature Extraction in Digital Intensity, Color and Range Images"‘, Springer
Lecture Notes on Earth Sciences, Summer School on Data Analysis and the Statistical Foundations of Geomatics,
1999
J. Immerkaer: "‘Fast Noise Variance Estimation"‘, Computer Vision and Image Understanding, Vol. 64, No. 2, pp.
300-302, 1996
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


5.6. FEATURES 493

[out] VARIANT Alpha HRegionX.FitSurfaceFirstOrder ([in] HImageX Image,


[in] String Algorithm, [in] long Iterations, [in] double ClippingFactor,
[out] VARIANT Beta, [out] VARIANT Gamma )
[out] VARIANT Alpha HImageX.FitSurfaceFirstOrder
([in] HRegionX Regions, [in] String Algorithm, [in] long Iterations,
[in] double ClippingFactor, [out] VARIANT Beta, [out] VARIANT Gamma )
void HOperatorSetX.FitSurfaceFirstOrder ([in] IHObjectX Regions,
[in] IHObjectX Image, [in] VARIANT Algorithm, [in] VARIANT Iterations,
[in] VARIANT ClippingFactor, [out] VARIANT Alpha, [out] VARIANT Beta,
[out] VARIANT Gamma )

Calculate gray value moments and approximation by a first order surface (plane).
The operator FitSurfaceFirstOrder calculates the gray value moments and the parameters of the approxi-
mation of the gray values by a first order surface. The calculation is done by minimizing the distance between the
gray values and the surface. A first order surface is described by the following formula:

Image0 (r, c) = Alpha(r − r_center) + Beta(c − c_center) + Gamma

r_center and c_center are the center coordinates of intersection of the input region with the full image domain. By
the minimization process the parameters from Alpha to Gamma is calculated.
The algorithm used for the fitting can be selected via Algorithm:
’regression’ Standard ’least squares’ line fitting.
’huber’ Weighted ’least squares’ fitting, where the impact of outliers is decreased based on the approach of
Huber.
’tukey’ Weighted ’least squares’ fitting, where the impact of outliers is decreased based on the approach of
Tukey.
The parameter ClippingFactor (a scaling factor for the standard deviation) controls the amount of damping
outliers: The smaller the value chosen for ClippingFactor the more outliers are detected. The detection of
outliers is repeated. The parameter Iterations specifies the number of iterations. In the modus ’regression’
this value is ignored.
Parameter
. Regions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Regions to be checked.
. Image (input iconic) . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, uint2, direction, cyclic, real )
Corresponding gray values.
. Algorithm (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Algorithm for the fitting.
Default Value : ’regression’
List of values : Algorithm ∈ {’regression’, ’huber’, ’tukey’}
. Iterations (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Maximum number of iterations (unused for ’regression’).
Default Value : 5
Restriction : (Iterations ≥ 0)
. ClippingFactor (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Clipping factor for the elimination of outliers.
Default Value : 2.0
List of values : ClippingFactor ∈ {1.0, 1.5, 2.0, 2.5, 3.0}
Restriction : (ClippingF actor > 0)
. Alpha (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Parameter Alpha of the approximating surface.
. Beta (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Parameter Beta of the approximating surface.
. Gamma (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Parameter Gamma of the approximating surface.

HALCON 8.0.2
494 CHAPTER 5. IMAGE

Result
The operator FitSurfaceSecondOrder returns the value TRUE if an image with the defined gray values
(byte) is entered and the parameters are correct. If necessary an exception handling is raised.
Parallelization Information
FitSurfaceFirstOrder is reentrant and automatically parallelized (on tuple level).
See also
MomentsGrayPlane, FitSurfaceSecondOrder
Module
Foundation

[out] VARIANT Alpha HRegionX.FitSurfaceSecondOrder


([in] HImageX Image, [in] String Algorithm, [in] long Iterations,
[in] double ClippingFactor, [out] VARIANT Beta, [out] VARIANT Gamma,
[out] VARIANT Delta, [out] VARIANT Epsilon, [out] VARIANT Zeta )
[out] VARIANT Alpha HImageX.FitSurfaceSecondOrder
([in] HRegionX Regions, [in] String Algorithm, [in] long Iterations,
[in] double ClippingFactor, [out] VARIANT Beta, [out] VARIANT Gamma,
[out] VARIANT Delta, [out] VARIANT Epsilon, [out] VARIANT Zeta )
void HOperatorSetX.FitSurfaceSecondOrder ([in] IHObjectX Regions,
[in] IHObjectX Image, [in] VARIANT Algorithm, [in] VARIANT Iterations,
[in] VARIANT ClippingFactor, [out] VARIANT Alpha, [out] VARIANT Beta,
[out] VARIANT Gamma, [out] VARIANT Delta, [out] VARIANT Epsilon,
[out] VARIANT Zeta )

Calculate gray value moments and approximation by a second order surface.


The operator FitSurfaceSecondOrder calculates the gray value moments and the parameters of the approx-
imation of the gray values by a second order surface. The calculation is done by minimizing the distance between
the gray values and the surface. A second order surface is described by the following formula:

Image(r, c) = Alpha(r−r_center)∗∗2+Beta(c−c_center)∗∗2+Gamma(r−r_center)∗(c−c_center)+Delta(r−r_center)

r_center and c_center are the center coordinates of the intersection of the input region with the full image domain.
By the minimization process the parameters from Alpha to Zeta is calculated.
The algorithm used for the fitting can be selected via Algorithm:
’regression’ Standard ’least squares’ fitting.
’huber’ Weighted ’least squares’ fitting, where the impact of outliers is decreased based on the approach of
Huber.
’tukey’ Weighted ’least squares’ fitting, where the impact of outliers is decreased based on the approach of
Tukey.
The parameter ClippingFactor (a scaling factor for the standard deviation) controls the amount of damping
outliers: The smaller the value chosen for ClippingFactor the more outliers are detected. The detection of
outliers is repeated. The parameter Iterations specifies the number of iterations. In the modus ’regression’
this value is ignored.
Parameter

. Regions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Regions to be checked.
. Image (input iconic) . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, uint2, direction, cyclic, real )
Corresponding gray values.
. Algorithm (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Algorithm for the fitting.
Default Value : ’regression’
List of values : Algorithm ∈ {’regression’, ’tukey’, ’huber’}

HALCON/COM Reference Manual, 2008-5-13


5.6. FEATURES 495

. Iterations (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT


Maximum number of iterations (unused for ’regression’).
Default Value : 5
Restriction : (Iterations ≥ 0)
. ClippingFactor (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Clipping factor for the elimination of outliers.
Default Value : 2.0
List of values : ClippingFactor ∈ {1.0, 1.5, 2.0, 2.5, 3.0}
Restriction : (ClippingF actor > 0)
. Alpha (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Parameter Alpha of the approximating surface.
. Beta (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Parameter Beta of the approximating surface.
. Gamma (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Parameter Gamma of the approximating surface.
. Delta (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Parameter Delta of the approximating surface.
. Epsilon (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Parameter Epsilon of the approximating surface.
. Zeta (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Parameter Zeta of the approximating surface.
Result
The operator FitSurfaceSecondOrder returns the value TRUE if an image with the defined gray values
(byte) is entered and the parameters are correct. If necessary an exception handling is raised.
Parallelization Information
FitSurfaceSecondOrder is reentrant and automatically parallelized (on tuple level).
See also
MomentsGrayPlane, FitSurfaceFirstOrder
Module
Foundation

[out] VARIANT Entropy HRegionX.FuzzyEntropy ([in] HImageX Image,


[in] long Apar, [in] long Cpar )
[out] VARIANT Entropy HImageX.FuzzyEntropy ([in] HRegionX Regions,
[in] long Apar, [in] long Cpar )
void HOperatorSetX.FuzzyEntropy ([in] IHObjectX Regions,
[in] IHObjectX Image, [in] VARIANT Apar, [in] VARIANT Cpar,
[out] VARIANT Entropy )

Determine the fuzzy entropy of regions.


FuzzyEntropy calculates the fuzzy entropy of a fuzzy set. To do so, the image is regarded as a fuzzy set. The
entropy then is a measure of how well the image approximates a white or black image. It is defined as follows:

1
P
H(X) = M N ln2 l Te (l)h(l)

where M × N is the size of the image, and h(l) is the histogram of the image. Furthermore,

Te (l) = −µ(l) ln µ(l) − (1 − µ(l)) ln(1 − µ(l))

Here, u(x(m, n)) is a fuzzy membership function defining the fuzzy set (see FuzzyPerimeter). The same
restrictions hold as in FuzzyPerimeter.

HALCON 8.0.2
496 CHAPTER 5. IMAGE

Parameter
. Regions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Regions for which the fuzzy entropy is to be calculated.
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte )
Input image containing the fuzzy membership values.
. Apar (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Start of the fuzzy function.
Default Value : 0
Suggested values : Apar ∈ {0, 5, 10, 20, 50, 100}
Typical range of values : 0 ≤ Apar ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 5
. Cpar (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
End of the fuzzy function.
Default Value : 255
Suggested values : Cpar ∈ {50, 100, 150, 200, 220, 255}
Typical range of values : 0 ≤ Cpar ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 5
Restriction : (Apar ≤ Cpar)
. Entropy (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Fuzzy entropy of a region.
Example

/* To find a Fuzzy Entropy from an Image */


read_image(Image,’affe’)
fuzzy_entropy(Trans,Trans,0,255,Entro).

Result
The operator FuzzyEntropy returns the value TRUE if the parameters are correct. Otherwise an exception is
raised.
Parallelization Information
FuzzyEntropy is reentrant and automatically parallelized (on tuple level).
See also
FuzzyPerimeter
References
M.K. Kundu, S.K. Pal: ‘"Automatic selection of object enhancement operator with quantitative justification based
on fuzzy set theoretic measures”; Pattern Recognition Letters 11; 1990; pp. 811-829.
Module
Foundation

[out] VARIANT Perimeter HRegionX.FuzzyPerimeter ([in] HImageX Image,


[in] long Apar, [in] long Cpar )
[out] VARIANT Perimeter HImageX.FuzzyPerimeter ([in] HRegionX Regions,
[in] long Apar, [in] long Cpar )
void HOperatorSetX.FuzzyPerimeter ([in] IHObjectX Regions,
[in] IHObjectX Image, [in] VARIANT Apar, [in] VARIANT Cpar,
[out] VARIANT Perimeter )

Calculate the fuzzy perimeter of a region.


The operator FuzzyPerimeter is used to determine the differences of fuzzy membership between an image
point and its neighbor points. The right and lower neighbor are taken into account. The fuzzy perimeter is then
defined as follows:

HALCON/COM Reference Manual, 2008-5-13


5.6. FEATURES 497

M
X −1 N
X −1 M
X −1 N
X −1
p(X) = |µX (xm,n ) − µX (xm,n+1 )| + |µX (xm,n ) − µX (xm+1,n )|
m=1 n=1 m=1 n=1

where M × N is the size of the image, and u(x(m, n)) is the fuzzy membership function (i.e., the input image).
This implementation uses Zadeh’s Standard-S function, which is defined as follows:


 0,  x≤a
 x−a 2
 2 , a<x≤b

c−a
µX (x) = 
2

x−a
 1 − 2 c−a , b < x ≤ c



1, c≤x

The parameters a, b and c obey the following restrictions: b = a+c


2 is the inflection point of the function, ∆b =
b − a = c − b is the bandwith, and for x = b µ(x) = 0.5 holds. In FuzzyPerimeter, the parameters Apar
and Cpar are defined as follows: b is Apar+2
Cpar .
Parameter
. Regions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Regions for which the fuzzy perimeter is to be calculated.
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte )
Input image containing the fuzzy membership values.
. Apar (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Start of the fuzzy function.
Default Value : 0
Suggested values : Apar ∈ {0, 5, 10, 20, 50, 100}
Typical range of values : 0 ≤ Apar ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 5
. Cpar (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
End of the fuzzy function.
Default Value : 255
Suggested values : Cpar ∈ {50, 100, 150, 200, 220, 255}
Typical range of values : 0 ≤ Cpar ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 5
Restriction : (Apar ≤ Cpar)
. Perimeter (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Fuzzy perimeter of a region.
Example

/* To find a Fuzzy Entropy from an Image */


read_image(Image,’affe’)
fuzzy_perimeter(Trans,Trans,0,255,Per).

Result
The operator FuzzyPerimeter returns the value TRUE if the parameters are correct. Otherwise an exception
is raised.
Parallelization Information
FuzzyPerimeter is reentrant and automatically parallelized (on tuple level).
See also
FuzzyEntropy
References
M.K. Kundu, S.K. Pal: ‘"Automatic selection of object enhancement operator with quantitative justification based
on fuzzy set theoretic measures”; Pattern Recognition Letters 11; 1990; pp. 811-829.
Module
Foundation

HALCON 8.0.2
498 CHAPTER 5. IMAGE

[out] HImageX Matrix HRegionX.GenCoocMatrix ([in] HImageX Image,


[in] long LdGray, [in] long Direction )
[out] HImageX Matrix HImageX.GenCoocMatrix ([in] HRegionX Regions,
[in] long LdGray, [in] long Direction )
void HOperatorSetX.GenCoocMatrix ([in] IHObjectX Regions,
[in] IHObjectX Image, [out] HUntypedObjectX Matrix, [in] VARIANT LdGray,
[in] VARIANT Direction )

Calculate the co-occurrence matrix of a region in an image.


The operator GenCoocMatrix determines from the input regions how often the gray values i and j are located
next to each other in a certain direction (0, 45, 90, 135 degrees), stores this number in the co-occurrence matrix at
the locations (i, j) and (j, i) (the matrix is symmetrical), and finally scales the matrix with the number of entries.
LdGray indicates the number of gray values to be distinguished (namely 2LdGray ).
Example (LdGray = 2, i.e. 4 gray values are distinguished):
Input image Co-occurrence matrix
with gray values: (not scaled)

0 0 3 2 0 0 1 0 1 1 0
1 1 2 0 2 2 0 1 0 1 1
1 2 3 0 2 0 1 1 1 0 0
1 0 1 0 0 1 0 0

0 2 0 0 0 1 0 0
2 2 1 0 1 2 0 1
0 1 0 2 0 0 2 0
0 0 2 0 0 1 0 0
Parameter

. Regions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Region to be checked.
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte )
Image providing the gray values.
. Matrix (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX ( real )
Co-occurrence matrix (matrices).
. LdGray (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of gray values to be distinguished (2LdGray ).
Default Value : 6
List of values : LdGray ∈ {1, 2, 3, 4, 5, 6, 7, 8}
Typical range of values : 1 ≤ LdGray ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 1
. Direction (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Direction of neighbor relation.
Default Value : 0
List of values : Direction ∈ {0, 45, 90, 135}
Result
The operator GenCoocMatrix returns the value TRUE if an image with defined gray values is entered and
the parameters are correct. The behavior in case of empty input (no input images available) is set via the oper-
ator SetSystem(::’noObjectResult’,<Result>:), the behavior in case of empty region is set via
SetSystem(::’emptyRegionResult’,<Result>:). If necessary an exception handling is raised.
Parallelization Information
GenCoocMatrix is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
DrawRegion, GenCircle, GenEllipse, GenRectangle1, GenRectangle2, Threshold,
ErosionCircle, BinomialFilter, GaussImage, SmoothImage, SubImage

HALCON/COM Reference Manual, 2008-5-13


5.6. FEATURES 499

See also
CoocFeatureMatrix
Alternatives
CoocFeatureImage
Module
Foundation

[out] VARIANT AbsoluteHisto HRegionX.GrayHisto ([in] HImageX Image,


[out] VARIANT RelativeHisto )
[out] VARIANT AbsoluteHisto HImageX.GrayHisto ([in] HRegionX Regions,
[out] VARIANT RelativeHisto )
void HOperatorSetX.GrayHisto ([in] IHObjectX Regions,
[in] IHObjectX Image, [out] VARIANT AbsoluteHisto,
[out] VARIANT RelativeHisto )

Calculate the gray value distribution.


The operator GrayHisto calculates for the image (Image) within Regions the absolute (AbsoluteHisto)
and relative (RelativeHisto) histogram of the gray values.
Both histograms are tupels of 256 values, which — beginning at 0 — contain the frequencies of the individual gray
values of the image.
AbsoluteHisto indicates the absolute frequencies of the gray values in integers, and RelativeHisto indi-
cates the relative, i.e. the absolute frequencies divided by the area of the image as floating point numbers.
real-, int2-, uint2-, and int4-images are transformed into byte-images (first the largest and smallest gray value in the
image are determined, and then the original gray values are mapped linearly into the area 0..255) and then processed
as mentioned above. The histogram can also be returned directly as a graphic via the operators SetPaint(::
WindowHandle,’histogram’:) and DispImage.
Attention
Real, int2, uint2, and int4 images are reduced to 256 gray values.
Parameter

. Regions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Region in which the histogram is to be calculated.
. Image (input iconic) . . . . . . image ; HImageX / IHObjectX ( byte, cyclic, direction, int1, int2, uint2, int4,
real )
Image the gray value distribution of which is to be calculated.
. AbsoluteHisto (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . histogram ; VARIANT ( integer )
Absolute frequencies of the gray values.
. RelativeHisto (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . histogram ; VARIANT ( real )
Frequencies, normalized to the area of the region.
Complexity
If F is the area of the region the runtime complexity is O(F + 255).
Result
The operator GrayHisto returns the value TRUE if the image has defined gray values and the parameters are
correct. The behavior in case of empty input (no input images available) is set via the operator SetSystem
(::’noObjectResult’,<Result>:), the behavior in case of empty region is set via SetSystem(::
’emptyRegionResult’,<Result>:). If necessary an exception handling is raised.
Parallelization Information
GrayHisto is reentrant and processed without parallelization.
Possible Successors
HistoToThresh, GenRegionHisto
See also
SetPaint, DispImage, Histo2Dim, ScaleImageMax, EntropyGray

HALCON 8.0.2
500 CHAPTER 5. IMAGE

Alternatives
MinMaxGray, Intensity, GrayHistoAbs
Module
Foundation

[out] VARIANT AbsoluteHisto HRegionX.GrayHistoAbs ([in] HImageX Image,


[in] VARIANT Quantization )
[out] VARIANT AbsoluteHisto HImageX.GrayHistoAbs ([in] HRegionX Regions,
[in] VARIANT Quantization )
void HOperatorSetX.GrayHistoAbs ([in] IHObjectX Regions,
[in] IHObjectX Image, [in] VARIANT Quantization,
[out] VARIANT AbsoluteHisto )

Calculate the gray value distribution.


The operator GrayHistoAbs calculates for the image (Image) within Regions the absolute
(AbsoluteHisto) ) histogram of the gray values.
The parameter Quantization defines, how many frequencies of neighbored gray values are added for one
frequency value. The resulting histogram AbsoluteHisto is a tuple, whose indices are mapped on the gray
values of the input image Image and whose elements contain the frequencies of the gray values. The indices i of
the frequency value are calculated from the gray values g and the quantisation q as follows:
 
g + 0.5
i= for unsigned image types,
q
 
g − (M IN − 0.5)
i= for signed image types,
q
whereas MIN denotes the minimal gray value, e.g., -128 for an int1 image type. Therefore, the size of the tuple
results from the ratio of the full domain of gray values and the quantisation, e.g. for images of int2 in d 65536
3.0 e =
21846 . The origin gray value of the signed image types int1 resp. int2 is mapped on the index 128 resp. 32768,
negative resp. positive gray values have smaller resp. greater indices.
The histogram can also be returned directly as a graphic via the operators SetPaint(::
WindowHandle,’histogram’:) and DispImage.
Parameter
. Regions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Region in which the histogram is to be calculated.
. Image (input iconic) . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, cyclic, direction, int1, int2, uint2 )
Image the gray value distribution of which is to be calculated.
. Quantization (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Quantization of the gray values.
Default Value : 1.0
List of values : Quantization ∈ {1.0, 2.0, 3.0, 5.0, 10.0}
Restriction : (Quantization ≥ 1.0)
. AbsoluteHisto (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . histogram ; VARIANT ( integer )
Absolute frequencies of the gray values.
Result
The operator GrayHistoAbs returns the value TRUE if the image has defined gray values and the parameters
are correct. The behavior in case of empty input (no input images available) is set via the operator SetSystem
(::’noObjectResult’,<Result>:), the behavior in case of empty region is set via SetSystem(::
’emptyRegionResult’,<Result>:). If necessary an exception handling is raised.
Parallelization Information
GrayHistoAbs is reentrant and processed without parallelization.
Possible Successors
HistoToThresh, GenRegionHisto

HALCON/COM Reference Manual, 2008-5-13


5.6. FEATURES 501

See also
SetPaint, DispImage, Histo2Dim, ScaleImageMax, EntropyGray
Alternatives
MinMaxGray, Intensity, GrayHisto
Module
Foundation

[out] VARIANT HorProjection HRegionX.GrayProjections


([in] HImageX Image, [in] String Mode, [out] VARIANT VertProjection )
[out] VARIANT HorProjection HImageX.GrayProjections
([in] HRegionX Region, [in] String Mode, [out] VARIANT VertProjection )
void HOperatorSetX.GrayProjections ([in] IHObjectX Region,
[in] IHObjectX Image, [in] VARIANT Mode, [out] VARIANT HorProjection,
[out] VARIANT VertProjection )

Calculate horizontal and vertical gray-value projections.


GrayProjections calculates the horizontal and vertical gray-value projections, i.e., the mean values in the
horizontal and vertical direction of the gray values of the input image Image within the input region Region.
If Mode = ’simple’ is selected the projection is performed in the direction of the coordinate axes of the image, i.e.:

1 X
HorProjection(r) = Image(r + r0 , c + c0 )
n(r + r0 )
Region
(r+r 0 ,c+c0 )∈
1 X
VertProjection(c) = Image(r + r0 , c + c0 )
n(c + c0 )
(r+r 0 ,c+c0 )∈Region

Here, (r0 , c0 ) denotes the upper left corner of the smallest enclosing axis-parallel rectangle of the input region (see
SmallestRectangle1), and n(x) denotes the number of region points in the corresponding row r + r0 or
column c + c0 . Hence, the horizontal projection returns a one-dimensional function that reflects the vertical gray
value changes. Likewise, the vertical projection returns a function that reflects the horizontal gray value changes.
If Mode = ’rectangle’is selected the projection is performed in the direction of the major axes of the smallest en-
closing rectangle of arbitrary orientation of the input region (see SmallestRectangle2). Here, the horizontal
projection direction corresponds to the larger axis, while the vertical direction corresponds to the smaller axis. In
this mode, all gray values within the smallest enclosing rectangle of arbitrary orientation of the input region are
used to compute the projections.
Parameter
. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
Region to be processed.
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, int2, uint2 )
Grayvalues for projections.
. Mode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Method to compute the projections.
Default Value : ’simple’
List of values : Mode ∈ {’simple’, ’rectangle’}
. HorProjection (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Horizontal projection.
. VertProjection (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Vertical projection.
Parallelization Information
GrayProjections is reentrant and processed without parallelization.
Module
1D Metrology

HALCON 8.0.2
502 CHAPTER 5. IMAGE

[out] HImageX Histo2Dim HRegionX.Histo2Dim ([in] HImageX ImageCol,


[in] HImageX ImageRow )
[out] HImageX Histo2Dim HImageX.Histo2Dim ([in] HRegionX Regions,
[in] HImageX ImageRow )
void HOperatorSetX.Histo2Dim ([in] IHObjectX Regions,
[in] IHObjectX ImageCol, [in] IHObjectX ImageRow,
[out] HUntypedObjectX Histo2Dim )

Calculate the histogram of two-channel gray value images.


The operator Histo2Dim calculates the 2-dimensional histogram of two images within Regions. The gray
values of channel 1 (ImageCol) are interpreted as row index, those of channel 2 (ImageRow) as column index.
The gray value at one point P (g1, g2) in the output image Histo2Dim indicates the frequency of the gray value
combination (g1,g2) with g1 indicating the line index and g2 the column index.
Parameter

. Regions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Region in which the histogram is to be calculated.
. ImageCol (input iconic) . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, direction, cyclic, int1 )
Channel 1.
. ImageRow (input iconic) . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, direction, cyclic, int1 )
Channel 2.
. Histo2Dim (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / HUntypedObjectX ( int4 )
Histogram to be calculated.
Example

read_image(Image,’affe’)
texture_laws(Image,Texture,’el’,1,5)
draw_region(Region,WindowHandle)
histo_2dim(Region,Texture,Image,Histo2Dim)
disp_image(Histo2Dim,WindowHandle).

Complexity
If F is the plane of the region, the runtime complexity is O(F + 2562 ).
Result
The operator Histo2Dim returns the value TRUE if both images have defined gray values. The be-
havior in case of empty input (no input images available) is set via the operator SetSystem(::
’noObjectResult’,<Result>:), the behavior in case of empty region is set via SetSystem(::
’emptyRegionResult’,<Result>:). If necessary an exception handling is raised.
Parallelization Information
Histo2Dim is reentrant and processed without parallelization.
Possible Predecessors
Decompose3, Decompose2, DrawRegion
Possible Successors
Threshold, Class2DimSup, Pouring, LocalMax, GraySkeleton
See also
GetGrayval
Alternatives
GrayHisto, GrayHistoAbs
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


5.6. FEATURES 503

[out] VARIANT Mean HRegionX.Intensity ([in] HImageX Image,


[out] VARIANT Deviation )
[out] VARIANT Mean HImageX.Intensity ([in] HRegionX Regions,
[out] VARIANT Deviation )
void HOperatorSetX.Intensity ([in] IHObjectX Regions,
[in] IHObjectX Image, [out] VARIANT Mean, [out] VARIANT Deviation )

Calculate the mean and deviation of gray values.


The operator Intensity calculates the mean and the deviation of the gray values in the input image within
Regions. If R is a region, p a pixel from R with the gray value g(p) and F the plane (F = |R|), the features are
defined by:
P
p∈R g(p)
Mean :=
F
sP
p∈R (g(p) − Mean)2
Deviation :=
F

Attention
The calculation of Deviation does not follow the usual definition if the region of the image contains only one
pixel. In this case 0.0 is returned.
Parameter

. Regions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Regions the features of which are to be calculated.
. Image (input iconic) . . . . . . image ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2, uint2, int4,
real )
Gray value image.
. Mean (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Mean gray value of a region.
. Deviation (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Deviation of gray values within a region.
Complexity
If F is the area of the region, the runtime complexity is O(F ).
Result
The operator Intensity returns the value TRUE. The behavior in case of empty input (no input images avail-
able) is set via the operator SetSystem(::’noObjectResult’,<Result>:), the behavior in case of
empty region is set via SetSystem(::’emptyRegionResult’,<Result>:). If necessary an exception
handling is raised.
Parallelization Information
Intensity is reentrant and automatically parallelized (on tuple level).
Possible Successors
Threshold
See also
MeanImage, MeanImage, GrayHisto, GrayHistoAbs
Alternatives
SelectGray, MinMaxGray
Module
Foundation

HALCON 8.0.2
504 CHAPTER 5. IMAGE

[out] VARIANT Min HRegionX.MinMaxGray ([in] HImageX Image,


[in] VARIANT Percent, [out] VARIANT Max, [out] VARIANT Range )
[out] VARIANT Min HImageX.MinMaxGray ([in] HRegionX Regions,
[in] VARIANT Percent, [out] VARIANT Max, [out] VARIANT Range )
void HOperatorSetX.MinMaxGray ([in] IHObjectX Regions,
[in] IHObjectX Image, [in] VARIANT Percent, [out] VARIANT Min,
[out] VARIANT Max, [out] VARIANT Range )

Determine the minimum and maximum gray values within regions.


The operator MinMaxGray creates the histogram of the absolute frequencies of the gray values within Regions
in the input image Image (see GrayHisto) and calculates the number of pixels Percent corresponding to
the area of the input image. Then it goes inwards on both sides of the histogram by this number of pixels and
determines the smallest and the largest gray value:
e.g.:
Area = 60, percent = 5, i.e. 3 pixels
histogram = [2,8,0,7,13,0,0,. . . ,0,10,10,5,3,1,1]
⇒ Maximum = 255, Minimum = 0, Range = 255
MinMaxGray returns: Maximum = 253, Minimum = 1, Range = 252
For image of type int4 and real, the above calculation is not performed via histograms, but using a rank selection
algorithm. If Percent is set to 50, Min = Max = Median. If Percent is 0 no histogram is calculated in order
to enhance the runtime.
Parameter

. Regions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Regions, the features of which are to be calculated.
. Image (input iconic) . . . . . . image ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2, uint2, int4,
real )
Gray value image.
. Percent (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Percentage below (above) the absolute maximum (minimum).
Default Value : 0
Suggested values : Percent ∈ {0, 1, 2, 5, 7, 10, 15, 20, 30, 40, 50}
Restriction : ((0 ≤ P ercent) ∧ (P ercent ≤ 50))
. Min (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
“Minimum” gray value.
. Max (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
“Maximum” gray value.
Restriction : (M ax ≥ M in)
. Range (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Difference between Max and Min.
Restriction : (Range ≥ 0)
Example

/* Threshold segmentation with training region: */


read_image(Image,’fabrik’)
draw_region(Region,WindowHandle)
min_max_gray(Region,Image,5,Min,Max,_)
threshold(Bild,Seg,Min,Max)
disp_region(Seg,WindowHandle).

Result
The operator MinMaxGray returns the value TRUE if the input image has the defined gray values and the
parameters are correct. The behavior in case of empty input (no input images available) is set via the operator
SetSystem(::’noObjectResult’,<Result>:). The behaviour in case of an empty region is set via

HALCON/COM Reference Manual, 2008-5-13


5.6. FEATURES 505

the operator SetSystem(::’emptyRegionResult’,<Result>:). If necessary an exception handling


is raised.
Parallelization Information
MinMaxGray is reentrant and processed without parallelization.
Possible Predecessors
DrawRegion, GenCircle, GenEllipse, GenRectangle1, Threshold, Regiongrowing
Possible Successors
Threshold
See also
GrayHisto, ScaleImage, ScaleImageMax, LearnNdimNorm
Alternatives
SelectGray, Intensity
Module
Foundation

[out] VARIANT MRow HRegionX.MomentsGrayPlane ([in] HImageX Image,


[out] VARIANT MCol, [out] VARIANT Alpha, [out] VARIANT Beta,
[out] VARIANT Mean )
[out] VARIANT MRow HImageX.MomentsGrayPlane ([in] HRegionX Regions,
[out] VARIANT MCol, [out] VARIANT Alpha, [out] VARIANT Beta,
[out] VARIANT Mean )
void HOperatorSetX.MomentsGrayPlane ([in] IHObjectX Regions,
[in] IHObjectX Image, [out] VARIANT MRow, [out] VARIANT MCol,
[out] VARIANT Alpha, [out] VARIANT Beta, [out] VARIANT Mean )

Calculate gray value moments and approximation by a plane.


The operator MomentsGrayPlane calculates the gray value moments and the parameters of the approximation
of the gray values by a plane. The calculation is carried out according to the following formula:

1 X 1 X
MRow = (r − r)(Image(r, c) − Mean) MCol = (c − c)(Image(r, c) − Mean)
F2 F2
(r,c)∈Regions (r,c)∈Regions

MRowF m02 − m11 MCol m20 MColF − MRowF m11


Alpha = m20 m02 − m211 Beta =
F m20 m02 − m211

where F is the plane, r, c the center, and m11 , m20 , and m02 the scaled moments of Regions.
The parameters Alpha, Beta and Mean describe a plane above the region:

Image0 (r, c) = Alpha(r − r) + Beta(c − c) + Mean

Thus Alpha indicates the gradient in the direction of the line axis (“down”), Beta the gradient in the direction of
the column axis (to the “right”).
Parameter
. Regions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Regions to be checked.
. Image (input iconic) . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, direction, cyclic, uint2, real )
Corresponding gray values.
. MRow (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Mixed moments along a line.
. MCol (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Mixed moments along a column.

HALCON 8.0.2
506 CHAPTER 5. IMAGE

. Alpha (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )


Parameter Alpha of the approximating plane.
. Beta (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Parameter Beta of the approximating plane.
. Mean (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Mean gray value.
Result
The operator MomentsGrayPlane returns the value TRUE if an image with the defined gray values (byte) is
entered and the parameters are correct. The behavior in case of empty input (no input images available) is set
via the operator SetSystem(::’noObjectResult’,<Result>:), the behavior in case of empty region
is set via SetSystem(::’emptyRegionResult’,<Result>:). If necessary an exception handling is
raised.
Parallelization Information
MomentsGrayPlane is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
DrawRegion, GenCircle, GenEllipse, GenRectangle1, GenRectangle2, Threshold,
Regiongrowing
See also
Intensity, MomentsRegion2Nd
References
R. Haralick, L. Shapiro; “Computer and Robot Vision”; Addison-Wesley, 1992, pp 75-76
Module
Foundation

[out] VARIANT Deviation HRegionX.PlaneDeviation ([in] HImageX Image )


[out] VARIANT Deviation HImageX.PlaneDeviation ([in] HRegionX Regions )
void HOperatorSetX.PlaneDeviation ([in] IHObjectX Regions,
[in] IHObjectX Image, [out] VARIANT Deviation )

Calculate the deviation of the gray values from the approximating image plane.
The operator PlaneDeviation calculates the deviation of the gray values in Image from the approximation
of the gray values through a plane. Contrary to the standard deviation in case of Intensity slanted gray value
planes also receive the value zero. The gray value plane is calculated according to GenImageGrayRamp.
If F is the plane, α, β, µ the parameters of the image plane and (r0 , c0 ) the center, Deviation is defined by:
s
sum(r,c)∈Regions ((α(r − r0 ) + β(c − c0 ) + µ) − Image(r, c))2
Deviation = .
F

Attention
It should be noted that the calculation of Deviation does not follow the usual definition. It is defined to return
the value 0.0 for an image with only one pixel.
Parameter
. Regions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Regions, of which the plane deviation is to be calculated.
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, cyclic )
Gray value image.
. Deviation (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Deviation of the gray values within a region.
Complexity
If F is the area of the region the runtime complexity amounts to O(F ).
Result
The operator PlaneDeviation returns the value TRUE if Image is of the type byte. The be-
havior in case of empty input (no input images available) is set via the operator SetSystem(::

HALCON/COM Reference Manual, 2008-5-13


5.6. FEATURES 507

’noObjectResult’,<Result>:), the behavior in case of empty region is set via SetSystem(::


’emptyRegionResult’,<Result>:). If necessary an exception handling is raised.
Parallelization Information
PlaneDeviation is reentrant and automatically parallelized (on tuple level).
See also
MomentsGrayPlane
Alternatives
Intensity, GenImageGrayRamp, SubImage
Module
Foundation

[out] HRegionX SelectedRegions HRegionX.SelectGray ([in] HImageX Image,


[in] VARIANT Features, [in] String Operation, [in] VARIANT Min,
[in] VARIANT Max )
void HOperatorSetX.SelectGray ([in] IHObjectX Regions,
[in] IHObjectX Image, [out] HUntypedObjectX SelectedRegions,
[in] VARIANT Features, [in] VARIANT Operation, [in] VARIANT Min,
[in] VARIANT Max )

Select regions based on gray value features.


The operator SelectGray has a number of regions (Regions) as input. For each of these regions the features
(Features) are calculated. If each (Operation = ’and’) or at least one (Operation = ’or’) of the calculated
features is within the limits determined by the parameter, the region is transferred (duplicated) into the output. The
parameter Image contains an image which returns the gray values for calculating the features.
Condition:

Mini ≤ Featuresi (Regions, Image) ≤ Maxi

Possble values for Features:


’area’ Gray value volume of region (see AreaCenterGray)
’row’ Row index of the center of gravity (see AreaCenterGray)
’column’ Column index of the center of gravity (see AreaCenterGray)
’ra’ Major axis of equivallent ellipse (see EllipticAxisGray)
’rb’ Minor axis of equivallent ellipse (see EllipticAxisGray)
’phi’ Orientation of equivallent ellipse (see EllipticAxisGray)
’min’ Minimum gray value (see MinMaxGray)
’max’ Maximum gray value (see MinMaxGray)
’mean’ Mean gray value (see Intensity)
’deviation’ Deviation of gray values (see Intensity)
’plane_deviation’ Deviation from the approximating plane (see PlaneDeviation)
’anisotropy’ Anisotropy (see EntropyGray)
’entropy’ Entropy (see EntropyGray)
’fuzzy_entropy’ Fuzzy entropie of region (see FuzzyEntropy, with a fuzzy function from Apar=0 to
Cpar=255)
’fuzzy_perimeter’ Fuzzy perimeter of region (see FuzzyPerimeter, with a fuzzy function from Apar=0 to
Cpar=255)
’moments_row’ Mixed moments along a row (see MomentsGrayPlane)
’moments_column’ Mixed moments along a column (see MomentsGrayPlane)
’alpha’ Approximating plane, parameter Alpha (see MomentsGrayPlane)
’beta’ Approximating plane, parameter Beta (see MomentsGrayPlane)

HALCON 8.0.2
508 CHAPTER 5. IMAGE

Attention
If only one feature is used the value of Operation is meaningless. Several features are processed in the order in
which they are entered. The maximum number of features is limited to 100.
Parameter
. Regions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
Regions to be examined.
. Image (input iconic) . . . . . . image ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2, uint2, int4,
real )
Gray value image.
. SelectedRegions (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX
Regions having features within the limits.
. Features (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Names of the features.
Default Value : ’mean’
List of values : Features ∈ {’area’, ’row’, ’column’, ’ra’, ’rb’, ’phi’, ’min’, ’max’, ’mean’, ’deviation’,
’plane_deviation’, ’anisotropy’, ’entropy’, ’fuzzy_entropy’, ’fuzzy_perimeter’, ’moments_row’,
’moments_column’, ’alpha’, ’beta’}
. Operation (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Logical connection of features.
Default Value : ’and’
List of values : Operation ∈ {’and’, ’or’}
. Min (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( integer, real )
Lower limit(s) of features.
Default Value : 128.0
Suggested values : Min ∈ {0.5, 1.0, 10.0, 20.0, 50.0, 128.0, 255.0, 1000.0}
. Max (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( integer, real )
Upper limit(s) of features.
Default Value : 255.0
Suggested values : Max ∈ {0.5, 1.0, 10.0, 20.0, 50.0, 128.0, 255.0, 1000.0}
Complexity
If F is the area of the region and N the number of features the runtime complexity is O(F ∗ N ).
Result
The operator SelectGray returns the value TRUE if the input image has the defined gray values and the
parameters are correct. The behavior in case of empty input (no input images available) is set via the opera-
tor SetSystem(::’noObjectResult’,<Result>:), the behavior in case of empty region is set via
SetSystem(::’emptyRegionResult’,<Result>:). If necessary an exception handling is raised.
Parallelization Information
SelectGray is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Connection, MeanImage, EntropyImage, SobelAmp, MedianSeparate
Possible Successors
SelectShape, SelectGray, ShapeTrans, ReduceDomain, CountObj
See also
DeviationImage, EntropyGray, Intensity, MeanImage, MinMaxGray, SelectObj
Module
Foundation

[out] VARIANT AbsoluteHisto HRegionX.ShapeHistoAll ([in] HImageX Image,


[in] String Feature, [out] VARIANT RelativeHisto )
void HOperatorSetX.ShapeHistoAll ([in] IHObjectX Region,
[in] IHObjectX Image, [in] VARIANT Feature, [out] VARIANT AbsoluteHisto,
[out] VARIANT RelativeHisto )

Determine a histogram of features along all threshold values.

HALCON/COM Reference Manual, 2008-5-13


5.6. FEATURES 509

The operator ShapeHistoAll carries out 255 threshold operations within Region with the gray values of
Image. The entry i in the histogram corresponds to the number of connected components/holes of this image
segmented with the threshold i (Feature = ’connected_components’, ’holes’) or the mean value of the feature
values of the regions segmented in this way (Feature = ’convexity’, ’compactness’, ’ansisometry’), respectively.
The histogram can also be displayed directly as a graphic via the operators SetPaint(::
WindowHandle,’componentHistogram’:) and DispImage.
Attention
The operator ShapeHistoAll expects a region and exactly one gray value image as input. Because of the
power of this operator the runtime of ShapeHistoAll is relatively large!
Parameter
. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
Region in which the features are to be examined.
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte )
Gray value image.
. Feature (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Feature to be examined.
Default Value : ’connected_components’
List of values : Feature ∈ {’connected_components’, ’convexity’, ’compactness’, ’anisometry’, ’holes’}
. AbsoluteHisto (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . histogram ; VARIANT ( integer, real )
Absolute distribution of the feature.
. RelativeHisto (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . histogram ; VARIANT ( real )
Relative distribution of the feature.
Example

/* Simulation von shape_histo_all mit Merkmal ’connected_components’: */


my_shape_histo_all(Region,Image,AbsHisto,RelHisto):
reduce_domain(Region,Image,RegionGray)
for(0,255,i)
threshold(RegionGray,Seg,i,255)
connect_and_holes(Seg,AbsHisto[i],_)
clear_obj([Seg,H])
end_for()
eval(0,Sum)
for(0,255,i)
eval(Sum+AbsHisto[i],Sum)
end_for()
for(0,255,i)
eval(AbsHisto[i]/Sum,RelHisto[i])
end_for()

Complexity
If F is the area
√ √ of the input region and N the mean number of connected components the runtime complexity is
O(255(F + F N )).
Result
The operator ShapeHistoAll returns the value TRUE if an image with the defined gray values is en-
tered. The behavior in case of empty input (no input images) is set via the operator SetSystem(::
’noObjectResult’,<Result>:), the behavior in case of empty region is set via SetSystem(::
’emptyRegionResult’,<Result>:). If necessary an exception handling is raised.
Parallelization Information
ShapeHistoAll is reentrant and processed without parallelization.
Possible Successors
HistoToThresh, Threshold, GenRegionHisto
See also
Connection, Convexity, Compactness, ConnectAndHoles, EntropyGray, GrayHisto,
SetPaint, CountObj

HALCON 8.0.2
510 CHAPTER 5. IMAGE

Alternatives
ShapeHistoPoint
Module
Foundation

[out] VARIANT AbsoluteHisto HRegionX.ShapeHistoPoint


([in] HImageX Image, [in] String Feature, [in] long Row, [in] long Column,
[out] VARIANT RelativeHisto )
void HOperatorSetX.ShapeHistoPoint ([in] IHObjectX Region,
[in] IHObjectX Image, [in] VARIANT Feature, [in] VARIANT Row,
[in] VARIANT Column, [out] VARIANT AbsoluteHisto,
[out] VARIANT RelativeHisto )

Determine a histogram of features along all threshold values.


Like ShapeHistoAll the operator ShapeHistoPoint carries out 255 threshold value operations within
Region with the gray values of Image. Contrary to ShapeHistoAll only the segmented region containing
the pixel (Row, Column) is taken into account here. The entry i in the histogram then corresponds to the number
of holes of this region segmented with the threshold i (Feature = ’holes’) or the feature value of the region
(Feature = ’convexity’, ’compactness’, ’ansisometry’), respectively.
The histogram can also be displayed directly as a graphic via the operators SetPaint(::
WindowHandle,’componentHistogram’:) and DispImage.
Parameter
. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
Region in which the features are to be examined.
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte )
Gray value image.
. Feature (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Feature to be examined.
Default Value : ’convexity’
List of values : Feature ∈ {’convexity’, ’compactness’, ’anisometry’, ’holes’}
. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; long / VARIANT
Row of the pixel which the region must contain.
Default Value : 256
Suggested values : Row ∈ {10, 50, 100, 200, 300, 400}
. Column (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; long / VARIANT
Column of the pixel which the region must contain.
Default Value : 256
Suggested values : Column ∈ {10, 50, 100, 200, 300, 400}
. AbsoluteHisto (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . histogram ; VARIANT ( integer, real )
Absolute distribution of the feature.
. RelativeHisto (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . histogram ; VARIANT ( real )
Relative distribution of the feature.
Result
The operator ShapeHistoPoint returns the value TRUE if an image with defined gray values is entered.
The behavior in case of empty input (no input images available) is set via the operator SetSystem(::
’noObjectResult’,<Result>:), the behavior in case of empty region is set via SetSystem(::
’emptyRegionResult’,<Result>:). If necessary an exception handling is raised.
Parallelization Information
ShapeHistoPoint is reentrant and processed without parallelization.
Possible Predecessors
GetMbutton, AreaCenter
Possible Successors
HistoToThresh, Threshold, GenRegionHisto

HALCON/COM Reference Manual, 2008-5-13


5.7. FORMAT 511

See also
Connection, ConnectAndHoles, Convexity, Compactness, SetPaint
Alternatives
ShapeHistoAll
Module
Foundation

5.7 Format
[out] HImageX ImagePart HImageX.ChangeFormat ([in] long Width,
[in] long Height )
void HOperatorSetX.ChangeFormat ([in] IHObjectX Image,
[out] HUntypedObjectX ImagePart, [in] VARIANT Width, [in] VARIANT Height )

Change image size.


The operator ChangeFormat increases or decreases the size of the input images to the indicated height or width,
respectively. If the image is reduced, parts are cut off at the “right” or “lower” edge of the image, respectively.
If the image is enlarged, the additional areas are set to 0. The definition domain of the new image is equal to the
domain of the input image, clipped to the size of the new image. No zooming is carried out.
Parameter

. Image (input iconic) . . . . . . image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2,
uint2, int4, real, complex, vector_field )
Input image.
. ImagePart (output iconic) . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, direction, cyclic,
int1, int2, uint2, int4, real, complex, vector_field )
Image with new format.
. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; long / VARIANT
Width of new image.
Default Value : 512
Suggested values : Width ∈ {32, 64, 128, 256, 512, 768, 1024}
. Height (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; long / VARIANT
Height of new image.
Default Value : 512
Suggested values : Height ∈ {32, 64, 128, 256, 512, 525, 1024}
Parallelization Information
ChangeFormat is reentrant and automatically parallelized (on tuple level).
Possible Successors
DispImage
See also
ZoomImageSize, ZoomImageFactor
Alternatives
CropPart
Module
Foundation

HImageX.CropDomain ( )
[out] HImageX ImagePart
void HOperatorSetX.CropDomain ([in] IHObjectX Image,
[out] HUntypedObjectX ImagePart )

Cut out of defined gray values.

HALCON 8.0.2
512 CHAPTER 5. IMAGE

The operator CropDomain cuts a rectangular area from the input images. This rectangle is the smallest sur-
rounding rectangle of the domain of the imput image. The new definition domain includes all pixels of the new
image. The new image matrix has the size of the rectangle.
Parameter
. Image (input iconic) . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic,
int1, int2, uint2, int4, real )
Input image.
. ImagePart (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX ( byte,
direction, cyclic, int1, int2, uint2, int4,
real )
Image area.
Parallelization Information
CropDomain is reentrant and automatically parallelized (on tuple level).
Possible Successors
DispImage
See also
ZoomImageSize, ZoomImageFactor
Alternatives
CropPart, CropRectangle1, ChangeFormat, ReduceDomain
Module
Foundation

[out] HImageX ImagePart HImageX.CropDomainRel ([in] long Top,


[in] long Left, [in] long Bottom, [in] long Right )
void HOperatorSetX.CropDomainRel ([in] IHObjectX Image,
[out] HUntypedObjectX ImagePart, [in] VARIANT Top, [in] VARIANT Left,
[in] VARIANT Bottom, [in] VARIANT Right )

Cut out an image area relative to the domain.


CropDomainRel cuts a rectangular area from the input images. The area is determined by the surrounding
rectangle of the domain of the input image. The rectangle can be influenced by the control parameters to modify
at the top (Top), at the left (Left), at the bottom (Bottom), and at the right (Right). Positive values results in
a smaller, negative values in a larger size. If all parameters are set to zero, the region remains unchanged.
Parameter
. Image (input iconic) . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic,
int1, int2, uint2, int4, real )
Input image.
. ImagePart (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX ( byte,
direction, cyclic, int1, int2, uint2, int4,
real )
Image area.
. Top (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of rows clipped at the top.
Default Value : -1
Suggested values : Top ∈ {-20, -10, -5, -3, -2, -1, 0, 1, 2, 3, 4, 5, 10, 20}
. Left (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of columns clipped at the left.
Default Value : -1
Suggested values : Left ∈ {-20, -10, -5, -3, -2, -1, 0, 1, 2, 3, 4, 5, 10, 20}
. Bottom (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of rows clipped at the bottom.
Default Value : -1
Suggested values : Bottom ∈ {-20, -10, -5, -3, -2, -1, 0, 1, 2, 3, 4, 5, 10, 20}

HALCON/COM Reference Manual, 2008-5-13


5.7. FORMAT 513

. Right (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT


Number of columns clipped at the right.
Default Value : -1
Suggested values : Right ∈ {-20, -10, -5, -3, -2, -1, 0, 1, 2, 3, 4, 5, 10, 20}
Result
CropDomainRel returns TRUE if all parameters are correct. The behavior in case of empty input (no regions
given) can be set via SetSystem(’noObjectResult’,<Result>) and the behavior in case of an empty
input region via SetSystem(’emptyRegionResult’,<Result>). If necessary, an exception handling is
raised.
Parallelization Information
CropDomainRel is reentrant and automatically parallelized (on tuple level, channel level).
Possible Predecessors
ReduceDomain, Threshold, Connection, Regiongrowing, Pouring
See also
SmallestRectangle1, Intersection, GenRectangle1, ClipRegion
Alternatives
CropDomain, CropRectangle1
Module
Foundation

[out] HImageX ImagePart HImageX.CropPart ([in] long Row, [in] long Column,
[in] long Width, [in] long Height )
void HOperatorSetX.CropPart ([in] IHObjectX Image,
[out] HUntypedObjectX ImagePart, [in] VARIANT Row, [in] VARIANT Column,
[in] VARIANT Width, [in] VARIANT Height )

Cut out a rectangular image area.


The operator CropPart cuts a rectangular area from the input images. The area is indicated by a rectangle
(upper left corner and size). The area must be within the image. The definition domain includes all pixels of the
new image. The new image matrix has the size of a rectangle.
Parameter

. Image (input iconic) . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic,


int1, int2, uint2, int4, real )
Input image.
. ImagePart (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX ( byte,
direction, cyclic, int1, int2, uint2, int4,
real )
Image area.
. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.origin.y ; long / VARIANT
Line index of upper left corner of image area.
Default Value : 100
Suggested values : Row ∈ {10, 20, 50, 100, 200, 300, 500}
Typical range of values : 0 ≤ Row ≤ 0
. Column (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.origin.x ; long / VARIANT
Column index of upper left corner of image area.
Default Value : 100
Suggested values : Column ∈ {10, 20, 50, 100, 200, 300, 500}
Typical range of values : 0 ≤ Column ≤ 0
. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.extent.x ; long / VARIANT
Width of new image.
Default Value : 128
Suggested values : Width ∈ {32, 64, 128, 256, 512, 768}
Typical range of values : 0 ≤ Width ≤ 0

HALCON 8.0.2
514 CHAPTER 5. IMAGE

. Height (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.extent.y ; long / VARIANT


Height of new image.
Default Value : 128
Suggested values : Height ∈ {32, 64, 128, 256, 512, 525}
Typical range of values : 0 ≤ Height ≤ 0
Parallelization Information
CropPart is reentrant and automatically parallelized (on tuple level).
Possible Successors
DispImage
See also
ZoomImageSize, ZoomImageFactor
Alternatives
CropRectangle1, CropDomain, ChangeFormat, ReduceDomain
Module
Foundation

[out] HImageX ImagePart HImageX.CropRectangle1 ([in] long Row1,


[in] long Column1, [in] long Row2, [in] long Column2 )
void HOperatorSetX.CropRectangle1 ([in] IHObjectX Image,
[out] HUntypedObjectX ImagePart, [in] VARIANT Row1, [in] VARIANT Column1,
[in] VARIANT Row2, [in] VARIANT Column2 )

Cut out a rectangular image area.


The operator CropRectangle1 cuts a rectangular area from the input images. The area is indicated by a
rectangle (upper left and lower right corner). The area must be within the image. The definition domain includes
all pixels of the new image. The new image matrix has the size of a rectangle.
Parameter
. Image (input iconic) . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic,
int1, int2, uint2, int4, real )
Input image.
. ImagePart (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX ( byte,
direction, cyclic, int1, int2, uint2, int4,
real )
Image area.
. Row1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.origin.y ; long / VARIANT
Line index of upper left corner of image area.
Default Value : 100
Suggested values : Row1 ∈ {10, 20, 50, 100, 200, 300, 500}
Typical range of values : 0 ≤ Row1 ≤ 0
. Column1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.origin.x ; long / VARIANT
Column index of upper left corner of image area.
Default Value : 100
Suggested values : Column1 ∈ {10, 20, 50, 100, 200, 300, 500}
Typical range of values : 0 ≤ Column1 ≤ 0
. Row2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.corner.y ; long / VARIANT
Line index of lower right corner of image area.
Default Value : 200
Suggested values : Row2 ∈ {10, 20, 50, 100, 200, 300, 500}
Typical range of values : 0 ≤ Row2 ≤ 0
. Column2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.corner.x ; long / VARIANT
Column index of lower right corner of image area.
Default Value : 200
Suggested values : Column2 ∈ {10, 20, 50, 100, 200, 300, 500}
Typical range of values : 0 ≤ Column2 ≤ 0

HALCON/COM Reference Manual, 2008-5-13


5.7. FORMAT 515

Parallelization Information
CropRectangle1 is reentrant and automatically parallelized (on tuple level).
Possible Successors
DispImage
See also
ZoomImageSize, ZoomImageFactor
Alternatives
CropPart, CropDomain, ChangeFormat, ReduceDomain
Module
Foundation

[out] HImageX TiledImage HImageX.TileChannels ([in] long NumColumns,


[in] String TileOrder )
void HOperatorSetX.TileChannels ([in] IHObjectX Image,
[out] HUntypedObjectX TiledImage, [in] VARIANT NumColumns,
[in] VARIANT TileOrder )

Tile multiple images into a large image.


TileChannels tiles an image consisting of multiple channels into a large single-channel image. The input
image Image contains Num images of the same size, which are stored in the individual channels. The out-
put image TiledImage contains a single channel image, where the Num input channels have been tiled into
NumColumns columns. In particular, this means that TileChannels cannot tile color images. For this pur-
pose, TileImages can be used. The parameter TileOrder determines the order in which the images are
copied into the output in the cases in which this is not already determined by NumColumns (i.e., if NumColumns
!= 1 and NumColumns != Num). If TileOrder = ’horizontal’ the images are copied in the horizontal direction,
i.e., the second channel of Image will be to the right of the first channel. If TileOrder = ’vertical’ the images
are copied in the vertical direction, i.e., the second channel of Image will be below the first channel. The domain
of TiledImage is obtained by copying the domain of Image to the corresponding locations in the output im-
age. If Num is not a multiple of NumColumns the output image will have undefined gray values in the lower right
corner of the image. The output domain will reflect this.
Attention

Parameter
. Image (input iconic) . . . . . . multichannel-image-array ; HImageX / IHObjectX ( byte, direction, cyclic,
int1, int2, uint2, int4, real )
Input image.
. TiledImage (output iconic) . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, direction,
cyclic, int1, int2, uint2, int4, real )
Tiled output image.
. NumColumns (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of columns to use for the output image.
Default Value : 1
Suggested values : NumColumns ∈ {1, 2, 3, 4, 5, 6, 7}
Restriction : (N umColumns ≥ 1)
. TileOrder (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Order of the input images in the output image.
Default Value : ’vertical’
List of values : TileOrder ∈ {’horizontal’, ’vertical’}
Example

/* Grab 5 single-channel images and stack them vertically. */


gen_rectangle1 (Image, 0, 0, Height-1, Width-1)
for I := 1 to 5 by 1

HALCON 8.0.2
516 CHAPTER 5. IMAGE

grab_image_async (ImageGrabbed, FGHandle, -1)


append_channel (Image, ImageGrabbed, Image)
endfor
tile_channels (Image, TiledImage, 1, ’vertical’)

Result
TileChannels returns TRUE if all parameters are correct and no error occurs during execution. If the input
is empty the behavior can be set via SetSystem(::’noObjectResult’,<Result>:). If necessary, an
exception handling is raised.
Parallelization Information
TileChannels is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
AppendChannel
See also
ChangeFormat, CropPart, CropRectangle1
Alternatives
TileImages, TileImagesOffset
Module
Foundation

[out] HImageX TiledImage HImageX.TileImages ([in] long NumColumns,


[in] String TileOrder )
void HOperatorSetX.TileImages ([in] IHObjectX Images,
[out] HUntypedObjectX TiledImage, [in] VARIANT NumColumns,
[in] VARIANT TileOrder )

Tile multiple image objects into a large image.


TileImages tiles multiple input image objects, which must contain the same number of channels, into a large
image. The input image object Images contains Num images, which may be of different size. The output image
TiledImage contains as many channels as the input images. In the output image the Num input images have been
tiled into NumColumns columns. Each tile has the same size, which is determined by the maximum width and
height of all input images. If an input image is smaller than the tile size it is copied to the center of the respective
tile. The parameter TileOrder determines the order in which the images are copied into the output in the cases
in which this is not already determined by NumColumns (i.e., if NumColumns != 1 and NumColumns != Num).
If TileOrder = ’horizontal’ the images are copied in the horizontal direction, i.e., the second image of Images
will be to the right of the first image. If TileOrder = ’vertical’ the images are copied in the vertical direction,
i.e., the second image of Images will be below the first image. The domain of TiledImage is obtained by
copying the domains of Images to the corresponding locations in the output image. If Num is not a multiple of
NumColumns the output image will have undefined gray values in the lower right corner of the image. The output
domain will reflect this.
Attention

Parameter

. Images (input iconic) . . . . . . (multichannel-)image ; HImageX / IHObjectX ( byte, direction, cyclic, int1,
int2, uint2, int4, real )
Input images.
. TiledImage (output iconic) . . . . . . (multichannel-)image ; HImageX / HUntypedObjectX ( byte, direc-
tion, cyclic, int1, int2, uint2, int4, real )
Tiled output image.

HALCON/COM Reference Manual, 2008-5-13


5.7. FORMAT 517

. NumColumns (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT


Number of columns to use for the output image.
Default Value : 1
Suggested values : NumColumns ∈ {1, 2, 3, 4, 5, 6, 7}
Restriction : (N umColumns ≥ 1)
. TileOrder (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Order of the input images in the output image.
Default Value : ’vertical’
List of values : TileOrder ∈ {’horizontal’, ’vertical’}
Example

/* Grab 5 (multi-channel) images and stack them vertically. */


gen_empty_obj (Images)
for I := 1 to 5 by 1
grab_image_async (ImageGrabbed, FGHandle, -1)
concat_obj (Images, ImageGrabbed, Images)
endfor
tile_images (Images, TiledImage, 1, ’vertical’)

Result
TileImages returns TRUE if all parameters are correct and no error occurs during execution. If the input is
empty the behavior can be set via SetSystem(::’noObjectResult’,<Result>:). If necessary, an
exception handling is raised.
Parallelization Information
TileImages is reentrant and automatically parallelized (on channel level).
Possible Predecessors
AppendChannel
See also
ChangeFormat, CropPart, CropRectangle1
Alternatives
TileChannels, TileImagesOffset
Module
Foundation

[out] HImageX TiledImage HImageX.TileImagesOffset


([in] VARIANT OffsetRow, [in] VARIANT OffsetCol, [in] VARIANT Row1,
[in] VARIANT Col1, [in] VARIANT Row2, [in] VARIANT Col2, [in] long Width,
[in] long Height )
void HOperatorSetX.TileImagesOffset ([in] IHObjectX Images,
[out] HUntypedObjectX TiledImage, [in] VARIANT OffsetRow,
[in] VARIANT OffsetCol, [in] VARIANT Row1, [in] VARIANT Col1,
[in] VARIANT Row2, [in] VARIANT Col2, [in] VARIANT Width,
[in] VARIANT Height )

Tile multiple image objects into a large image with explicit positioning information.
TileImagesOffset tiles multiple input image objects, which must contain the same number of channels, into
a large image. The input image object Images contains Num images, which may be of different size. The output
image TiledImage contains as many channels as the input images. The size of the output image is determined
by the parameters Width and Height. The position of the upper left corner of the input images in the output
images is determined by the parameters OffsetRow and OffsetCol. Both parameters must contain exactly
Num values. Optionally, each input image can be cropped to an arbitrary rectangle that is smaller than the input
image. To do so, the parameters Row1, Col1, Row2, and Col2 must be set accordingly. If any of these four
parameters is set to -1, the corresponding input image is not cropped. In any case, all four parameters must contain

HALCON 8.0.2
518 CHAPTER 5. IMAGE

Num values. If the input images are cropped the position parameters OffsetRow and OffsetCol refer to the
upper left corner of the cropped image. If the input images overlap each other in the output image (while taking
into account their respective domains), the image with the higher index in Images overwrites the image data of
the image with the lower index. The domain of TiledImage is obtained by copying the domains of Images to
the corresponding locations in the output image.
Attention
If the input images all have the same size and tile the output image exactly, the operator TileImages usually
will be slightly faster.
Parameter
. Images (input iconic) . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, direction,
cyclic, int1, int2, uint2, int4, real )
Input images.
. TiledImage (output iconic) . . . . . . (multichannel-)image ; HImageX / HUntypedObjectX ( byte, direc-
tion, cyclic, int1, int2, uint2, int4, real )
Tiled output image.
. OffsetRow (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( integer )
Row coordinate of the upper left corner of the input images in the output image.
Default Value : 0
Suggested values : OffsetRow ∈ {0, 50, 100, 150, 200, 250}
. OffsetCol (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( integer )
Column coordinate of the upper left corner of the input images in the output image.
Default Value : 0
Suggested values : OffsetCol ∈ {0, 50, 100, 150, 200, 250}
. Row1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.origin.y(-array) ; VARIANT ( integer )
Row coordinate of the upper left corner of the copied part of the respective input image.
Default Value : -1
Suggested values : Row1 ∈ {-1, 0, 10, 20, 50, 100, 200, 300, 500}
. Col1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.origin.x(-array) ; VARIANT ( integer )
Column coordinate of the upper left corner of the copied part of the respective input image.
Default Value : -1
Suggested values : Col1 ∈ {-1, 0, 10, 20, 50, 100, 200, 300, 500}
. Row2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.corner.y(-array) ; VARIANT ( integer )
Row coordinate of the lower right corner of the copied part of the respective input image.
Default Value : -1
Suggested values : Row2 ∈ {-1, 0, 10, 20, 50, 100, 200, 300, 500}
. Col2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.corner.x(-array) ; VARIANT ( integer )
Column coordinate of the lower right corner of the copied part of the respective input image.
Default Value : -1
Suggested values : Col2 ∈ {-1, 0, 10, 20, 50, 100, 200, 300, 500}
. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; long / VARIANT
Width of the output image.
Default Value : 512
Suggested values : Width ∈ {32, 64, 128, 256, 512, 768, 1024, 2048, 4096}
. Height (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; long / VARIANT
Height of the output image.
Default Value : 512
Suggested values : Height ∈ {32, 64, 128, 256, 512, 525, 1024, 2048, 4096}
Example

/* Example 1 */
/* Grab 2 (multi-channel) NTSC images, crop the bottom 5 lines off */
/* of each image, the right 5 columns off of the first image, and */
/* the left five lines off of the second image, and put the cropped */
/* images side-by-side. */
gen_empty_obj (Images)
for I := 1 to 2 by 1

HALCON/COM Reference Manual, 2008-5-13


5.8. MANIPULATION 519

grab_image_async (ImageGrabbed, FGHandle, -1)


concat_obj (Images, ImageGrabbed, Images)
endfor
tile_images_offset (Images, TiledImage, [0,635], [0,0], [0,0],
[0,5], [474,474], [634,639])

/* Example 2 */
/* Enlarge image by 15 rows and columns on all sides */
EnlargeColsBy := 15
EnlargeRowsBy := 15
get_image_pointer1 (Image, Pointer, Type, WidthImage, HeightImage)
tile_images_offset (Image, EnlargedImage, EnlargeRowsBy, EnlargeColsBy,
-1, -1, -1, -1, WidthImage + EnlargeColsBy*2,
HeightImage + EnlargeRowsBy*2)

Result
TileImagesOffset returns TRUE if all parameters are correct and no error occurs during execution. If the
input is empty the behavior can be set via SetSystem(::’noObjectResult’,<Result>:). If necessary,
an exception handling is raised.
Parallelization Information
TileImagesOffset is reentrant and automatically parallelized (on channel level).
Possible Predecessors
AppendChannel
See also
ChangeFormat, CropPart, CropRectangle1
Alternatives
TileChannels, TileImages
Module
Foundation

5.8 Manipulation

void HImageX.OverpaintGray ([in] HImageX ImageSource )


void HOperatorSetX.OverpaintGray ([in] IHObjectX ImageDestination,
[in] IHObjectX ImageSource )

Overpaint the gray values of an image.


OverpaintGray copies the gray values of the image given in ImageSource into the image in
ImageDestination. Only the gray values of the domain of ImageSource are copied (see
ReduceDomain).
If you do not want to modify ImageDestination itself, you can use the operator PaintGray, which returns
the result in a newly created image.
Attention
OverpaintGray modifies the content of an already existing image (ImageDestination). Besides, even
other image objects may be affected: For example, if you created ImageDestination via CopyObj from
another image object (or vice versa), OverpaintGray will also modify the image matrix of this other image
object. Therefore, OverpaintGray should only be used to overpaint newly created image objects. Typical op-
erators for this task are, e.g., GenImageConst (creates a new image with a specified size), GenImageProto
(creates an image with the size of a specified prototype image) or CopyImage (creates an image as the copy of a
specified image).

HALCON 8.0.2
520 CHAPTER 5. IMAGE

Parameter

. ImageDestination (input iconic) . . . . . . image ; HImageX / IHObjectX ( byte, direction, cyclic, int1,
int2, uint2, int4, real, complex, vector_field )
Input image to be painted over.
. ImageSource (input iconic) . . . . . . image ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2,
uint2, int4, real, complex, vector_field )
Input image containing the desired gray values.
Example

/* Copy a circular part of the image ’monkey’ into a new image (New1): */

read_image(Image,’monkey’)
gen_circle(Circle,200,200,150)
reduce_domain(Image,Circle,Mask)
/* New image with black (0) background */
gen_image_proto(Image,New1,0.0)
/* Copy a part of the image ’monkey’ into New1 */
overpaint_gray(New1,Mask).

Result
OverpaintGray returns TRUE if all parameters are correct. If necessary, an exception is raised.
Parallelization Information
OverpaintGray is reentrant and processed without parallelization.
Possible Predecessors
ReadImage, GenImageConst, GenImageProto
See also
PaintRegion, OverpaintRegion
Alternatives
GetImagePointer1, PaintGray, SetGrayval, CopyImage
Module
Foundation

void HImageX.OverpaintRegion ([in] HRegionX Region,


[in] VARIANT Grayval, [in] String Type )
void HRegionX.OverpaintRegion ([in] HImageX Image,
[in] VARIANT Grayval, [in] String Type )
void HOperatorSetX.OverpaintRegion ([in] IHObjectX Image,
[in] IHObjectX Region, [in] VARIANT Grayval, [in] VARIANT Type )

Overpaint regions in an image.


OverpaintRegion paints the regions given in Region with a constant gray value into the image given in
Image. These gray values can either be specified for each channel once, valid for all regions, or for each region
separately. To define the latter, group the channel gray values g of each region and concatenate them to a tuple
according to the regions’ order, e.g., for a three channel image:

[g(channel1,region1), g(channel2,region1), g(channel3,region1), g(channel1,region2), . . .]

The parameter Type determines whether the region should be painted filled (’fill’) or whether only its boundary
should be painted (’margin’).
If you do not want to modify Image itself, you can use the operator PaintRegion, which returns the result in
a newly created image.

HALCON/COM Reference Manual, 2008-5-13


5.8. MANIPULATION 521

Attention
OverpaintRegion modifies the content of an already existing image (Image). Besides, even other image
objects may be affected: For example, if you created Image via CopyObj from another image object (or
vice versa), OverpaintRegion will also modify the image matrix of this other image object. Therefore,
OverpaintRegion should only be used to overpaint newly created image objects. Typical operators for this
task are, e.g., GenImageConst (creates a new image with a specified size), GenImageProto (creates an
image with the size of a specified prototype image) or CopyImage (creates an image as the copy of a specified
image).
Parameter

. Image (input iconic) . . . . . . image ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2, uint2, int4,
real, complex )
Image in which the regions are to be painted.
. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Regions to be painted into the input image.
. Grayval (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( integer, real )
Desired gray values of the regions.
Default Value : 255.0
Suggested values : Grayval ∈ {0.0, 1.0, 2.0, 5.0, 10.0, 16.0, 32.0, 64.0, 128.0, 253.0, 254.0, 255.0}
. Type (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Paint regions filled or as boundaries.
Default Value : ’fill’
List of values : Type ∈ {’fill’, ’margin’}
Example

/* Paint a rectangle into a new image (New1) */

gen_rectangle1(Rectangle,100.0,100.0,300.0,300.0)
/* generate a black image */
gen_image_const(New1,"byte", 768, 576)
/* paint a white rectangle */
overpaint_region(New1,Rectangle,255.0,’fill’,).

Result
OverpaintRegion returns TRUE if all parameters are correct. If the input is empty the behavior can be set via
SetSystem(::’noObjectResult’,<Result>:). If necessary, an exception is raised.
Parallelization Information
OverpaintRegion is reentrant and processed without parallelization.
Possible Predecessors
ReadImage, GenImageConst, GenImageProto, ReduceDomain
See also
ReduceDomain, SetDraw, PaintGray, OverpaintGray, GenImageConst
Alternatives
SetGrayval, PaintRegion, PaintXld
Module
Foundation

[out] HImageX MixedImage HImageX.PaintGray


([in] HImageX ImageDestination )
void HOperatorSetX.PaintGray ([in] IHObjectX ImageSource,
[in] IHObjectX ImageDestination, [out] HUntypedObjectX MixedImage )

Paint the gray values of an image into another image.

HALCON 8.0.2
522 CHAPTER 5. IMAGE

PaintGray paints the gray values of the image given in ImageSource into the image in
ImageDestination and returns the resulting image in MixedImage. Only the gray values of the domain
of ImageSource are copied (see ReduceDomain).
As an alternative to PaintGray, you can use the operator OverpaintGray, which directly paints the gray
values into ImageDestination.
Parameter
. ImageSource (input iconic) . . . . . . image ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2,
uint2, int4, real, complex, vector_field )
Input image containing the desired gray values.
. ImageDestination (input iconic) . . . . . . image ; HImageX / IHObjectX ( byte, direction, cyclic, int1,
int2, uint2, int4, real, complex, vector_field )
Input image to be painted over.
. MixedImage (output iconic) . . . . . . image ; HImageX / HUntypedObjectX ( byte, direction, cyclic, int1,
int2, uint2, int4, real, complex, vector_field )
Result image.
Example

/* Copy a circular part of the image ’monkey’ into the image ’fabrik’: */

read_image(Image,’monkey’)
gen_circle(Circle,200,200,150)
reduce_domain(Image,Circle,Mask)
read_image(Image2,’fabrik’)
/* Copy a part of the image ’monkey’ into ’fabrik’ */
paint_gray(Mask,Image2,MixedImage).

Result
PaintGray returns TRUE if all parameters are correct. If necessary, an exception is raised.
Parallelization Information
PaintGray is reentrant and processed without parallelization.
Possible Predecessors
ReadImage, GenImageConst, GenImageProto
See also
PaintRegion, OverpaintRegion
Alternatives
GetImagePointer1, SetGrayval, CopyImage, OverpaintGray
Module
Foundation

[out] HImageX ImageResult HRegionX.PaintRegion ([in] HImageX Image,


[in] VARIANT Grayval, [in] String Type )
[out] HImageX ImageResult HImageX.PaintRegion ([in] HRegionX Region,
[in] VARIANT Grayval, [in] String Type )
void HOperatorSetX.PaintRegion ([in] IHObjectX Region,
[in] IHObjectX Image, [out] HUntypedObjectX ImageResult,
[in] VARIANT Grayval, [in] VARIANT Type )

Paint regions into an image.


PaintRegion paints the regions given in Region with a constant gray value into the image given in Image
and returns the result in ImageResult. These gray values can either be specified for each channel once, valid
for all regions, or for each region separately. To define the latter, group the channel gray values g of each region
and concatenate them to a tuple according to the regions’ order, e.g., for a three channel image:

HALCON/COM Reference Manual, 2008-5-13


5.8. MANIPULATION 523

[g(channel1,region1), g(channel2,region1), g(channel3,region1), g(channel1,region2), . . .]

The parameter Type determines whether the region should be painted filled (’fill’) or whether only its boundary
should be painted (’margin’).
As an alternative to PaintRegion, you can use the operator OverpaintRegion, which directly paints the
regions into Image.
Parameter

. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Regions to be painted into the input image.
. Image (input iconic) . . . . . . image ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2, uint2, int4,
real, complex )
Image in which the regions are to be painted.
. ImageResult (output iconic) . . . . . . image ; HImageX / HUntypedObjectX ( byte, direction, cyclic, int1,
int2, uint2, int4, real, complex )
Image containing the result.
. Grayval (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( integer, real )
Desired gray values of the regions.
Default Value : 255.0
Suggested values : Grayval ∈ {0.0, 1.0, 2.0, 5.0, 10.0, 16.0, 32.0, 64.0, 128.0, 253.0, 254.0, 255.0}
. Type (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Paint regions filled or as boundaries.
Default Value : ’fill’
List of values : Type ∈ {’fill’, ’margin’}
Example

/* Paint a rectangle into the image ’monkey’ */

read_image(Image,’monkey’)
gen_rectangle1(Rectangle,100.0,100.0,300.0,300.0)
/* paint a white rectangle */
paint_region(Rectangle,Image,ImageResult,255.0,’fill’,).

Result
PaintRegion returns TRUE if all parameters are correct. If the input is empty the behavior can be set via
SetSystem(::’noObjectResult’,<Result>:). If necessary, an exception is raised.
Parallelization Information
PaintRegion is reentrant and processed without parallelization.
Possible Predecessors
ReadImage, GenImageConst, GenImageProto, ReduceDomain
See also
ReduceDomain, PaintGray, OverpaintGray, SetDraw, GenImageConst
Alternatives
SetGrayval, OverpaintRegion, PaintXld
Module
Foundation

HALCON 8.0.2
524 CHAPTER 5. IMAGE

[out] HImageX ImageResult HXLDX.PaintXld ([in] HImageX Image,


[in] VARIANT Grayval )
[out] HImageX ImageResult HImageX.PaintXld ([in] IHXLDX XLD,
[in] VARIANT Grayval )
void HOperatorSetX.PaintXld ([in] IHObjectX XLD, [in] IHObjectX Image,
[out] HUntypedObjectX ImageResult, [in] VARIANT Grayval )

Paint XLD objects into an image.


PaintXld paints the XLD objects XLD of type contour or polygon with the constant gray values Grayval into
each channel of the background image given in Image and returns the result in ImageResult. Open contours
of XLD objects are closed and their enclosed regions are filled up. The rim of the subpixel XLD objects is painted
onto the background image using anti-aliasing. Note that only objects without crossings or touching segments are
painted correctly.
Grayval contains the gray values for painting the XLD objects. These gray values can either be specified for
each channel once, valid for all XLD objects, or for each XLD object separately. To define the latter, group the
channel gray values g of each XLD object and concatenate them to a tuple according to the order of the XLD
objects, e.g., for a three channel image:

[g(channel1,xld1), g(channel2,xld1), g(channel3,xld1), g(channel1,xld2), . . .]

Parameter
. XLD (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xld(-array) ; IHXLDX / IHObjectX
XLD objects to be painted into the input image.
. Image (input iconic) . . . . . . image ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2, uint2, int4,
real, complex )
Image in which the xld objects are to be painted.
. ImageResult (output iconic) . . . . . . image ; HImageX / HUntypedObjectX ( byte, direction, cyclic, int1,
int2, uint2, int4, real, complex )
Image containing the result.
. Grayval (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( integer, real )
Desired gray value of the xld object.
Default Value : 255.0
Suggested values : Grayval ∈ {0.0, 1.0, 2.0, 5.0, 10.0, 16.0, 32.0, 64.0, 128.0, 253.0, 254.0, 255.0}
Example

/* Paint colored xld objects into a gray image */

/* read and copy image to generate a three channel image */


read_image(Image1,’green-dot’)
copy_image(Image1,Image2)
copy_image(Image1,Image3)
compose3(Image1,Image2,Image3,Image)
/* extract subpixel border */
threshold_sub_pix(Image1,Border,128)
/* select the circle and the arrows */
select_obj(Border,circle,14)
select_obj(Border,arrows,16)
concat_obj(circle,arrows,green_dot)
/* paint a green circle and white arrows (to paint all
* objects e.g. blue, pass [0,0,255] tuple for GrayVal) */
paint_xld(green_dot,Image,ImageResult,[0,255,0,255,255,255])

Result
PaintXld returns TRUE if all parameters are correct. If the input is empty the behavior can be set via
SetSystem(::’noObjectResult’,<Result>:). If necessary, an exception is raised.

HALCON/COM Reference Manual, 2008-5-13


5.8. MANIPULATION 525

Parallelization Information
PaintXld is reentrant and processed without parallelization.
Possible Predecessors
ReadImage, GenImageConst, GenImageProto, GenContourPolygonXld, ThresholdSubPix
See also
GenImageConst
Alternatives
SetGrayval, PaintGray, PaintRegion
Module
Foundation

void HImageX.SetGrayval ([in] VARIANT Row, [in] VARIANT Column,


[in] VARIANT Grayval )
void HOperatorSetX.SetGrayval ([in] IHObjectX Image, [in] VARIANT Row,
[in] VARIANT Column, [in] VARIANT Grayval )

Set single gray values in an image.


SetGrayval sets the gray values of the input image Image at the positions (Row,Column) to the values speci-
fied by Grayval. The number of values in Grayval must match the number of points passed to the operator.
Parameter

. Image (input iconic) . . . . . . image ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2, uint2, int4,
real )
Image to be modified.
. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( integer )
Row coordinates of the pixels to be modified.
Default Value : 0
Suggested values : Row ∈ {0, 10, 50, 127, 255, 511}
Restriction : (Row ∧ (Image < height))
. Column (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( integer )
Column coordinates of the pixels to be modified.
Default Value : 0
Suggested values : Column ∈ {0, 10, 50, 127, 255, 511}
Restriction : (Column ∧ (Image < width))
. Grayval (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . grayval(-array) ; VARIANT ( integer, real )
Gray values to be used.
Default Value : 255.0
Suggested values : Grayval ∈ {0.0, 1.0, 10.0, 128.0, 255.0}
Result
SetGrayval returns TRUE if all parameters are correct. If the input is empty the behavior can be set via
SetSystem(::’noObjectResult’,<Result>:). If necessary, an exception is raised.
Parallelization Information
SetGrayval is reentrant and processed without parallelization.
Possible Predecessors
ReadImage, GetImagePointer1, GenImageProto, GenImage1
See also
GetGrayval, GenImageConst, GenImage1, GenImageProto
Alternatives
GetImagePointer1, PaintGray, PaintRegion
Module
Foundation

HALCON 8.0.2
526 CHAPTER 5. IMAGE

5.9 Type-Conversion

[out] HImageX ImageReal HImageX.ComplexToReal


([out] HImageX ImageImaginary )
void HOperatorSetX.ComplexToReal ([in] IHObjectX ImageComplex,
[out] HUntypedObjectX ImageReal, [out] HUntypedObjectX ImageImaginary )

Convert a complex image into two real images.


ComplexToReal converts a complex image ImageComplex into two real images ImageReal and
ImageImaginary, which contain the real and imaginary part of the complex image.
Parameter

. ImageComplex (input iconic) . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( complex )


Complex image.
. ImageReal (output iconic) . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX ( real )
Real part.
. ImageImaginary (output iconic) . . . . . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX ( real )
Imaginary part.
Parallelization Information
ComplexToReal is reentrant and automatically parallelized (on tuple level).
See also
RealToComplex
Module
Foundation

[out] HImageX ImageConverted HImageX.ConvertImageType


([in] String NewType )
void HOperatorSetX.ConvertImageType ([in] IHObjectX Image,
[out] HUntypedObjectX ImageConverted, [in] VARIANT NewType )

Convert the type of an image.


ConvertImageType converts images of an arbitrary type into an arbitrary new image type. If the conversion
is done from a larger to a smaller gray value range (e.g., from ’int4’ to ’byte’), too large or too small values are
simply “clipped.” It is therefore advisable to adapt the range of gray values by calling ScaleImage before
calling this operator. For images of type complex, only the real part is converted. The imaginary part is ignored.
This facilitates an efficient conversion of images that have been transformed back from the frequency domain.
Such images always have an imaginary part of 0.
Attention
If the source and destination image type are identical, no new image matrix is allocated.
Parameter

. Image (input iconic) . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic,


int1, int2, uint2, int4, real, complex )
Image whose image type is to be changed.
. ImageConverted (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX
( byte, direction, cyclic, int1,
int2, uint2, int4, real, complex
)
Converted image.
. NewType (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Desired image type (i.e., type of the gray values).
Default Value : ’byte’
List of values : NewType ∈ {’int1’, ’int2’, ’uint2’, ’int4’, ’byte’, ’real’, ’direction’, ’cyclic’, ’complex’}

HALCON/COM Reference Manual, 2008-5-13


5.9. TYPE-CONVERSION 527

Result
ConvertImageType returns TRUE if all parameters are correct. If the input is empty the behavior can be set
via SetSystem(’noObjectResult’,<Result>). If necessary, an exception is raised.
Parallelization Information
ConvertImageType is reentrant and automatically parallelized (on tuple level, channel level, domain level).
Possible Predecessors
ScaleImage
See also
ScaleImage, AbsImage
Module
Foundation

[out] HImageX ImageComplex HImageX.RealToComplex


([in] HImageX ImageImaginary )
void HOperatorSetX.RealToComplex ([in] IHObjectX ImageReal,
[in] IHObjectX ImageImaginary, [out] HUntypedObjectX ImageComplex )

Convert two real images into a complex image.


RealToComplex converts two real images ImageReal and ImageImaginary, which contain the real and
imaginary part of a complex image, into a complex image ImageComplex.
Parameter

. ImageReal (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( real )


Real part.
. ImageImaginary (input iconic) . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( real )
Imaginary part.
. ImageComplex (output iconic) . . . . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX ( complex )
Complex image.
Parallelization Information
RealToComplex is reentrant and automatically parallelized (on tuple level).
See also
ComplexToReal
Module
Foundation

HImageX.RealToVectorField ([in] HImageX Col )


[out] HImageX VectorField
void HOperatorSetX.RealToVectorField ([in] IHObjectX Row,
[in] IHObjectX Col, [out] HUntypedObjectX VectorField )

Convert two real-valued images into a vector field image.


RealToVectorField converts two real-valued images Row and Col into a vector field image VectorField.
The input images contain the vector components in the row and column direction, respectively.
Parameter

. Row (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( real )


Vector component in the row direction.
. Col (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( real )
Vector component in the column direction.
. VectorField (output iconic) . . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX ( vector_field )
Displacement vector field.

HALCON 8.0.2
528 CHAPTER 5. IMAGE

Parallelization Information
RealToVectorField is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
VectorFieldToReal
Module
Foundation

HImageX.VectorFieldToReal ([out] HImageX Col )


[out] HImageX Row
void HOperatorSetX.VectorFieldToReal ([in] IHObjectX VectorField,
[out] HUntypedObjectX Row, [out] HUntypedObjectX Col )

Convert a vector field image into two real-valued images.


VectorFieldToReal converts the vector field image VectorField into two real-valued images Row and
Col. The output images contain the vector components in the row and column direction, respectively.
Parameter

. VectorField (input iconic) . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( vector_field )


Vector field.
. Row (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX ( real )
Vector component in the row direction.
. Col (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX ( real )
Vector component in the column direction.
Parallelization Information
VectorFieldToReal is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
OpticalFlowMg
See also
OpticalFlowMg
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


Chapter 6

Lines

6.1 Access
[out] VARIANT ArcCenterRow HMiscX.ApproxChain ([in] long Row,
[in] long Column, [in] double MinWidthCoord, [in] double MaxWidthCoord,
[in] double ThreshStart, [in] double ThreshEnd, [in] double ThreshStep,
[in] double MinWidthSmooth, [in] double MaxWidthSmooth,
[in] long MinWidthCurve, [in] long MaxWidthCurve, [in] double Weight1,
[in] double Weight2, [in] double Weight3, [out] VARIANT ArcCenterCol,
[out] VARIANT ArcAngle, [out] VARIANT ArcBeginRow, [out] VARIANT ArcBeginCol,
[out] VARIANT LineBeginRow, [out] VARIANT LineBeginCol,
[out] VARIANT LineEndRow, [out] VARIANT LineEndCol, [out] VARIANT Order )
void HOperatorSetX.ApproxChain ([in] VARIANT Row, [in] VARIANT Column,
[in] VARIANT MinWidthCoord, [in] VARIANT MaxWidthCoord,
[in] VARIANT ThreshStart, [in] VARIANT ThreshEnd, [in] VARIANT ThreshStep,
[in] VARIANT MinWidthSmooth, [in] VARIANT MaxWidthSmooth,
[in] VARIANT MinWidthCurve, [in] VARIANT MaxWidthCurve, [in] VARIANT Weight1,
[in] VARIANT Weight2, [in] VARIANT Weight3, [out] VARIANT ArcCenterRow,
[out] VARIANT ArcCenterCol, [out] VARIANT ArcAngle,
[out] VARIANT ArcBeginRow, [out] VARIANT ArcBeginCol,
[out] VARIANT LineBeginRow, [out] VARIANT LineBeginCol,
[out] VARIANT LineEndRow, [out] VARIANT LineEndCol, [out] VARIANT Order )

Approximate a contour by arcs and lines.


The coordinates of a curve are approximated by a row of lines and arcs. The procedure tries values from
a user-definable range for certain parameters. The limits of these ranges are explicitly stated in the parame-
ter list of the function (MinWidthCoord ... MaxWidthCoord, ThreshStart ... ThreshEnd, MinWidthSmooth ...
MaxWidthSmooth, MinWidthCurve ... MaxWidthCurve). Additionally, the step width for the parameter area of
the threshold value for pointed corners has to be indicated (ThreshStep). By narrowing the covered areas the
runtime of the calculation can be shortened, but the result may deteriorate.
The parameters Weight1, Weight2 and Weight3 indicate whether the desired weighting is placed more on precision
of the approximation, obtaining as much large segments as possible or as few small segments as possible. Thus,
for (Weight1,Weight2,Weight3) (1,0,0) creates a very precise approximation and (0,1,1) an approximation with as
few large segments as possible.
The result of the procedure is returned separately as arcs and lines. If one is interested in the sequence of the
segments the individual resulting elements can be read successively from the resulting tuples; the sequence can be
taken from the return parameter order (0: next element is next line segment, 1: next element is next arc segment).
Attention
Contours which can possibly consist of only one segment should also be examined with a threshold maximum
(ThreshEnd) > 1.0, because otherwise at least one “corner point” is determined in any case.

529
530 CHAPTER 6. LINES

Parameter

. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; long / VARIANT


Row of the contour.
Default Value : 32
. Column (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; long / VARIANT
Column of the contour.
Default Value : 32
. MinWidthCoord (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Minimum width of Gauss operator for coordinate smoothing (> 0.4).
Default Value : 0.5
Suggested values : MinWidthCoord ∈ {0.5, 0.7, 1.0, 1.2, 1.5, 1.7}
Typical range of values : 0.4 ≤ MinWidthCoord ≤ 0.4(lin)
Minimum Increment : 0.01
Recommended Increment : 0.1
. MaxWidthCoord (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Maximum width of Gauss operator for coordinate smoothing (> 0.4).
Default Value : 2.4
Suggested values : MaxWidthCoord ∈ {0.5, 0.7, 1.0, 1.2, 1.5, 1.7}
Typical range of values : 0.4 ≤ MaxWidthCoord ≤ 0.4(lin)
Minimum Increment : 0.01
Recommended Increment : 0.1
. ThreshStart (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Minimum threshold value of the curvature for accepting a corner (relative to the largest curvature present).
Default Value : 0.3
Suggested values : ThreshStart ∈ {0.3, 0.4, 0.5, 0.6, 0.7, 0.8}
Typical range of values : 0.1 ≤ ThreshStart ≤ 0.1(lin)
Minimum Increment : 0.01
Recommended Increment : 0.1
. ThreshEnd (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Maximum threshold value of the curvature for accepting a corner (relative to the largest curvature present).
Default Value : 0.9
Suggested values : ThreshEnd ∈ {0.3, 0.4, 0.5, 0.6, 0.7, 0.8}
Typical range of values : 0.1 ≤ ThreshEnd ≤ 0.1(lin)
Minimum Increment : 0.01
Recommended Increment : 0.1
. ThreshStep (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Step width for threshold increase.
Default Value : 0.2
Suggested values : ThreshStep ∈ {0.3, 0.4, 0.5}
Typical range of values : 0.1 ≤ ThreshStep ≤ 0.1(lin)
Minimum Increment : 0.01
Recommended Increment : 0.1
. MinWidthSmooth (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Minimum width of Gauss operator for smoothing the curvature function (> 0.4).
Default Value : 0.5
Suggested values : MinWidthSmooth ∈ {0.5, 0.7, 1.0, 1.2, 1.5, 1.7}
Typical range of values : 0.4 ≤ MinWidthSmooth ≤ 0.4(lin)
Minimum Increment : 0.01
Recommended Increment : 0.1
. MaxWidthSmooth (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Maximum width of Gauss operator for smoothing the curvature function.
Default Value : 2.4
Suggested values : MaxWidthSmooth ∈ {0.5, 0.7, 1.0, 1.2, 1.5, 1.7}
Typical range of values : 0.4 ≤ MaxWidthSmooth ≤ 0.4(lin)
Minimum Increment : 0.01
Recommended Increment : 0.1

HALCON/COM Reference Manual, 2008-5-13


6.1. ACCESS 531

. MinWidthCurve (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT


Minimum width of curve area for curvature determination (> 0.4).
Default Value : 2
Suggested values : MinWidthCurve ∈ {2, 5, 7}
Typical range of values : 1 ≤ MinWidthCurve ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 2
. MaxWidthCurve (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Maximum width of curve area for curvature determination.
Default Value : 12
Suggested values : MaxWidthCurve ∈ {2, 5, 7}
Typical range of values : 1 ≤ MaxWidthCurve ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 2
. Weight1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Weighting factor for approximation precision.
Default Value : 1.0
Suggested values : Weight1 ∈ {0.0, 0.5, 1.0}
Typical range of values : 0.0 ≤ Weight1 ≤ 0.0(lin)
Minimum Increment : 0.1
Recommended Increment : 0.5
. Weight2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Weighting factor for large segments.
Default Value : 1.0
Suggested values : Weight2 ∈ {0.0, 0.5, 1.0}
Typical range of values : 0.0 ≤ Weight2 ≤ 0.0(lin)
Minimum Increment : 0.1
Recommended Increment : 0.5
. Weight3 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Weighting factor for small segments.
Default Value : 1.0
Suggested values : Weight3 ∈ {0.0, 0.5, 1.0}
Typical range of values : 0.0 ≤ Weight3 ≤ 0.0(lin)
Minimum Increment : 0.1
Recommended Increment : 0.5
. ArcCenterRow (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . arc.center.y ; VARIANT ( integer )
Row of the center of an arc.
. ArcCenterCol (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . arc.center.x ; VARIANT ( integer )
Column of the center of an arc.
. ArcAngle (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . arc.angle.rad ; VARIANT ( real )
Angle of an arc.
. ArcBeginRow (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . arc.begin.y ; VARIANT ( integer )
Row of the starting point of an arc.
. ArcBeginCol (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . arc.begin.x ; VARIANT ( integer )
Column of the starting point of an arc.
. LineBeginRow (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.begin.y ; VARIANT ( integer )
Row of the starting point of a line segment.
. LineBeginCol (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.begin.x ; VARIANT ( integer )
Column of the starting point of a line segment.
. LineEndRow (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.end.y ; VARIANT ( integer )
Row of the ending point of a line segment.
. LineEndCol (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.end.x ; VARIANT ( integer )
Column of the ending point of a line segment.
. Order (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Sequence of line (value 0) and arc segments (value 1).
Result
The operator ApproxChain returns the value TRUE if the parameters are correct. Otherwise an exception is
raised.

HALCON 8.0.2
532 CHAPTER 6. LINES

Parallelization Information
ApproxChain is reentrant and processed without parallelization.
Possible Predecessors
SobelAmp, EdgesImage, GetRegionContour, Threshold, HysteresisThreshold
Possible Successors
SetLineWidth, DispArc, DispLine
See also
GetRegionChain, SmallestCircle, DispCircle, DispLine
Alternatives
GetRegionPolygon, ApproxChainSimple
Module
Foundation

[out] VARIANT ArcCenterRow HMiscX.ApproxChainSimple ([in] long Row,


[in] long Column, [out] VARIANT ArcCenterCol, [out] VARIANT ArcAngle,
[out] VARIANT ArcBeginRow, [out] VARIANT ArcBeginCol,
[out] VARIANT LineBeginRow, [out] VARIANT LineBeginCol,
[out] VARIANT LineEndRow, [out] VARIANT LineEndCol, [out] VARIANT Order )
void HOperatorSetX.ApproxChainSimple ([in] VARIANT Row,
[in] VARIANT Column, [out] VARIANT ArcCenterRow, [out] VARIANT ArcCenterCol,
[out] VARIANT ArcAngle, [out] VARIANT ArcBeginRow, [out] VARIANT ArcBeginCol,
[out] VARIANT LineBeginRow, [out] VARIANT LineBeginCol,
[out] VARIANT LineEndRow, [out] VARIANT LineEndCol, [out] VARIANT Order )

Approximate a contour by arcs and lines.


The contour of a curve is approximated by a sequence of lines and arcs.
The result of the procedure is returned separately as arcs and lines. If one is interested in the sequence of the
segments the individual resulting elements can be read successively from the resulting tuples. The sequence can be
taken from the return parameter order (0: next element is next line segment, 1: next element is next arc segment).
The operator ApproxChainSimple behaves similarly as ApproxChain except that in the case of
ApproxChainSimple the missing parameters are internally allocated as follows: MinWidthCoord = 1.0,
MaxWidthCoord = 3.0, ThreshStart = 0.5, ThreshEnd = 0.9, ThreshStep = 0.3, MinWidthSmooth = 1.0,
MaxWidthSmooth = 3.0, MinWidthCurve = 2, MaxWidthCurve = 9, Weight1 = 1.0, Weight2 = 1.0, Weight3 =
1.0.
Parameter
. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; long / VARIANT
Row of the contour.
Default Value : 32
. Column (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; long / VARIANT
Column of the contour.
Default Value : 32
. ArcCenterRow (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . arc.center.y ; VARIANT ( integer )
Row of the center of an arc.
. ArcCenterCol (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . arc.center.x ; VARIANT ( integer )
Column of the center of an arc.
. ArcAngle (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . arc.angle.rad ; VARIANT ( real )
Angle of an arc.
. ArcBeginRow (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . arc.begin.y ; VARIANT ( integer )
Row of the starting point of an arc.
. ArcBeginCol (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . arc.begin.x ; VARIANT ( integer )
Column of the starting point of an arc.
. LineBeginRow (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.begin.y ; VARIANT ( integer )
Row of the starting point of a line segment.

HALCON/COM Reference Manual, 2008-5-13


6.2. FEATURES 533

. LineBeginCol (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.begin.x ; VARIANT ( integer )


Column of the starting point of a line segment.
. LineEndRow (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.end.y ; VARIANT ( integer )
Row of the ending point of a line segment.
. LineEndCol (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.end.x ; VARIANT ( integer )
Column of the ending point of a line segment.
. Order (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Sequence of line (value 0) and arc segments (value 1).
Result
The operator ApproxChainSimple returns the value TRUE if the parameters are correct. Otherwise an excep-
tion is raised.
Parallelization Information
ApproxChainSimple is reentrant and processed without parallelization.
Possible Predecessors
SobelAmp, EdgesImage, GetRegionContour, Threshold, HysteresisThreshold
Possible Successors
SetLineWidth, DispArc, DispLine
See also
GetRegionChain, SmallestCircle, DispCircle, DispLine
Alternatives
GetRegionPolygon, ApproxChain
Module
Foundation

6.2 Features
[out] VARIANT Phi HMiscX.LineOrientation ([in] VARIANT RowBegin,
[in] VARIANT ColBegin, [in] VARIANT RowEnd, [in] VARIANT ColEnd )
void HOperatorSetX.LineOrientation ([in] VARIANT RowBegin,
[in] VARIANT ColBegin, [in] VARIANT RowEnd, [in] VARIANT ColEnd,
[out] VARIANT Phi )

Calculate the orientation of lines.


The operator LineOrientation returns the orientation (−π/2 < Phi ≤ π/2) of the given lines. If more than
one line is to be treated the line and column indices can be passed as tuples. In this case Phi is, of course, also a
tuple and contains the corresponding orientations.
The procedure is typically applied to model lines in order to select parallel image lines, which were found, e.g., by
DetectEdgeSegments, via the operator SelectLines.
Parameter

. RowBegin (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.begin.y(-array) ; VARIANT ( integer, real )


Row coordinates of the starting points of the input lines.
. ColBegin (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.begin.x(-array) ; VARIANT ( integer, real )
Column coordinates of the starting points of the input lines.
. RowEnd (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.end.y(-array) ; VARIANT ( integer, real )
Row coordinates of the ending points of the input lines.
. ColEnd (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.end.x(-array) ; VARIANT ( integer, real )
Column coordinates of the ending points of the input lines.
. Phi (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad(-array) ; VARIANT ( real )
Orientation of the input lines.
Result
LineOrientation always returns the value TRUE.

HALCON 8.0.2
534 CHAPTER 6. LINES

Parallelization Information
LineOrientation is reentrant and processed without parallelization.
Possible Predecessors
SobelAmp, EdgesImage, Threshold, HysteresisThreshold, SplitSkeletonRegion,
SplitSkeletonLines
Possible Successors
SetLineWidth, DispLine
See also
LinePosition, SelectLines, PartitionLines, DetectEdgeSegments
Alternatives
LinePosition, SelectLines, PartitionLines
Module
Foundation

[out] VARIANT RowCenter HMiscX.LinePosition ([in] VARIANT RowBegin,


[in] VARIANT ColBegin, [in] VARIANT RowEnd, [in] VARIANT ColEnd,
[out] VARIANT ColCenter, [out] VARIANT Length, [out] VARIANT Phi )
void HOperatorSetX.LinePosition ([in] VARIANT RowBegin,
[in] VARIANT ColBegin, [in] VARIANT RowEnd, [in] VARIANT ColEnd,
[out] VARIANT RowCenter, [out] VARIANT ColCenter, [out] VARIANT Length,
[out] VARIANT Phi )

Calculate the center of gravity, length, and orientation of a line.


The operator LinePosition returns the center (RowCenter, ColCenter), the (Euclidean) length (Length)
and the orientation (−π/2 < Phi ≤ π/2) of the given lines. If more than one line is to be treated the line and
column indices can be passed as tuples. In this case the output parameters, of course, are also tuples.
The routine is applied, for example, to model lines in order to determine search regions for the edge detection (
DetectEdgeSegments).
Parameter
. RowBegin (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.begin.y(-array) ; VARIANT ( integer )
Row coordinates of the starting points of the input lines.
. ColBegin (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.begin.x(-array) ; VARIANT ( integer )
Column coordinates of the starting points of the input lines.
. RowEnd (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.end.y(-array) ; VARIANT ( integer )
Row coordinates of the ending points of the input lines.
. ColEnd (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.end.x(-array) ; VARIANT ( integer )
Column coordinates of the ending points of the input lines.
. RowCenter (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( real )
Row coordinates of the centers of gravity of the input lines.
. ColCenter (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( real )
Column coordinates of the centers of gravity of the input lines.
. Length (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Euclidean length of the input lines.
. Phi (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad(-array) ; VARIANT ( real )
Orientation of the input lines.
Result
LinePosition always returns the value TRUE.
Parallelization Information
LinePosition is reentrant and processed without parallelization.
Possible Predecessors
SobelAmp, EdgesImage, Threshold, HysteresisThreshold, SplitSkeletonRegion,
SplitSkeletonLines

HALCON/COM Reference Manual, 2008-5-13


6.2. FEATURES 535

Possible Successors
SetLineWidth, DispLine
See also
LineOrientation, SelectLines, PartitionLines, DetectEdgeSegments
Alternatives
LineOrientation, SelectLines, PartitionLines
Module
Foundation

[out] VARIANT RowBeginOut HMiscX.PartitionLines


([in] VARIANT RowBeginIn, [in] VARIANT ColBeginIn, [in] VARIANT RowEndIn,
[in] VARIANT ColEndIn, [in] VARIANT Feature, [in] String Operation,
[in] VARIANT Min, [in] VARIANT Max, [out] VARIANT ColBeginOut,
[out] VARIANT RowEndOut, [out] VARIANT ColEndOut, [out] VARIANT FailRowBOut,
[out] VARIANT FailColBOut, [out] VARIANT FailRowEOut,
[out] VARIANT FailColEOut )
void HOperatorSetX.PartitionLines ([in] VARIANT RowBeginIn,
[in] VARIANT ColBeginIn, [in] VARIANT RowEndIn, [in] VARIANT ColEndIn,
[in] VARIANT Feature, [in] VARIANT Operation, [in] VARIANT Min,
[in] VARIANT Max, [out] VARIANT RowBeginOut, [out] VARIANT ColBeginOut,
[out] VARIANT RowEndOut, [out] VARIANT ColEndOut, [out] VARIANT FailRowBOut,
[out] VARIANT FailColBOut, [out] VARIANT FailRowEOut,
[out] VARIANT FailColEOut )

Partition lines according to various criteria.


The operator PartitionLines divides lines into two sets according to various criteria. For each input line the
indicated features (Feature) are calculated. If each (Operation = ’and’) or at least one (Operation = ’or’)
of the calculated features is within the given limits (Min,Max) the line is transferred into the first set (parameters
RowBeginOut to ColEndOut), otherwise into the second set (parameters FailRowBOut to FailColEOut).
Condition: M ini ≤ F eaturei (Line) ≤ M axi

Possible values for Feature:

’length’ (Euclidean) length of the line


’row’ Line index of the center
’column’ Column index of the center
’phi’ Orientation of the line (− π2 < ϕ ≤ π
2)

Attention
If only one feature is used the value of Operation is meaningless. Several features are processed according to
the sequence in which they are passed.
Parameter

. RowBeginIn (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.begin.y ; VARIANT ( integer )


Row coordinates of the starting points of the input lines.
. ColBeginIn (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.begin.x ; VARIANT ( integer )
Column coordinates of the starting points of the input lines.
. RowEndIn (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.end.y ; VARIANT ( integer )
Row coordinates of the ending points of the input lines.
. ColEndIn (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.end.x ; VARIANT ( integer )
Column coordinates of the ending points of the input lines.
. Feature (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Features to be used for selection.
List of values : Feature ∈ {’length’, ’row’, ’column’, ’phi’}

HALCON 8.0.2
536 CHAPTER 6. LINES

. Operation (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT


Desired combination of the features.
List of values : Operation ∈ {’and’, ’or’}
. Min (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( integer, real, string )
Lower limits of the features or ’min’.
Default Value : ’min’
. Max (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( integer, real, string )
Upper limits of the features or ’max’.
Default Value : ’max’
. RowBeginOut (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.begin.y ; VARIANT ( integer )
Row coordinates of the starting points of the lines fulfilling the conditions.
. ColBeginOut (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.begin.x ; VARIANT ( integer )
Column coordinates of the starting points of the lines fulfilling the conditions.
. RowEndOut (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.end.y ; VARIANT ( integer )
Row coordinates of the ending points of the lines fulfilling the conditions.
. ColEndOut (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.begin.x ; VARIANT ( integer )
Column coordinates of the ending points of the lines fulfilling the conditions.
. FailRowBOut (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.begin.y ; VARIANT ( integer )
Row coordinates of the starting points of the lines not fulfilling the conditions.
. FailColBOut (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.begin.x ; VARIANT ( integer )
Column coordinates of the starting points of the lines not fulfilling the conditions.
. FailRowEOut (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.end.y ; VARIANT ( integer )
Row coordinates of the ending points of the lines not fulfilling the conditions.
. FailColEOut (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.end.x ; VARIANT ( integer )
Column coordinates of the ending points of the lines not fulfilling the conditions.
Result
The operator PartitionLines returns the value TRUE if the parameter values are correct. Otherwise an
exception is raised.
Parallelization Information
PartitionLines is reentrant and processed without parallelization.
Possible Predecessors
SobelAmp, EdgesImage, Threshold, HysteresisThreshold, SplitSkeletonRegion,
SplitSkeletonLines
Possible Successors
SetLineWidth, DispLine
See also
SelectLines, SelectLinesLongest, DetectEdgeSegments, SelectShape
Alternatives
LineOrientation, LinePosition, SelectLines, SelectLinesLongest
Module
Foundation

[out] VARIANT RowBeginOut HMiscX.SelectLines ([in] VARIANT RowBeginIn,


[in] VARIANT ColBeginIn, [in] VARIANT RowEndIn, [in] VARIANT ColEndIn,
[in] VARIANT Feature, [in] String Operation, [in] VARIANT Min,
[in] VARIANT Max, [out] VARIANT ColBeginOut, [out] VARIANT RowEndOut,
[out] VARIANT ColEndOut )
void HOperatorSetX.SelectLines ([in] VARIANT RowBeginIn,
[in] VARIANT ColBeginIn, [in] VARIANT RowEndIn, [in] VARIANT ColEndIn,
[in] VARIANT Feature, [in] VARIANT Operation, [in] VARIANT Min,
[in] VARIANT Max, [out] VARIANT RowBeginOut, [out] VARIANT ColBeginOut,
[out] VARIANT RowEndOut, [out] VARIANT ColEndOut )

Select lines according to various criteria.

HALCON/COM Reference Manual, 2008-5-13


6.2. FEATURES 537

The operator SelectLines chooses lines according to various criteria. For every input line the indicated
features (Feature) are calculated. If each (Operation = ’and’) or at least one (Operation = ’or’) of the
calculated features is within the given limits (Min,Max) the line is transferred into the output.
Condition: M ini ≤ F eaturei (Line) ≤ M axi

Possible values for Feature:

’length’ (Euclidean) length of the line


’row’ Line index of the center
’column’ Column index of the center
’phi’ Orientation of the line (− π2 < ϕ ≤ π
2)

Attention
If only one feature is used the value of Operation is meaningless. Several features are processed according to
the sequence in which they are passed.
Parameter

. RowBeginIn (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.begin.y ; VARIANT ( integer )


Row coordinates of the starting points of the input lines.
. ColBeginIn (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.begin.x ; VARIANT ( integer )
Column coordinates of the starting points of the input lines.
. RowEndIn (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.end.y ; VARIANT ( integer )
Row coordinates of the ending points of the input lines.
. ColEndIn (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.end.x ; VARIANT ( integer )
Column coordinates of the ending points of the input lines.
. Feature (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Features to be used for selection.
Default Value : ’length’
List of values : Feature ∈ {’length’, ’row’, ’column’, ’phi’}
. Operation (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Desired combination of the features.
Default Value : ’and’
List of values : Operation ∈ {’and’, ’or’}
. Min (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( integer, real, string )
Lower limits of the features or ’min’.
Default Value : ’min’
. Max (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( integer, real, string )
Upper limits of the features or ’max’.
Default Value : ’max’
. RowBeginOut (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.begin.y ; VARIANT ( integer )
Row coordinates of the starting points of the output lines.
. ColBeginOut (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.begin.x ; VARIANT ( integer )
Column coordinates of the starting points of the output lines.
. RowEndOut (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.end.y ; VARIANT ( integer )
Row coordinates of the ending points of the output lines.
. ColEndOut (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.end.x ; VARIANT ( integer )
Column coordinates of the ending points of the output lines.
Result
The operator SelectLines returns the value TRUE if the parameter values are correct. Otherwise an exception
is raised.
Parallelization Information
SelectLines is reentrant and processed without parallelization.
Possible Predecessors
SobelAmp, EdgesImage, Threshold, HysteresisThreshold, SplitSkeletonRegion,
SplitSkeletonLines

HALCON 8.0.2
538 CHAPTER 6. LINES

Possible Successors
SetLineWidth, DispLine
See also
PartitionLines, SelectLinesLongest, DetectEdgeSegments, SelectShape
Alternatives
LineOrientation, LinePosition, PartitionLines
Module
Foundation

[out] VARIANT RowBeginOut HMiscX.SelectLinesLongest


([in] VARIANT RowBeginIn, [in] VARIANT ColBeginIn, [in] VARIANT RowEndIn,
[in] VARIANT ColEndIn, [in] long Num, [out] VARIANT ColBeginOut,
[out] VARIANT RowEndOut, [out] VARIANT ColEndOut )
void HOperatorSetX.SelectLinesLongest ([in] VARIANT RowBeginIn,
[in] VARIANT ColBeginIn, [in] VARIANT RowEndIn, [in] VARIANT ColEndIn,
[in] VARIANT Num, [out] VARIANT RowBeginOut, [out] VARIANT ColBeginOut,
[out] VARIANT RowEndOut, [out] VARIANT ColEndOut )

Select the longest input lines.


The operator SelectLinesLongest selects the Num longest input lines from the input lines described by the
tuples RowBeginIn, ColBeginIn, RowEndIn and ColEndIn.
Parameter
. RowBeginIn (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.begin.y ; VARIANT ( integer )
Row coordinates of the starting points of the input lines.
. ColBeginIn (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.begin.x ; VARIANT ( integer )
Column coordinates of the starting points of the input lines.
. RowEndIn (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.end.y ; VARIANT ( integer )
Row coordinates of the ending points of the input lines.
. ColEndIn (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.end.x ; VARIANT ( integer )
Column coordinates of the ending points of the input lines.
. Num (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
(Maximum) desired number of output lines.
Default Value : 10
. RowBeginOut (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.begin.y ; VARIANT ( integer )
Row coordinates of the starting points of the output lines.
. ColBeginOut (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.begin.x ; VARIANT ( integer )
Column coordinates of the starting points of the output lines.
. RowEndOut (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.end.y ; VARIANT ( integer )
Row coordinates of the ending points of the output lines.
. ColEndOut (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.end.x ; VARIANT ( integer )
Column coordinates of the ending points of the output lines.
Result
The operator SelectLinesLongest returns the value TRUE if the parameter values are correct. Otherwise
an exception is raised.
Parallelization Information
SelectLinesLongest is reentrant and processed without parallelization.
Possible Predecessors
SobelAmp, EdgesImage, Threshold, HysteresisThreshold, SplitSkeletonRegion,
SplitSkeletonLines
Possible Successors
SetLineWidth, DispLine
See also
SelectLines, PartitionLines, DetectEdgeSegments, SelectShape

HALCON/COM Reference Manual, 2008-5-13


6.2. FEATURES 539

Alternatives
LineOrientation, LinePosition, SelectLines, PartitionLines
Module
Foundation

HALCON 8.0.2
540 CHAPTER 6. LINES

HALCON/COM Reference Manual, 2008-5-13


Chapter 7

Matching

7.1 Component-Based

void HMiscX.ClearAllComponentModels ( )
void HOperatorSetX.ClearAllComponentModels ( )

Free the memory of all component models.


The operator ClearAllComponentModels frees the memory of all component models that were
created by CreateComponentModel or CreateTrainedComponentModel. After calling
ClearAllComponentModels, no model can be used any longer.
Attention
ClearAllComponentModels exists solely for the purpose of implementing the “reset program” functionality
in HDevelop. ClearAllComponentModels must not be used in any application.
Result
ClearAllComponentModels always returns TRUE.
Parallelization Information
ClearAllComponentModels is processed completely exclusively without parallelization.
Possible Predecessors
CreateComponentModel, CreateTrainedComponentModel, WriteComponentModel
Alternatives
ClearComponentModel
Module
Matching

void HMiscX.ClearAllTrainingComponents ( )
void HOperatorSetX.ClearAllTrainingComponents ( )

Free the memory of all component training results.


The operator ClearAllTrainingComponents frees the memory of all training results that were created
by TrainModelComponents. After calling ClearAllTrainingComponents, no training result can be
used any longer.
Attention
ClearAllTrainingComponents exists solely for the purpose of implementing the “reset program” func-
tionality in HDevelop. ClearAllTrainingComponents must not be used in any application.
Result
ClearAllTrainingComponents always returns TRUE.

541
542 CHAPTER 7. MATCHING

Parallelization Information
ClearAllTrainingComponents is processed completely exclusively without parallelization.
Possible Predecessors
TrainModelComponents, WriteTrainingComponents
See also
ClearTrainingComponents
Module
Matching

void HOperatorSetX.ClearComponentModel
([in] VARIANT ComponentModelID )

Free the memory of a component model.


The operator ClearComponentModel frees the memory of a component model that was cre-
ated by CreateComponentModel or CreateTrainedComponentModel. After calling
ClearComponentModel, the model can no longer be used. The handle ComponentModelID becomes
invalid.
Parameter
. ComponentModelID (input control) . . . . . . . . . . . component_model ; HComponentModelX / VARIANT
Handle of the component model.
Result
If the handle of the model is valid, the operator ClearComponentModel returns the value TRUE. If necessary,
an exception is raised.
Parallelization Information
ClearComponentModel is processed completely exclusively without parallelization.
Possible Predecessors
CreateComponentModel, CreateTrainedComponentModel, ReadComponentModel,
WriteComponentModel
See also
ClearAllComponentModels
Module
Matching

void HOperatorSetX.ClearTrainingComponents
([in] VARIANT ComponentTrainingID )

Free the memory of a component training result.


The operator ClearTrainingComponents frees the memory of a training result that was created by
TrainModelComponents. After calling ClearTrainingComponents, the training result can no longer
be used. The handle ComponentTrainingID becomes invalid.
Parameter
. ComponentTrainingID (input control) . . . . component_training ; HComponentTrainingX / VARIANT
Handle of the training result.
Result
If the handle of the training result is valid, the operator ClearTrainingComponents returns the value TRUE.
If necessary, an exception is raised.
Parallelization Information
ClearTrainingComponents is processed completely exclusively without parallelization.
Possible Predecessors
TrainModelComponents, WriteTrainingComponents

HALCON/COM Reference Manual, 2008-5-13


7.1. COMPONENT-BASED 543

See also
ClearAllTrainingComponents
Module
Matching

[out] HRegionX ModelComponents HImageX.ClusterModelComponents


([in] HComponentTrainingX ComponentTrainingID,
[in] String AmbiguityCriterion, [in] double MaxContourOverlap,
[in] double ClusterThreshold )
[out] HRegionX ModelComponents
HComponentTrainingX.ClusterModelComponents
([in] HImageX TrainingImages, [in] String AmbiguityCriterion,
[in] double MaxContourOverlap, [in] double ClusterThreshold )
void HOperatorSetX.ClusterModelComponents
([in] IHObjectX TrainingImages, [out] HUntypedObjectX ModelComponents,
[in] VARIANT ComponentTrainingID, [in] VARIANT AmbiguityCriterion,
[in] VARIANT MaxContourOverlap, [in] VARIANT ClusterThreshold )

Adopt new parameters that are used to create the model components into the training result.
With ClusterModelComponents you can modify parameters after a first training has been performed using
TrainModelComponents. ClusterModelComponents sets the criterion AmbiguityCriterion that
is used to solve the ambiguities, the maximum contour overlap MaxContourOverlap, and the cluster threshold
of the training result ComponentTrainingID to the specified values. A detailed description of these parameters
can be found in the documentation of TrainModelComponents. By modifying these parameters, the way in
which the initial components are merged into rigid model components changes. For example, the greater the cluster
threshold is chosen, the fewer initial components are merged.
The rigid model components are returned in ModelComponents. In order to receive reasonable results, it is
essential that the same training images that were used to perform the training with TrainModelComponents
are passed in TrainingImages. The pose of the newly clustered components within the training images is
determined using the shape-based matching. As in TrainModelComponents, one can decide whether the
shape models should be pregenerated by using SetSystem(’pregenerateShapeModels’,...). Fur-
thermore, SetSystem(’borderShapeModels’,...) can be used to determine whether the models must
lie completely within the training images or whether they can extend partially beyond the image border.
Thus, you can select suitable parameter values interactively by repeatedly calling
InspectClusteredComponents with different parameter values and then setting the chosen values
by using GetTrainingComponents.
Parameter
. TrainingImages (input iconic) . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, uint2 )
Training images that were used for training the model components.
. ModelComponents (output iconic) . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Contour regions of rigid model components.
. ComponentTrainingID (input control) . . . . component_training ; HComponentTrainingX / VARIANT
Handle of the training result.
. AmbiguityCriterion (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Criterion for solving the ambiguities.
Default Value : ’rigidity’
List of values : AmbiguityCriterion ∈ {’distance’, ’orientation’, ’distance_orientation’, ’rigidity’}
. MaxContourOverlap (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Maximum contour overlap of the found initial components.
Default Value : 0.2
Suggested values : MaxContourOverlap ∈ {0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}
Minimum Increment : 0.01
Recommended Increment : 0.05
Restriction : ((0 ≤ M axContourOverlap) ∧ (M axContourOverlap ≤ 1))

HALCON 8.0.2
544 CHAPTER 7. MATCHING

. ClusterThreshold (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT


Threshold for clustering the initial components.
Default Value : 0.5
Suggested values : ClusterThreshold ∈ {0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}
Restriction : ((0 ≤ ClusterT hreshold) ∧ (ClusterT hreshold ≤ 1))
Example

* Get the model image.


read_image (ModelImage, ’model_image.tif’)
* Define the regions for the initial components.
gen_rectangle2 (InitialComponentRegions, 212, 233, 0.62, 167, 29)
gen_rectangle2 (Rectangle2, 298, 363, 1.17, 162, 34)
gen_rectangle2 (Rectangle3, 63, 444, -0.26, 50, 27)
gen_rectangle2 (Rectangle4, 120, 473, 0, 33, 20)
InitialComponentRegions := [InitialComponentRegions,Rectangle2]
InitialComponentRegions := [InitialComponentRegions,Rectangle3]
InitialComponentRegions := [InitialComponentRegions,Rectangle4]
* Get the training images
TrainingImages := []
for i := 1 to 4 by 1
read_image (TrainingImage, ’training_image-’+i$’02’+’.tif’)
TrainingImages := [TrainingImages,TrainingImage]
endfor
* Extract the model components and train the relations.
train_model_components (ModelImage, InitialComponentRegions, TrainingImages,
ModelComponents, 22, 60, 30, 0.65, 0, 0, rad(60),
’speed’, ’rigidity’, 0.2, 0.5, ComponentTrainingID)
* Find the best value for the parameter ClusterThreshold.
inspect_clustered_components (ModelComponents, ComponentTrainingID,
’rigidity’, 0.2, 0.4)
* Adopt the ClusterThreshold into the training result.
cluster_model_components (TrainingImages, ModelComponents,
ComponentTrainingID, ’rigidity’, 0.2, 0.4)
* Create the component model based on the training result.
create_trained_component_model (ComponentTrainingID, -rad(30), rad(60), 10,
0.5, ’auto’, ’auto’, ’none’, ’use_polarity’,
’false’, ComponentModelID, RootRanking)

Result
If the parameter values are correct, the operator ClusterModelComponents returns the value TRUE.
If the input is empty (no input images are available) the behavior can be set via SetSystem
(’noObjectResult’,<Result>). If necessary, an exception is raised.
Parallelization Information
ClusterModelComponents is processed completely exclusively without parallelization.
Possible Predecessors
TrainModelComponents, InspectClusteredComponents
Possible Successors
GetTrainingComponents, CreateTrainedComponentModel, ModifyComponentRelations,
WriteTrainingComponents, GetComponentRelations, ClearTrainingComponents,
ClearAllTrainingComponents
Module
Matching

HALCON/COM Reference Manual, 2008-5-13


7.1. COMPONENT-BASED 545

[out] HComponentModelX ComponentModelID HImageX.CreateComponentModel


([in] HRegionX ComponentRegions, [in] VARIANT VariationRow,
[in] VARIANT VariationColumn, [in] VARIANT VariationAngle,
[in] double AngleStart, [in] double AngleExtent,
[in] VARIANT ContrastLowComp, [in] VARIANT ContrastHighComp,
[in] VARIANT MinSizeComp, [in] VARIANT MinContrastComp,
[in] VARIANT MinScoreComp, [in] VARIANT NumLevelsComp,
[in] VARIANT AngleStepComp, [in] String OptimizationComp,
[in] VARIANT MetricComp, [in] VARIANT PregenerationComp,
[out] VARIANT RootRanking )
void HComponentModelX.CreateComponentModel ([in] HImageX ModelImage,
[in] HRegionX ComponentRegions, [in] VARIANT VariationRow,
[in] VARIANT VariationColumn, [in] VARIANT VariationAngle,
[in] double AngleStart, [in] double AngleExtent,
[in] VARIANT ContrastLowComp, [in] VARIANT ContrastHighComp,
[in] VARIANT MinSizeComp, [in] VARIANT MinContrastComp,
[in] VARIANT MinScoreComp, [in] VARIANT NumLevelsComp,
[in] VARIANT AngleStepComp, [in] String OptimizationComp,
[in] VARIANT MetricComp, [in] VARIANT PregenerationComp,
[out] VARIANT RootRanking )
void HOperatorSetX.CreateComponentModel ([in] IHObjectX ModelImage,
[in] IHObjectX ComponentRegions, [in] VARIANT VariationRow,
[in] VARIANT VariationColumn, [in] VARIANT VariationAngle,
[in] VARIANT AngleStart, [in] VARIANT AngleExtent,
[in] VARIANT ContrastLowComp, [in] VARIANT ContrastHighComp,
[in] VARIANT MinSizeComp, [in] VARIANT MinContrastComp,
[in] VARIANT MinScoreComp, [in] VARIANT NumLevelsComp,
[in] VARIANT AngleStepComp, [in] VARIANT OptimizationComp,
[in] VARIANT MetricComp, [in] VARIANT PregenerationComp,
[out] VARIANT ComponentModelID, [out] VARIANT RootRanking )

Prepare a component model for matching based on explicitly specified components and relations.
CreateComponentModel prepares patterns, which are passed in the form of a model image ModelImage
and several regions ComponentRegions, as a component model for matching. The output parameter
ComponentModelID is a handle for this model, which is used in subsequent calls to FindComponentModel.
In contrast to CreateTrainedComponentModel, no preceding training with TrainModelComponents
needs to be performed before calling CreateComponentModel.
Each of the regions passed in ComponentRegions describes a separate model component. Later, the index of
a component region in ComponentRegions is used to denote the model component. The reference point of a
component is the center of gravity of its associated region, which is passed in ComponentRegions. It can be
calculated by calling AreaCenter.
The relative movements (relations) of the model components can be set by passing VariationRow,
VariationColumn, and VariationAngle. Because directly passing the relations is complicated, instead of
the relations the variations of the model components are passed. The variations describe the movements of the com-
ponents independently from each other relative to their poses in the model image ModelImage. The parameters
VariationRow and VariationColumn describe the movement of the components in row and column di-
rection by ± 21 VariationRow and ± 12 VariationColumn, respectively. The parameter VariationAngle
describes the angle variation of the component by ± 12 VariationAngle. Based on these values, the relations
are automatically computed. The three parameters must either contain one element, in which case the parameter is
used for all model components, or must contain the same number of elements as ComponentRegions, in which
case each parameter element refers to the corresponding model component in ComponentRegions.
The parameters AngleStart and AngleExtent determine the range of possible rotations of the component
model in an image.
Internally, a separate shape model is built for each model component (see CreateShapeModel). There-
fore, the parameters ContrastLowComp, ContrastHighComp, MinSizeComp, MinContrastComp,
MinScoreComp, NumLevelsComp, AngleStepComp, OptimizationComp, MetricComp, and

HALCON 8.0.2
546 CHAPTER 7. MATCHING

PregenerationComp correspond to the parameters of CreateShapeModel, with the following differ-


ences: First, in the parameter Contrast of CreateShapeModel the upper as well as the lower threshold
for the hysteresis threshold method can be passed. Additionally, a third value, which suppresses small con-
nected contour regions, can be passed. In contrast, the operator CreateComponentModel offers three sepa-
rate parameters ContrastHighComp, ContrastLowComp, and MinScoreComp in order to set these three
values. Consequently, also the automatic computation of the contrast threshold(s) is different. If both hystere-
sis threshold should be automatically determined, both ContrastLowComp and ContrastHighComp must
be set to ’auto’. In contrast, if only one threshold value should be determined, ContrastLowComp must
be set to ’auto’ while ContrastHighComp must be set to an arbitrary value different from ’auto’. Sec-
ondly, the parameter Optimization of CreateShapeModel provides the possibility to reduce the num-
ber of model points as well as the possibility to completely pregenerate the shape model. In contrast, the
operator CreateTrainedComponentModel uses a separate parameter PregenerationComp in order
to decide whether the shape models should be completely pregenerated or not. A third difference concerning
the parameter MinScoreComp should be noted. When using the shape-based matching, this parameter needs
not be passed when preparing the shape model using CreateShapeModel, but only during the search us-
ing FindShapeModel. In contrast, when preparing the component model it is favorable to analyze rota-
tional symmetries of the model components and similarities between the model components. However, this
analysis only leads to meaningful results if the value for MinScoreComp that is used during the search (see
FindComponentModel) is already approximately known.
In addition to the parameters ContrastLowComp, ContrastHighComp, and MinSizeComp also the pa-
rameters MinContrastComp, NumLevelsComp, AngleStepComp, and OptimizationComp can be au-
tomatically determined by passing ’auto’ for the respective parameters.
All component-specific input parameters (parameter names terminate with the suffix Comp) must either contain
one element, in which case the parameter is used for all model components, or must contain the same number of
elements as the number of regions in ComponentRegions, in which case each parameter element refers to the
corresponding element in ComponentRegions.
In addition to the individual shape models, the component model also contains information about the way the
single model components must be searched relative to each other using FindComponentModel in order to
minimize the computation time of the search. For this, the components are represented in a tree structure. First, the
component that stands at the root of this search tree (root component) is searched. Then, the remaining components
are searched relative to the pose of their predecessor in the search tree.
The root component can be passed as an input parameter of FindComponentModel during the search. To what
extent a model component is suited to act as the root component depends on several factors. In principle, a model
component that can be found in the image with a high probability should be chosen. Therefore, a component
that is sometimes occluded to a high degree or that is missing in some cases is not well suited to act as the root
component. Additionally, the computation time that is associated with the root component during the search
can serve as a criterion. A ranking of the model components that is based on the latter criterion is returned in
RootRanking. In this parameter the indices of the model components are sorted in descending order according
to their associated search time, i.e., RootRanking[0] contains the index of the model component that, chosen
as root component, allows the fastest search. Note that the ranking returned in RootRanking represents only
a coarse estimation. Furthermore, the calculation of the root ranking assumes that the image size as well as the
value of the system parameter ’border_shape_models’ are identical when calling CreateComponentModel
and FindComponentModel.
Parameter

. ModelImage (input iconic) . . . . . . . . . . . . . . . (multichannel-)image ; HImageX / IHObjectX ( byte, uint2 )


Input image from which the shape models of the model components should be created.
. ComponentRegions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
Input regions from which the shape models of the model components should be created.
. VariationRow (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Variation of the model components in row direction.
Suggested values : VariationRow ∈ {0, 1, 2, 3, 4, 5, 10, 20, 30, 40, 50, 100, 150}
Restriction : (V ariationRow ≥ 0)
. VariationColumn (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Variation of the model components in column direction.
Suggested values : VariationColumn ∈ {0, 1, 2, 3, 4, 5, 10, 20, 30, 40, 50, 100, 150}
Restriction : (V ariationColumn ≥ 0)

HALCON/COM Reference Manual, 2008-5-13


7.1. COMPONENT-BASED 547

. VariationAngle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad(-array) ; VARIANT ( real )


Angle variation of the model components.
Suggested values : VariationAngle ∈ {0, 0.017, 0, 035, 0.05, 0.07, 0.09, 0.17, 0.35, 0.52, 0.67, 0.87}
Restriction : (V ariationAngle ≥ 0)
. AngleStart (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; double / VARIANT
Smallest rotation of the component model.
Default Value : -0.39
Suggested values : AngleStart ∈ {-3.14, -1.57, -0.79, -0.39, -0.20, 0.0}
. AngleExtent (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; double / VARIANT
Extent of the rotation of the component model.
Default Value : 0.79
Suggested values : AngleExtent ∈ {6.28, 3.14, 1.57, 0.79, 0.39}
Restriction : (AngleExtent ≥ 0)
. ContrastLowComp (input control) . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer, string )
Lower hysteresis threshold for the contrast of the components in the model image.
Default Value : ’auto’
Suggested values : ContrastLowComp ∈ {’auto’, 10, 20, 30, 40, 60, 80, 100, 120, 140, 160}
Restriction : (ContrastLowComp > 0)
. ContrastHighComp (input control) . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer, string )
Upper hysteresis threshold for the contrast of the components in the model image.
Default Value : ’auto’
Suggested values : ContrastHighComp ∈ {’auto’, 10, 20, 30, 40, 60, 80, 100, 120, 140, 160}
Restriction : ((ContrastHighComp > 0) ∧ (ContrastHighComp ≥ ContrastLowComp))
. MinSizeComp (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer, string )
Minimum size of the contour regions in the model.
Default Value : ’auto’
Suggested values : MinSizeComp ∈ {’auto’, 0, 5, 10, 20, 30, 40}
Restriction : (M inSizeComp ≥ 0)
. MinContrastComp (input control) . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer, string )
Minimum contrast of the components in the search images.
Default Value : ’auto’
Suggested values : MinContrastComp ∈ {’auto’, 10, 20, 20, 40}
Restriction : ((M inContrastComp ≤ ContrastLowComp) ∧ (M inContrastComp ≥ 0))
. MinScoreComp (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Minimum score of the instances of the components to be found.
Default Value : 0.5
Suggested values : MinScoreComp ∈ {0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}
Minimum Increment : 0.01
Recommended Increment : 0.05
Restriction : ((0 ≤ M inScoreComp) ∧ (M inScoreComp ≤ 1))
. NumLevelsComp (input control) . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer, string )
Maximum number of pyramid levels for the components.
Default Value : ’auto’
List of values : NumLevelsComp ∈ {’auto’, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
. AngleStepComp (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad(-array) ; VARIANT ( real, string )
Step length of the angles (resolution) for the components.
Default Value : ’auto’
Suggested values : AngleStepComp ∈ {’auto’, 0.0175, 0.0349, 0.0524, 0.0698, 0.0873}
Restriction : (AngleStepComp ≥ 0)
. OptimizationComp (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Kind of optimization for the components.
Default Value : ’auto’
List of values : OptimizationComp ∈ {’auto’, ’none’, ’point_reduction_low’, ’point_reduction_medium’,
’point_reduction_high’}
. MetricComp (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .string(-array) ; VARIANT ( string )
Match metric used for the components.
Default Value : ’use_polarity’
List of values : MetricComp ∈ {’use_polarity’, ’ignore_global_polarity’, ’ignore_local_polarity’,

HALCON 8.0.2
548 CHAPTER 7. MATCHING

’ignore_color_polarity’}
. PregenerationComp (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Complete pregeneration of the shape models for the components if equal to ’true’.
Default Value : ’false’
List of values : PregenerationComp ∈ {’true’, ’false’}
. ComponentModelID (output control) . . . . . . . . . . component_model ; HComponentModelX / VARIANT
Handle of the component model.
. RootRanking (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Ranking of the model components expressing the suitability to act as the root component.
Example

* Read the model image.


read_image (ModelImage, ’model_image.tif’)
* Describe the model components.
gen_rectangle2 (ComponentRegions, 318, 109, -1.62, 34, 19)
gen_rectangle2 (Rectangle2, 342, 238, -1.63, 32, 17)
gen_rectangle2 (Rectangle3, 355, 505, 1.41, 25, 17)
ComponentRegions := [ComponentRegions,Rectangle2]
ComponentRegions := [ComponentRegions,Rectangle3]
* Create the component model by explicitly specifying the relations.
create_component_model (ModelImage, ComponentRegions, 20, 20, rad(25), 0,
rad(360), 15, 40, 15, 10, 0.8, ’auto’, ’auto’,
’none’, ’use_polarity’, ’false’, ComponentModelID,
RootRanking)
* Find the component model in a run-time image.
read_image (SearchImage, ’search_image.tif’)
find_component_model (SearchImage, ComponentModelID, RootRanking, 0,
rad(360), 0.5, 0, 0.5, ’stop_search’,
’search_from_best’, ’none’, 0.8, ’least_squares’, 0,
0.8, ModelStart, ModelEnd, Score, RowComp, ColumnComp,
AngleComp, ScoreComp, ModelComp)

Result
If the parameters are valid, the operator CreateComponentModel returns the value TRUE. If necessary an
exception is raised.
Parallelization Information
CreateComponentModel is processed completely exclusively without parallelization.
Possible Predecessors
DrawRegion, ConcatObj
Possible Successors
FindComponentModel
See also
CreateShapeModel, FindShapeModel
Alternatives
CreateTrainedComponentModel
Module
Matching

HALCON/COM Reference Manual, 2008-5-13


7.1. COMPONENT-BASED 549

[out] HComponentModelX ComponentModelID


HComponentTrainingX.CreateTrainedComponentModel
([in] double AngleStart, [in] double AngleExtent,
[in] VARIANT MinContrastComp, [in] VARIANT MinScoreComp,
[in] VARIANT NumLevelsComp, [in] VARIANT AngleStepComp,
[in] String OptimizationComp, [in] VARIANT MetricComp,
[in] VARIANT PregenerationComp, [out] VARIANT RootRanking )
void HComponentModelX.CreateTrainedComponentModel
([in] HComponentTrainingX ComponentTrainingID, [in] double AngleStart,
[in] double AngleExtent, [in] VARIANT MinContrastComp,
[in] VARIANT MinScoreComp, [in] VARIANT NumLevelsComp,
[in] VARIANT AngleStepComp, [in] String OptimizationComp,
[in] VARIANT MetricComp, [in] VARIANT PregenerationComp,
[out] VARIANT RootRanking )
void HOperatorSetX.CreateTrainedComponentModel
([in] VARIANT ComponentTrainingID, [in] VARIANT AngleStart,
[in] VARIANT AngleExtent, [in] VARIANT MinContrastComp,
[in] VARIANT MinScoreComp, [in] VARIANT NumLevelsComp,
[in] VARIANT AngleStepComp, [in] VARIANT OptimizationComp,
[in] VARIANT MetricComp, [in] VARIANT PregenerationComp,
[out] VARIANT ComponentModelID, [out] VARIANT RootRanking )

Prepare a component model for matching based on trained components.


CreateTrainedComponentModel prepares the training result, which is passed in
ComponentTrainingID, as a component model for matching. The output parameter ComponentModelID
is a handle for this model, which is used in subsequent calls to FindComponentModel. In con-
trast to CreateComponentModel, the model components must have been previously trained using
TrainModelComponents before calling CreateTrainedComponentModel.
The parameters AngleStart and AngleExtent determine the range of possible rotations of the component
model in an image.
Internally, a separate shape model is built for each model component (see CreateShapeModel).
Therefore, the parameters MinContrastComp, MinScoreComp, NumLevelsComp, AngleStepComp,
OptimizationComp, MetricComp, and PregenerationComp correspond to the parameters of
CreateShapeModel, with the following differences: First, the parameter Optimization of
CreateShapeModel provides the possibility to reduce the number of model points as well as the possibil-
ity to completely pregenerate the shape model. In contrast, the operator CreateTrainedComponentModel
uses a separate parameter PregenerationComp in order to decide whether the shape models should be com-
pletely pregenerated or not. A second difference concerning the parameter MinScoreComp should be noted.
When using the shape-based matching, this parameter needs not be passed when preparing the shape model us-
ing CreateShapeModel but only during the search using FindShapeModel. In contrast, when prepar-
ing the component model it is favorable to analyze rotational symmetries of the model components and sim-
ilarities between the model components. However, this analysis only leads to meaningful results if the value
for MinScoreComp that is used during the search (see FindComponentModel) is already approximately
known. After the search with FindComponentModel the pose parameters of the components in a search im-
age are returned. Note that the pose parameters refer to the reference points of the components. The reference
point of a component is the center of gravity of its associated region that is returned in ModelComponents of
TrainModelComponents.
The parameters MinContrastComp, NumLevelsComp, AngleStepComp, and OptimizationComp can
be automatically determined by passing ’auto’ for the respective parameters.
All component-specific input parameters (parameter names terminate with the suffix Comp) must either contain
one element, in which case the parameter is used for all model components, or must contain the same number
of elements as the number of model components contained in ComponentTrainingID, in which case each
parameter element refers to the corresponding component in ComponentTrainingID.
In addition to the individual shape models, the component model also contains information about the way the
single model components must be searched relative to each other using FindComponentModel in order to
minimize the computation time of the search. For this, the components are represented in a tree structure. First, the

HALCON 8.0.2
550 CHAPTER 7. MATCHING

component that stands at the root of this search tree (root component) is searched. Then, the remaining components
are searched relative to the pose of their predecessor in the search tree.
The root component can be passed as an input parameter of FindComponentModel during the search. To what
extent a model component is suited to act as root component depends on several factors. In principle, a model
component that can be found in the image with a high probability should be chosen. Therefore, a component that
is sometimes occluded to a high degree or that is missing in some cases is not well suited to act as root component.
Additionally, the computation time that is associated with the root component during the search can serve as a
criterion. A ranking of the model components that is based on the latter criterion is returned in RootRanking.
In this parameter the indices of the model components are sorted in descending order according to their associ-
ated computation time, i.e., RootRanking[0] contains the index of the model component that, chosen as root
component, allows the fastest search. Note that the ranking returned in RootRanking represents only a coarse
estimation. Furthermore, the calculation of the root ranking assumes that the image size as well as the value of the
system parameter ’border_shape_models’ are identical when calling CreateTrainedComponentModel and
FindComponentModel.
Parameter
. ComponentTrainingID (input control) . . . . component_training ; HComponentTrainingX / VARIANT
Handle of the training result.
. AngleStart (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; double / VARIANT
Smallest rotation of the component model.
Default Value : -0.39
Suggested values : AngleStart ∈ {-3.14, -1.57, -0.79, -0.39, -0.20, 0.0}
. AngleExtent (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; double / VARIANT
Extent of the rotation of the component model.
Default Value : 0.79
Suggested values : AngleExtent ∈ {6.28, 3.14, 1.57, 0.79, 0.39}
Restriction : (AngleExtent ≥ 0)
. MinContrastComp (input control) . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer, string )
Minimum contrast of the components in the search images.
Default Value : ’auto’
Suggested values : MinContrastComp ∈ {’auto’, 10, 20, 20, 40}
Restriction : (M inContrastComp ≥ 0)
. MinScoreComp (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Minimum score of the instances of the components to be found.
Default Value : 0.5
Suggested values : MinScoreComp ∈ {0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}
Minimum Increment : 0.01
Recommended Increment : 0.05
Restriction : ((0 ≤ M inScoreComp) ∧ (M inScoreComp ≤ 1))
. NumLevelsComp (input control) . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer, string )
Maximum number of pyramid levels for the components.
Default Value : ’auto’
List of values : NumLevelsComp ∈ {’auto’, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
. AngleStepComp (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad(-array) ; VARIANT ( real, string )
Step length of the angles (resolution) for the components.
Default Value : ’auto’
Suggested values : AngleStepComp ∈ {’auto’, 0.0175, 0.0349, 0.0524, 0.0698, 0.0873}
Restriction : (AngleStepComp ≥ 0)
. OptimizationComp (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Kind of optimization for the components.
Default Value : ’auto’
List of values : OptimizationComp ∈ {’auto’, ’none’, ’point_reduction_low’, ’point_reduction_medium’,
’point_reduction_high’}
. MetricComp (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .string(-array) ; VARIANT ( string )
Match metric used for the components.
Default Value : ’use_polarity’
List of values : MetricComp ∈ {’use_polarity’, ’ignore_global_polarity’, ’ignore_local_polarity’,
’ignore_color_polarity’}

HALCON/COM Reference Manual, 2008-5-13


7.1. COMPONENT-BASED 551

. PregenerationComp (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )


Complete pregeneration of the shape models for the components if equal to ’true’.
Default Value : ’false’
List of values : PregenerationComp ∈ {’true’, ’false’}
. ComponentModelID (output control) . . . . . . . . . . component_model ; HComponentModelX / VARIANT
Handle of the component model.
. RootRanking (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Ranking of the model components expressing the suitability to act as the root component.
Example

* Get the model image.


read_image (ModelImage, ’model_image.tif’)
* Define the regions for the initial components.
gen_rectangle2 (InitialComponentRegions, 212, 233, 0.62, 167, 29)
gen_rectangle2 (Rectangle2, 298, 363, 1.17, 162, 34)
gen_rectangle2 (Rectangle3, 63, 444, -0.26, 50, 27)
gen_rectangle2 (Rectangle4, 120, 473, 0, 33, 20)
InitialComponentRegions := [InitialComponentRegions,Rectangle2]
InitialComponentRegions := [InitialComponentRegions,Rectangle3]
InitialComponentRegions := [InitialComponentRegions,Rectangle4]
* Get the training images.
TrainingImages := []
for i := 1 to 4 by 1
read_image (TrainingImage, ’training_image-’+i+’.tif’)
TrainingImages := [TrainingImages,TrainingImage]
endfor
* Extract the model components and train the relations.
train_model_components (ModelImage, InitialComponentRegions, TrainingImages,
ModelComponents, 22, 60, 30, 0.65, 0, 0, rad(60),
’speed’, ’rigidity’, 0.2, 0.4, ComponentTrainingID)
* Create the component model based on the training result.
create_trained_component_model (ComponentTrainingID, -rad(30), rad(60), 10,
0.5, ’auto’, ’auto’, ’none’, ’use_polarity’,
’false’, ComponentModelID, RootRanking)
* Find the component model in a run-time image.
read_image (SearchImage, ’search_image.tif’)
find_component_model (SearchImage, ComponentModelID, RootRanking, -rad(30),
rad(60), 0.5, 0, 0.5, ’stop_search’, ’prune_branch’,
’none’, 0.55, ’least_squares’, 0, 0.9, ModelStart,
ModelEnd, Score, RowComp, ColumnComp, AngleComp,
ScoreComp, ModelComp)

Result
If the parameters are valid, the operator CreateTrainedComponentModel returns the value TRUE. If nec-
essary an exception is raised.
Parallelization Information
CreateTrainedComponentModel is processed completely exclusively without parallelization.
Possible Predecessors
TrainModelComponents, ReadTrainingComponents
Possible Successors
FindComponentModel
See also
CreateShapeModel, FindShapeModel
Alternatives
CreateComponentModel

HALCON 8.0.2
552 CHAPTER 7. MATCHING

Module
Matching

[out] VARIANT ModelStart HImageX.FindComponentModel


([in] HComponentModelX ComponentModelID, [in] VARIANT RootComponent,
[in] VARIANT AngleStartRoot, [in] VARIANT AngleExtentRoot,
[in] double MinScore, [in] long NumMatches, [in] double MaxOverlap,
[in] String IfRootNotFound, [in] String IfComponentNotFound,
[in] String PosePrediction, [in] VARIANT MinScoreComp,
[in] VARIANT SubPixelComp, [in] VARIANT NumLevelsComp,
[in] VARIANT GreedinessComp, [out] VARIANT ModelEnd, [out] VARIANT Score,
[out] VARIANT RowComp, [out] VARIANT ColumnComp, [out] VARIANT AngleComp,
[out] VARIANT ScoreComp, [out] VARIANT ModelComp )
[out] VARIANT ModelStart HComponentModelX.FindComponentModel
([in] HImageX Image, [in] VARIANT RootComponent, [in] VARIANT AngleStartRoot,
[in] VARIANT AngleExtentRoot, [in] double MinScore, [in] long NumMatches,
[in] double MaxOverlap, [in] String IfRootNotFound,
[in] String IfComponentNotFound, [in] String PosePrediction,
[in] VARIANT MinScoreComp, [in] VARIANT SubPixelComp,
[in] VARIANT NumLevelsComp, [in] VARIANT GreedinessComp,
[out] VARIANT ModelEnd, [out] VARIANT Score, [out] VARIANT RowComp,
[out] VARIANT ColumnComp, [out] VARIANT AngleComp, [out] VARIANT ScoreComp,
[out] VARIANT ModelComp )
void HOperatorSetX.FindComponentModel ([in] IHObjectX Image,
[in] VARIANT ComponentModelID, [in] VARIANT RootComponent,
[in] VARIANT AngleStartRoot, [in] VARIANT AngleExtentRoot,
[in] VARIANT MinScore, [in] VARIANT NumMatches, [in] VARIANT MaxOverlap,
[in] VARIANT IfRootNotFound, [in] VARIANT IfComponentNotFound,
[in] VARIANT PosePrediction, [in] VARIANT MinScoreComp,
[in] VARIANT SubPixelComp, [in] VARIANT NumLevelsComp,
[in] VARIANT GreedinessComp, [out] VARIANT ModelStart,
[out] VARIANT ModelEnd, [out] VARIANT Score, [out] VARIANT RowComp,
[out] VARIANT ColumnComp, [out] VARIANT AngleComp, [out] VARIANT ScoreComp,
[out] VARIANT ModelComp )

Find the best matches of a component model in an image.


The operator FindComponentModel finds the best NumMatches instances of the component model
ComponentModelID in the input image Image. The model must have been created previously by calling
CreateTrainedComponentModel, CreateComponentModel, or ReadComponentModel.
The components of the component model ComponentModelID are represented in in a tree structure. The com-
ponent that stands at the root of this search tree (root component) is searched within the full search space, i.e., at
all allowed positions and in the allowed range of orientations (see below). In contrast, the remaining components
are searched relative to the pose of their predecessor in the search tree within a restricted search space that is com-
puted from the relations (recursive search). The index of the root component can be passed in RootComponent.
To what extent a model component is suited to act as root component depends on several factors. In principle, a
model component that can be found in the image with a high probability, should be chosen. Therefore, a com-
ponent that is sometimes occluded to a high degree or that is missing in some cases is not well suited to act as
root component. The behavior of the operator when dealing with a missing or strongly occluded root compo-
nent can be set with IfRootNotFound (see below). Also, the computation time that is associated with the
root component during the search can serve as a criterion. A ranking of the model components that is based
on the latter criterion is returned in RootRanking of the operator CreateTrainedComponentModel or
CreateComponentModel, respectively. If the complete ranking is passed in RootComponent, the first value
RootComponent[0] is automatically selected as the root component. The domain of the image Image deter-
mines the search space for the reference point, i.e., the allowed positions, of the root component. The parameters
AngleStartRoot and AngleExtentRoot specify the allowed angle range within which the root component
is searched. If necessary, the range of rotations is clipped to the range given when the component model was

HALCON/COM Reference Manual, 2008-5-13


7.1. COMPONENT-BASED 553

created with CreateTrainedComponentModel or CreateComponentModel, respectively. The angle


range for each component can be queried with GetShapeModelParams after requesting the corresponding
shape model handles with GetComponentModelParams.
The position and rotation of the model components of all found component model instances are returned in
RowComp, ColumnComp, and AngleComp. The coordinates RowComp and ColumnComp are the coordi-
nates of the origin (reference point) of the component in the search image. If the component model was created
with CreateTrainedComponentModel by training, the origin of the component is the center of gravity of
the respective returned contour region in ModelComponents of the operator TrainModelComponents.
Otherwise, if the component model was created manually with CreateComponentModel, the origin of the
component is the center of gravity of the corresponding passed component region ComponentRegion of the op-
erator CreateComponentModel. Since the relations between the components in ComponentModelID refer
to this reference point, the origin of the components must not be modified by using SetShapeModelOrigin.
Additionally, the score of each found component instance is returned in ScoreComp. The score is a number
between 0 and 1, and is an approximate measure of how much of the component is visible in the image. If,
for example, half of the component is occluded, the score cannot exceed 0.5. While ScoreComp represents
the score of the instances of the single components, Score contains the score of the instances of the entire
component model. More precisely, Score contains the weighted mean of the associated values of ScoreComp.
The weighting is performed according to the number of model points within the respective component.
In order to assign the values in RowComp, ColumnComp, AngleComp, and ScoreComp to the as-
sociated model component, the index of the model component (see CreateComponentModel and
TrainModelComponents, respectively) is returned in ModelComp. Furthermore, for each found instance
of the component model its associated component matches are given in ModelStart and ModelEnd. Thus,
the matches of the components that correspond to the first found instance of the component model are given
by the interval of indices [ModelStart[0],ModelEnd[0]]. The indices refer to the parameters RowComp,
ColumnComp, AngleComp, ScoreComp, and ModelComp. Assume, for example, that two instances of the
component model, which consists of three components, are found in the image, where for one instance only two
components (component 0 and component 2) could be found. Then the returned parameters could, for exam-
ple, have the following elements: RowComp = [100,200,300,150,250], ColumnComp = [200,210,220,400,425],
AngleComp = [0,0.1,-0.2,0.1,0.2,0], ScoreComp = [1,1,1,1,1], ModelComp = [0,1,2,0,2], ModelStart
= [0,3], ModelEnd = [2,4], Score = [1,1]. The operator GetFoundComponentModel can be used to
visualize the result of the search and to extract the component matches of a certain component model instance.
By default, the components are searched at image positions where the components lie completely within the im-
age. This means that the components will not be found if they extend beyond the borders of the image, even
if they would achieve a score greater than MinScoreComp (see below). This behavior can be changed with
SetSystem(’borderShapeModels’,’true’), which will cause components that extend beyond the im-
age border to be found if they achieve a score greater than MinScoreComp. Here, points lying outside the image
are regarded as being occluded, i.e., they lower the score. It should be noted that the runtime of the search will
increase in this mode.
The parameter MinScore determines what score a potential match of the component model must at least have to
be regarded as an instance of the component model in the image. If the component model can be expected never
to be occluded in the images, MinScore may be set as high as 0.8 or even 0.9. If a missing or strongly occluded
root component must be assumed, and hence IfRootNotFound is set to ’select_new_root’ (see below), the
search is faster the larger MinScore is chosen. Otherwise, the value of this parameter only slightly influences the
computation time.
The maximum number of model instances to be found can be determined with NumMatches. If more than
NumMatches instances with a score greater than MinScore are found in the image, only the best NumMatches
instances are returned. If fewer than NumMatches are found, only that number is returned, i.e., the parameter
MinScore takes precedence over NumMatches. If all model instances exceeding MinScore in the image
should be found, NumMatches must be set to 0.
In some cases, found instances only differ in the pose of one or a few components. The parameter MaxOverlap
determines by what fraction (i.e., a number between 0 and 1) two instances may at most overlap in order to
consider them as different instances, and hence to return them separately. If two instances overlap each other by
more than MaxOverlap only the best instance is returned. The calculation of the overlap is based on the smallest
enclosing rectangles of arbitrary orientation (see SmallestRectangle2) of the found component instances. If
MaxOverlap = 0, the found instances may not overlap at all, while for MaxOverlap = 1 no check for overlap
is performed, and hence all instances are returned.

HALCON 8.0.2
554 CHAPTER 7. MATCHING

The parameter IfRootNotFound specifies the behavior of the operator when dealing with a missing or
strongly occluded root component. This parameter strongly influences the computation time of the operator. If
IfRootNotFound is set to ’stop_search’, it is assumed that the root component is always found in the image.
Consequently, for instances for which the root component could not be found the search for the remaining compo-
nents is not continued. If IfRootNotFound is set to ’select_new_root’, different components are successively
chosen as the root component and searched within the full search space. The order in which the selection of the
root component is performed corresponds to the order passed in RootRanking. The poses of the found in-
stances of all root components are then used to start the recursive search for the remaining components. Hence,
it is possible to find instances even if the original root component is not found. However, the computation time
of the search increases significantly in comparison to the search when choosing ’stop_search’. The number of
root components to search depends on the value specified for MinScore. The higher the value for MinScore
is chosen the fewer root components must be searched, and thus the faster the search is performed. If the number
of elements in RootComponent is less than the number of required root components during the search, the root
components are completed by the automatically computed order (see CreateTrainedComponentModel or
CreateComponentModel).
The parameter IfComponentNotFound specifies the behavior of the operator when dealing with missing or
strongly occluded components other than the root component. Here, it can be stated in which way components
that must be searched relative to the pose of another (predecessor) component should be treated if the predecessor
component was not found. If IfComponentNotFound is set to ’prune_branch’, such components are not
searched at all and are also treated as ’not found’. If IfComponentNotFound is set to ’search_from_upper’,
such components are searched relative to the pose of the predecessor component of the predecessor component. If
IfComponentNotFound is set to ’search_from_best’, such components are searched relative to the pose of the
already found component from which the relative search can be performed with minimum computational effort.
The parameter PosePrediction determines whether the pose of components that could not be found should
be estimated. If PosePrediction is set to ’none’, only the poses of the found components are returned. In
contrast, if PosePrediction is set to ’from_neighbors’ or ’from_all’, the poses of components that could not
be found are estimated and returned with a score of ScoreComp = 0.0. The estimation of the poses is then either
based on the poses of the found neighboring components in the search tree (’from_neighbors’) or on the poses of
all found components (’from_all’).
Internally, the shape-based matching is used for the component-based matching in order to search the individ-
ual components (see FindShapeModel). Therefore, the parameters MinScoreComp, SubPixelComp,
NumLevelsComp, and GreedinessComp have the same meaning as the corresponding parameters in
FindShapeModel. These parameters must either contain one element, in which case the parameter is used for
all components, or must contain the same number of elements as model components in ComponentModelID,
in which case each parameter element refers to the corresponding component in ComponentModelID.
NumLevelsComp may also contain two elements or twice the number of elements as model components. The
first value determines the number of pyramid levels to use. The second value determines the lowest pyramid level
to which the found matches are tracked. If different values should be used for different components, the number
of pyramid levels and the lowest pyramid level must be specified interleaved in NumLevelsComp. If, for ex-
ample, two components are contained in ComponentModelID, and the number of pyramid levels is 5 for the
first component and 4 for the second component, and the lowest pyramid level is 2 for the first component and 1
for the second component, NumLevelsComp = [5,2,4,1] must be selected. Further details can be found in the
documentation of FindShapeModels.
Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . (multichannel-)image ; HImageX / IHObjectX ( byte, uint2 )


Input image in which the component model should be found.
. ComponentModelID (input control) . . . . . . . . . . . component_model ; HComponentModelX / VARIANT
Handle of the component model.
. RootComponent (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Index of the root component.
Suggested values : RootComponent ∈ {0, 1, 2, 3, 4, 5, 6, 7, 8}
. AngleStartRoot (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad(-array) ; VARIANT ( real )
Smallest rotation of the root component
Default Value : -0.39
Suggested values : AngleStartRoot ∈ {-3.14, -1.57, -0.78, -0.39, -0.20, 0.0}

HALCON/COM Reference Manual, 2008-5-13


7.1. COMPONENT-BASED 555

. AngleExtentRoot (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad(-array) ; VARIANT ( real )


Extent of the rotation of the root component.
Default Value : 0.78
Suggested values : AngleExtentRoot ∈ {6.28, 3.14, 1.57, 0.78, 0.39, 0.0}
Restriction : (AngleExtentRoot ≥ 0)
. MinScore (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Minimum score of the instances of the component model to be found.
Default Value : 0.5
Suggested values : MinScore ∈ {0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}
Minimum Increment : 0.01
Recommended Increment : 0.05
Restriction : ((0 ≤ M inScore) ∧ (M inScore ≤ 1))
. NumMatches (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of instances of the component model to be found.
Default Value : 1
Suggested values : NumMatches ∈ {0, 1, 2, 3, 4, 5, 10, 20}
. MaxOverlap (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Maximum overlap of the instances of the component models to be found.
Default Value : 0.5
Suggested values : MaxOverlap ∈ {0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}
Minimum Increment : 0.01
Recommended Increment : 0.05
Restriction : ((0 ≤ M axOverlap) ∧ (M axOverlap ≤ 1))
. IfRootNotFound (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Behavior if the root component is missing.
Default Value : ’stop_search’
List of values : IfRootNotFound ∈ {’stop_search’, ’select_new_root’}
. IfComponentNotFound (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Behavior if a component is missing.
Default Value : ’prune_branch’
List of values : IfComponentNotFound ∈ {’prune_branch’, ’search_from_upper’, ’search_from_best’}
. PosePrediction (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Pose prediction of components that are not found.
Default Value : ’none’
List of values : PosePrediction ∈ {’none’, ’from_neighbors’, ’from_all’}
. MinScoreComp (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Minimum score of the instances of the components to be found.
Default Value : 0.5
Suggested values : MinScoreComp ∈ {0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}
Minimum Increment : 0.01
Recommended Increment : 0.05
Restriction : ((0 ≤ M inScoreComp) ∧ (M inScoreComp ≤ 1))
. SubPixelComp (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Subpixel accuracy of the component poses if not equal to ’none’.
Default Value : ’least_squares’
List of values : SubPixelComp ∈ {’none’, ’interpolation’, ’least_squares’, ’least_squares_high’,
’least_squares_very_high’}
. NumLevelsComp (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Number of pyramid levels for the components used in the matching (and lowest pyramid level to use if
|NumLevelsComp| = 2n).
Default Value : 0
List of values : NumLevelsComp ∈ {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

HALCON 8.0.2
556 CHAPTER 7. MATCHING

. GreedinessComp (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )


“Greediness” of the search heuristic for the components (0: safe but slow; 1: fast but matches may be missed).
Default Value : 0.9
Suggested values : GreedinessComp ∈ {0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}
Minimum Increment : 0.01
Recommended Increment : 0.05
Restriction : ((0 ≤ GreedinessComp) ∧ (GreedinessComp ≤ 1))
. ModelStart (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Start index of each found instance of the component model in the tuples describing the component matches.
. ModelEnd (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
End index of each found instance of the component model in the tuples describing the component matches.
. Score (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Score of the found instances of the component model.
. RowComp (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( real )
Row coordinate of the found component matches.
. ColumnComp (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( real )
Column coordinate of the found component matches.
. AngleComp (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad(-array) ; VARIANT ( real )
Rotation angle of the found component matches.
. ScoreComp (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Score of the found component matches.
. ModelComp (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Index of the found components.
Result
If the parameter values are correct, the operator FindComponentModel returns the value TRUE.
If the input is empty (no input image available) the behavior can be set via SetSystem
(’noObjectResult’,<Result>). If necessary, an exception is raised.
Parallelization Information
FindComponentModel is reentrant and processed without parallelization.
Possible Predecessors
CreateTrainedComponentModel, CreateComponentModel, ReadComponentModel
Possible Successors
GetFoundComponentModel
See also
FindShapeModel, FindShapeModels, GetShapeModelParams, GetComponentModelParams,
TrainModelComponents, SetShapeModelOrigin, SmallestRectangle2
Alternatives
FindShapeModels
Module
Matching

[out] HRegionX InitialComponents HImageX.GenInitialComponents


([in] VARIANT ContrastLow, [in] VARIANT ContrastHigh, [in] VARIANT MinSize,
[in] String Mode, [in] VARIANT GenericName, [in] VARIANT GenericValue )
void HOperatorSetX.GenInitialComponents ([in] IHObjectX ModelImage,
[out] HUntypedObjectX InitialComponents, [in] VARIANT ContrastLow,
[in] VARIANT ContrastHigh, [in] VARIANT MinSize, [in] VARIANT Mode,
[in] VARIANT GenericName, [in] VARIANT GenericValue )

Extract the initial components of a component model.


In general, there are two possibilities to use GenInitialComponents. The first possibility should be
chosen if the components of the component model are not known. Then GenInitialComponents
automatically extracts the initial components of a component model from a model image. The second

HALCON/COM Reference Manual, 2008-5-13


7.1. COMPONENT-BASED 557

possibility can be chosen if the components of the component model are approximately known. Then
GenInitialComponents can be used to find suitable parameter values for the model feature extraction in
TrainModelComponents and CreateComponentModel. Hence, the second possibility is comparable to
the function of InspectShapeModel within the shape-based matching.
When using the first possibility, GenInitialComponents extracts the initial components of a component
model from a model image ModelImage. As already mentioned, this is especially useful if the components of
the component model are not known. In this case, the resulting initial components can be used to automatically
train the component model with TrainModelComponents, which extracts the (final) model components and
the relations between them. GenInitialComponents returns the initial components in a region object tuple
InitialComponents that contains a representation for each initial component in form of contour regions.
For the automatic determination of the initial components, the domain of the model image ModelImage must
contain the entire compound object including all components. Mode specifies the method used for the auto-
matic computation. Currently, only the mode ’connection’ is available. In this mode the automatic computa-
tion is performed in two steps: In the first step, features are extracted using the parameters ContrastLow,
ContrastHigh, and MinSize. These three parameters define the contours of which the initial components
should consist and should be chosen such that only the significant features of the model image are contained in the
initial components. ContrastLow and ContrastHigh specify the gray value contrast of the points that should
be contained in the initial components. The contrast is a measure for local gray value differences between the ob-
ject and the background and between different parts of the object. The model image is segmented using a method
similar to the hysteresis threshold method used in EdgesImage. Here, ContrastLow determines the lower
threshold, while ContrastHigh determines the upper threshold. If the same value is passed for ContrastLow
and ContrastHigh a simple thresholding operation is performed. For more information about the hysteresis
threshold method, see HysteresisThreshold. MinSize can be used to select only significant features for
the initial components based on the size of the connected contour regions, i.e., connected contour regions with
fewer than MinSize points are suppressed.
The resulting connected contour regions are iteratively merged in the second step. For this, two contour regions
are merged if the distance between both regions is smaller than a certain threshold (see below). Finally, the merged
regions are returned in InitialComponents and can be used to train the component model by passing them
to TrainModelComponents.
To control the internal image processing, the parameters GenericName and GenericValue are used. This
is done by passing the names of the control parameters to be changed in GenericName as a list of strings. In
GenericValue the values are passed at the corresponding index positions.
Normally, none of the values needs to be changed. A change should only be applied in case of unsatisfying
results of the automatic determination of the initial components. The two parameters that can be changed are
’merge_distance’ and ’merge_fraction’; both are used during the iterative merging of contour regions (see above).
First, the fraction of contour pixels of one contour region that at most have a distance of ’merge_distance’ from
another contour region is computed. If this fraction exceeds the value that is passed in ’merge_fraction’ the
two contour regions are merged. Consequently, the higher ’merge_distance’ and the lower ’merge_fraction’ is
chosen the more contour regions are merged. The default value of ’merge_distance’ is 5 and the default value of
’merge_fraction’ is 0.5 (corresponds to 50 percent).
When using the second possibility, i.e., the components of the component model are approximately
known, the training by using TrainModelComponents can be performed without previously execut-
ing GenInitialComponents. If this is desired, the initial components can be specified by the
user and directly passed to TrainModelComponents. Furthermore, if the components as well as
the relative movements (relations) of the components are known, GenInitialComponents as well as
TrainModelComponents need not be executed. In fact, by immediately passing the components as well
as the relations to CreateComponentModel, the component model can be created without any training.
In both cases, however, GenInitialComponents can be used to evaluate the effect of the feature ex-
traction parameters ContrastLow, ContrastHigh, and MinSize of TrainModelComponents and
CreateComponentModel, and hence to find suitable parameter values for a certain application.
For this, the image regions for the (initial) components must be explicitly given, i.e., for each (initial) component
a separate image from which the (initial) component should be created is passed. In this case, ModelImage
contains multiple image objects. The domain of each image object is used as the region of interest for calculating
the corresponding (initial) component. The image matrix of all image objects in the tuple must be identical, i.e.,
ModelImage cannot be constructed in an arbitrary manner using ConcatObj, but must be created from the
same image using AddChannels or equivalent calls. If this is not the case, an error message is returned. If
the paramters ContrastLow, ContrastHigh, or MinSize only contain one element, this value is applied

HALCON 8.0.2
558 CHAPTER 7. MATCHING

to the creation of all (initial) components. In contrast, if different values for different (initial) components should
be used, tuples of values can be passed for these three parameters. In this case, the tuples must have a length
that corresponds to the number of (initial) components, i.e., the number of image objects in ModelImage. The
contour regions of the (initial) components are returned in InitialComponents.
Thus, the second possibility is equivalent to the function of InspectShapeModel within the shape-based
matching. However, in contrast to InspectShapeModel, GenInitialComponents does not return the
contour regions on multiple image pyramid levels. Therefore, if the number of pyramid levels to be used should be
chosen manually, preferably InspectShapeModel should be called individually for each (initial) component.
For both described possibilities the parameters ContrastLow, ContrastHigh, and MinSize can be au-
tomatically determined. If both hysteresis threshold should be automatically determined, both ContrastLow
and ContrastHigh must be set to ’auto’. In contrast, if only one threshold value should be determined,
ContrastLow must be set to ’auto’ while ContrastHigh must be set to an arbitrary value different from
’auto’.
If the input image ModelImage has one channel the representation of the model is created with the method that is
used in CreateComponentModel or CreateTrainedComponentModel for the metrics ’use_polarity’,
’ignore_global_polarity’, and ’ignore_local_polarity’. If the input image has more than one channel the represen-
tation is created with the method that is used for the metric ’ignore_color_polarity’.
Parameter
. ModelImage (input iconic) . . . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, uint2 )
Input image from which the initial components should be extracted.
. InitialComponents (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX
Contour regions of initial components.
. ContrastLow (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer, string )
Lower hysteresis threshold for the contrast of the initial components in the image.
Default Value : ’auto’
Suggested values : ContrastLow ∈ {’auto’, 10, 20, 30, 40, 60, 80, 100, 120, 140, 160}
Restriction : (ContrastLow > 0)
. ContrastHigh (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer, string )
Upper hysteresis threshold for the contrast of the initial components in the image.
Default Value : ’auto’
Suggested values : ContrastHigh ∈ {’auto’, 10, 20, 30, 40, 60, 80, 100, 120, 140, 160}
Restriction : ((ContrastHigh > 0) ∧ (ContrastHigh ≥ ContrastLow))
. MinSize (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer, string )
Minimum size of the initial components.
Default Value : ’auto’
Suggested values : MinSize ∈ {’auto’, 0, 5, 10, 20, 30, 40}
Restriction : (M inSize ≥ 0)
. Mode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Type of automatic segmentation.
Default Value : ’connection’
List of values : Mode ∈ {’connection’}
. GenericName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Names of optional control parameters.
Default Value : []
List of values : GenericName ∈ {’merge_distance’, ’merge_fraction’}
. GenericValue (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( integer, real )
Values of optional control parameters.
Default Value : []
Example

* First example that shows the use of gen_initial_components to automatically


extract the initial components from a model image.

* Get the model image.


read_image (Image, ’model_image.tif’)
* Define the entire model region.

HALCON/COM Reference Manual, 2008-5-13


7.1. COMPONENT-BASED 559

gen_rectangle1 (ModelRegion, 119, 106, 330, 537)


reduce_domain (Image, ModelRegion, ModelImage)
* Automatically generate the initial components.
gen_initial_components (ModelImage, InitialComponents, 40, 40, 20,
’connection’, [], [])
* Extract the model components and train the relations.
train_model_components (ModelImage, InitialComponents, TrainingImages,
ModelComponents, 40, 40, 20, 0.85, 0, 0, rad(15),
’speed’, ’rigidity’, 0.2, 0.5, ComponentTrainingID)
* Create the component model based on the training result.
create_trained_component_model (ComponentTrainingID, -rad(30), rad(60), 10,
0.8, ’auto’, ’auto’, ’none’, ’use_polarity’,
’false’, ComponentModelID, RootRanking)

* Second example that shows the use of gen_initial_components to evaluate


the effect of the feature extraction parameters.

* Get the model image.


read_image (ModelImage, ’model_image.tif’)
* Define the regions for the components.
gen_rectangle2 (ComponentRegions, 318, 109, -1.62, 34, 19)
gen_rectangle2 (Rectangle2, 342, 238, -1.63, 32, 17)
gen_rectangle2 (Rectangle3, 355, 505, 1.41, 25, 17)
ComponentRegions := [ComponentRegions,Rectangle2]
ComponentRegions := [ComponentRegions,Rectangle3]
add_channels (ComponentRegions, ModelImage, ModelImageReduced)
gen_initial_components (ModelImageReduced, InitialComponents, 15, 40, 15,
’connection’, [], [])
* Create the component model by explicitly specifying the relations.
create_component_model (ModelImage, ComponentRegions, 20, 20, rad(25), 0,
rad(360), 15, 40, 15, 10, 0.8, ’auto’, ’auto’,
’none’, ’use_polarity’, ’false’, ComponentModelID,
RootRanking)

Result
If the parameter values are correct, the operator GenInitialComponents returns the value TRUE.
If the input is empty (no input images are available) the behavior can be set via SetSystem
(’noObjectResult’,<Result>). If necessary, an exception is raised.
Parallelization Information
GenInitialComponents is reentrant and processed without parallelization.
Possible Predecessors
DrawRegion, AddChannels, ReduceDomain
Possible Successors
TrainModelComponents
Alternatives
InspectShapeModel
Module
Matching

HALCON 8.0.2
560 CHAPTER 7. MATCHING

[out] VARIANT MinScoreComp HComponentModelX.GetComponentModelParams


([out] VARIANT RootRanking, [out] HShapeModelX ShapeModelIDs )
void HOperatorSetX.GetComponentModelParams
([in] VARIANT ComponentModelID, [out] VARIANT MinScoreComp,
[out] VARIANT RootRanking, [out] VARIANT ShapeModelIDs )

Return the parameters of a component model.


The operator GetComponentModelParams returns the parameters of the component model
ComponentModelID. In particular, this output can be used to check the parameters RootRanking and
MinScoreComp after reading the component model with ReadComponentModel. Additionally, the operator
returns the shape model IDs ShapeModelIDs of the model components. The order of the returned shape model
IDs corresponds to the indices of the components within the component model ComponentModelID. The IDs
can be used to query their shape model parameters with GetShapeModelParams.
Parameter

. ComponentModelID (input control) . . . . . . . . . . . component_model ; HComponentModelX / VARIANT


Handle of the component model.
. MinScoreComp (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Minimum score of the instances of the components to be found.
. RootRanking (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Ranking of the model components expressing their suitability to act as root component.
. ShapeModelIDs (output control) . . . . . . . . shape_model(-array) ; HShapeModelX / VARIANT ( integer )
Handles of the shape models of the individual model components.
Example

read_component_model (’pliers.cpm’, ComponentModelID)


get_component_model_params (ComponentModelID, MinScoreComp, RootRanking,
ShapeModelIDs)
for i := 0 to |ShapeModelIDs|-1 by 1
get_shape_model_params (ShapeModelIDs[i], NumLevels, AngleStart,
AngleExtent, AngleStep, ScaleMin, ScaleMax,
ScaleStep, Metric, MinContrast)
endfor

Result
If the handle of the component model is valid, the operator GetComponentModelParams returns the value
TRUE. If necessary, an exception is raised.
Parallelization Information
GetComponentModelParams is reentrant and processed without parallelization.
Possible Predecessors
CreateTrainedComponentModel, CreateComponentModel
See also
GetShapeModelParams
Module
Matching

HALCON/COM Reference Manual, 2008-5-13


7.1. COMPONENT-BASED 561

[out] HRegionX Tree HComponentModelX.GetComponentModelTree


([out] HRegionX Relations, [in] VARIANT RootComponent, [in] VARIANT Image,
[out] VARIANT StartNode, [out] VARIANT EndNode, [out] VARIANT Row,
[out] VARIANT Column, [out] VARIANT Phi, [out] VARIANT Length1,
[out] VARIANT Length2, [out] VARIANT AngleStart, [out] VARIANT AngleExtent )
void HOperatorSetX.GetComponentModelTree
([out] HUntypedObjectX Tree, [out] HUntypedObjectX Relations,
[in] VARIANT ComponentModelID, [in] VARIANT RootComponent,
[in] VARIANT Image, [out] VARIANT StartNode, [out] VARIANT EndNode,
[out] VARIANT Row, [out] VARIANT Column, [out] VARIANT Phi,
[out] VARIANT Length1, [out] VARIANT Length2, [out] VARIANT AngleStart,
[out] VARIANT AngleExtent )

Return the search tree of a component model.


GetComponentModelTree returns the search tree Tree and the associated relations Relations of the
component model that is passed in ComponentModelID in form of regions as well as in numerical form.
GetComponentModelTree is particularly useful in order to visualize the search order of the components,
which was automatically computed in CreateTrainedComponentModel or CreateComponentModel.
Because the search tree depends on the selected root component, the root component must be passed in
RootComponent. The nodes in the tree Tree represent the model components, the connecting lines between
the nodes indicate which components are searched relative to each other. The position of the nodes corresponds to
the position of the components in the model image (if Image = ’model_image’ or Image = 0) or in a training
image (if Image ≥ 1). In the latter case, the component model must have been created based on a component
training result with CreateTrainedComponentModel.
Let n be the number of components in ComponentModelID. The region object tuple Relations of length
n is designed as follows: For each component a separate region is returned. The positions of all components in
the image are represented by circles with a radius of 3 pixels. For each component other than the root compo-
nent RootComponent, additionally the position relation and the orientation relation relative to the predecessor
component in the search tree are represented. The position relation is represented by a rectangle, the orientation
relation is represented by a circle sector with a radius of 30 pixels. The center of the circle is placed at the mean
relative position of the component. The rectangle describes the movement of the reference point of the respective
component relative to the pose of its predecessor component, the circle sector describes the variation of the relative
orientation. A relative orientation of 0 corresponds to the relative orientation of both components in the model
image.
In addition to the regions, the search tree as well as the associated relations are also returned in numerical form.
The search tree is described by the two tuples StartNode and EndNode, both of length n, which contain the
start and the end node of all arcs in the tree. The nodes contain the indices of the components. This means that
during the search the component that is described by the end node is searched relative to the pose of the component
that is described by the start node (predecessor component). Since the root component is not searched relative to
any other component, and hence does not have a predecessor component, the associated start node is set to -1. The
relations are returned in Row, Column, Phi, Length1, Length2, AngleStart, and AngleExtent. These
parameters are tuples of length n, and contain the relations of all components relative to their associated predeces-
sor component, where the order of the values within the tuples is determined by the index of the corresponding
component. The position relation is described by the parameters of the corresponding rectangle Row, Column,
Phi, Length1, and Length2 (see GenRectangle2). The orientation relation is described by the starting
angle AngleStart and the angle extent AngleExtent.
For the root component as well as for components that do not have a predecessor in the current image or that
have not been found in the current image, an empty region is returned and the corresponding values of the seven
parameters are set to 0.
Parameter
. Tree (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX
Search tree.
. Relations (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX
Relations of components that are connected in the search tree.
. ComponentModelID (input control) . . . . . . . . . . . component_model ; HComponentModelX / VARIANT
Handle of the component model.

HALCON 8.0.2
562 CHAPTER 7. MATCHING

. RootComponent (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )


Index of the root component.
Suggested values : RootComponent ∈ {0, 1, 2, 3, 4, 5, 6, 7, 8}
. Image (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( string, integer )
Image for which the tree is to be returned.
Default Value : ’model_image’
Suggested values : Image ∈ {’model_image’, 0, 1, 2, 3, 4, 5, 6, 7, 8}
. StartNode (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Component index of the start node of an arc in the search tree.
. EndNode (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Component index of the end node of an arc in the search tree.
. Row (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle2.center.y(-array) ; VARIANT ( real )
Row coordinate of the center of the rectangle representing the relation.
. Column (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle2.center.x(-array) ; VARIANT ( real )
Column index of the center of the rectangle representing the relation.
. Phi (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle2.angle.rad(-array) ; VARIANT ( real )
Orientation of the rectangle representing the relation (radians).
Restriction : (((−(pi)/2) < P hi) ∧ (P hi ≤ (pi/2)))
. Length1 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle2.width(-array) ; VARIANT ( real )
First radius (half length) of the rectangle representing the relation.
Restriction : (Length1 ≥ 0.0)
. Length2 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle2.height(-array) ; VARIANT ( real )
Second radius (half width) of the rectangle representing the relation.
Restriction : ((Length2 ≥ 0.0) ∧ (Length2 ≤ Length1))
. AngleStart (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad(-array) ; VARIANT ( real )
Smallest relative orientation angle.
. AngleExtent (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad(-array) ; VARIANT ( real )
Extent of the relative orientation angle.
Example

* Read the model image.


read_image (ModelImage, ’model_image.tif’)
* Describe the model components.
gen_rectangle2 (ComponentRegions, 318, 109, -1.62, 34, 19)
gen_rectangle2 (Rectangle2, 342, 238, -1.63, 32, 17)
gen_rectangle2 (Rectangle3, 355, 505, 1.41, 25, 17)
ComponentRegions := [ComponentRegions,Rectangle2]
ComponentRegions := [ComponentRegions,Rectangle3]
* Create the component model.
create_component_model (ModelImage, ComponentRegions, 20, 20, rad(25), 0,
rad(360), 15, 40, 15, 10, 0.8, 0, 0, ’none’,
’use_polarity’, ’true’, ComponentModelID,
RootRanking)
* Get the component model tree.
get_component_model_tree (Tree, Relations, ComponentModelID, RootRanking,
’model_image’, StartNode, EndNode, Row, Column,
Phi, Length1, Length2, AngleStart, AngleExtent)
dev_set_colored (12)
dev_display (ModelImage)
dev_display (Tree)
dev_display (Relations)

Result
If the parameters are valid, the operator GetComponentModelTree returns the value TRUE. If necessary an
exception is raised.

HALCON/COM Reference Manual, 2008-5-13


7.1. COMPONENT-BASED 563

Parallelization Information
GetComponentModelTree is reentrant and processed without parallelization.
Possible Predecessors
CreateTrainedComponentModel, CreateComponentModel
See also
TrainModelComponents
Module
Matching

[out] HRegionX Relations HComponentTrainingX.GetComponentRelations


([in] long ReferenceComponent, [in] VARIANT Image, [out] VARIANT Row,
[out] VARIANT Column, [out] VARIANT Phi, [out] VARIANT Length1,
[out] VARIANT Length2, [out] VARIANT AngleStart, [out] VARIANT AngleExtent )
void HOperatorSetX.GetComponentRelations
([out] HUntypedObjectX Relations, [in] VARIANT ComponentTrainingID,
[in] VARIANT ReferenceComponent, [in] VARIANT Image, [out] VARIANT Row,
[out] VARIANT Column, [out] VARIANT Phi, [out] VARIANT Length1,
[out] VARIANT Length2, [out] VARIANT AngleStart, [out] VARIANT AngleExtent )

Return the relations between the model components that are contained in a training result.
GetComponentRelations returns the relations between model components after training them with
TrainModelComponents. With the parameter ReferenceComponent, you can select a reference com-
ponent. GetComponentRelations then returns the relations between the reference component and all other
components in the model image (if Image = ’model_image’ or Image = 0) or in a training image (if Image ≥ 1).
In order to obtain the relations in the ith training image, Image must be set to i. The result of the training returned
by TrainModelComponents must be passed in ComponentTrainingID. ReferenceComponent de-
scribes the index of the reference component and must be within the range of 0 and n-1, if n is the number of model
components (see TrainModelComponents).
The relations are returned in form of regions in Relations as well as in form of numerical values in Row,
Column, Phi, Length1, Length2, AngleStart, and AngleExtent.
The region object tuple Relations is designed as follows. For each component a separate region is returned.
Consequently, Relations contains n regions, where the order of the regions within the tuple is determined by the
index of the corresponding components. The positions of all components in the image are represented by circles
with a radius of 3 pixels. For each component other than the reference component ReferenceComponent, ad-
ditionally the position relation and the orientation relation relative to the reference component are represented.
The position relation is represented by a rectangle and the orientation relation is represend by a circle sec-
tor with a radius of 30 pixels. The center of the circle is placed at the mean relative position of the compo-
nent. The rectangle describes the movement of the reference point of the respective component relative to the
pose of the reference component, while the circle sector describes the variation of the relative orientation (see
TrainModelComponents). A relative orientation of 0 corresponds to the relative orientation of both compo-
nents in the model image. If both components appear in the same relative orientation in all images, the circle sector
consequently degenerates to a straight line.
In addition to the region object tuple Relations, the relations are also returned in form of numerical values in
Row, Column, Phi, Length1, Length2, AngleStart, and AngleExtent. These parameters are tuples
of length n and contain the relations of all components relative to the reference component, where the order of
the values within the tuples is determined by the index of the corresponding component. The position relation is
described by the parameters of the corresponding rectangle Row, Column, Phi, Length1, and Length2 (see
GenRectangle2). The orientation relation is described by the starting angle AngleStart and the angle extent
AngleExtent. For the reference component only the position within the image is returned in Row and Column.
All other values are set to 0.
If the reference component has not been found in the current image, an array of empty regions is returned and the
corresponding parameter values are set to 0.
The operator GetComponentRelations is particularly useful in order to visualize the result of the train-
ing that was performed with TrainModelComponents. With this, it is possible to evaluate the varia-

HALCON 8.0.2
564 CHAPTER 7. MATCHING

tions that are contained in the training images. Sometimes it might be reasonable to restart the training with
TrainModelComponents while using a different set of training images.
Parameter

. Relations (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX


Region representation of the relations.
. ComponentTrainingID (input control) . . . . component_training ; HComponentTrainingX / VARIANT
Handle of the training result.
. ReferenceComponent (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Index of reference component.
Restriction : (Ref erenceComponent ≥ 0)
. Image (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( string, integer )
Image for which the component relations are to be returned.
Default Value : ’model_image’
Suggested values : Image ∈ {’model_image’, 0, 1, 2, 3, 4, 5, 6, 7, 8}
. Row (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle2.center.y(-array) ; VARIANT ( real )
Row coordinate of the center of the rectangle representing the relation.
. Column (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle2.center.x(-array) ; VARIANT ( real )
Column index of the center of the rectangle representing the relation.
. Phi (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle2.angle.rad(-array) ; VARIANT ( real )
Orientation of the rectangle representing the relation (radians).
Restriction : (((−(pi)/2) < P hi) ∧ (P hi ≤ (pi/2)))
. Length1 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle2.width(-array) ; VARIANT ( real )
First radius (half length) of the rectangle representing the relation.
Restriction : (Length1 ≥ 0.0)
. Length2 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle2.height(-array) ; VARIANT ( real )
Second radius (half width) of the rectangle representing the relation.
Restriction : ((Length2 ≥ 0.0) ∧ (Length2 ≤ Length1))
. AngleStart (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad(-array) ; VARIANT ( real )
Smallest relative orientation angle.
. AngleExtent (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad(-array) ; VARIANT ( real )
Extent of the relative orientation angles.
Result
If the handle of the training result is valid, the operator GetComponentRelations returns the value TRUE.
If necessary an exception is raised.
Parallelization Information
GetComponentRelations is reentrant and processed without parallelization.
Possible Predecessors
TrainModelComponents
Possible Successors
TrainModelComponents
See also
GenRectangle2
Module
Matching

HALCON/COM Reference Manual, 2008-5-13


7.1. COMPONENT-BASED 565

[out] HRegionX FoundComponents


HComponentModelX.GetFoundComponentModel ([in] VARIANT ModelStart,
[in] VARIANT ModelEnd, [in] VARIANT RowComp, [in] VARIANT ColumnComp,
[in] VARIANT AngleComp, [in] VARIANT ScoreComp, [in] VARIANT ModelComp,
[in] long ModelMatch, [in] String MarkOrientation, [out] VARIANT RowCompInst,
[out] VARIANT ColumnCompInst, [out] VARIANT AngleCompInst,
[out] VARIANT ScoreCompInst )
void HOperatorSetX.GetFoundComponentModel
([out] HUntypedObjectX FoundComponents, [in] VARIANT ComponentModelID,
[in] VARIANT ModelStart, [in] VARIANT ModelEnd, [in] VARIANT RowComp,
[in] VARIANT ColumnComp, [in] VARIANT AngleComp, [in] VARIANT ScoreComp,
[in] VARIANT ModelComp, [in] VARIANT ModelMatch,
[in] VARIANT MarkOrientation, [out] VARIANT RowCompInst,
[out] VARIANT ColumnCompInst, [out] VARIANT AngleCompInst,
[out] VARIANT ScoreCompInst )

Return the components of a found instance of a component model.


GetFoundComponentModel returns the components of a found instance of the component model
ComponentModelID in form of contour regions in FoundComponents as well as in numerical form.
The operator GetFoundComponentModel is particularly useful in order to visualize the matches that have
been obtained by FindComponentModel.
The pose of the returned components corresponds to their pose in the search image as returned by
FindComponentModel. Hence, the parameters ModelStart, ModelEnd, RowComp, ColumnComp,
AngleComp, ScoreComp, and ModelComp must be passed to GetFoundComponentModel as they have
been returned by FindComponentModel. In ModelMatch the index of the found instance of the component
model must be passed. Consequently, ModelMatch must lie within the range between 0 and m-1, where m is
the number of elements in ModelStart and ModelEnd, and hence corresponds to the number of found model
instances. For example, if the best match should be retuned, ModelMatch should be set to 0.
When dealing with rotationally symmetric components, one may wish to mark the current orientation of the found
component. This can be achieved by setting MarkOrientation to ’true’. In this case, the contour region
of each component is complemented by an arrow at its reference point that points in the reference direction.
The reference direction of a component is based on the orientation of the component in the model image (see
TrainModelComponents or CreateComponentModel) and is represented by an arrow that starts at the
reference point and points to the right in the horizontal direction.
For convenience, the pose parameters as well as the score of each component of the found model instance
are additionally returned in numerical form in RowCompInst, ColumnCompInst, AngleCompInst, and
ScoreCompInst. The four tuples are always of length n, where n is the number of components in the com-
ponent model ComponentModelID. If a component could not be found during the search, an empty region
is passed in the corresponding element of FoundComponents and the value of the corresponding element in
RowCompInst, ColumnCompInst, AngleCompInst, and ScoreCompInst is set to 0.
Parameter
. FoundComponents (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX
Found components of the selected component model instance.
. ComponentModelID (input control) . . . . . . . . . . . component_model ; HComponentModelX / VARIANT
Handle of the component model.
. ModelStart (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Start index of each found instance of the component model in the tuples describing the component matches.
. ModelEnd (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
End index of each found instance of the component model to the tuples describing the component matches.
. RowComp (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( real )
Row coordinate of the found component matches.
. ColumnComp (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( real )
Column coordinate of the found component matches.
. AngleComp (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad(-array) ; VARIANT ( real )
Rotation angle of the found component matches.

HALCON 8.0.2
566 CHAPTER 7. MATCHING

. ScoreComp (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )


Score of the found component matches.
. ModelComp (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Index of the found components.
. ModelMatch (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Index of the found instance of the component model to be returned.
. MarkOrientation (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Mark the orientation of the components.
Default Value : ’false’
List of values : MarkOrientation ∈ {’true’, ’false’}
. RowCompInst (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( real )
Row coordinate of all components of the selected model instance.
. ColumnCompInst (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( real )
Column coordinate of all components of the selected model instance.
. AngleCompInst (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad(-array) ; VARIANT ( real )
Rotation angle of all components of the selected model instance.
. ScoreCompInst (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Score of all components of the selected model instance.
Example

* Read a component model from file.


read_component_model (’pliers.cpm’, ComponentModelID)
* Find the component model in a run-time image.
read_image (SearchImage, ’search_image.tif’)
find_component_model (SearchImage, ComponentModelID, RootRanking, 0,
rad(360), 0.5, 0, 0.5, ’stop_search’, ’prune_branch’,
’none’, 0.8, ’least_squares’, 0, 0.8, ModelStart,
ModelEnd, Score, RowComp, ColumnComp, AngleComp,
ScoreComp, ModelComp)
* Visualize the found instances.
for i := 0 to |ModelStart|-1 by 1
get_found_component_model (FoundComponents, ComponentModelID,
ModelStart, ModelEnd, RowComp, ColumnComp,
AngleComp, ScoreComp, ModelComp, i, ’false’,
RowCompInst, ColumnCompInst, AngleCompInst,
ScoreCompInst)
dev_display (FoundComponents)
endfor

Result
If the parameters are valid, the operator GetFoundComponentModel returns the value TRUE. If necessary an
exception is raised.
Parallelization Information
GetFoundComponentModel is reentrant and processed without parallelization.
Possible Predecessors
FindComponentModel
See also
TrainModelComponents, CreateComponentModel
Module
Matching

HALCON/COM Reference Manual, 2008-5-13


7.1. COMPONENT-BASED 567

[out] HRegionX TrainingComponents


HComponentTrainingX.GetTrainingComponents ([in] VARIANT Components,
[in] VARIANT Image, [in] String MarkOrientation, [out] VARIANT Row,
[out] VARIANT Column, [out] VARIANT Angle, [out] VARIANT Score )
void HOperatorSetX.GetTrainingComponents
([out] HUntypedObjectX TrainingComponents, [in] VARIANT ComponentTrainingID,
[in] VARIANT Components, [in] VARIANT Image, [in] VARIANT MarkOrientation,
[out] VARIANT Row, [out] VARIANT Column, [out] VARIANT Angle,
[out] VARIANT Score )

Return the initial or model components in a certain image.


GetTrainingComponents returns all initial components (if Components = ’initial_components’) or all
model components (if Components = ’model_components’) in TrainingComponents in form of contour
regions as well as in numerical form. Alternatively, by directly passing the index of an initial component, all found
poses of that initial component (i.e., the poses before solving the ambiguities in TrainModelComponents)
are returned.
The pose of the returned components corresponds to their pose in the model image (if Image = ’model_image’
or Image = 0) or in a training image (if Image ≥ 1). In order to obtain the components in the pose at which they
were found in the ith training image, Image must be set to i. Furthermore, when dealing with rotationally sym-
metric components, one may wish to mark the current orientation of the found component. This can be achieved
by setting MarkOrientation to ’true’. In this case, the contour region of each component is complemented by
an arrow at its reference point pointing in the reference direction. The reference direction of a component is based
on the orientation of the component in the model image and is represented by an arrow that starts at the reference
point and points to the right in the horizontal direction.
In addition to the contour regions, the pose and the score of all found components is returned in Row,
Column, Angle, and Score (see FindShapeModel). If Components was set to ’initial_components’
or ’model_components’, the tuples TrainingComponents, Row, Column, Angle, and Score al-
ways contain the same number of elements as initial components or model components contained in
ComponentTrainingID, respectively. If one component was not found in the image, an empty region is
returned in the corresponding element of TrainingComponents and the elements of the four output control
parameters are set to the value 0. In contrast, if the index of an initial component is passed in Components, these
tuples contain as many elements as matches of the corresponding initial component were found in the image.
The operator GetTrainingComponents is particularly useful in order to visualize the result of the
training ComponentTrainingID, which was performed with TrainModelComponents. With this,
it is possible to evaluate the suitability of the training images or to inspect the influence of the param-
eters of TrainModelComponents. Sometimes it might be reasonable to restart the training with
TrainModelComponents using a different set of training images or after adjusting the parameters.
Parameter
. TrainingComponents (output iconic) . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Contour regions of the initial components or of the model components.
. ComponentTrainingID (input control) . . . . component_training ; HComponentTrainingX / VARIANT
Handle of the training result.
. Components (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( string, integer )
Type of returned components or index of an initial component.
Default Value : ’model_components’
Suggested values : Components ∈ {’model_components’, ’initial_components’, 0, 1, 2, 3, 4, 5}
. Image (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( string, integer )
Image for which the components are to be returned.
Default Value : ’model_image’
Suggested values : Image ∈ {’model_image’, 0, 1, 2, 3, 4, 5, 6, 7, 8}
. MarkOrientation (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Mark the orientation of the components.
Default Value : ’false’
List of values : MarkOrientation ∈ {’true’, ’false’}
. Row (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( real )
Row coordinate of the found instances of all initial components or model components.

HALCON 8.0.2
568 CHAPTER 7. MATCHING

. Column (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( real )


Column coordinate of the found instances of all initial components or model components.
. Angle (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad(-array) ; VARIANT ( real )
Rotation angle of the found instances of all components.
. Score (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Score of the found instances of all components.
Example

* Get the model image.


read_image (ModelImage, ’model_image.tif’)
* Define the regions for the initial components.
gen_rectangle2 (InitialComponentRegions, 212, 233, 0.62, 167, 29)
gen_rectangle2 (Rectangle2, 298, 363, 1.17, 162, 34)
gen_rectangle2 (Rectangle3, 63, 444, -0.26, 50, 27)
gen_rectangle2 (Rectangle4, 120, 473, 0, 33, 20)
InitialComponentRegions := [InitialComponentRegions,Rectangle2]
InitialComponentRegions := [InitialComponentRegions,Rectangle3]
InitialComponentRegions := [InitialComponentRegions,Rectangle4]
* Get the training images.
TrainingImages := []
for i := 1 to 4 by 1
read_image (TrainingImage, ’training_image-’+i+’.tif’)
TrainingImages := [TrainingImages,TrainingImage]
endfor
* Extract the model components and train the relations.
train_model_components (ModelImage, InitialComponentRegions, TrainingImages,
ModelComponents, 22, 60, 30, 0.6, 0, 0, rad(60),
’speed’, ’rigidity’, 0.2, 0.4, ComponentTrainingID)
* Visualize the result of the training.
NumInitComp := |InitialComponentRegions|
NumTrainings := |TrainingImages|
for i := 1 to NumTrainings by 1
TrainingImage := TrainingImages[i]
for j := 0 to NumInitComp-1 by 1
* Visualize the ambiguous poses of each initial component.
get_training_components (TrainingComponents, ComponentTrainingID,
j, i, ’false’, Row, Column, Angle, Score)
endfor
* Visualize the final poses of the initial components.
get_training_components (TrainingComponents, ComponentTrainingID,
’initial_components’, i, ’false’,
Row, Column, Angle, Score)
* Visualize the final poses of the model components.
get_training_components (TrainingComponents, ComponentTrainingID,
’model_components’, i, ’false’,
Row, Column, Angle, Score)
endfor

Result
If the handle of the training result is valid, the operator GetTrainingComponents returns the value TRUE.
If necessary an exception is raised.
Parallelization Information
GetTrainingComponents is reentrant and processed without parallelization.
Possible Predecessors
TrainModelComponents
Possible Successors
TrainModelComponents

HALCON/COM Reference Manual, 2008-5-13


7.1. COMPONENT-BASED 569

See also
FindShapeModel
Module
Matching

[out] HRegionX ModelComponents


HComponentTrainingX.InspectClusteredComponents
([in] String AmbiguityCriterion, [in] double MaxContourOverlap,
[in] double ClusterThreshold )
void HOperatorSetX.InspectClusteredComponents
([out] HUntypedObjectX ModelComponents, [in] VARIANT ComponentTrainingID,
[in] VARIANT AmbiguityCriterion, [in] VARIANT MaxContourOverlap,
[in] VARIANT ClusterThreshold )

Inspect the rigid model components obtained from the training.


InspectClusteredComponents creates a representation of the rigid model components based on the train-
ing result ComponentTrainingID in form of contour regions. The resulting rigid model components are
computed depending on the criterion that is used to solve the ambiguities AmbiguityCriterion, the maxi-
mum allowable contour overlap MaxContourOverlap, and the cluster threshold ClusterThreshold (see
TrainModelComponents). The cluster threshold, for example, influences the merging of the initial compo-
nents. The greater the threshold is chosen, the fewer initial components are merged. The determined rigid model
components are returned in ModelComponents.
Hence, after the components have been trained once by using TrainModelComponents,
InspectClusteredComponents can be used to estimate the effect of different values for the param-
eters AmbiguityCriterion, MaxContourOverlap, and ClusterThreshold without performing the
complete training procedure several times. Once the desired parameter values have been found, they can be
efficiently adopted into the training result by using ClusterModelComponents.
Parameter
. ModelComponents (output iconic) . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Contour regions of rigid model components.
. ComponentTrainingID (input control) . . . . component_training ; HComponentTrainingX / VARIANT
Handle of the training result.
. AmbiguityCriterion (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Criterion for solving the ambiguities.
Default Value : ’rigidity’
List of values : AmbiguityCriterion ∈ {’distance’, ’orientation’, ’distance_orientation’, ’rigidity’}
. MaxContourOverlap (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Maximum contour overlap of the found initial components.
Default Value : 0.2
Suggested values : MaxContourOverlap ∈ {0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}
Minimum Increment : 0.01
Recommended Increment : 0.05
Restriction : ((0 ≤ M axContourOverlap) ∧ (M axContourOverlap ≤ 1))
. ClusterThreshold (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Threshold for clustering the initial components.
Default Value : 0.5
Suggested values : ClusterThreshold ∈ {0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}
Restriction : ((0 ≤ ClusterT hreshold) ∧ (ClusterT hreshold ≤ 1))
Example

* Get the model image.


read_image (ModelImage, ’model_image.tif’)
* Define the regions for the initial components.
gen_rectangle2 (InitialComponentRegions, 212, 233, 0.62, 167, 29)

HALCON 8.0.2
570 CHAPTER 7. MATCHING

gen_rectangle2 (Rectangle2, 298, 363, 1.17, 162, 34)


gen_rectangle2 (Rectangle3, 63, 444, -0.26, 50, 27)
gen_rectangle2 (Rectangle4, 120, 473, 0, 33, 20)
InitialComponentRegions := [InitialComponentRegions,Rectangle2]
InitialComponentRegions := [InitialComponentRegions,Rectangle3]
InitialComponentRegions := [InitialComponentRegions,Rectangle4]
* Get the training images
TrainingImages := []
for i := 1 to 4 by 1
read_image (TrainingImage, ’training_image-’+i$’02’+’.tif’)
TrainingImages := [TrainingImages,TrainingImage]
endfor
* Extract the model components and train the relations.
train_model_components (ModelImage, InitialComponentRegions, TrainingImages,
ModelComponents, 22, 60, 30, 0.65, 0, 0, rad(60),
’speed’, ’rigidity’, 0.2, 0.5, ComponentTrainingID)
* Find the best value for the parameter ClusterThreshold.
inspect_clustered_components (ModelComponents, ComponentTrainingID,
’rigidity’, 0.2, 0.4)
* Adopt the ClusterThreshold into the training result.
cluster_model_components (ModelComponents, ModelComponents,
ComponentTrainingID, ’rigidity’, 0.2, 0.4)
* Create the component model based on the training result.
create_trained_component_model (ComponentTrainingID, -rad(30), rad(60), 10,
0.5, ’auto’, ’auto’, ’none’, ’use_polarity’,
’false’, ComponentModelID, RootRanking)

Result
If the handle of the training result is valid, the operator InspectClusteredComponents returns the value
TRUE. If necessary an exception is raised.
Parallelization Information
InspectClusteredComponents is reentrant and processed without parallelization.
Possible Predecessors
TrainModelComponents
Possible Successors
ClusterModelComponents
Module
Matching

void HComponentTrainingX.ModifyComponentRelations
([in] VARIANT ReferenceComponent, [in] VARIANT ToleranceComponent,
[in] VARIANT PositionTolerance, [in] VARIANT AngleTolerance )
void HOperatorSetX.ModifyComponentRelations
([in] VARIANT ComponentTrainingID, [in] VARIANT ReferenceComponent,
[in] VARIANT ToleranceComponent, [in] VARIANT PositionTolerance,
[in] VARIANT AngleTolerance )

Modify the relations within a training result.


ModifyComponentRelations modifies the relations between the model components within the component
training result ComponentTrainingID. The selection of the relation(s) that should be changed is performed
by setting ReferenceComponent and ToleranceComponent, respectively. This means that the relative
movement of component ToleranceComponent with respect to the component ReferenceComponent is
modified.

HALCON/COM Reference Manual, 2008-5-13


7.1. COMPONENT-BASED 571

The size of the change is specified as follows: By specifying a position tolerance PositionTolerance, the
semi-axes of the rectangle that describes the reference point’s movement (see TrainModelComponents)
are enlarged by PositionTolerance pixels. Accordingly, by specifying an orientation toler-
ance AngleTolerance, the angle range that describes the variation of the relative orientation (see
TrainModelComponents) is enlarged by AngleTolerance to both sides. Consequently, negative tolerance
values lead to a decreased size of the relations. The operator ModifyComponentRelations is particularly
useful when the training images that were used during the training do not cover the entire spectrum of the relative
movements.
In order to select the relations that should be modified, values for ReferenceComponent and
ToleranceComponent can be passed in one of the following ways: For each of both parameters either one
value, several values, or the string ’all’ can be passed. The following table summarizes the different possibilities
by giving the affected relations for different combinations of parameter values. Here, four model components are
assumed (0, 1, 2, and 3). If, for example, ReferenceComponent is set to 0 and ToleranceComponent
is set to 1, then the relation (0,1), which corresponds to the relative movement of component 1 with respect to
component 0, will be modified.
ReferenceComponent ToleranceComponent Affected Relation(s)
’all’ ’all’ (0,1) (0,2) (0,3)
(1,0) (1,2) (1,3)
(2,0) (2,1) (2,3)
(3,0) (3,1) (3,2)
’all’ [1,2] (0,1) (0,2)
(1,2)
(2,1)
(3,1) (3,2)
[0,1] ’all’ (0,1) (0,2) (0,3)
(1,0) (1,2) (1,3)
0 1 (0,1)
0 [1,2] (0,1) (0,2)
[0,1] 2 (0,2) (1,2)
[0,1,2] [1,2,3] (0,1) (1,2) (2,3)
The number of tolerance values passed in PositionTolerance and AngleTolerance must be either 1 or
be equal to the number of affected relations. In the former case all affected relations are modified by the same
value, whereas in the latter case each relation can be modified individually by passing different values within a
tuple.
Parameter

. ComponentTrainingID (input control) . . . . component_training ; HComponentTrainingX / VARIANT


Handle of the training result.
. ReferenceComponent (input control) . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( integer, string )
Model component(s) relative to which the movement(s) should be modified.
Default Value : ’all’
Suggested values : ReferenceComponent ∈ {’all’, 0, 1, 2, 3, 4, 5, 6}
. ToleranceComponent (input control) . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( integer, string )
Model component(s) of which the relative movement(s) should be modified.
Default Value : ’all’
Suggested values : ToleranceComponent ∈ {’all’, 0, 1, 2, 3, 4, 5, 6}
. PositionTolerance (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .real(-array) ; VARIANT ( real )
Change of the position relation in pixels.
Suggested values : PositionTolerance ∈ {1, 2, 3, 4, 5, 10, 20, 30}
. AngleTolerance (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad(-array) ; VARIANT ( real )
Change of the orientation relation in radians.
Suggested values : AngleTolerance ∈ {0.017, 0.035, 0, 052, 0, 070, 0.087, 0.175, 0.349}
Result
If the handle of the training result is valid, the operator ModifyComponentRelations returns the value
TRUE. If necessary an exception is raised.
Parallelization Information
ModifyComponentRelations is processed completely exclusively without parallelization.

HALCON 8.0.2
572 CHAPTER 7. MATCHING

Possible Predecessors
TrainModelComponents
Possible Successors
CreateTrainedComponentModel
Module
Matching

void HComponentModelX.ReadComponentModel ([in] String FileName )


void HOperatorSetX.ReadComponentModel ([in] VARIANT FileName,
[out] VARIANT ComponentModelID )

Read a component model from a file.


The operator ReadComponentModel reads a component model, which has been written with
WriteComponentModel, from the file FileName and returns it in ComponentModelID.
Parameter
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.read ; String / VARIANT
File name.
. ComponentModelID (output control) . . . . . . . . . . component_model ; HComponentModelX / VARIANT
Handle of the component model.
Result
If the file name is valid, the operator ReadComponentModel returns the value TRUE. If necessary, an exception
handling is raised.
Parallelization Information
ReadComponentModel is processed completely exclusively without parallelization.
Possible Successors
FindComponentModel
Module
Matching

void HComponentTrainingX.ReadTrainingComponents
([in] String FileName )
void HOperatorSetX.ReadTrainingComponents ([in] VARIANT FileName,
[out] VARIANT ComponentTrainingID )

Read a component training result from a file.


The operator ReadTrainingComponents reads a component training result, which has been written with
WriteTrainingComponents, from the file FileName and returns it in ComponentTrainingID.
Parameter
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.read ; String / VARIANT
File name.
. ComponentTrainingID (output control) . . . component_training ; HComponentTrainingX / VARIANT
Handle of the training result.
Result
If the file name is valid, the operator ReadTrainingComponents returns the value TRUE. If necessary, an
exception handling is raised.
Parallelization Information
ReadTrainingComponents is processed completely exclusively without parallelization.
Possible Successors
CreateTrainedComponentModel

HALCON/COM Reference Manual, 2008-5-13


7.1. COMPONENT-BASED 573

See also
TrainModelComponents, ClearTrainingComponents
Module
Matching

[out] HRegionX ModelComponents HImageX.TrainModelComponents


([in] HRegionX InitialComponents, [in] HImageX TrainingImages,
[in] VARIANT ContrastLow, [in] VARIANT ContrastHigh, [in] VARIANT MinSize,
[in] VARIANT MinScore, [in] VARIANT SearchRowTol,
[in] VARIANT SearchColumnTol, [in] VARIANT SearchAngleTol,
[in] String TrainingEmphasis, [in] String AmbiguityCriterion,
[in] double MaxContourOverlap, [in] double ClusterThreshold,
[out] HComponentTrainingX ComponentTrainingID )
void HComponentTrainingX.TrainModelComponents
([in] HImageX ModelImage, [in] HRegionX InitialComponents,
[in] HImageX TrainingImages, [out] HRegionX ModelComponents,
[in] VARIANT ContrastLow, [in] VARIANT ContrastHigh, [in] VARIANT MinSize,
[in] VARIANT MinScore, [in] VARIANT SearchRowTol,
[in] VARIANT SearchColumnTol, [in] VARIANT SearchAngleTol,
[in] String TrainingEmphasis, [in] String AmbiguityCriterion,
[in] double MaxContourOverlap, [in] double ClusterThreshold )
void HOperatorSetX.TrainModelComponents ([in] IHObjectX ModelImage,
[in] IHObjectX InitialComponents, [in] IHObjectX TrainingImages,
[out] HUntypedObjectX ModelComponents, [in] VARIANT ContrastLow,
[in] VARIANT ContrastHigh, [in] VARIANT MinSize, [in] VARIANT MinScore,
[in] VARIANT SearchRowTol, [in] VARIANT SearchColumnTol,
[in] VARIANT SearchAngleTol, [in] VARIANT TrainingEmphasis,
[in] VARIANT AmbiguityCriterion, [in] VARIANT MaxContourOverlap,
[in] VARIANT ClusterThreshold, [out] VARIANT ComponentTrainingID )

Train components and relations for the component-based matching.


TrainModelComponents extracts the final (rigid) model components and trains their mutual relations, i.e.,
their relative movements, on the basis of the initial components by considering several training images. The result
of the training is returned in the handle ComponentTrainingID. The training result can be subsequently used
to create the actual component model using CreateTrainedComponentModel.
TrainModelComponents should be used in cases where the relations of the components are not known
and should be trained automatically. In contrast, if the relations are known no training needs to be per-
formed with TrainModelComponents. Instead, the component model can be directly created with
CreateComponentModel.
If the initial components have been automatically created by using GenInitialComponents,
InitialComponents contains the contour regions of the initial components. In contrast, if the initial com-
ponents should be defined by the user, they can be directly passed in InitialComponents. However, in-
stead of the contour regions for each initial component, its enclosing region must be passed in the tuple. The
(contour) regions refer to the model image ModelImage. If the initial components have been obtained using
GenInitialComponents, the model image should be the same as in GenInitialComponents. Please
note that each initial component is part of at most one rigid model component. This is because during the training
initial components can be merged into rigid model components if required (see below). However, they cannot be
split and distributed to several rigid model components.
TrainModelComponents uses the following approach to perform the training: In the first step, the initial
components are searched in all training images. In some cases, one initial component may be found in an training
image more than once. Thus, in the second step, the resulting ambiguities are solved, i.e., the most probable pose
of each initial component is found. Consequently, after solving the ambiguities, in all training images at most one
pose of each initial component is available. In the next step the poses are analyzed and those initial components
that do not show any relative movement are clustered to the final rigid model components. Finally, in the last step

HALCON 8.0.2
574 CHAPTER 7. MATCHING

the relations between the model components are computed by analyzing their relative poses over the sequence of
training images. The parameters that are associated with the mentioned steps are explained in the following.
The training is performed based on several training images, which are passed in TrainingImages. Each train-
ing image must show at most one instance of the compound object and should contain the full range of allowed
relative movements of the model components. If, for example, the component model of an on/off switch should be
trained, one training image that shows the switch turned off is sufficient if the switch in the model image is turned
on, or vice versa.
The principle of the training is to find the initial components in all training images and to analyze their
poses. For this, for each initial component a shape model is created (see CreateShapeModel),
which is then used to determine the poses (position and orientation) of the initial components in the
training images (see FindShapeModel). Depending on the mode that is set by using SetSystem
(’pregenerateShapeModels’,...), the shape model is either pregenerated completely or computed on-
line during the search. The mode influences the computation time as well as the robustness of the training. Further-
more, it should be noted that if single-channel image are used in ModelImage as well as in TrainingImages
the metric ’use_polarity’ is used internally for CreateShapeModel, while if multichannel images are used
in either ModelImage or TrainingImages the metric ’ignore_color_polarity’ is used. Finally, it should
be noted that while the number of channels in ModelImage and TrainingImages may be different, e.g.,
to facilitate model generation from synthetically generated images, the number of channels in all the images in
TrainingImages must be identical. For further details see CreateShapeModel. The creation of the shape
models can be influenced by choosing appropriate values for the parameters ContrastLow, ContrastHigh,
and MinSize. These parameters have the same meaning as in GenInitialComponents and can be au-
tomatically determined by passing ’auto’: If both hysteresis threshold should be automatically determined, both
ContrastLow and ContrastHigh must be set to ’auto’. In contrast, if only one threshold value should be
determined, ContrastLow must be set to ’auto’ while ContrastHigh must be set to an arbitrary value differ-
ent from ’auto’. If the initial components have been automatically created by GenInitialComponents,
the parameters ContrastLow, ContrastHigh, and MinSize should be set to the same values as in
GenInitialComponents.
To influence the search for the initial components, the parameters MinScore, SearchRowTol,
SearchColumnTol, SearchAngleTol, and TrainingEmphasis can be set. The parameter MinScore
determines what score a potential match must at least have to be regarded as an instance of the initial component
in the training image. The larger MinScore is chosen, the faster the training is. If the initial components can
be expected never to be occluded in the training images, MinScore may be set as high as 0.8 or even 0.9 (see
FindShapeModel).
By default, the components are searched only at points in which the component lies completely within the re-
spective training image. This means that a component will not be found if it extends beyond the borders of the
image, even if it would achieve a score greater than MinScore. This behavior can be changed with SetSystem
(’borderShapeModels’,’true’), which will cause components that extend beyond the image border to
be found if they achieve a score greater than MinScore. Here, points lying outside the image are regarded as
being occluded, i.e., they lower the score. It should be noted that the runtime of the training will increase in this
mode.
When dealing with a high number of initial components and many training images, the training may take a long
time (up to several minutes). In order to speed up the training it is possible to restrict the search space for the single
initial components in the training images. For this, the poses of the initial components in the model image are used
as reference pose. The parameters SearchRowTol and SearchColumnTol specify the position tolerance
region relative to the reference position in which the search is performed. Assume, for example, that the position of
an initial component in the model image is (100,200) and SearchRowTol is set to 20 and SearchColumnTol
is set to 10. Then, this initial component is searched in the training images only within the axis-aligned rectangle
that is determined by the upper left corner (80,190) and the lower right corner (120,210). The same holds for
the orientation angle range, which can be restricted by specifying the angle tolerance SearchAngleTol to
the angle range of [-SearchAngleTol,+SearchAngleTol]. Thus, it is possible to considerably reduce the
computational effort during the training by an adequate acquisition of the training images. If one of the three
parameters is set to -1, no restriction of the search space is applied in the corresponding dimension.
The input parameters ContrastLow, ContrastHigh, MinSize, MinScore, SearchRowTol,
SearchColumnTol, and SearchAngleTol must either contain one element, in which case the parameter is
used for all initial components, or must contain the same number of elements as the initial components contained
in InitialComponents, in which case each parameter element refers to the corresponding initial component
in InitialComponents.

HALCON/COM Reference Manual, 2008-5-13


7.1. COMPONENT-BASED 575

The parameter TrainingEmphasis offers another possibility to influence the computation time of the training
and to simultaneously affect its robustness. If TrainingEmphasis is set to ’speed’, on the one hand the training
is comparatively fast, on the other hand it may happen in some cases that some initial components are not found in
the training images or are found at a wrong pose. Consequently, this would lead to an incorrect computation of the
rigid model components and their relations. The poses of the found initial components in the individual training
images can be examined by using GetTrainingComponents. If erroneous matches occur the training should
be restarted with TrainingEmphasis set to ’reliability’. This results in a higher robustness at the cost of a
longer computation time.
Furthermore, during the pose determination of the initial components ambiguities may occur if the initial com-
ponents are rotationally symmetric or if several initial components are identical or at least similar to each other.
To solve the ambiguities, the most probable pose is calculated for each initial component in each training im-
age. For this, the individual ambiguous poses are evaluated. The pose of an initial component receives a good
evaluation if the relative pose of the initial component with respect to the other initial components is similar to
the corresponding relative pose in the model image. The method to evaluate this similarity can be chosen with
AmbiguityCriterion. In almost all cases the best results are obtained with ’rigidity’, which assumes the
rigidity of the compound object. The more the rigidity of the compound object is violated by the pose of the initial
component, the worse its evaluation is. In the case of ’distance’, only the distance between the initial components
is considered during the evaluation. Hence, the pose of the initial component receives a good evaluation if its dis-
tances to the other initial components is similar to the corresponding distances in the model image. Accordingly,
when choosing ’orientation’, only the relative orientation is considered during the evaluation. Finally, the simulta-
neous consideration of distance and orientation can be achieved by choosing ’distance_orientation’. In contrast to
’rigidity’, the relative pose of the initial components is not considered when using ’distance_orientation’.
The process of solving the ambiguities can be further influenced by the parameter MaxContourOverlap. This
parameter describes the extent by which the contours of two initial component matches may overlap each other.
Let the letters ’I’ and ’T’, for example, be two initial components that should be searched in a training image
that shows the string ’IT’. Then, the initial component ’T’ should be found at its correct pose. In contrast, the
initial component ’I’ will be found at its correct pose (’I’) but also at the pose of the ’T’ because of the simi-
larity of the two components. To discard the wrong match of the initial component ’I’, an appropriate value for
MaxContourOverlap can be chosen: If overlapping matches should be tolerated, MaxContourOverlap
should be set to 1. If overlapping matches should be completely avoided, MaxContourOverlap should be set
to 0. By choosing a value between 0 and 1, the maximum percentage of overlapping contour pixels can be adjusted.
The decision which initial components can be clustered to rigid model components is made based on the poses
of the initial components in the model image and in the training images. Two initial components are merged
if they do not show any relative movement over all images. Assume that in the case of the above mentioned
switch the training image would show the same switch state as the model image, the algorithm would merge the
respective initial components because it assumes that the entire switch is one rigid model component. The extent
by which initial components are merged can be influenced with the parameter ClusterThreshold. This cluster
threshold is based on the probability that two initial components belong to the same rigid model component. Thus,
ClusterThreshold describes the minimum probability which two initial components must have in order to be
merged. Since the threshold is based on a probability value, it must lie in the interval between 0 and 1. The greater
the threshold is chosen, the smaller the number of initial components that are merged. If a threshold of 0 is chosen,
all initial components are merged into one rigid component, while for a threshold of 1 no merging is performed
and each initial component is adopted as one rigid model component.
The final rigid model components are returned in ModelComponents. Later, the index of a component region
in ModelComponents is used to denote the model component. The poses of the components in the training
images can be examined by using GetTrainingComponents.
After the determination of the model components their relative movements are analyzed by determining the move-
ment of one component with respect to a second component for each pair of components. For this, the components
are referred to their reference points. The reference point of a component is the center of gravity of its contour
region, which is returned in ModelComponents. It can be calculated by calling AreaCenter. Finally, the
relative movement is represented by the smallest enclosing rectangle of arbitrary orientation of the reference point
movement and by the smallest enclosing angle interval of the relative orientation of the second component over all
images. The determined relations can be inspected by using GetComponentRelations.
Parameter

. ModelImage (input iconic) . . . . . . . . . . . . . . . (multichannel-)image ; HImageX / IHObjectX ( byte, uint2 )


Input image from which the shape models of the initial components should be created.

HALCON 8.0.2
576 CHAPTER 7. MATCHING

. InitialComponents (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX


Contour regions or enclosing regions of the initial components.
. TrainingImages (input iconic) . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, uint2 )
Training images that are used for training the model components.
. ModelComponents (output iconic) . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Contour regions of rigid model components.
. ContrastLow (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer, string )
Lower hysteresis threshold for the contrast of the initial components in the image.
Default Value : ’auto’
Suggested values : ContrastLow ∈ {’auto’, 10, 20, 30, 40, 60, 80, 100, 120, 140, 160}
Restriction : (ContrastLow > 0)
. ContrastHigh (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer, string )
Upper hysteresis threshold for the contrast of the initial components in the image.
Default Value : ’auto’
Suggested values : ContrastHigh ∈ {’auto’, 10, 20, 30, 40, 60, 80, 100, 120, 140, 160}
Restriction : ((ContrastHigh > 0) ∧ (ContrastHigh ≥ ContrastLow))
. MinSize (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer, string )
Minimum size of connected contour regions.
Default Value : ’auto’
Suggested values : MinSize ∈ {’auto’, 0, 5, 10, 20, 30, 40}
Restriction : (M inSize ≥ 0)
. MinScore (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Minimum score of the instances of the initial components to be found.
Default Value : 0.5
Suggested values : MinScore ∈ {0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}
Minimum Increment : 0.01
Recommended Increment : 0.05
Restriction : ((0 ≤ M inScore) ∧ (M inScore ≤ 1))
. SearchRowTol (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Search tolerance in row direction.
Default Value : -1
Suggested values : SearchRowTol ∈ {0, 10, 20, 30, 50, 100}
Restriction : ((SearchRowT ol = −1) ∨ (SearchColumnT ol ≥ 0))
. SearchColumnTol (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Search tolerance in column direction.
Default Value : -1
Suggested values : SearchColumnTol ∈ {0, 10, 20, 30, 50, 100}
Restriction : ((SearchColumnT ol = −1) ∨ (SearchColumnT ol ≥ 0))
. SearchAngleTol (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad(-array) ; VARIANT ( real )
Angle search tolerance.
Default Value : -1
Suggested values : SearchAngleTol ∈ {0.0, 0.17, 0.39, 0.78, 1.57}
Restriction : ((SearchAngleT ol = −1) ∨ (SearchAngleT ol ≥ 0))
. TrainingEmphasis (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Decision whether the training emphasis should lie on a fast computation or on a high robustness.
Default Value : ’speed’
List of values : TrainingEmphasis ∈ {’speed’, ’reliability’}
. AmbiguityCriterion (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Criterion for solving ambiguous matches of the initial components in the training images.
Default Value : ’rigidity’
List of values : AmbiguityCriterion ∈ {’distance’, ’orientation’, ’distance_orientation’, ’rigidity’}
. MaxContourOverlap (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Maximum contour overlap of the found initial components in a training image.
Default Value : 0.2
Suggested values : MaxContourOverlap ∈ {0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}
Minimum Increment : 0.01
Recommended Increment : 0.05
Restriction : ((0 ≤ M axContourOverlap) ∧ (M axContourOverlap ≤ 1))

HALCON/COM Reference Manual, 2008-5-13


7.1. COMPONENT-BASED 577

. ClusterThreshold (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT


Threshold for clustering the initial components.
Default Value : 0.5
Suggested values : ClusterThreshold ∈ {0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}
Restriction : ((0 ≤ ClusterT hreshold) ∧ (ClusterT hreshold ≤ 1))
. ComponentTrainingID (output control) . . . component_training ; HComponentTrainingX / VARIANT
Handle of the training result.
Example

* Get the model image.


read_image (ModelImage, ’model_image.tif’)
* Define the regions for the initial components.
gen_rectangle2 (InitialComponentRegions, 212, 233, 0.62, 167, 29)
gen_rectangle2 (Rectangle2, 298, 363, 1.17, 162, 34)
gen_rectangle2 (Rectangle3, 63, 444, -0.26, 50, 27)
gen_rectangle2 (Rectangle4, 120, 473, 0, 33, 20)
InitialComponentRegions := [InitialComponentRegions,Rectangle2]
InitialComponentRegions := [InitialComponentRegions,Rectangle3]
InitialComponentRegions := [InitialComponentRegions,Rectangle4]
* Get the training images.
TrainingImages := []
for i := 1 to 4 by 1
read_image (TrainingImage, ’training_image-’+i+’.tif’)
TrainingImages := [TrainingImages,TrainingImage]
endfor
* Extract the model components and train the relations.
train_model_components (ModelImage, InitialComponentRegions, TrainingImages,
ModelComponents, 22, 60, 30, 0.6, 0, 0, rad(60),
’speed’, ’rigidity’, 0.2, 0.4, ComponentTrainingID)

Result
If the parameter values are correct, the operator TrainModelComponents returns the value TRUE.
If the input is empty (no input images are available) the behavior can be set via SetSystem
(’noObjectResult’,<Result>). If necessary, an exception is raised.
Parallelization Information
TrainModelComponents is processed completely exclusively without parallelization.
Possible Predecessors
GenInitialComponents
Possible Successors
InspectClusteredComponents, ClusterModelComponents, ModifyComponentRelations,
WriteTrainingComponents, GetTrainingComponents, GetComponentRelations,
CreateTrainedComponentModel, ClearTrainingComponents,
ClearAllTrainingComponents
See also
CreateShapeModel, FindShapeModel
Module
Matching

void HComponentModelX.WriteComponentModel ([in] String FileName )


void HOperatorSetX.WriteComponentModel
([in] VARIANT ComponentModelID, [in] VARIANT FileName )

Write a component model to a file.

HALCON 8.0.2
578 CHAPTER 7. MATCHING

The operator WriteComponentModel writes the component model ComponentModelID to the file
FileName. The model can be read again with ReadComponentModel.
Parameter

. ComponentModelID (input control) . . . . . . . . . . . component_model ; HComponentModelX / VARIANT


Handle of the component model.
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.write ; String / VARIANT
File name.
Result
If the file name is valid (write permission), the operator WriteComponentModel returns the value TRUE. If
necessary, an exception handling is raised.
Parallelization Information
WriteComponentModel is reentrant and processed without parallelization.
Possible Predecessors
CreateComponentModel, CreateTrainedComponentModel
Module
Matching

void HComponentTrainingX.WriteTrainingComponents
([in] String FileName )
void HOperatorSetX.WriteTrainingComponents
([in] VARIANT ComponentTrainingID, [in] VARIANT FileName )

Write a component training result to a file.


The operator WriteTrainingComponents writes the component training result ComponentTrainingID
to the file FileName. The training result can be read again with ReadTrainingComponents.
Parameter

. ComponentTrainingID (input control) . . . . component_training ; HComponentTrainingX / VARIANT


Handle of the training result.
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.write ; String / VARIANT
File name.
Result
If the file name is valid (write permission), the operator WriteTrainingComponents returns the value TRUE.
If necessary, an exception handling is raised.
Parallelization Information
WriteTrainingComponents is reentrant and processed without parallelization.
Possible Predecessors
TrainModelComponents
Module
Matching

7.2 Correlation-Based
void HMiscX.ClearAllNccModels ( )
void HOperatorSetX.ClearAllNccModels ( )

Free the memory of all NCC models.


The operator ClearAllNccModels frees the memory of all NCC models that were created by
CreateNccModel. After calling ClearAllNccModels, no model can be used any longer.

HALCON/COM Reference Manual, 2008-5-13


7.2. CORRELATION-BASED 579

Attention
ClearAllNccModels exists solely for the purpose of implementing the “reset program” functionality in HDe-
velop. ClearAllNccModels must not be used in any application.
Result
ClearAllNccModels always returns TRUE.
Parallelization Information
ClearAllNccModels is processed completely exclusively without parallelization.
Possible Predecessors
CreateNccModel, ReadNccModel, WriteNccModel
Alternatives
ClearNccModel
Module
Matching

void HOperatorSetX.ClearNccModel ([in] VARIANT ModelID )

Free the memory of an NCC model.


The operator ClearNccModel frees the memory of an NCC model that was created by CreateNccModel.
After calling ClearNccModel, the model can no longer be used. The handle ModelID becomes invalid.
Parameter

. ModelID (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .ncc_model ; HNccModelX / VARIANT


Handle of the model.
Result
If the handle of the model is valid, the operator ClearNccModel returns the value TRUE. If necessary an
exception is raised.
Parallelization Information
ClearNccModel is processed completely exclusively without parallelization.
Possible Predecessors
CreateNccModel, ReadNccModel, WriteNccModel
See also
ClearAllNccModels
Module
Matching

[out] HNccModelX ModelID HImageX.CreateNccModel ([in] VARIANT NumLevels,


[in] double AngleStart, [in] double AngleExtent, [in] VARIANT AngleStep,
[in] String Metric )
void HNccModelX.CreateNccModel ([in] HImageX Template,
[in] VARIANT NumLevels, [in] double AngleStart, [in] double AngleExtent,
[in] VARIANT AngleStep, [in] String Metric )
void HOperatorSetX.CreateNccModel ([in] IHObjectX Template,
[in] VARIANT NumLevels, [in] VARIANT AngleStart, [in] VARIANT AngleExtent,
[in] VARIANT AngleStep, [in] VARIANT Metric, [out] VARIANT ModelID )

Prepare an NCC model for matching.


The operator CreateNccModel prepares a template, which is passed in the image Template, as an NCC
model used for matching using the normalized cross correlation (NCC). The ROI of the model is passed as the
domain of Template.

HALCON 8.0.2
580 CHAPTER 7. MATCHING

The model is generated using multiple image pyramid levels at multiple rotations on each level and is stored
in memory. The output parameter ModelID is a handle for this model, which is used in subsequent calls to
FindNccModel.
The number of pyramid levels is determined with the parameter NumLevels. It should be chosen as large as pos-
sible because by this the time necessary to find the object is significantly reduced. On the other hand, NumLevels
must be chosen such that the model is still recognizable and contains a sufficient number of points (at least eight) on
the highest pyramid level. This can be checked using the domains of the output images of GenGaussPyramid.
If not enough model points are generated, the number of pyramid levels is reduced internally until enough model
points are found on the highest pyramid level. If this procedure would lead to a model with no pyramid levels, i.e., if
the number of model points is already too small on the lowest pyramid level, CreateNccModel returns an error
message. If NumLevels is set to ’auto’ or 0, CreateNccModel determines the number of pyramid levels auto-
matically. The automatically computed number of pyramid levels can be queried using GetNccModelParams.
In rare cases, it might happen that CreateNccModel determines a value for the number of pyramid levels that
is too large or too small. If the number of pyramid levels is chosen too large, the model may not be recognized
in the image or it may be necessary to select very low parameters for MinScore in FindNccModel in order
to find the model. If the number of pyramid levels is chosen too small, the time required to find the model in
FindNccModel may increase. In these cases, the number of pyramid levels should be selected by inspecting the
output of GenGaussPyramid. Here, Mode = ’constant’ and Scale = 0.5 should be used.
The parameters AngleStart and AngleExtent determine the range of possible rotations, in which the model
can occur in the image. Note that the model can only be found in this range of angles by FindNccModel. The
parameter AngleStep determines the step length within the selected range of angles. Hence, if subpixel accuracy
is not specified in FindNccModel, this parameter specifies the accuracy that is achievable for the angles in
FindNccModel. AngleStep should be chosen based on the size of the object. Smaller models do not possess
many different discrete rotations in the image, and hence AngleStep should be chosen larger for smaller models.
If AngleExtent is not an integer multiple of AngleStep, AngleStep is modified accordingly.
The model is pre-generated for the selected angle range and stored in memory. The memory required to store the
model is proportional to the number of angle steps and the number of points in the model. Hence, if AngleStep
is too small or AngleExtent too big, it may happen that the model no longer fits into the (virtual) memory. In
this case, either AngleStep must be enlarged or AngleExtent must be reduced. In any case, it is desirable
that the model completely fits into the main memory, because this avoids paging by the operating system, and
hence the time to find the object will be much smaller. Since angles can be determined with subpixel resolution
by FindNccModel, AngleStep ≥ 1 can be selected for models of a diameter smaller than about 200 pix-
els. If AngleStep = 0 auto 0 or 0 is selected, CreateNccModel automatically determines a suitable angle
step length based on the size of the model. The automatically computed angle step length can be queried using
GetNccModelParams.
The parameter Metric determines the conditions under which the model is recognized in the image. If Metric
= ’use_polarity’, the object in the image and the model must have the same contrast. If, for example, the model is
a bright object on a dark background, the object is found only if it is also brighter than the background. If Metric
= ’ignore_global_polarity’, the object is found in the image also if the contrast reverses globally. In the above
example, the object hence is also found if it is darker than the background. The runtime of FindNccModel will
increase slightly in this case.
The center of gravity of the domain (region) of the model image Template is used as the origin (reference point)
of the model. A different origin can be set with SetNccModelOrigin.
Parameter

. Template (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, uint2 )


Input image whose domain will be used to create the model.
. NumLevels (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer, string )
Maximum number of pyramid levels.
Default Value : ’auto’
List of values : NumLevels ∈ {’auto’, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
. AngleStart (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; double / VARIANT
Smallest rotation of the pattern.
Default Value : -0.39
Suggested values : AngleStart ∈ {-3.14, -1.57, -0.79, -0.39, -0.20, 0.0}

HALCON/COM Reference Manual, 2008-5-13


7.2. CORRELATION-BASED 581

. AngleExtent (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; double / VARIANT


Extent of the rotation angles.
Default Value : 0.79
Suggested values : AngleExtent ∈ {6.29, 3.14, 1.57, 0.79, 0.39}
Restriction : (AngleExtent ≥ 0)
. AngleStep (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; VARIANT ( real, string )
Step length of the angles (resolution).
Default Value : ’auto’
Suggested values : AngleStep ∈ {’auto’, 0, 0.0175, 0.0349, 0.0524, 0.0698, 0.0873}
Restriction : ((AngleStep ≥ 0) ∧ (AngleStep ≤ (pi/16)))
. Metric (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Match metric.
Default Value : ’use_polarity’
List of values : Metric ∈ {’use_polarity’, ’ignore_global_polarity’}
. ModelID (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ncc_model ; HNccModelX / VARIANT
Handle of the model.
Result
If the parameters are valid, the operator CreateNccModel returns the value TRUE. If the parameter
NumLevels are chosen such that the model contains too few points, the error 8510 is raised.
Parallelization Information
CreateNccModel is processed completely exclusively without parallelization.
Possible Predecessors
DrawRegion, ReduceDomain, Threshold
Possible Successors
FindNccModel, GetNccModelParams, ClearNccModel, WriteNccModel, SetNccModelOrigin
Alternatives
CreateShapeModel, CreateScaledShapeModel, CreateAnisoShapeModel,
CreateTemplateRot
Module
Matching

[out] VARIANT Row HImageX.FindNccModel ([in] HNccModelX ModelID,


[in] double AngleStart, [in] double AngleExtent, [in] double MinScore,
[in] long NumMatches, [in] double MaxOverlap, [in] String SubPixel,
[in] VARIANT NumLevels, [out] VARIANT Column, [out] VARIANT Angle,
[out] VARIANT Score )
[out] VARIANT Row HNccModelX.FindNccModel ([in] HImageX Image,
[in] double AngleStart, [in] double AngleExtent, [in] double MinScore,
[in] long NumMatches, [in] double MaxOverlap, [in] String SubPixel,
[in] VARIANT NumLevels, [out] VARIANT Column, [out] VARIANT Angle,
[out] VARIANT Score )
void HOperatorSetX.FindNccModel ([in] IHObjectX Image,
[in] VARIANT ModelID, [in] VARIANT AngleStart, [in] VARIANT AngleExtent,
[in] VARIANT MinScore, [in] VARIANT NumMatches, [in] VARIANT MaxOverlap,
[in] VARIANT SubPixel, [in] VARIANT NumLevels, [out] VARIANT Row,
[out] VARIANT Column, [out] VARIANT Angle, [out] VARIANT Score )

Find the best matches of an NCC model in an image.


The operator FindNccModel finds the best NumMatches instances of the NCC model ModelID in the
input image Image. The model must have been created previously by calling CreateNccModel or
ReadNccModel.
The position and rotation of the found instances of the model is returned in Row, Column, and Angle. The
coordinates Row and Column are the coordinates of the origin of the shape model in the search image. By default,

HALCON 8.0.2
582 CHAPTER 7. MATCHING

the origin is the center of gravity of the domain (region) of the image that was used to create the NCC model with
CreateNccModel. A different origin can be set with SetNccModelOrigin. Additionally, the score of each
found instance is returned in Score. The score is the normalized cross correlation of the template t(r, c) and the
image i(r, c):

1 X t(u, v) − mt i(r + u, c + v) − mi (r, c)


ncc(r, c) = p · p
n s2t s2i (r, c)
(u,v)∈R

Here, n denotes the number of points in the template, R denotes the domain (ROI) of the template, mt is the mean
gray value of the template

1 X
mt = t(u, v)
n
(u,v)∈R

s2t is the variance of the gray values of the template

1 X 2
s2t = (t(u, v) − mt )
n
(u,v)∈R

mi (r, c) is the mean gray value of the image at position (r, c) over all points of the template (i.e., the template
points are shifted by (r, c))

1 X
mi (r, c) = i(r + u, c + v)
n
(u,v)∈R

and s2i (r, c) is the variance of the gray values of the image at position (r, c) over all points of the template

1 X 2
s2i (r, c) = (i(r + u, c + v) − mi (r, c))
n
(u,v)∈R

The NCC measures how well the template and image correspond at a particular point (r, c). It assumes values
between −1 and 1. The larger the absolute value of the correlation, the larger the degree of correspondence
between the template and image. A value of 1 means that the gray values in the image are a linear transformation
of the gray values in the template:

i(r + u, c + v) = at(u, v) + b

where a > 0. Similarly, a value of −1 means that the gray values in the image are a linear transformation of the
gray values in the template with a < 0. Hence, in this case the template occurs with a reversed polarity in the
image. Because of the above property, the NCC is invariant to linear illumination changes.
The NCC as defined above is used if the NCC model has been created with Metric = ’use_polarity’. If the model
has been created with Metric = ’ignore_global_polarity’, the absolute value of ncc(r, c) is used as the score.
It should be noted that the NCC is very sensitive to occlusion and clutter as well as to nonlinear illumination
changes in the image. If a model should be found in the presence of occlusion, clutter, or nonlinear illumination
changes the search should be performed using the shape-based matching (see, e.g., CreateShapeModel).
The domain of the image Image determines the search space for the reference point of the model, i.e.,
for the center of gravity of the domain (region) of the image that was used to create the shape model with
CreateNccModel. A different origin set with SetNccModelOrigin is not taken into account here. The
model is searched within those points of the domain of the image, in which the model lies completely within the
image. This means that the model will not be found if it extends beyond the borders of the image, even if it would
achieve a score greater than MinScore (see below).
The parameters AngleStart and AngleExtent determine the range of rotations for which the model is
searched. If necessary, the range of rotations is clipped to the range given when the model was created with
CreateNccModel. In particular, this means that the angle ranges of the model and the search must truly overlap.
The angle range in the search is not adapted modulo 2π. To simplify the presentation, all angles in the remainder

HALCON/COM Reference Manual, 2008-5-13


7.2. CORRELATION-BASED 583

of the paragraph are given in degrees, whereas they have to be specified in radians in FindNccModel. Hence,
if the model, for example, was created with AngleStart = −20◦ and AngleExtent = 40◦ and the angle
search space in FindNccModel is, for example, set to AngleStart = 350◦ and AngleExtent = 20◦ , the
model will not be found, even though the angle ranges would overlap if they were regarded modulo 360◦ . To find
the model, in this example it would be necessary to select AngleStart = −10◦ .
The parameter MinScore determines what score a potential match must at least have to be regarded as an instance
of the model in the image. The larger MinScore is chosen, the faster the search is.
The maximum number of instances to be found can be determined with NumMatches. If more than
NumMatches instances with a score greater than MinScore are found in the image, only the best NumMatches
instances are returned. If fewer than NumMatches are found, only that number is returned, i.e., the parameter
MinScore takes precedence over NumMatches.
If the model exhibits symmetries it may happen that multiple instances with similar positions but different rotations
are found in the image. If the model has repeating structures it may happen that multiple instances with identical
rotations are found at similar positions in the image. The parameter MaxOverlap determines by what fraction
(i.e., a number between 0 and 1) two instances may at most overlap in order to consider them as different instances,
and hence to be returned separately. If two instances overlap each other by more than MaxOverlap only the
best instance is returned. The calculation of the overlap is based on the smallest enclosing rectangle of arbitrary
orientation (see SmallestRectangle2) of the found instances. If MaxOverlap = 0, the found instances
may not overlap at all, while for MaxOverlap = 1 all instances are returned.
The parameter SubPixel determines whether the instances should be extracted with subpixel accuracy. If
SubPixel is set to ’false’, the model’s pose is only determined with pixel accuracy and the angle resolution
that was specified with CreateNccModel. If SubPixel is set to ’true’, the position as well as the rotation are
determined with subpixel accuracy. In this mode, the model’s pose is interpolated from the score function. This
mode costs almost no computation time and achieves a high accuracy. Hence, SubPixel should usually be set to
’true’.
The number of pyramid levels used during the search is determined with NumLevels. If necessary, the number of
levels is clipped to the range given when the shape model was created with CreateNccModel. If NumLevels
is set to 0, the number of pyramid levels specified in CreateNccModel is used. Optionally, NumLevels can
contain a second value that determines the lowest pyramid level to which the found matches are tracked. Hence, a
value of [4,2] for NumLevels means that the matching starts at the fourth pyramid level and tracks the matches
to the second lowest pyramid level (the lowest pyramid level is denoted by a value of 1). This mechanism can
be used to decrease the runtime of the matching. It should be noted, however, that in general the accuracy of the
extracted pose parameters is lower in this mode than in the normal mode, in which the matches are tracked to the
lowest pyramid level. If the lowest pyramid level to use is chosen too large, it may happen that the desired accuracy
cannot be achieved, or that wrong instances of the model are found because the model is not specific enough on the
higher pyramid levels to facilitate a reliable selection of the correct instance of the model. In this case, the lowest
pyramid level to use must be set to a smaller value.
Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, uint2 )


Input image in which the model should be found.
. ModelID (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .ncc_model ; HNccModelX / VARIANT
Handle of the model.
. AngleStart (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; double / VARIANT
Smallest rotation of the model.
Default Value : -0.39
Suggested values : AngleStart ∈ {-3.14, -1.57, -0.78, -0.39, -0.20, 0.0}
. AngleExtent (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; double / VARIANT
Extent of the rotation angles.
Default Value : 0.78
Suggested values : AngleExtent ∈ {6.29, 3.14, 1.57, 0.78, 0.39, 0.0}
Restriction : (AngleExtent ≥ 0)

HALCON 8.0.2
584 CHAPTER 7. MATCHING

. MinScore (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT


Minimum score of the instances of the model to be found.
Default Value : 0.8
Suggested values : MinScore ∈ {0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}
Typical range of values : 0 ≤ MinScore ≤ 0
Minimum Increment : 0.01
Recommended Increment : 0.05
. NumMatches (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of instances of the model to be found.
Default Value : 1
Suggested values : NumMatches ∈ {0, 1, 2, 3, 4, 5, 10, 20}
. MaxOverlap (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Maximum overlap of the instances of the model to be found.
Default Value : 0.5
Suggested values : MaxOverlap ∈ {0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}
Typical range of values : 0 ≤ MaxOverlap ≤ 0
Minimum Increment : 0.01
Recommended Increment : 0.05
. SubPixel (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Subpixel accuracy.
Default Value : ’true’
List of values : SubPixel ∈ {’false’, ’true’}
. NumLevels (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Number of pyramid levels used in the matching (and lowest pyramid level to use if |NumLevels| = 2).
Default Value : 0
List of values : NumLevels ∈ {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
. Row (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; VARIANT ( real )
Row coordinate of the found instances of the model.
. Column (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; VARIANT ( real )
Column coordinate of the found instances of the model.
. Angle (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; VARIANT ( real )
Rotation angle of the found instances of the model.
. Score (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Score of the found instances of the model.
Example

create_ncc_model (TemplateImage, ’auto’, rad(-45), rad(90), ’auto’,


’use_polarity’, ModelID)
find_ncc_model (SearchImage, ModelID, rad(-45), rad(90), 0.7, 1,
0.5, ’true’, 0, Row, Column, Angle, Score)
vector_angle_to_rigid (0, 0, 0, Row, Column, Angle, HomMat2D)
affine_trans_pixel (HomMat2D, 0, 0, RowObject, ColumnObject)
disp_cross (WindowHandle, RowObject, ColumnObject, 10, 0)

Result
If the parameter values are correct, the operator FindNccModel returns the value TRUE. If the input is empty
(no input images are available) the behavior can be set via SetSystem(’noObjectResult’,<Result>).
If necessary, an exception is raised.
Parallelization Information
FindNccModel is reentrant and processed without parallelization.
Possible Predecessors
CreateNccModel, ReadNccModel, SetNccModelOrigin
Possible Successors
ClearNccModel

HALCON/COM Reference Manual, 2008-5-13


7.2. CORRELATION-BASED 585

Alternatives
FindShapeModel, FindScaledShapeModel, FindAnisoShapeModel, FindShapeModels,
FindScaledShapeModels, FindAnisoShapeModels, BestMatchRotMg
Module
Matching

[out] double Row HNccModelX.GetNccModelOrigin ([out] double Column )


void HOperatorSetX.GetNccModelOrigin ([in] VARIANT ModelID,
[out] VARIANT Row, [out] VARIANT Column )

Return the origin (reference point) of an NCC model.


The operator GetNccModelOrigin returns the origin (reference point) of the NCC model ModelID. The
origin is specified relative to the center of gravity of the domain (region) of the image that was used to create the
NCC model with CreateNccModel. Hence, an origin of (0,0) means that the center of gravity of the domain
of the model image is used as the origin. An origin of (-20,-40) means that the origin lies to the upper left of the
center of gravity.
Parameter
. ModelID (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .ncc_model ; HNccModelX / VARIANT
Handle of the model.
. Row (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; double / VARIANT
Row coordinate of the origin of the NCC model.
. Column (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; double / VARIANT
Column coordinate of the origin of the NCC model.
Result
If the handle of the model is valid, the operator GetNccModelOrigin returns the value TRUE. If necessary an
exception is raised.
Parallelization Information
GetNccModelOrigin is reentrant and processed without parallelization.
Possible Predecessors
CreateNccModel, ReadNccModel, SetNccModelOrigin
Possible Successors
FindNccModel
See also
AreaCenter
Module
Matching

[out] long NumLevels HNccModelX.GetNccModelParams


([out] double AngleStart, [out] double AngleExtent, [out] double AngleStep,
[out] String Metric )
void HOperatorSetX.GetNccModelParams ([in] VARIANT ModelID,
[out] VARIANT NumLevels, [out] VARIANT AngleStart, [out] VARIANT AngleExtent,
[out] VARIANT AngleStep, [out] VARIANT Metric )

Return the parameters of an NCC model.


The operator GetNccModelParams returns the parameters of the NCC model ModelID that were used to
create it using CreateNccModel. In particular, this output can be used to check the parameters NumLevels
and AngleStep if they were determined automatically during the model creation with CreateNccModel.
Furthermore, this output can be used to check the parameters if the model was read with ReadNccModel.

HALCON 8.0.2
586 CHAPTER 7. MATCHING

Parameter

. ModelID (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .ncc_model ; HNccModelX / VARIANT


Handle of the model.
. NumLevels (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of pyramid levels.
. AngleStart (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; double / VARIANT
Smallest rotation of the pattern.
. AngleExtent (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; double / VARIANT
Extent of the rotation angles.
Restriction : (AngleExtent ≥ 0)
. AngleStep (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; double / VARIANT
Step length of the angles (resolution).
Restriction : (AngleStep ≥ 0)
. Metric (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Match metric.
Result
If the handle of the model is valid, the operator GetNccModelParams returns the value TRUE. If necessary an
exception is raised.
Parallelization Information
GetNccModelParams is reentrant and processed without parallelization.
Possible Predecessors
CreateNccModel, ReadNccModel
See also
FindNccModel
Module
Matching

void HNccModelX.ReadNccModel ([in] String FileName )


void HOperatorSetX.ReadNccModel ([in] VARIANT FileName,
[out] VARIANT ModelID )

Read an NCC model from a file.


The operator ReadNccModel reads an NCC model, which has been written with WriteNccModel, from the
file FileName.
Parameter

. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.read ; String / VARIANT


File name.
. ModelID (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ncc_model ; HNccModelX / VARIANT
Handle of the model.
Result
If the file name is valid, the operator ReadNccModel returns the value TRUE. If necessary an exception is raised.
Parallelization Information
ReadNccModel is processed completely exclusively without parallelization.
Possible Successors
FindNccModel
See also
CreateNccModel, ClearNccModel
Module
Matching

HALCON/COM Reference Manual, 2008-5-13


7.2. CORRELATION-BASED 587

void HNccModelX.SetNccModelOrigin ([in] double Row,


[in] double Column )
void HOperatorSetX.SetNccModelOrigin ([in] VARIANT ModelID,
[in] VARIANT Row, [in] VARIANT Column )

Set the origin (reference point) of an NCC model.


The operator SetNccModelOrigin sets the origin (reference point) of the NCC model ModelID to a new
value. The origin is specified relative to the center of gravity of the domain (region) of the image that was used to
create the NCC model with CreateNccModel. Hence, an origin of (0,0) means that the center of gravity of the
domain of the model image is used as the origin. An origin of (-20,-40) means that the origin lies to the upper left
of the center of gravity.
Parameter
. ModelID (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .ncc_model ; HNccModelX / VARIANT
Handle of the model.
. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; double / VARIANT
Row coordinate of the origin of the NCC model.
. Column (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; double / VARIANT
Column coordinate of the origin of the NCC model.
Result
If the handle of the model is valid, the operator SetNccModelOrigin returns the value TRUE. If necessary an
exception is raised.
Parallelization Information
SetNccModelOrigin is processed completely exclusively without parallelization.
Possible Predecessors
CreateNccModel, ReadNccModel
Possible Successors
FindNccModel, GetNccModelOrigin
See also
AreaCenter
Module
Matching

void HNccModelX.WriteNccModel ([in] String FileName )


void HOperatorSetX.WriteNccModel ([in] VARIANT ModelID,
[in] VARIANT FileName )

Write an NCC model to a file.


The operator WriteNccModel writes an NCC model to the file FileName. The model can be read again with
ReadNccModel.
Parameter
. ModelID (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .ncc_model ; HNccModelX / VARIANT
Handle of the model.
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.write ; String / VARIANT
File name.
Result
If the file name is valid (write permission), the operator WriteNccModel returns the value TRUE. If necessary
an exception is raised.
Parallelization Information
WriteNccModel is reentrant and processed without parallelization.
Possible Predecessors
CreateNccModel

HALCON 8.0.2
588 CHAPTER 7. MATCHING

Module
Matching

7.3 Gray-Value-Based

void HImageX.AdaptTemplate ([in] HTemplateX TemplateID )


void HTemplateX.AdaptTemplate ([in] HImageX Image )
void HOperatorSetX.AdaptTemplate ([in] IHObjectX Image,
[in] VARIANT TemplateID )

Adapting a template to the size of an image.


The operator AdaptTemplate serves to adapt a template which has been created by CreateTemplate to
the size of an image. The operator AdaptTemplate can be called before the template is used with images of
another size, or if the image used to create the template had another size. If it is not called explicitly it will be
called internally each time another image size is used. The contents of the image is hereby irrelevant; only the
width of Image will be considered.
Parameter
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte )
Image which determines the size of the later matching.
. TemplateID (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . template ; HTemplateX / VARIANT
Template number.
Result
If the parameter values are correct, the operator AdaptTemplate returns the value TRUE. If necessary, an
exception handling is raised.
Parallelization Information
AdaptTemplate is reentrant and processed without parallelization.
Possible Predecessors
CreateTemplate, CreateTemplateRot, ReadTemplate
Possible Successors
SetReferenceTemplate, BestMatch, FastMatch, FastMatchMg, SetOffsetTemplate,
BestMatchMg, BestMatchPreMg, BestMatchRot, BestMatchRotMg
Module
Matching

[out] VARIANT Row HImageX.BestMatch ([in] HTemplateX TemplateID,


[in] double MaxError, [in] String SubPixel, [out] VARIANT Column,
[out] VARIANT Error )
[out] VARIANT Row HTemplateX.BestMatch ([in] HImageX Image,
[in] double MaxError, [in] String SubPixel, [out] VARIANT Column,
[out] VARIANT Error )
void HOperatorSetX.BestMatch ([in] IHObjectX Image,
[in] VARIANT TemplateID, [in] VARIANT MaxError, [in] VARIANT SubPixel,
[out] VARIANT Row, [out] VARIANT Column, [out] VARIANT Error )

Searching the best matching of a template and an image.


The operator BestMatch performs a matching of the template of TemplateID and Image. Hereby the
template will be moved over the points of Image so that the template will lie always inside Image. BestMatch
works similar to FastMatch, with the exception, that each time a better match is found the value of MaxError
is internally updated to a lower value to reduce runtime.
With regard to the parameter SubPixel, the position will be indicated by subpixel accuracy. The matching
criterion (“displaced frame difference”) is defined as follows:

HALCON/COM Reference Manual, 2008-5-13


7.3. GRAY-VALUE-BASED 589

P
u,v |Image[row − u, col − v] − TemplateID[u, v]|
error[row, col] =
area(T emplateID)

The runtime of the operator depends on the size of the domain of Image. Therefore it is important to restrict the
domain as far as possible, i.e. to apply the operator only in a very confined “region of interest”. The parameter
MaxError determines the maximal error which the searched position is allowed to have at most. The lower this
value is, the faster the operator runs.
Row and Column return the position of the best match, whereby Error indicates the average difference of the
grayvalues. If no position with an error below MaxError was found the position (0, 0) and a matching result of
255 for Error are returned. In this case MaxError has to be set larger.
The maximum error of the position (without noise) is 0.1 pixel. The average error is 0.03 pixel.
Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte )


Input image inside of which the pattern has to be found.
. TemplateID (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . template ; HTemplateX / VARIANT
Template number.
. MaxError (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Maximum average difference of the grayvalues.
Default Value : 20
Suggested values : MaxError ∈ {0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 15, 17, 20, 30, 40, 50, 60, 70}
Typical range of values : 0 ≤ MaxError ≤ 0
Minimum Increment : 1
Recommended Increment : 3
. SubPixel (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Subpixel accuracy in case of ’true’.
Default Value : ’false’
List of values : SubPixel ∈ {’true’, ’false’}
. Row (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( real )
Row position of the best match.
. Column (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( real )
Column position of the best match.
. Error (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Average divergence of the grayvalues of the best match.
Result
If the parameter values are correct, the operator BestMatch returns the value TRUE. If the input is empty (no
input images are available) the behaviour can be set via SetSystem(’noObjectResult’,<Result>). If
necessary, an exception handling is raised.
Parallelization Information
BestMatch is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
CreateTemplate, ReadTemplate, SetOffsetTemplate, SetReferenceTemplate,
AdaptTemplate, DrawRegion, DrawRectangle1, ReduceDomain
Alternatives
FastMatch, FastMatchMg, BestMatchMg, BestMatchPreMg, BestMatchRot, BestMatchRotMg,
ExhaustiveMatch, ExhaustiveMatchMg
Module
Matching

HALCON 8.0.2
590 CHAPTER 7. MATCHING

[out] double Row HImageX.BestMatchMg ([in] HTemplateX TemplateID,


[in] double MaxError, [in] String SubPixel, [in] long NumLevels,
[in] VARIANT WhichLevels, [out] double Column, [out] double Error )
[out] double Row HTemplateX.BestMatchMg ([in] HImageX Image,
[in] double MaxError, [in] String SubPixel, [in] long NumLevels,
[in] VARIANT WhichLevels, [out] double Column, [out] double Error )
void HOperatorSetX.BestMatchMg ([in] IHObjectX Image,
[in] VARIANT TemplateID, [in] VARIANT MaxError, [in] VARIANT SubPixel,
[in] VARIANT NumLevels, [in] VARIANT WhichLevels, [out] VARIANT Row,
[out] VARIANT Column, [out] VARIANT Error )

Searching the best grayvalue matches in a pyramid.


BestMatchMg applies gray value matching using an image pyramid. BestMatchMg works analogously to
BestMatch, but it is faster due to the use of a pyramid. Input is an image with an optionally reduced domain.
The paramter MaxError specifies the maximum error for template matching. Using smaller values results in a
reduced runtime but it is possible that the pattern might be missed. The value of MaxError has to set larger
compared with BestMatch, because the error is at higher levels of the pyramid often increased.
SubPixel specifies if the result is calculated with sub pixel accuracy or not. A value of 1 for SubPixel results
in an operator similar to BestMatch, i.e. only the original gray values are used. For values larger than 1, the
algorithm starts at the lowest resultion and searches for a position with the lowest matching error. At the next higher
resolution this position is refined. This is continued up to the maximum resolution (WhichLevels = ’all’). As an
alternative Method the mode WhichLevels with value ’original’ can be used. In this case not only the position
with the lowest error but all points below MaxError are analysed further on in the next higher resolution. This
method is slower but it is more stable and the possibilty to miss the correct position is very low. In this case it is
often possible to start with a lower resolution (higher level in Pyramid, i.e. larger value for NumLevels) which
leads to a reduced runtime. Besides the values ’all’ and ’original’ for WhichLevels you can specify the pyramid
level explicitly where to switch between a “match all” and the ”best match”. Here 0 corresponds to ’original’ and
NumLevels - 1 is equivalent to ’all’. A value in between is in most cases a good compromise between speed
and a stable detection. A larger value for WhichLevels results in a reduced runtime, a smaller value results in a
more stable detection. The value of NumLevels has to equal or smaller than the value used to create the template.
The position of the found matching position is returned in Row and Column. The corresponding error is given
in Error. If no point below MaxError is found a value of 255 for Error and 0 for Row and Column is
returned. If the desired object is missed (no object found or wrong position) you have to set MaxError higher or
WhichLevels lower. Check also if the illumination has changed (see SetOffsetTemplate).
The maximum error of the position (without noise) is 0.1 pixel. The average error is 0.03 pixel.
Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte )


Input image inside of which the pattern has to be found.
. TemplateID (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . template ; HTemplateX / VARIANT
Template number.
. MaxError (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Maximal average difference of the grayvalues.
Default Value : 30
Suggested values : MaxError ∈ {0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 15, 17, 20, 30, 40, 50, 60, 70}
Typical range of values : 0 ≤ MaxError ≤ 0
Minimum Increment : 1
Recommended Increment : 3
. SubPixel (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Exactness in subpixels in case of ’true’.
Default Value : ’false’
List of values : SubPixel ∈ {’true’, ’false’}
. NumLevels (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of the used resolution levels.
Default Value : 4
List of values : NumLevels ∈ {1, 2, 3, 4, 5, 6}

HALCON/COM Reference Manual, 2008-5-13


7.3. GRAY-VALUE-BASED 591

. WhichLevels (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( string, integer )


Resolution level up to which the method “best match” is used.
Default Value : 2
Suggested values : WhichLevels ∈ {’all’, ’original’, 0, 1, 2, 3, 4, 5, 6}
. Row (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; double / VARIANT
Row position of the best match.
. Column (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; double / VARIANT
Column position of the best match.
. Error (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Average divergence of the grayvalues in the best match.
Result
If the parameter values are correct, the operator BestMatchMg returns the value TRUE. If the input is empty (no
input images are available) the behaviour can be set via SetSystem(’noObjectResult’,<Result>). If
necessary, an exception handling is raised.
Parallelization Information
BestMatchMg is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
CreateTemplate, ReadTemplate, AdaptTemplate, DrawRegion, DrawRectangle1,
ReduceDomain, SetReferenceTemplate, SetOffsetTemplate
Alternatives
FastMatch, FastMatchMg, BestMatch, BestMatchPreMg, BestMatchRot, BestMatchRotMg,
ExhaustiveMatch, ExhaustiveMatchMg
Module
Matching

[out] double Row HImageX.BestMatchPreMg ([in] HTemplateX TemplateID,


[in] double MaxError, [in] String SubPixel, [in] long NumLevels,
[in] VARIANT WhichLevels, [out] double Column, [out] double Error )
[out] double Row HTemplateX.BestMatchPreMg ([in] HImageX ImagePyramid,
[in] double MaxError, [in] String SubPixel, [in] long NumLevels,
[in] VARIANT WhichLevels, [out] double Column, [out] double Error )
void HOperatorSetX.BestMatchPreMg ([in] IHObjectX ImagePyramid,
[in] VARIANT TemplateID, [in] VARIANT MaxError, [in] VARIANT SubPixel,
[in] VARIANT NumLevels, [in] VARIANT WhichLevels, [out] VARIANT Row,
[out] VARIANT Column, [out] VARIANT Error )

Searching the best grayvalue matches in a pre generated pyramid.


BestMatchPreMg applies gray value matching using an image pyramid. BestMatchPreMg works analo-
gously to BestMatchMg, but it makes use of pre calculated pyramid which has to be generated beforehand using
GenGaussPyramid. This reduces runtime if more than one match has to be done or the pyramid has be used
otherwise. The pyramid has to be generated using the zooming factor 0.5 and the mode ’constant’.
Parameter
. ImagePyramid (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte )
Image pyramid inside of which the pattern has to be found.
. TemplateID (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . template ; HTemplateX / VARIANT
Template number.
. MaxError (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Maximal average difference of the grayvalues.
Default Value : 30
Suggested values : MaxError ∈ {0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 15, 17, 20, 30, 40, 50, 60, 70}
Typical range of values : 0 ≤ MaxError ≤ 0
Minimum Increment : 1
Recommended Increment : 3

HALCON 8.0.2
592 CHAPTER 7. MATCHING

. SubPixel (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT


Exactness in subpixels in case of ’true’.
Default Value : ’false’
List of values : SubPixel ∈ {’true’, ’false’}
. NumLevels (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of the used resolution levels.
Default Value : 3
List of values : NumLevels ∈ {1, 2, 3, 4, 5, 6}
. WhichLevels (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( string, integer )
Resolution level up to which the method “best match” is used.
Default Value : ’original’
Suggested values : WhichLevels ∈ {’all’, ’original’, 0, 1, 2, 3, 4, 5, 6}
. Row (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; double / VARIANT
Row position of the best match.
. Column (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; double / VARIANT
Column position of the best match.
. Error (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Average divergence of the grayvalues in the best match.
Result
If the parameter values are correct, the operator BestMatchPreMg returns the value TRUE. If the input is empty
(no input images are available) the behaviour can be set via SetSystem(’noObjectResult’,<Result>).
If necessary, an exception handling is raised.
Parallelization Information
BestMatchPreMg is reentrant and processed without parallelization.
Possible Predecessors
GenGaussPyramid, CreateTemplate, ReadTemplate, AdaptTemplate, DrawRegion,
DrawRectangle1, ReduceDomain, SetReferenceTemplate
Alternatives
FastMatch, FastMatchMg, ExhaustiveMatch, ExhaustiveMatchMg
Module
Matching

[out] VARIANT Row HImageX.BestMatchRot ([in] HTemplateX TemplateID,


[in] double AngleStart, [in] double AngleExtend, [in] double MaxError,
[in] String SubPixel, [out] VARIANT Column, [out] VARIANT Angle,
[out] VARIANT Error )
[out] VARIANT Row HTemplateX.BestMatchRot ([in] HImageX Image,
[in] double AngleStart, [in] double AngleExtend, [in] double MaxError,
[in] String SubPixel, [out] VARIANT Column, [out] VARIANT Angle,
[out] VARIANT Error )
void HOperatorSetX.BestMatchRot ([in] IHObjectX Image,
[in] VARIANT TemplateID, [in] VARIANT AngleStart, [in] VARIANT AngleExtend,
[in] VARIANT MaxError, [in] VARIANT SubPixel, [out] VARIANT Row,
[out] VARIANT Column, [out] VARIANT Angle, [out] VARIANT Error )

Searching the best matching of a template and an image with rotation.


The operator BestMatchRot performs a matching of the template of TemplateID and Image. It works
similar to BestMatch with the extension that the pattern can be rotated. The parameters AngleStart and
AngleExtend define the maximum rotation of the pattern: AngleStart specifies the maximum counter clock-
wise rotation and AngleExtend the maximum clockwise rotation relative to this angle. Both values have to
smaller or equal to the values used for the creation of the pattern (see CreateTemplateRot). In addition to
BestMatch BestMatchRot returns the rotion angle of the pattern in Angle (radiant). The accuracy of this
angle depends on the parameter AngleStep of CreateTemplateRot. In the case of SubPixel = ’true’ the
position and the angle are calculated with “sub pixel” accuracy.

HALCON/COM Reference Manual, 2008-5-13


7.3. GRAY-VALUE-BASED 593

Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte )


Input image inside of which the pattern has to be found.
. TemplateID (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . template ; HTemplateX / VARIANT
Template number.
. AngleStart (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; double / VARIANT
Smallest Rotation of the pattern.
Default Value : -0.39
Suggested values : AngleStart ∈ {-3.14, -1.57, -0.79, -0.39, -0.20, 0.0}
. AngleExtend (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; double / VARIANT
Maximum positive Extension of AngleStart.
Default Value : 0.79
Suggested values : AngleExtend ∈ {6.28, 3.14, 1.57, 0.79, 0.39}
Restriction : (AngleExtend > 0)
. MaxError (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Maximum average difference of the grayvalues.
Default Value : 30
Suggested values : MaxError ∈ {0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 15, 17, 20, 30, 40, 50, 60, 70}
Typical range of values : 0 ≤ MaxError ≤ 0
Minimum Increment : 1
Recommended Increment : 3
. SubPixel (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Subpixel accuracy in case of ’true’.
Default Value : ’false’
List of values : SubPixel ∈ {’true’, ’false’}
. Row (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( real )
Row position of the best match.
. Column (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( real )
Column position of the best match.
. Angle (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad(-array) ; VARIANT ( real )
Rotation angle of pattern.
. Error (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Average divergence of the grayvalues of the best match.
Result
If the parameter values are correct, the operator BestMatchRot returns the value TRUE. If the input is empty
(no input images are available) the behaviour can be set via SetSystem(’noObjectResult’,<Result>).
If necessary, an exception handling is raised.
Parallelization Information
BestMatchRot is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
CreateTemplateRot, ReadTemplate, SetOffsetTemplate, SetReferenceTemplate,
AdaptTemplate, DrawRegion, DrawRectangle1, ReduceDomain
See also
BestMatch, BestMatchMg
Alternatives
BestMatchRotMg
Module
Matching

HALCON 8.0.2
594 CHAPTER 7. MATCHING

[out] VARIANT Row HImageX.BestMatchRotMg ([in] HTemplateX TemplateID,


[in] double AngleStart, [in] double AngleExtend, [in] double MaxError,
[in] String SubPixel, [in] long NumLevels, [out] VARIANT Column,
[out] VARIANT Angle, [out] VARIANT Error )
[out] VARIANT Row HTemplateX.BestMatchRotMg ([in] HImageX Image,
[in] double AngleStart, [in] double AngleExtend, [in] double MaxError,
[in] String SubPixel, [in] long NumLevels, [out] VARIANT Column,
[out] VARIANT Angle, [out] VARIANT Error )
void HOperatorSetX.BestMatchRotMg ([in] IHObjectX Image,
[in] VARIANT TemplateID, [in] VARIANT AngleStart, [in] VARIANT AngleExtend,
[in] VARIANT MaxError, [in] VARIANT SubPixel, [in] VARIANT NumLevels,
[out] VARIANT Row, [out] VARIANT Column, [out] VARIANT Angle,
[out] VARIANT Error )

Searching the best matching of a template and a pyramid with rotation.


The operator BestMatchRotMg performs a matching of the template of TemplateID and Image. It works
similar to BestMatchMg with the extension that the pattern can be rotated analogously to BestMatchRot.
The parameters AngleStart and AngleExtend define the maximum rotation of the pattern: AngleStart
specifies the maximum counter clockwise rotation and AngleExtend the maximum clockwise rotation rela-
tive to this angle. Both values have to smaller or equal to the values used for the creation of the pattern (see
CreateTemplateRot). In addition to BestMatchMg BestMatchRotMg returns the rotion angle of the
pattern in Angle (radiant).
The value of MaxError must be set larger in comparison with the operator BestMatchRot, because often the
error is larger at higher levels of the pyramid.
In the case of SubPixel = ’true’ the position and the angle are calculated with “sub pixel” accuracy.
The value of NumLevels has to equal or smaller than the value used to create the template.
Parameter
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte )
Input image inside of which the pattern has to be found.
. TemplateID (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . template ; HTemplateX / VARIANT
Template number.
. AngleStart (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; double / VARIANT
Smallest Rotation of the pattern.
Default Value : -0.39
Suggested values : AngleStart ∈ {-3.14, -1.57, -0.79, -0.39, -0.20, 0.0}
. AngleExtend (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; double / VARIANT
Maximum positive Extension of AngleStart.
Default Value : 0.79
Suggested values : AngleExtend ∈ {6.28, 3.14, 1.57, 0.79, 0.39}
Restriction : (AngleExtend > 0)
. MaxError (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Maximum average difference of the grayvalues.
Default Value : 40
Suggested values : MaxError ∈ {0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 15, 17, 20, 30, 40, 50, 60, 70}
Typical range of values : 0 ≤ MaxError ≤ 0
Minimum Increment : 1
Recommended Increment : 1
. SubPixel (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Subpixel accuracy in case of ’true’.
Default Value : ’false’
List of values : SubPixel ∈ {’true’, ’false’}
. NumLevels (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of the used resolution levels.
Default Value : 3
List of values : NumLevels ∈ {1, 2, 3, 4, 5, 6}

HALCON/COM Reference Manual, 2008-5-13


7.3. GRAY-VALUE-BASED 595

. Row (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( real )


Row position of the best match.
. Column (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( real )
Column position of the best match.
. Angle (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad(-array) ; VARIANT ( real )
Rotation angle of pattern.
. Error (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Average divergence of the grayvalues of the best match.
Result
If the parameter values are correct, the operator BestMatchRotMg returns the value TRUE. If the input is empty
(no input images are available) the behaviour can be set via SetSystem(’noObjectResult’,<Result>).
If necessary, an exception handling is raised.
Parallelization Information
BestMatchRotMg is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
CreateTemplateRot, SetReferenceTemplate, SetOffsetTemplate, AdaptTemplate,
DrawRegion, DrawRectangle1, ReduceDomain
See also
FastMatch
Alternatives
BestMatchRot, BestMatchMg
Module
Matching

void HMiscX.ClearAllTemplates ( )
void HOperatorSetX.ClearAllTemplates ( )

Deallocation of the memory of all templates.


The operator ClearAllTemplates deallocates the memory of all template that were created by
CreateTemplate or CreateTemplateRot. After calling ClearAllTemplates, no template can be
used any longer.
Attention
ClearAllTemplates exists solely for the purpose of implementing the “reset program” functionality in HDe-
velop. ClearAllTemplates must not be used in any application.
Result
ClearAllTemplates always returns TRUE.
Parallelization Information
ClearAllTemplates is processed completely exclusively without parallelization.
Possible Predecessors
CreateTemplate, CreateTemplateRot, ReadTemplate, WriteTemplate
Alternatives
ClearTemplate
Module
Matching

void HOperatorSetX.ClearTemplate ([in] VARIANT TemplateID )

Deallocation of the memory of a template.

HALCON 8.0.2
596 CHAPTER 7. MATCHING

The operator ClearTemplate deallocates the memory of a template which has been created by
CreateTemplate or CreateTemplateRot. After execution of the operator ClearTemplate the tem-
plate can no longer be used. The value of TemplateID is not valid. However, the number can be used again by
further calls of CreateTemplate or CreateTemplateRot.
Parameter

. TemplateID (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . template ; HTemplateX / VARIANT


Template number.
Result
If the number of the template is valid, the operator ClearTemplate returns the value TRUE. If necessary an
exception handling will be raised.
Parallelization Information
ClearTemplate is processed completely exclusively without parallelization.
Possible Predecessors
CreateTemplate, CreateTemplateRot, ReadTemplate, WriteTemplate
See also
ClearAllTemplates
Module
Matching

[out] HTemplateX TemplateID HImageX.CreateTemplate


([in] long FirstError, [in] long NumLevel, [in] String Optimize,
[in] String GrayValues )
void HTemplateX.CreateTemplate ([in] HImageX Template,
[in] long FirstError, [in] long NumLevel, [in] String Optimize,
[in] String GrayValues )
void HOperatorSetX.CreateTemplate ([in] IHObjectX Template,
[in] VARIANT FirstError, [in] VARIANT NumLevel, [in] VARIANT Optimize,
[in] VARIANT GrayValues, [out] VARIANT TemplateID )

Preparing a pattern for template matching.


The operator CreateTemplate preprocesses a pattern (Template), which is passed as an image, for the
template matching. After the transformation, a number (TemplateID) is assigned to the template for being used
in the further process. The shape and the size of Template can be chosen arbitrarily. You have to be aware, that
the matching is only applied to that part of an image where Template fits completely into the image.
The template has be chosen such that it contains no pixels of the (changing) background. Here you can make
use of the artitrary shape of a template which is not restricted to a rectangle. To create a template you can use
segmentation operators like Threshold. In the case of sub pixel accurate matching Template has in addition
to be one pixel smaller than the pattern (i.e. one pixel border to the changing background). This can be done e.g.
by applying the operator ErosionCircle.
The parameter NumLevel specifies the number of pyramid levels (NumLevel = 1 means only original gray
values) which can be used for matching. The number of levels used later for matching will be below or equal this
value. If the pattern becomes to small due to zooming, the maximum number of pyramid levels is automatically
reduced (without error message).
The parameter GrayValues defines, wheter the original gray values (’original’, ’normalized) or the edge ampli-
tude (’gradient’, ’sobel’) is used. With ’original’ the sum of the differences is used as feature which is very stable
and fast if there is no change in illumination. ’normalized is used if the illumination changes. The method is a bit
slower and not quite as stable. If there is no change in illumination the mode ’original’ should be used. The edge
amplitude is another method to be invariant to changes in illumination. The disadvantage is the increased execution
time and the higher sensitivity to changes in the shape of the pattern. The mode ’gradient’ is slighy faster but more
sensitive to noise.
The maximum error for matching has typically to be chosen higher when using the edge amplitude. The mode
chosen by GrayValues leads automatically to calling the appropriate filter during matching — if necessary.

HALCON/COM Reference Manual, 2008-5-13


7.3. GRAY-VALUE-BASED 597

As an alternative to the gradient approach the operator SetOffsetTemplate can be used, if the change in
illumination is known.
The parameter Optimize specifies if the pattern has to optimized for runtime. This optimization results in a
longer time to create the template but reduces the time for matching. In addition the optimization leads to a more
stable matching, i.e., the possibilty to miss good matches is reduced. The optimization process selects the most
stable and significant gray values to be tested first during the matching process. Using this technique a wrong
match can be eliminated very early.
The reference position for the template is its center of gravity. I.e. if you apply the template to the orig-
inal image the center of gravity is returned. This default reference can be adapted using the operator
SetReferenceTemplate.
In sub pixel mode a special position correction is calculated which is added after each matching: The template is
applied to the original image and the difference between the found position and the center of gravity is used as a
correction vector. This is important for patterns in a textured context or for asymetric pattern. For most templates
this correction vector is near null.
If the pattern is no longer used, it has to be freed by the operator ClearTemplate in order to deallocate the
memory.
Before the use of the template, which is stored independently of the image size, it can be adapted explicitly to the
size of a definite image size by using AdaptTemplate.
Parameter

. Template (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte )


Input image whose domain will be processed for the pattern matching.
. FirstError (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Not yet in use.
Default Value : 255
List of values : FirstError ∈ {255}
. NumLevel (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Maximal number of pyramid levels.
Default Value : 4
List of values : NumLevel ∈ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
. Optimize (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Kind of optimizing.
Default Value : ’sort’
List of values : Optimize ∈ {’none’, ’sort’}
. GrayValues (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Kind of grayvalues.
Default Value : ’original’
List of values : GrayValues ∈ {’original’, ’normalized’, ’gradient’, ’sobel’}
. TemplateID (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . template ; HTemplateX / VARIANT
Template number.
Result
If the parameters are valid, the operator CreateTemplate returns the value TRUE. If necessary an exception
handling will be raised.
Parallelization Information
CreateTemplate is processed completely exclusively without parallelization.
Possible Predecessors
DrawRegion, ReduceDomain, Threshold
Possible Successors
AdaptTemplate, SetReferenceTemplate, ClearTemplate, WriteTemplate,
SetOffsetTemplate, BestMatch, BestMatchMg, FastMatch, FastMatchMg
Alternatives
CreateTemplateRot, ReadTemplate
Module
Matching

HALCON 8.0.2
598 CHAPTER 7. MATCHING

[out] HTemplateX TemplateID HImageX.CreateTemplateRot


([in] long NumLevel, [in] double AngleStart, [in] double AngleExtend,
[in] double AngleStep, [in] String Optimize, [in] String GrayValues )
void HTemplateX.CreateTemplateRot ([in] HImageX Template,
[in] long NumLevel, [in] double AngleStart, [in] double AngleExtend,
[in] double AngleStep, [in] String Optimize, [in] String GrayValues )
void HOperatorSetX.CreateTemplateRot ([in] IHObjectX Template,
[in] VARIANT NumLevel, [in] VARIANT AngleStart, [in] VARIANT AngleExtend,
[in] VARIANT AngleStep, [in] VARIANT Optimize, [in] VARIANT GrayValues,
[out] VARIANT TemplateID )

Preparing a pattern for template matching with rotation.


The operator CreateTemplateRot preprocesses a pattern, which is passed as an image, for the template
matching. An extension to CreateTemplate the matching can applied to rotated patterns. The parameters
AngleStart and AngleExtend define the maximum rotation of the pattern: AngleStart specifies the
maximum counter clockwise rotation and AngleExtend the maximum clockwise rotation relative to this angle.
Therefore AngleExtend has to be smaller than 2π. With the parameter AngleStep the maximum angle
resolution (on the highest resolution level) can be specified.
You have to be aware, that all possible rotations are calculated beforehand to reduce runtime during matching. This
leads to a higher execution time for CreateTemplateRot and high memory requirements for the template.
The amount of memory depends on the parameters AngleExtend and AngleStep. The number of pyramid
levels can be neglected. If A is the number of pixels of Template, the memory M needed for the template in
byte is about:

A ∗ 12 ∗ AngleExtend
M=
AngleStep

After the transformation, a number (TemplateID) is assigned to the template for being used in the further
process.
A description of the other parameters can be found at the operator CreateTemplate.
Attention
You have to be aware, that depending on the resolution a large number of pre calculated patterns have to be created
which might result in a large amount of memory needed.
Parameter

. Template (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte )


Input image whose domain will be processed for the pattern matching.
. NumLevel (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Maximal number of pyramid levels.
Default Value : 4
List of values : NumLevel ∈ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
. AngleStart (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; double / VARIANT
Smallest Rotation of the pattern.
Default Value : -0.39
Suggested values : AngleStart ∈ {-3.14, -1.57, -0.79, -0.39, -0.20, 0.0}
. AngleExtend (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; double / VARIANT
Maximum positive Extension of AngleStart.
Default Value : 0.79
Suggested values : AngleExtend ∈ {6.28, 3.14, 1.57, 0.79, 0.39}
Restriction : (AngleExtend > 0)
. AngleStep (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; double / VARIANT
Step rate (angle precision) of matching.
Default Value : 0.0982
Suggested values : AngleStep ∈ {0.3927, 0.1963, 0.0982, 0.0491, 0.0245}
Restriction : (AngleStep > 0)

HALCON/COM Reference Manual, 2008-5-13


7.3. GRAY-VALUE-BASED 599

. Optimize (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT


Kind of optimizing.
Default Value : ’sort’
List of values : Optimize ∈ {’none’, ’sort’}
. GrayValues (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Kind of grayvalues.
Default Value : ’original’
List of values : GrayValues ∈ {’original’, ’normalized’, ’gradient’, ’sobel’}
. TemplateID (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . template ; HTemplateX / VARIANT
Template number.
Result
If the parameters are valid, the operator CreateTemplateRot returns the value TRUE. If necessary an excep-
tion handling will be raised.
Parallelization Information
CreateTemplateRot is processed completely exclusively without parallelization.
Possible Predecessors
DrawRegion, ReduceDomain, Threshold
Possible Successors
BestMatchRot, BestMatchRotMg, AdaptTemplate, SetReferenceTemplate, ClearTemplate,
SetOffsetTemplate, WriteTemplate
Alternatives
CreateTemplate
Module
Matching

[out] HRegionX Matches HImageX.FastMatch ([in] HTemplateX TemplateID,


[in] double MaxError )
[out] HRegionX Matches HTemplateX.FastMatch ([in] HImageX Image,
[in] double MaxError )
void HOperatorSetX.FastMatch ([in] IHObjectX Image,
[out] HUntypedObjectX Matches, [in] VARIANT TemplateID,
[in] VARIANT MaxError )

Searching all good matches of a template and an image.


The operator FastMatch performs a matching of the template of TemplateID and Image. Hereby the
template will be moved over the points of Image so that the template always lies completely inside of Image.
The matching criterion (“displaced frame difference”) is defined as follows:
P
u,v |Image[row − u, col − v] − TemplateID[u, v]|
error[row, col] =
area(T emplateID)

The difference between FastMatch and ExhaustiveMatch is that the matching for one position is stopped
if the error is to high. This leads to a reduced runtime but one might miss correct matches. The runtime of the
operator depends mainly on the size of the domain of Image. Therefore it is important to restrict the domain as
far as possible, i.e. to apply the operator only in a very confined “region of interest”. The parameter MaxError
determines the maximal error which the searched position is allowed to show. The lower this value is, the faster
the operator runs.
All points which show a matching error smaller than MaxError will be returned in the output region Matches.
This region can be used for further processing. For example by using a connection and BestMatch to find all
the matching objects. If no point has a match error below MaxError the empty region (i.e no points) is returned.

HALCON 8.0.2
600 CHAPTER 7. MATCHING

Parameter
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte )
Input image inside of which the pattern has to be found.
. Matches (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
All points whose error lies below a certain threshold.
. TemplateID (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . template ; HTemplateX / VARIANT
Template number.
. MaxError (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Maximal average difference of the grayvalues.
Default Value : 20
Suggested values : MaxError ∈ {0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 15, 17, 20, 30}
Typical range of values : 0 ≤ MaxError ≤ 0
Minimum Increment : 1
Recommended Increment : 1
Result
If the parameter values are correct, the operator FastMatch returns the value TRUE. If the input is empty (no
input images are available) the behaviour can be set via SetSystem(’noObjectResult’,<Result>). If
necessary, an exception handling is raised.
Parallelization Information
FastMatch is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
CreateTemplate, ReadTemplate, AdaptTemplate, DrawRegion, DrawRectangle1,
ReduceDomain
Possible Successors
Connection, BestMatch
Alternatives
BestMatch, BestMatchMg, FastMatchMg, ExhaustiveMatch, ExhaustiveMatchMg
Module
Matching

[out] HRegionX Matches HImageX.FastMatchMg ([in] HTemplateX TemplateID,


[in] double MaxError, [in] VARIANT NumLevel )
[out] HRegionX Matches HTemplateX.FastMatchMg ([in] HImageX Image,
[in] double MaxError, [in] VARIANT NumLevel )
void HOperatorSetX.FastMatchMg ([in] IHObjectX Image,
[out] HUntypedObjectX Matches, [in] VARIANT TemplateID,
[in] VARIANT MaxError, [in] VARIANT NumLevel )

Searching all good grayvalue matches in a pyramid.


The operator FastMatchMg like the operator FastMatch performs a matching of the template of
TemplateID and Image. In contrast to FastMatch, however, the search for good matches starts in scaled
down images (pyramid). The number of levels of the pyramid will be determined by NumLevel. Hereby the value
1 indicates that no pyramid will be used. In this case the operator FastMatchMg is equivalent to the operator
FastMatch. The value 2 triggers the search in the image with half the framesize. The search for all those points
showing an error small enough in the scaled down image (error smaller than MaxError) will be refined at the
corresponding positions in the original image (Image).
The runtime of matching dependends on the parameter MaxError: the larger the value the longer is the processing
time, because more points of the pattern have to be tested. If MaxError is to low the pattern will not be found.
The value has therefore to be optimized for every application.
NumLevel indicates the number of levels of the pyramid, including the original image. Optionally a second value
can be given. This value specifies the number (0..n) of the lowest level which is used the the matching. The region
found up to this level will then be zoomed to the size of the original level. This can used to increase the runtime in
the case that the accuracy does not have to be so high.

HALCON/COM Reference Manual, 2008-5-13


7.3. GRAY-VALUE-BASED 601

Parameter
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte )
Input image inside of which the pattern has to be found.
. Matches (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
All points which have an error below a certain threshold.
. TemplateID (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . template ; HTemplateX / VARIANT
Template number.
. MaxError (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Maximal average difference of the grayvalues.
Default Value : 30
Suggested values : MaxError ∈ {0, 1, 2, 3, 4, 5, 6, 7, 9, 11, 15, 17, 20, 30, 40, 50, 60, 70}
Typical range of values : 0 ≤ MaxError ≤ 0
Minimum Increment : 1
Recommended Increment : 3
. NumLevel (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Number of levels in the pyramid.
Default Value : 3
List of values : NumLevel ∈ {1, 2, 3, 4, 5, 6, 7, 8}
Result
If the parameter values are correct, the operator FastMatchMg returns the value TRUE. If the input is empty (no
input images are available) the behaviour can be set via SetSystem(’noObjectResult’,<Result>). If
necessary, an exception handling is raised.
Parallelization Information
FastMatchMg is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
CreateTemplate, ReadTemplate, AdaptTemplate, DrawRegion, DrawRectangle1,
ReduceDomain
Alternatives
BestMatch, BestMatchMg, FastMatch, ExhaustiveMatch, ExhaustiveMatchMg
Module
Matching

void HTemplateX.ReadTemplate ([in] String FileName )


void HOperatorSetX.ReadTemplate ([in] VARIANT FileName,
[out] VARIANT TemplateID )

Reading a template from file.


The operator ReadTemplate reads a matching template from file which has been written with
WriteTemplate.
Parameter
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.read ; String / VARIANT
file name.
. TemplateID (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . template ; HTemplateX / VARIANT
Template number.
Result
If the file name is valid, the operator ReadTemplate returns the value TRUE. If necessary an exception handling
will be raised.
Parallelization Information
ReadTemplate is processed completely exclusively without parallelization.
Possible Successors
AdaptTemplate, SetReferenceTemplate, SetOffsetTemplate, BestMatch, FastMatch,
BestMatchRot

HALCON 8.0.2
602 CHAPTER 7. MATCHING

Module
Matching

void HTemplateX.SetOffsetTemplate ([in] long GrayOffset )


void HOperatorSetX.SetOffsetTemplate ([in] VARIANT TemplateID,
[in] VARIANT GrayOffset )

Gray value offset for template.


SetOffsetTemplate adds a gray value offset to the template to eliminate gray value changes in the image.
The parameter GrayOffset specifies a difference relative to the gray values of the pattern when it was created
with CreateTemplate (not relative to the last call of SetOffsetTemplate). The values of GrayOffset
has to be chosen according to the gray values of the image: A brighter image results in a positive value, a darker
image results in a negative value. SetOffsetTemplate has to be called each time the gray values of the image
changes. The gray values can be meassured in a reference area using Intensity or MinMaxGray
Parameter
. TemplateID (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . template ; HTemplateX / VARIANT
Template number.
. GrayOffset (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; long / VARIANT
Offset of gray values.
Default Value : 0
Suggested values : GrayOffset ∈ {-10, -5, -2, -1, 0, 1, 2, 5, 10}
Typical range of values : -255 ≤ GrayOffset ≤ -255
Minimum Increment : 1
Recommended Increment : 1
Result
If the parameter values are correct, the operator SetOffsetTemplate returns the value TRUE. If necessary,
an exception handling is raised.
Parallelization Information
SetOffsetTemplate is reentrant and processed without parallelization.
Possible Predecessors
CreateTemplate, AdaptTemplate, ReadTemplate
Possible Successors
BestMatch, BestMatchMg, BestMatchRot, FastMatch, FastMatchMg
Module
Matching

void HTemplateX.SetReferenceTemplate ([in] double Row,


[in] double Column )
void HOperatorSetX.SetReferenceTemplate ([in] VARIANT TemplateID,
[in] VARIANT Row, [in] VARIANT Column )

Define reference position for a matching template.


SetReferenceTemplate allows to define a new reference position for a template. As default after call-
ing CreateTemplate or CreateTemplateRot the center of gravity of the template is used. Using
SetReferenceTemplate the reference position can be redefined. In the case of the center of gravity as
reference the vector (0, 0) is returned after matching for a null translation of the pattern relative to the image.
Parameter
. TemplateID (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . template ; HTemplateX / VARIANT
Template number.
. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; double / VARIANT
Reference position of template (row).

HALCON/COM Reference Manual, 2008-5-13


7.4. SHAPE-BASED 603

. Column (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; double / VARIANT


Reference position of template (column).
Result
If the parameter values are correct, the operator SetReferenceTemplate returns the value TRUE. If neces-
sary, an exception handling is raised.
Parallelization Information
SetReferenceTemplate is reentrant and processed without parallelization.
Possible Predecessors
CreateTemplate, CreateTemplateRot, ReadTemplate, AdaptTemplate
Possible Successors
BestMatch, BestMatchMg, BestMatchRot, FastMatch, FastMatchMg
Module
Matching

void HTemplateX.WriteTemplate ([in] String FileName )


void HOperatorSetX.WriteTemplate ([in] VARIANT TemplateID,
[in] VARIANT FileName )

Writing a template to file.


The operator WriteTemplate writes a matching template to file which can be read again with
ReadTemplate.
Parameter
. TemplateID (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . template ; HTemplateX / VARIANT
Template number.
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.write ; String / VARIANT
file name.
Result
If the file name is valid (permission to write), the operator WriteTemplate returns the value TRUE. If necessary
an exception handling will be raised.
Parallelization Information
WriteTemplate is reentrant and processed without parallelization.
Possible Predecessors
CreateTemplate, CreateTemplateRot
Module
Matching

7.4 Shape-Based

void HMiscX.ClearAllShapeModels ( )
void HOperatorSetX.ClearAllShapeModels ( )

Free the memory of all shape models.


The operator ClearAllShapeModels frees the memory of all shape models that were created by
CreateShapeModel, CreateScaledShapeModel, or CreateAnisoShapeModel. After calling
ClearAllShapeModels, no model can be used any longer.
Attention
ClearAllShapeModels exists solely for the purpose of implementing the “reset program” functionality in
HDevelop. ClearAllShapeModels must not be used in any application.
Result
ClearAllShapeModels always returns TRUE.

HALCON 8.0.2
604 CHAPTER 7. MATCHING

Parallelization Information
ClearAllShapeModels is processed completely exclusively without parallelization.
Possible Predecessors
CreateShapeModel, CreateScaledShapeModel, CreateAnisoShapeModel,
ReadShapeModel, WriteShapeModel
Alternatives
ClearShapeModel
Module
Matching

void HOperatorSetX.ClearShapeModel ([in] VARIANT ModelID )

Free the memory of a shape model.


The operator ClearShapeModel frees the memory of a shape model that was created by
CreateShapeModel, CreateScaledShapeModel, or CreateAnisoShapeModel. After calling
ClearShapeModel, the model can no longer be used. The handle ModelID becomes invalid.
Parameter

. ModelID (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . shape_model ; HShapeModelX / VARIANT


Handle of the model.
Result
If the handle of the model is valid, the operator ClearShapeModel returns the value TRUE. If necessary an
exception is raised.
Parallelization Information
ClearShapeModel is processed completely exclusively without parallelization.
Possible Predecessors
CreateShapeModel, CreateScaledShapeModel, CreateAnisoShapeModel,
ReadShapeModel, WriteShapeModel
See also
ClearAllShapeModels
Module
Matching

HALCON/COM Reference Manual, 2008-5-13


7.4. SHAPE-BASED 605

[out] HShapeModelX ModelID HImageX.CreateAnisoShapeModel


([in] VARIANT NumLevels, [in] double AngleStart, [in] double AngleExtent,
[in] VARIANT AngleStep, [in] double ScaleRMin, [in] double ScaleRMax,
[in] VARIANT ScaleRStep, [in] double ScaleCMin, [in] double ScaleCMax,
[in] VARIANT ScaleCStep, [in] VARIANT Optimization, [in] String Metric,
[in] VARIANT Contrast, [in] VARIANT MinContrast )
void HShapeModelX.CreateAnisoShapeModel ([in] HImageX Template,
[in] VARIANT NumLevels, [in] double AngleStart, [in] double AngleExtent,
[in] VARIANT AngleStep, [in] double ScaleRMin, [in] double ScaleRMax,
[in] VARIANT ScaleRStep, [in] double ScaleCMin, [in] double ScaleCMax,
[in] VARIANT ScaleCStep, [in] VARIANT Optimization, [in] String Metric,
[in] VARIANT Contrast, [in] VARIANT MinContrast )
void HOperatorSetX.CreateAnisoShapeModel ([in] IHObjectX Template,
[in] VARIANT NumLevels, [in] VARIANT AngleStart, [in] VARIANT AngleExtent,
[in] VARIANT AngleStep, [in] VARIANT ScaleRMin, [in] VARIANT ScaleRMax,
[in] VARIANT ScaleRStep, [in] VARIANT ScaleCMin, [in] VARIANT ScaleCMax,
[in] VARIANT ScaleCStep, [in] VARIANT Optimization, [in] VARIANT Metric,
[in] VARIANT Contrast, [in] VARIANT MinContrast, [out] VARIANT ModelID )

Prepare a shape model for anisotropic scale invariant matching.


The operator CreateAnisoShapeModel prepares a template, which is passed in the image Template, as
a shape model used for anisotropic scale invariant matching. The ROI of the model is passed as the domain of
Template.
The model is generated using multiple image pyramid levels and is stored in memory. If a complete pregeneration
of the model is selected (see below), the model is generated at multiple rotations and anisotropic scales (i.e.,
independent scales in the row and column direction) on each level. The output parameter ModelID is a handle
for this model, which is used in subsequent calls to FindAnisoShapeModel.
The number of pyramid levels is determined with the parameter NumLevels. It should be chosen as large as pos-
sible because by this the time necessary to find the object is significantly reduced. On the other hand, NumLevels
must be chosen such that the model is still recognizable and contains a sufficient number of points (at least four) on
the highest pyramid level. This can be checked using the output of InspectShapeModel. If not enough model
points are generated, the number of pyramid levels is reduced internally until enough model points are found on
the highest pyramid level. If this procedure would lead to a model with no pyramid levels, i.e., if the number of
model points is already too small on the lowest pyramid level, CreateAnisoShapeModel returns with an
error message. If NumLevels is set to ’auto’ (or 0 for backwards compatibility), CreateAnisoShapeModel
determines the number of pyramid levels automatically. The automatically computed number of pyramid levels can
be queried using GetShapeModelParams. In rare cases, it might happen that CreateAnisoShapeModel
determines a value for the number of pyramid levels that is too large or too small. If the number of pyramid levels is
chosen too large, the model may not be recognized in the image or it may be necessary to select very low parameters
for MinScore or Greediness in FindAnisoShapeModel in order to find the model. If the number of pyramid
levels is chosen too small, the time required to find the model in FindAnisoShapeModel may increase. In
these cases, the number of pyramid levels should be selected using the output of InspectShapeModel.
The parameters AngleStart and AngleExtent determine the range of possible rotations, in which
the model can occur in the image. Note that the model can only be found in this range of angles by
FindAnisoShapeModel. The parameter AngleStep determines the step length within the selected range
of angles. Hence, if subpixel accuracy is not specified in FindAnisoShapeModel, this parameter specifies
the accuracy that is achievable for the angles in FindAnisoShapeModel. AngleStep should be chosen
based on the size of the object. Smaller models do not have many different discrete rotations in the image, and
hence AngleStep should be chosen larger for smaller models. If AngleExtent is not an integer multiple of
AngleStep, AngleStep is modified accordingly.
The parameters ScaleRMin, ScaleRMax, ScaleCMin, and ScaleCMax determine the range of possible
anisotropic scales of the model in the row and column direction. A scale of 1 in both scale factors corresponds to
the original size of the model. The parameters ScaleRStep and ScaleCStep determine the step length within
the selected range of scales. Hence, if subpixel accuracy is not specified in FindAnisoShapeModel, these pa-
rameters specify the accuracy that is achievable for the scales in FindAnisoShapeModel. Like AngleStep,
ScaleRStep and ScaleCStep should be chosen based on the size of the object. If the respective range of

HALCON 8.0.2
606 CHAPTER 7. MATCHING

scales is not an integer multiple of ScaleRStep and ScaleCStep, ScaleRStep and ScaleCStep are
modified accordingly.
Note that the transformations are treated internally such that the scalings are applied first, followed by the rotation.
Therefore, the model should usually be aligned such that it appears horizontally or vertically in the model image.
If a complete pregeneration of the model is selected (see below), the model is pre-generated for the selected angle
and scale range and stored in memory. The memory required to store the model is proportional to the num-
ber of angle steps, the number of scale steps, and the number of points in the model. Hence, if AngleStep,
ScaleRStep, or ScaleCStep are too small or AngleExtent or the range of scales are too big, it may
happen that the model no longer fits into the (virtual) memory. In this case, AngleStep, ScaleRStep, or
ScaleCStep must be enlarged or AngleExtent or the range of scales must be reduced. In any case, it is desir-
able that the model completely fits into the main memory, because this avoids paging by the operating system, and
hence the time to find the object will be much smaller. Since angles can be determined with subpixel resolution by
FindAnisoShapeModel, AngleStep ≥ 1◦ and ScaleRStep, ScaleCStep ≥ 0.02 can be selected for
models of a diameter smaller than about 200 pixels. If AngleStep = 0 auto 0 or ScaleRStep, ScaleCStep =
0
auto 0 (or 0 for backwards compatibility in both cases) is selected, CreateAnisoShapeModel automatically
determines a suitable angle or scale step length, respectively, based on the size of the model. The automatically
computed angle and scale step lengths can be queried using GetShapeModelParams.
If a complete pregeneration of the model is not selected, the model is only created in a reference pose on each
pyramid level. In this case, the model must be transformed to the different angles and scales at runtime in
FindAnisoShapeModel. Because of this, the recognition of the model might require slightly more time.
For particularly large models, it may be useful to reduce the number of model points by setting Optimization
to a value different from ’none’. If Optimization = ’none’, all model points are stored. In all other cases, the
number of points is reduced according to the value of Optimization. If the number of points is reduced, it may
be necessary in FindAnisoShapeModel to set the parameter Greediness to a smaller value, e.g., 0.7 or 0.8.
For small models, the reduction of the number of model points does not result in a speed-up of the search because
in this case usually significantly more potential instances of the model must be examined. If Optimization
is set to ’auto’, CreateAnisoShapeModel automatically determines the reduction of the number of model
points.
Optionally, a second value can be passed in Optimization. This value determines whether the model is pre-
generated completely or not. To do so, the second value of Optimization must be set to either ’pregenera-
tion’ or ’no_pregeneration’. If the second value is not used (i.e., if only one value is passed), the mode that is
set with SetSystem(’pregenerateShapeModels’,...) is used. With the default value (’pregener-
ate_shape_models’ = ’false’), the model is not pregenerated completely. The complete pregeneration of the model
normally leads to slightly lower runtimes because the model does not need to be transformed at runtime. However,
in this case, the memory requirements and the time required to create the model are significantly higher. It should
also be noted that it cannot be expected that the two modes return exactly identical results because transforming
the model at runtime necessarily leads to different internal data for the transformed models than pregenerating
the transformed models. For example, if the model is not pregenerated completely, FindAnisoShapeModel
typically returns slightly lower scores, which may require setting a slightly lower value for MinScore than for a
completely pregenerated model. Furthermore, the poses obtained by interpolation may differ slightly in the two
modes. If maximum accuracy is desired, the pose of the model should be determined by least-squares adjustment.
The parameter Contrast determines the contrast the model points must have. The contrast is a measure for
local gray value differences between the object and the background and between different parts of the object.
Contrast should be chosen such that only the significant features of the template are used for the model.
Contrast can also contain a tuple with two values. In this case, the model is segmented using a method sim-
ilar to the hysteresis threshold method used in EdgesImage. Here, the first element of the tuple determines
the lower threshold, while the second element determines the upper threshold. For more information about the
hysteresis threshold method, see HysteresisThreshold. Optionally, Contrast can contain a third value
as the last element of the tuple. This value determines a threshold for the selection of significant model compo-
nents based on the size of the components, i.e., components that have fewer points than the minimum size thus
specified are suppressed. This threshold for the minimum size is divided by two for each successive pyramid
level. If small model components should be suppressed, but hysteresis thresholding should not be performed,
nevertheless three values must be specified in Contrast. In this case, the first two values can simply be set
to identical values. The effect of this parameter can be checked in advance with InspectShapeModel. If
Contrast is set to ’auto’, CreateAnisoShapeModel determines the three above described values auto-
matically. Alternatively, only the contrast (’auto_contrast’), the hysteresis thresholds (’auto_contrast_hyst’), or
the minimum size (’auto_min_size’) can be determined automatically. The remaining values that are not deter-

HALCON/COM Reference Manual, 2008-5-13


7.4. SHAPE-BASED 607

mined automatically can additionally be passed in the form of a tuple. Also various combinations are allowed:
If, for example, [’auto_contrast’,’auto_min_size’] is passed, both the contrast and the minimum size are deter-
mined automatically. If [’auto_min_size’,20,30] is passed, the minimum size is determined automatically while
the hysteresis thresholds are set to 20 and 30, etc. In certain cases, it might happen that the automatic determi-
nation of the contrast thresholds is not satisfying. For example, a manual setting of these parameters should be
preferred if certain model components should be included or suppressed because of application-specific reasons
or if the object contains several different contrasts. Therefore, the contrast thresholds should be automatically
determined with DetermineShapeModelParams and subsequently verified using InspectShapeModel
before calling CreateAnisoShapeModel.
With MinContrast, it can be determined which contrast the model must at least have in the recognition per-
formed by FindAnisoShapeModel. In other words, this parameter separates the model from the noise in
the image. Therefore, a good choice is the range of gray value changes caused by the noise in the image. If,
for example, the gray values fluctuate within a range of 10 gray levels, MinContrast should be set to 10. If
multichannel images are used for the model and the search images, and if the parameter Metric is set to ’ig-
nore_color_polarity’ (see below) the noise in one channel must be multiplied by the square root of the number
of channels to determine MinContrast. If, for example, the gray values fluctuate within a range of 10 gray
levels in a single channel and the image is a three-channel image MinContrast should be set to 17. Obviously,
MinContrast must be smaller than Contrast. If the model should be recognized in very low contrast im-
ages, MinContrast must be set to a correspondingly small value. If the model should be recognized even if it
is severely occluded, MinContrast should be slightly larger than the range of gray value fluctuations created
by noise in order to ensure that the position and rotation of the model are extracted robustly and accurately by
FindAnisoShapeModel. If MinContrast is set to ’auto’, the minimum contrast is determined automati-
cally based on the noise in the model image. Consequently, an automatic determination only makes sense if the
image noise during the recognition is similar to the noise in the model image. Furthermore, in some cases it is
advisable to increase the automatically determined value in order to increase the robustness against occlusions (see
above). The automatically computed minimum contrast can be queried using GetShapeModelParams.
The parameter Metric determines the conditions under which the model is recognized in the image. If Metric
= ’use_polarity’, the object in the image and the model must have the same contrast. If, for example, the
model is a bright object on a dark background, the object is found only if it is also brighter than the back-
ground. If Metric = ’ignore_global_polarity’, the object is found in the image also if the contrast reverses
globally. In the above example, the object hence is also found if it is darker than the background. The runtime of
FindAnisoShapeModel will increase slightly in this case. If Metric = ’ignore_local_polarity’, the model
is found even if the contrast changes locally. This mode can, for example, be useful if the object consists of a
part with medium gray value, within which either darker or brighter sub-objects lie. Since in this case the runtime
of FindAnisoShapeModel increases significantly, it is usually better to create several models that reflect the
possible contrast variations of the object with CreateAnisoShapeModel, and to match them simultaneously
with FindAnisoShapeModels. The above three metrics can only be applied to single-channel images. If a
multichannel image is used as the model image or as the search image only the first channel will be used (and no er-
ror message will be returned). If Metric = ’ignore_color_polarity’, the model is found even if the color contrast
changes locally. This is, for example, the case if parts of the object can change their color, e.g., from red to green. In
particular, this mode is useful if it is not known in advance in which channels the object is visible. In this mode, the
runtime of FindAnisoShapeModel can also increase significantly. The metric ’ignore_color_polarity’ can be
used for images with an arbitrary number of channels. If it is used for single-channel images it has the same effect
as ’ignore_local_polarity’. It should be noted that for Metric = ’ignore_color_polarity’ the number of channels
in the model creation with CreateAnisoShapeModel and in the search with FindAnisoShapeModel
can be different. This can, for example, be used to create a model from a synthetically generated single-channel
image. Furthermore, it should be noted that the channels do not need to contain a spectral subdivision of the light
(like in an RGB image). The channels can, for example, also contain images of the same object that were obtained
by illuminating the object from different directions.
The center of gravity of the domain (region) of the model image Template is used as the origin (reference point)
of the model. A different origin can be set with SetShapeModelOrigin.
Parameter

. Template (input iconic) . . . . . . . . . . . . . . . . . . (multichannel-)image ; HImageX / IHObjectX ( byte, uint2 )


Input image whose domain will be used to create the model.

HALCON 8.0.2
608 CHAPTER 7. MATCHING

. NumLevels (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer, string )


Maximum number of pyramid levels.
Default Value : ’auto’
List of values : NumLevels ∈ {’auto’, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
. AngleStart (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; double / VARIANT
Smallest rotation of the pattern.
Default Value : -0.39
Suggested values : AngleStart ∈ {-3.14, -1.57, -0.79, -0.39, -0.20, 0.0}
. AngleExtent (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; double / VARIANT
Extent of the rotation angles.
Default Value : 0.79
Suggested values : AngleExtent ∈ {6.29, 3.14, 1.57, 0.79, 0.39}
Restriction : (AngleExtent ≥ 0)
. AngleStep (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; VARIANT ( real, string )
Step length of the angles (resolution).
Default Value : ’auto’
Suggested values : AngleStep ∈ {’auto’, 0.0175, 0.0349, 0.0524, 0.0698, 0.0873}
Restriction : ((AngleStep ≥ 0) ∧ (AngleStep ≤ (pi/16)))
. ScaleRMin (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Minimum scale of the pattern in the row direction.
Default Value : 0.9
Suggested values : ScaleRMin ∈ {0.5, 0.6, 0.7, 0.8, 0.9, 1.0}
Restriction : (ScaleRM in > 0)
. ScaleRMax (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Maximum scale of the pattern in the row direction.
Default Value : 1.1
Suggested values : ScaleRMax ∈ {1.0, 1.1, 1.2, 1.3, 1.4, 1.5}
Restriction : (ScaleRM ax ≥ ScaleRM in)
. ScaleRStep (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, string )
Scale step length (resolution) in the row direction.
Default Value : ’auto’
Suggested values : ScaleRStep ∈ {’auto’, 0.01, 0.02, 0.05, 0.1, 0.15, 0.2}
Restriction : (ScaleRStep ≥ 0)
. ScaleCMin (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Minimum scale of the pattern in the column direction.
Default Value : 0.9
Suggested values : ScaleCMin ∈ {0.5, 0.6, 0.7, 0.8, 0.9, 1.0}
Restriction : (ScaleCM in > 0)
. ScaleCMax (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Maximum scale of the pattern in the column direction.
Default Value : 1.1
Suggested values : ScaleCMax ∈ {1.0, 1.1, 1.2, 1.3, 1.4, 1.5}
Restriction : (ScaleCM ax ≥ ScaleCM in)
. ScaleCStep (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, string )
Scale step length (resolution) in the column direction.
Default Value : ’auto’
Suggested values : ScaleCStep ∈ {’auto’, 0.01, 0.02, 0.05, 0.1, 0.15, 0.2}
Restriction : (ScaleCStep ≥ 0)
. Optimization (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Kind of optimization and optionally method used for generating the model.
Default Value : ’auto’
List of values : Optimization ∈ {’auto’, ’none’, ’point_reduction_low’, ’point_reduction_medium’,
’point_reduction_high’, ’pregeneration’, ’no_pregeneration’}
. Metric (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Match metric.
Default Value : ’use_polarity’
List of values : Metric ∈ {’use_polarity’, ’ignore_global_polarity’, ’ignore_local_polarity’,
’ignore_color_polarity’}

HALCON/COM Reference Manual, 2008-5-13


7.4. SHAPE-BASED 609

. Contrast (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( integer, string )


Threshold or hysteresis thresholds for the contrast of the object in the template image and optionally minimum
size of the object parts.
Default Value : ’auto’
Suggested values : Contrast ∈ {’auto’, ’auto_contrast’, ’auto_contrast_hyst’, ’auto_min_size’, 10, 20, 30,
40, 60, 80, 100, 120, 140, 160}
. MinContrast (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, string )
Minimum contrast of the objects in the search images.
Default Value : ’auto’
Suggested values : MinContrast ∈ {’auto’, 1, 2, 3, 5, 7, 10, 20, 30, 40}
Restriction : (M inContrast < Contrast)
. ModelID (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . shape_model ; HShapeModelX / VARIANT
Handle of the model.
Result
If the parameters are valid, the operator CreateAnisoShapeModel returns the value TRUE. If necessary an
exception is raised. If the parameters NumLevels and Contrast are chosen such that the model contains too
few points, the error 8510 is raised.
Parallelization Information
CreateAnisoShapeModel is processed completely exclusively without parallelization.
Possible Predecessors
DrawRegion, ReduceDomain, Threshold
Possible Successors
FindAnisoShapeModel, FindAnisoShapeModels, GetShapeModelParams,
ClearShapeModel, WriteShapeModel, SetShapeModelOrigin
See also
SetSystem, GetSystem
Alternatives
CreateShapeModel, CreateScaledShapeModel, CreateTemplateRot
Module
Matching

[out] HShapeModelX ModelID HImageX.CreateScaledShapeModel


([in] VARIANT NumLevels, [in] double AngleStart, [in] double AngleExtent,
[in] VARIANT AngleStep, [in] double ScaleMin, [in] double ScaleMax,
[in] VARIANT ScaleStep, [in] VARIANT Optimization, [in] String Metric,
[in] VARIANT Contrast, [in] VARIANT MinContrast )
void HShapeModelX.CreateScaledShapeModel ([in] HImageX Template,
[in] VARIANT NumLevels, [in] double AngleStart, [in] double AngleExtent,
[in] VARIANT AngleStep, [in] double ScaleMin, [in] double ScaleMax,
[in] VARIANT ScaleStep, [in] VARIANT Optimization, [in] String Metric,
[in] VARIANT Contrast, [in] VARIANT MinContrast )
void HOperatorSetX.CreateScaledShapeModel ([in] IHObjectX Template,
[in] VARIANT NumLevels, [in] VARIANT AngleStart, [in] VARIANT AngleExtent,
[in] VARIANT AngleStep, [in] VARIANT ScaleMin, [in] VARIANT ScaleMax,
[in] VARIANT ScaleStep, [in] VARIANT Optimization, [in] VARIANT Metric,
[in] VARIANT Contrast, [in] VARIANT MinContrast, [out] VARIANT ModelID )

Prepare a shape model for scale invariant matching.


The operator CreateScaledShapeModel prepares a template, which is passed in the image Template, as
a shape model used for scale invariant matching. The ROI of the model is passed as the domain of Template.
The model is generated using multiple image pyramid levels and is stored in memory. If a complete pre-
generation of the model is selected (see below), the model is generated at multiple rotations and scales on
each level. The output parameter ModelID is a handle for this model, which is used in subsequent calls to
FindScaledShapeModel.

HALCON 8.0.2
610 CHAPTER 7. MATCHING

The number of pyramid levels is determined with the parameter NumLevels. It should be chosen as large as pos-
sible because by this the time necessary to find the object is significantly reduced. On the other hand, NumLevels
must be chosen such that the model is still recognizable and contains a sufficient number of points (at least four) on
the highest pyramid level. This can be checked using the output of InspectShapeModel. If not enough model
points are generated, the number of pyramid levels is reduced internally until enough model points are found on the
highest pyramid level. If this procedure would lead to a model with no pyramid levels, i.e., if the number of model
points is already too small on the lowest pyramid level, CreateScaledShapeModel returns with an error mes-
sage. If NumLevels is set to ’auto’ (or 0 for backwards compatibility), CreateScaledShapeModel deter-
mines the number of pyramid levels automatically. The automatically computed number of pyramid levels can be
queried using GetShapeModelParams. In rare cases, it might happen that CreateScaledShapeModel
determines a value for the number of pyramid levels that is too large or too small. If the number of pyramid levels is
chosen too large, the model may not be recognized in the image or it may be necessary to select very low parameters
for MinScore or Greediness in FindScaledShapeModel in order to find the model. If the number of pyramid
levels is chosen too small, the time required to find the model in FindScaledShapeModel may increase. In
these cases, the number of pyramid levels should be selected using the output of InspectShapeModel.
The parameters AngleStart and AngleExtent determine the range of possible rotations, in which
the model can occur in the image. Note that the model can only be found in this range of angles by
FindScaledShapeModel. The parameter AngleStep determines the step length within the selected range
of angles. Hence, if subpixel accuracy is not specified in FindScaledShapeModel, this parameter specifies
the accuracy that is achievable for the angles in FindScaledShapeModel. AngleStep should be chosen
based on the size of the object. Smaller models do not have many different discrete rotations in the image, and
hence AngleStep should be chosen larger for smaller models. If AngleExtent is not an integer multiple of
AngleStep, AngleStep is modified accordingly.
The parameters ScaleMin and ScaleMax determine the range of possible scales (sizes) of the model. A scale of
1 corresponds to the original size of the model. The parameter ScaleStep determines the step length within the
selected range of scales. Hence, if subpixel accuracy is not specified in FindScaledShapeModel, this param-
eter specifies the accuracy that is achievable for the scales in FindScaledShapeModel. Like AngleStep,
ScaleStep should be chosen based on the size of the object. If the range of scales is not an integer multiple of
ScaleStep, ScaleStep is modified accordingly.
If a complete pregeneration of the model is selected (see below), the model is pre-generated for the selected angle
and scale range and stored in memory. The memory required to store the model is proportional to the number
of angle steps, the number of scale steps, and the number of points in the model. Hence, if AngleStep or
ScaleStep are too small or AngleExtent or the range of scales are too big, it may happen that the model
no longer fits into the (virtual) memory. In this case, either AngleStep or ScaleStep must be enlarged or
AngleExtent or the range of scales must be reduced. In any case, it is desirable that the model completely fits
into the main memory, because this avoids paging by the operating system, and hence the time to find the object
will be much smaller. Since angles can be determined with subpixel resolution by FindScaledShapeModel,
AngleStep ≥ 1◦ and ScaleStep ≥ 0.02 can be selected for models of a diameter smaller than about 200
pixels. If AngleStep = 0 auto 0 or ScaleStep = 0 auto 0 (or 0 for backwards compatibility in both cases) is
selected, CreateScaledShapeModel automatically determines a suitable angle or scale step length, respec-
tively, based on the size of the model. The automatically computed angle and scale step lengths can be queried
using GetShapeModelParams.
If a complete pregeneration of the model is not selected, the model is only created in a reference pose on each
pyramid level. In this case, the model must be transformed to the different angles and scales at runtime in
FindScaledShapeModel. Because of this, the recognition of the model might require slightly more time.
For particularly large models, it may be useful to reduce the number of model points by setting Optimization
to a value different from ’none’. If Optimization = ’none’, all model points are stored. In all other cases,
the number of points is reduced according to the value of Optimization. If the number of points is reduced,
it may be necessary in FindScaledShapeModel to set the parameter Greediness to a smaller value, e.g.,
0.7 or 0.8. For small models, the reduction of the number of model points does not result in a speed-up of the
search because in this case usually significantly more potential instances of the model must be examined. If
Optimization is set to ’auto’, CreateScaledShapeModel automatically determines the reduction of the
number of model points.
Optionally, a second value can be passed in Optimization. This value determines whether the model is pre-
generated completely or not. To do so, the second value of Optimization must be set to either ’pregenera-
tion’ or ’no_pregeneration’. If the second value is not used (i.e., if only one value is passed), the mode that is
set with SetSystem(’pregenerateShapeModels’,...) is used. With the default value (’pregener-

HALCON/COM Reference Manual, 2008-5-13


7.4. SHAPE-BASED 611

ate_shape_models’ = ’false’), the model is not pregenerated completely. The complete pregeneration of the model
normally leads to slightly lower runtimes because the model does not need to be transformed at runtime. However,
in this case, the memory requirements and the time required to create the model are significantly higher. It should
also be noted that it cannot be expected that the two modes return exactly identical results because transforming
the model at runtime necessarily leads to different internal data for the transformed models than pregenerating the
transformed models. For example, if the model is not pregenerated completely, FindScaledShapeModel
typically returns slightly lower scores, which may require setting a slightly lower value for MinScore than for a
completely pregenerated model. Furthermore, the poses obtained by interpolation may differ slightly in the two
modes. If maximum accuracy is desired, the pose of the model should be determined by least-squares adjustment.
The parameter Contrast determines the contrast the model points must have. The contrast is a measure for
local gray value differences between the object and the background and between different parts of the object.
Contrast should be chosen such that only the significant features of the template are used for the model.
Contrast can also contain a tuple with two values. In this case, the model is segmented using a method sim-
ilar to the hysteresis threshold method used in EdgesImage. Here, the first element of the tuple determines
the lower threshold, while the second element determines the upper threshold. For more information about the
hysteresis threshold method, see HysteresisThreshold. Optionally, Contrast can contain a third value
as the last element of the tuple. This value determines a threshold for the selection of significant model compo-
nents based on the size of the components, i.e., components that have fewer points than the minimum size thus
specified are suppressed. This threshold for the minimum size is divided by two for each successive pyramid
level. If small model components should be suppressed, but hysteresis thresholding should not be performed,
nevertheless three values must be specified in Contrast. In this case, the first two values can simply be set
to identical values. The effect of this parameter can be checked in advance with InspectShapeModel. If
Contrast is set to ’auto’, CreateScaledShapeModel determines the three above described values auto-
matically. Alternatively, only the contrast (’auto_contrast’), the hysteresis thresholds (’auto_contrast_hyst’), or
the minimum size (’auto_min_size’) can be determined automatically. The remaining values that are not deter-
mined automatically can additionally be passed in the form of a tuple. Also various combinations are allowed:
If, for example, [’auto_contrast’,’auto_min_size’] is passed, both the contrast and the minimum size are deter-
mined automatically. If [’auto_min_size’,20,30] is passed, the minimum size is determined automatically while
the hysteresis thresholds are set to 20 and 30, etc. In certain cases, it might happen that the automatic determi-
nation of the contrast thresholds is not satisfying. For example, a manual setting of these parameters should be
preferred if certain model components should be included or suppressed because of application-specific reasons
or if the object contains several different contrasts. Therefore, the contrast thresholds should be automatically
determined with DetermineShapeModelParams and subsequently verified using InspectShapeModel
before calling CreateScaledShapeModel.
With MinContrast, it can be determined which contrast the model must at least have in the recognition per-
formed by FindScaledShapeModel. In other words, this parameter separates the model from the noise in
the image. Therefore, a good choice is the range of gray value changes caused by the noise in the image. If,
for example, the gray values fluctuate within a range of 10 gray levels, MinContrast should be set to 10. If
multichannel images are used for the model and the search images, and if the parameter Metric is set to ’ig-
nore_color_polarity’ (see below) the noise in one channel must be multiplied by the square root of the number
of channels to determine MinContrast. If, for example, the gray values fluctuate within a range of 10 gray
levels in a single channel and the image is a three-channel image MinContrast should be set to 17. Obviously,
MinContrast must be smaller than Contrast. If the model should be recognized in very low contrast im-
ages, MinContrast must be set to a correspondingly small value. If the model should be recognized even if it
is severely occluded, MinContrast should be slightly larger than the range of gray value fluctuations created
by noise in order to ensure that the position and rotation of the model are extracted robustly and accurately by
FindScaledShapeModel. If MinContrast is set to ’auto’, the minimum contrast is determined automat-
ically based on the noise in the model image. Consequently, an automatic determination only makes sense if the
image noise during the recognition is similar to the noise in the model image. Furthermore, in some cases it is
advisable to increase the automatically determined value in order to increase the robustness against occlusions (see
above). The automatically computed minimum contrast can be queried using GetShapeModelParams.
The parameter Metric determines the conditions under which the model is recognized in the image. If Metric
= ’use_polarity’, the object in the image and the model must have the same contrast. If, for example, the
model is a bright object on a dark background, the object is found only if it is also brighter than the back-
ground. If Metric = ’ignore_global_polarity’, the object is found in the image also if the contrast reverses
globally. In the above example, the object hence is also found if it is darker than the background. The runtime
of FindScaledShapeModel will increase slightly in this case. If Metric = ’ignore_local_polarity’, the
model is found even if the contrast changes locally. This mode can, for example, be useful if the object consists

HALCON 8.0.2
612 CHAPTER 7. MATCHING

of a part with medium gray value, within which either darker or brighter sub-objects lie. Since in this case the
runtime of FindScaledShapeModel increases significantly, it is usually better to create several models that
reflect the possible contrast variations of the object with CreateScaledShapeModel, and to match them si-
multaneously with FindScaledShapeModels. The above three metrics can only be applied to single-channel
images. If a multichannel image is used as the model image or as the search image only the first channel will
be used (and no error message will be returned). If Metric = ’ignore_color_polarity’, the model is found even
if the color contrast changes locally. This is, for example, the case if parts of the object can change their color,
e.g., from red to green. In particular, this mode is useful if it is not known in advance in which channels the
object is visible. In this mode, the runtime of FindScaledShapeModel can also increase significantly. The
metric ’ignore_color_polarity’ can be used for images with an arbitrary number of channels. If it is used for
single-channel images it has the same effect as ’ignore_local_polarity’. It should be noted that for Metric =
’ignore_color_polarity’ the number of channels in the model creation with CreateScaledShapeModel and
in the search with FindScaledShapeModel can be different. This can, for example, be used to create a model
from a synthetically generated single-channel image. Furthermore, it should be noted that the channels do not need
to contain a spectral subdivision of the light (like in an RGB image). The channels can, for example, also contain
images of the same object that were obtained by illuminating the object from different directions.
The center of gravity of the domain (region) of the model image Template is used as the origin (reference point)
of the model. A different origin can be set with SetShapeModelOrigin.
Parameter

. Template (input iconic) . . . . . . . . . . . . . . . . . . (multichannel-)image ; HImageX / IHObjectX ( byte, uint2 )


Input image whose domain will be used to create the model.
. NumLevels (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer, string )
Maximum number of pyramid levels.
Default Value : ’auto’
List of values : NumLevels ∈ {’auto’, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
. AngleStart (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; double / VARIANT
Smallest rotation of the pattern.
Default Value : -0.39
Suggested values : AngleStart ∈ {-3.14, -1.57, -0.79, -0.39, -0.20, 0.0}
. AngleExtent (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; double / VARIANT
Extent of the rotation angles.
Default Value : 0.79
Suggested values : AngleExtent ∈ {6.29, 3.14, 1.57, 0.79, 0.39}
Restriction : (AngleExtent ≥ 0)
. AngleStep (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; VARIANT ( real, string )
Step length of the angles (resolution).
Default Value : ’auto’
Suggested values : AngleStep ∈ {’auto’, 0.0175, 0.0349, 0.0524, 0.0698, 0.0873}
Restriction : ((AngleStep ≥ 0) ∧ (AngleStep ≤ (pi/16)))
. ScaleMin (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Minimum scale of the pattern.
Default Value : 0.9
Suggested values : ScaleMin ∈ {0.5, 0.6, 0.7, 0.8, 0.9, 1.0}
Restriction : (ScaleM in > 0)
. ScaleMax (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Maximum scale of the pattern.
Default Value : 1.1
Suggested values : ScaleMax ∈ {1.0, 1.1, 1.2, 1.3, 1.4, 1.5}
Restriction : (ScaleM ax ≥ ScaleM in)
. ScaleStep (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .number ; VARIANT ( real, string )
Scale step length (resolution).
Default Value : ’auto’
Suggested values : ScaleStep ∈ {’auto’, 0.01, 0.02, 0.05, 0.1, 0.15, 0.2}
Restriction : (ScaleStep ≥ 0)

HALCON/COM Reference Manual, 2008-5-13


7.4. SHAPE-BASED 613

. Optimization (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )


Kind of optimization and optionally method used for generating the model.
Default Value : ’auto’
List of values : Optimization ∈ {’auto’, ’none’, ’point_reduction_low’, ’point_reduction_medium’,
’point_reduction_high’, ’pregeneration’, ’no_pregeneration’}
. Metric (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Match metric.
Default Value : ’use_polarity’
List of values : Metric ∈ {’use_polarity’, ’ignore_global_polarity’, ’ignore_local_polarity’,
’ignore_color_polarity’}
. Contrast (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( integer, string )
Threshold or hysteresis thresholds for the contrast of the object in the template image and optionally minimum
size of the object parts.
Default Value : ’auto’
Suggested values : Contrast ∈ {’auto’, ’auto_contrast’, ’auto_contrast_hyst’, ’auto_min_size’, 10, 20, 30,
40, 60, 80, 100, 120, 140, 160}
. MinContrast (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, string )
Minimum contrast of the objects in the search images.
Default Value : ’auto’
Suggested values : MinContrast ∈ {’auto’, 1, 2, 3, 5, 7, 10, 20, 30, 40}
Restriction : (M inContrast < Contrast)
. ModelID (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . shape_model ; HShapeModelX / VARIANT
Handle of the model.
Result
If the parameters are valid, the operator CreateScaledShapeModel returns the value TRUE. If necessary an
exception is raised. If the parameters NumLevels and Contrast are chosen such that the model contains too
few points, the error 8510 is raised.
Parallelization Information
CreateScaledShapeModel is processed completely exclusively without parallelization.
Possible Predecessors
DrawRegion, ReduceDomain, Threshold
Possible Successors
FindScaledShapeModel, FindScaledShapeModels, GetShapeModelParams,
ClearShapeModel, WriteShapeModel, SetShapeModelOrigin
See also
SetSystem, GetSystem
Alternatives
CreateShapeModel, CreateAnisoShapeModel, CreateTemplateRot
Module
Matching

HALCON 8.0.2
614 CHAPTER 7. MATCHING

[out] HShapeModelX ModelID HImageX.CreateShapeModel


([in] VARIANT NumLevels, [in] double AngleStart, [in] double AngleExtent,
[in] VARIANT AngleStep, [in] VARIANT Optimization, [in] String Metric,
[in] VARIANT Contrast, [in] VARIANT MinContrast )
void HShapeModelX.CreateShapeModel ([in] HImageX Template,
[in] VARIANT NumLevels, [in] double AngleStart, [in] double AngleExtent,
[in] VARIANT AngleStep, [in] VARIANT Optimization, [in] String Metric,
[in] VARIANT Contrast, [in] VARIANT MinContrast )
void HOperatorSetX.CreateShapeModel ([in] IHObjectX Template,
[in] VARIANT NumLevels, [in] VARIANT AngleStart, [in] VARIANT AngleExtent,
[in] VARIANT AngleStep, [in] VARIANT Optimization, [in] VARIANT Metric,
[in] VARIANT Contrast, [in] VARIANT MinContrast, [out] VARIANT ModelID )

Prepare a shape model for matching.


The operator CreateShapeModel prepares a template, which is passed in the image Template, as a shape
model used for matching. The ROI of the model is passed as the domain of Template.
The model is generated using multiple image pyramid levels and is stored in memory. If a complete pregeneration
of the model is selected (see below), the model is generated at multiple rotations on each level. The output
parameter ModelID is a handle for this model, which is used in subsequent calls to FindShapeModel.
The number of pyramid levels is determined with the parameter NumLevels. It should be chosen as large as pos-
sible because by this the time necessary to find the object is significantly reduced. On the other hand, NumLevels
must be chosen such that the model is still recognizable and contains a sufficient number of points (at least four)
on the highest pyramid level. This can be checked using the output of InspectShapeModel. If not enough
model points are generated, the number of pyramid levels is reduced internally until enough model points are found
on the highest pyramid level. If this procedure would lead to a model with no pyramid levels, i.e., if the number
of model points is already too small on the lowest pyramid level, CreateShapeModel returns with an error
message. If NumLevels is set to ’auto’ (or 0 for backwards compatibility), CreateShapeModel determines
the number of pyramid levels automatically. The automatically computed number of pyramid levels can be queried
using GetShapeModelParams. In rare cases, it might happen that CreateShapeModel determines a value
for the number of pyramid levels that is too large or too small. If the number of pyramid levels is chosen too large,
the model may not be recognized in the image or it may be necessary to select very low parameters for MinScore
or Greediness in FindShapeModel in order to find the model. If the number of pyramid levels is chosen too
small, the time required to find the model in FindShapeModel may increase. In these cases, the number of
pyramid levels should be selected using the output of InspectShapeModel.
The parameters AngleStart and AngleExtent determine the range of possible rotations, in which the model
can occur in the image. Note that the model can only be found in this range of angles by FindShapeModel. The
parameter AngleStep determines the step length within the selected range of angles. Hence, if subpixel accuracy
is not specified in FindShapeModel, this parameter specifies the accuracy that is achievable for the angles in
FindShapeModel. AngleStep should be chosen based on the size of the object. Smaller models do not
possess many different discrete rotations in the image, and hence AngleStep should be chosen larger for smaller
models. If AngleExtent is not an integer multiple of AngleStep, AngleStep is modified accordingly.
If a complete pregeneration of the model is selected (see below), the model is pre-generated for the selected
angle range and stored in memory. The memory required to store the model is proportional to the number of
angle steps and the number of points in the model. Hence, if AngleStep is too small or AngleExtent too
big, it may happen that the model no longer fits into the (virtual) memory. In this case, either AngleStep
must be enlarged or AngleExtent must be reduced. In any case, it is desirable that the model completely
fits into the main memory, because this avoids paging by the operating system, and hence the time to find the
object will be much smaller. Since angles can be determined with subpixel resolution by FindShapeModel,
AngleStep ≥ 1 can be selected for models of a diameter smaller than about 200 pixels. If AngleStep = 0 auto 0
(or 0 for backwards compatibility) is selected, CreateShapeModel automatically determines a suitable angle
step length based on the size of the model. The automatically computed angle step length can be queried using
GetShapeModelParams.
If a complete pregeneration of the model is not selected, the model is only created in a reference pose on each
pyramid level. In this case, the model must be transformed to the different angles and scales at runtime in
FindShapeModel. Because of this, the recognition of the model might require slightly more time.

HALCON/COM Reference Manual, 2008-5-13


7.4. SHAPE-BASED 615

For particularly large models, it may be useful to reduce the number of model points by setting Optimization
to a value different from ’none’. If Optimization = ’none’, all model points are stored. In all other cases, the
number of points is reduced according to the value of Optimization. If the number of points is reduced, it may
be necessary in FindShapeModel to set the parameter Greediness to a smaller value, e.g., 0.7 or 0.8. For
small models, the reduction of the number of model points does not result in a speed-up of the search because in
this case usually significantly more potential instances of the model must be examined. If Optimization is set
to ’auto’, CreateShapeModel automatically determines the reduction of the number of model points.
Optionally, a second value can be passed in Optimization. This value determines whether the model is pre-
generated completely or not. To do so, the second value of Optimization must be set to either ’pregenera-
tion’ or ’no_pregeneration’. If the second value is not used (i.e., if only one value is passed), the mode that is
set with SetSystem(’pregenerateShapeModels’,...) is used. With the default value (’pregener-
ate_shape_models’ = ’false’), the model is not pregenerated completely. The complete pregeneration of the model
normally leads to slightly lower runtimes because the model does not need to be transformed at runtime. However,
in this case, the memory requirements and the time required to create the model are significantly higher. It should
also be noted that it cannot be expected that the two modes return exactly identical results because transforming
the model at runtime necessarily leads to different internal data for the transformed models than pregenerating the
transformed models. For example, if the model is not pregenerated completely, FindShapeModel typically
returns slightly lower scores, which may require setting a slightly lower value for MinScore than for a completely
pregenerated model. Furthermore, the poses obtained by interpolation may differ slightly in the two modes. If
maximum accuracy is desired, the pose of the model should be determined by least-squares adjustment.
The parameter Contrast determines the contrast the model points must have. The contrast is a measure for
local gray value differences between the object and the background and between different parts of the object.
Contrast should be chosen such that only the significant features of the template are used for the model.
Contrast can also contain a tuple with two values. In this case, the model is segmented using a method similar
to the hysteresis threshold method used in EdgesImage. Here, the first element of the tuple determines the lower
threshold, while the second element determines the upper threshold. For more information about the hysteresis
threshold method, see HysteresisThreshold. Optionally, Contrast can contain a third value as the last
element of the tuple. This value determines a threshold for the selection of significant model components based
on the size of the components, i.e., components that have fewer points than the minimum size thus specified are
suppressed. This threshold for the minimum size is divided by two for each successive pyramid level. If small
model components should be suppressed, but hysteresis thresholding should not be performed, nevertheless three
values must be specified in Contrast. In this case, the first two values can simply be set to identical values. The
effect of this parameter can be checked in advance with InspectShapeModel. If Contrast is set to ’auto’,
CreateShapeModel determines the three above described values automatically. Alternatively, only the contrast
(’auto_contrast’), the hysteresis thresholds (’auto_contrast_hyst’), or the minimum size (’auto_min_size’) can be
determined automatically. The remaining values that are not determined automatically can additionally be passed
in the form of a tuple. Also various combinations are allowed: If, for example, [’auto_contrast’,’auto_min_size’]
is passed, both the contrast and the minimum size are determined automatically. If [’auto_min_size’,20,30] is
passed, the minimum size is determined automatically while the hysteresis thresholds are set to 20 and 30, etc.
In certain cases, it might happen that the automatic determination of the contrast thresholds is not satisfying. For
example, a manual setting of these parameters should be preferred if certain model components should be included
or suppressed because of application-specific reasons or if the object contains several different contrasts. There-
fore, the contrast thresholds should be automatically determined with DetermineShapeModelParams and
subsequently verified using InspectShapeModel before calling CreateShapeModel.
With MinContrast, it can be determined which contrast the model must at least have in the recognition per-
formed by FindShapeModel. In other words, this parameter separates the model from the noise in the image.
Therefore, a good choice is the range of gray value changes caused by the noise in the image. If, for example, the
gray values fluctuate within a range of 10 gray levels, MinContrast should be set to 10. If multichannel images
are used for the model and the search images, and if the parameter Metric is set to ’ignore_color_polarity’ (see
below) the noise in one channel must be multiplied by the square root of the number of channels to determine
MinContrast. If, for example, the gray values fluctuate within a range of 10 gray levels in a single channel
and the image is a three-channel image MinContrast should be set to 17. Obviously, MinContrast must
be smaller than Contrast. If the model should be recognized in very low contrast images, MinContrast
must be set to a correspondingly small value. If the model should be recognized even if it is severely occluded,
MinContrast should be slightly larger than the range of gray value fluctuations created by noise in order to
ensure that the position and rotation of the model are extracted robustly and accurately by FindShapeModel. If
MinContrast is set to ’auto’, the minimum contrast is determined automatically based on the noise in the model
image. Consequently, an automatic determination only makes sense if the image noise during the recognition is

HALCON 8.0.2
616 CHAPTER 7. MATCHING

similar to the noise in the model image. Furthermore, in some cases it is advisable to increase the automatically
determined value in order to increase the robustness against occlusions (see above). The automatically computed
minimum contrast can be queried using GetShapeModelParams.
The parameter Metric determines the conditions under which the model is recognized in the image. If Metric
= ’use_polarity’, the object in the image and the model must have the same contrast. If, for example, the model is
a bright object on a dark background, the object is found only if it is also brighter than the background. If Metric
= ’ignore_global_polarity’, the object is found in the image also if the contrast reverses globally. In the above
example, the object hence is also found if it is darker than the background. The runtime of FindShapeModel
will increase slightly in this case. If Metric = ’ignore_local_polarity’, the model is found even if the contrast
changes locally. This mode can, for example, be useful if the object consists of a part with medium gray value,
within which either darker or brighter sub-objects lie. Since in this case the runtime of FindShapeModel in-
creases significantly, it is usually better to create several models that reflect the possible contrast variations of the
object with CreateShapeModel, and to match them simultaneously with FindShapeModels. The above
three metrics can only be applied to single-channel images. If a multichannel image is used as the model image or
as the search image only the first channel will be used (and no error message will be returned). If Metric = ’ig-
nore_color_polarity’, the model is found even if the color contrast changes locally. This is, for example, the case if
parts of the object can change their color, e.g., from red to green. In particular, this mode is useful if it is not known
in advance in which channels the object is visible. In this mode, the runtime of FindShapeModel can also in-
crease significantly. The metric ’ignore_color_polarity’ can be used for images with an arbitrary number of chan-
nels. If it is used for single-channel images it has the same effect as ’ignore_local_polarity’. It should be noted that
for Metric = ’ignore_color_polarity’ the number of channels in the model creation with CreateShapeModel
and in the search with FindShapeModel can be different. This can, for example, be used to create a model
from a synthetically generated single-channel image. Furthermore, it should be noted that the channels do not need
to contain a spectral subdivision of the light (like in an RGB image). The channels can, for example, also contain
images of the same object that were obtained by illuminating the object from different directions.
The center of gravity of the domain (region) of the model image Template is used as the origin (reference point)
of the model. A different origin can be set with SetShapeModelOrigin.
Parameter
. Template (input iconic) . . . . . . . . . . . . . . . . . . (multichannel-)image ; HImageX / IHObjectX ( byte, uint2 )
Input image whose domain will be used to create the model.
. NumLevels (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer, string )
Maximum number of pyramid levels.
Default Value : ’auto’
List of values : NumLevels ∈ {’auto’, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
. AngleStart (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; double / VARIANT
Smallest rotation of the pattern.
Default Value : -0.39
Suggested values : AngleStart ∈ {-3.14, -1.57, -0.79, -0.39, -0.20, 0.0}
. AngleExtent (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; double / VARIANT
Extent of the rotation angles.
Default Value : 0.79
Suggested values : AngleExtent ∈ {6.29, 3.14, 1.57, 0.79, 0.39}
Restriction : (AngleExtent ≥ 0)
. AngleStep (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; VARIANT ( real, string )
Step length of the angles (resolution).
Default Value : ’auto’
Suggested values : AngleStep ∈ {’auto’, 0.0175, 0.0349, 0.0524, 0.0698, 0.0873}
Restriction : ((AngleStep ≥ 0) ∧ (AngleStep ≤ (pi/16)))
. Optimization (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Kind of optimization and optionally method used for generating the model.
Default Value : ’auto’
List of values : Optimization ∈ {’auto’, ’none’, ’point_reduction_low’, ’point_reduction_medium’,
’point_reduction_high’, ’pregeneration’, ’no_pregeneration’}
. Metric (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Match metric.
Default Value : ’use_polarity’
List of values : Metric ∈ {’use_polarity’, ’ignore_global_polarity’, ’ignore_local_polarity’,

HALCON/COM Reference Manual, 2008-5-13


7.4. SHAPE-BASED 617

’ignore_color_polarity’}
. Contrast (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( integer, string )
Threshold or hysteresis thresholds for the contrast of the object in the template image and optionally minimum
size of the object parts.
Default Value : ’auto’
Suggested values : Contrast ∈ {’auto’, ’auto_contrast’, ’auto_contrast_hyst’, ’auto_min_size’, 10, 20, 30,
40, 60, 80, 100, 120, 140, 160}
. MinContrast (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, string )
Minimum contrast of the objects in the search images.
Default Value : ’auto’
Suggested values : MinContrast ∈ {’auto’, 1, 2, 3, 5, 7, 10, 20, 30, 40}
Restriction : (M inContrast < Contrast)
. ModelID (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . shape_model ; HShapeModelX / VARIANT
Handle of the model.
Result
If the parameters are valid, the operator CreateShapeModel returns the value TRUE. If necessary an exception
is raised. If the parameters NumLevels and Contrast are chosen such that the model contains too few points,
the error 8510 is raised.
Parallelization Information
CreateShapeModel is processed completely exclusively without parallelization.
Possible Predecessors
DrawRegion, ReduceDomain, Threshold
Possible Successors
FindShapeModel, FindShapeModels, GetShapeModelParams, ClearShapeModel,
WriteShapeModel, SetShapeModelOrigin
See also
SetSystem, GetSystem
Alternatives
CreateScaledShapeModel, CreateAnisoShapeModel, CreateTemplateRot
Module
Matching

[out] VARIANT ParameterName HImageX.DetermineShapeModelParams


([in] VARIANT NumLevels, [in] double AngleStart, [in] double AngleExtent,
[in] VARIANT ScaleMin, [in] VARIANT ScaleMax, [in] String Optimization,
[in] String Metric, [in] VARIANT Contrast, [in] long MinContrast,
[in] VARIANT Parameters, [out] VARIANT ParameterValue )
void HOperatorSetX.DetermineShapeModelParams
([in] IHObjectX Template, [in] VARIANT NumLevels, [in] VARIANT AngleStart,
[in] VARIANT AngleExtent, [in] VARIANT ScaleMin, [in] VARIANT ScaleMax,
[in] VARIANT Optimization, [in] VARIANT Metric, [in] VARIANT Contrast,
[in] VARIANT MinContrast, [in] VARIANT Parameters,
[out] VARIANT ParameterName, [out] VARIANT ParameterValue )

Determine the parameters of a shape model.


DetermineShapeModelParams determines certain parameters of a shape model automatically from
the model image Template. The parameters to be determined can be specified with Parameters.
DetermineShapeModelParams can be used to determine the same parameters that are determined au-
tomatically when the respective parameter in CreateShapeModel, CreateScaledShapeModel, or
CreateAnisoShapeModel is set to ’auto’: the number of pyramid levels (Parameters = ’num_levels’),
the angle step length (Parameters = ’angle_step’), the scale step length (Parameters = ’scale_step’
for isotropic scaling and ’scale_r_step’ and/or ’scale_c_step’ for anisotropic scaling), the kind of optimiza-
tion (Parameters = ’optimization’), the threshold (Parameters = ’contrast’) or the hysteresis thresholds
(Parameters = ’contrast_hyst’) for the contrast, the minimum size of the object parts (Parameters =

HALCON 8.0.2
618 CHAPTER 7. MATCHING

’min_size’), and the minimum contrast (Parameters = ’min_contrast’). By passing a tuple of the above values
in Parameters, an arbitrary combination of these parameters can be determined. If all of the above parameters
should be determined, the value ’all’ can be passed. In this case both hysteresis thresholds are determined, i.e., the
operator behaves like passing ’contrast_hyst’ instead of ’contrast’.
DetermineShapeModelParams is mainly useful to determine the above parameters before creating the
model, e.g., in an interactive system, which makes suggestions for these parameters to the user, but enables the
user to modify the suggested values.
The automatically determined parameters are returned as a name-value pair in ParameterName and
ParameterValue. The parameter names in ParameterName are identical to the names in Parameters,
where, of course, the value ’all’ is replaced by the actual parameter names. An exception is the parameter ’con-
trast_hyst’, for which the two values ’contrast_low’ and ’contrast_high’ are returned.
The remaining parameters (NumLevels, AngleStart, AngleExtent, ScaleMin, ScaleMax,
Optimization, Metric, Contrast, and MinContrast) have the same meaning as in
CreateShapeModel, CreateScaledShapeModel, and CreateAnisoShapeModel. The de-
scription of these parameters can be looked up with these operators. These parameters are used by
DetermineShapeModelParams to calculate the parameters to be determined in the same manner as
in CreateShapeModel, CreateScaledShapeModel, and CreateAnisoShapeModel. It should be
noted that if the parameters of a shape model with isotropic scaling should be determined, i.e., if Parameters
contains ’scale_step’ either explicitly or implicitly via ’all’, the parameters ScaleMin and ScaleMax must
contain one value each. If the parameters of a shape model with anisotropic scaling should be determined, i.e., if
Parameters contains ’scale_r_step’ or ’scale_c_step’ either explicitly or implicitly, the parameters ScaleMin
and ScaleMax must contain two values each. In this case, the first value of the respective parameter refers to the
scaling in the row direction, while the second value refers to the scaling in the column direction.
Note that in DetermineShapeModelParams some parameters appear that can also be determined automat-
ically (NumLevels, Optimization, Contrast, MinContrast). If these parameters should not be deter-
mined automatically, i.e., their name is not passed in ParameterName, the corresponding parameters must con-
tain valid values and must not be set to ’auto’. In contrast, if these parameters are to be determined automatically,
their values are treated in the following way: If the optimization or the (hysteresis) contrast is to be determined
automatically, i.e., ParameterName contains the value ’optimization’ or ’contrast’ (’contrast_hyst’), the values
passed in Optimization and Contrast are ignored. In contrast, if the maximum number of pyramid levels or
the minimum contrast is to be determined automatically, i.e., ParameterName contains the value ’num_levels’
or ’min_contrast’, you can let HALCON determine suitable values and at the same time specify an upper or lower
boundary, respectively:
If the maximum number of pyramid levels should be specified in advance, NumLevels can be set to the particular
value. If in this case Parameters contains the value ’num_levels’, the computed number of pyramid levels is
at most NumLevels. If NumLevels is set to ’auto’ (or 0 for backwards compatibility), the number of pyramid
levels is determined without restrictions as large as possible.
If the minimum contrast should be specified in advance, MinContrast can be set to the particular value. If in this
case Parameters contains the value ’min_contrast’, the computed minimum contrast is at least MinContrast.
If MinContrast is set to ’auto’, the minimum contrast is determined without restrictions.
Parameter
. Template (input iconic) . . . . . . . . . . . . . . . . . . (multichannel-)image ; HImageX / IHObjectX ( byte, uint2 )
Input image whose domain will be used to create the model.
. NumLevels (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer, string )
Maximum number of pyramid levels.
Default Value : ’auto’
List of values : NumLevels ∈ {’auto’, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
. AngleStart (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; double / VARIANT
Smallest rotation of the model.
Default Value : -0.39
Suggested values : AngleStart ∈ {-3.14, -1.57, -0.79, -0.39, -0.20, 0.0}
. AngleExtent (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; double / VARIANT
Extent of the rotation angles.
Default Value : 0.79
Suggested values : AngleExtent ∈ {6.29, 3.14, 1.57, 0.79, 0.39}
Restriction : (AngleExtent ≥ 0)

HALCON/COM Reference Manual, 2008-5-13


7.4. SHAPE-BASED 619

. ScaleMin (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( real )


Minimum scale of the model.
Default Value : 0.9
Suggested values : ScaleMin ∈ {0.5, 0.6, 0.7, 0.8, 0.9, 1.0}
Restriction : (ScaleM in > 0)
. ScaleMax (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( real )
Maximum scale of the model.
Default Value : 1.1
Suggested values : ScaleMax ∈ {1.0, 1.1, 1.2, 1.3, 1.4, 1.5}
Restriction : (ScaleM ax ≥ ScaleM in)
. Optimization (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Kind of optimization.
Default Value : ’auto’
List of values : Optimization ∈ {’auto’, ’none’, ’point_reduction_low’, ’point_reduction_medium’,
’point_reduction_high’}
. Metric (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Match metric.
Default Value : ’use_polarity’
List of values : Metric ∈ {’use_polarity’, ’ignore_global_polarity’, ’ignore_local_polarity’,
’ignore_color_polarity’}
. Contrast (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( integer, string )
Threshold or hysteresis thresholds for the contrast of the object in the template image and optionally minimum
size of the object parts.
Default Value : ’auto’
Suggested values : Contrast ∈ {’auto’, ’auto_contrast’, ’auto_contrast_hyst’, ’auto_min_size’, 10, 20, 30,
40, 60, 80, 100, 120, 140, 160}
. MinContrast (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; long / VARIANT
Minimum contrast of the objects in the search images.
Default Value : ’auto’
Suggested values : MinContrast ∈ {’auto’, 1, 2, 3, 5, 7, 10, 20, 30, 40}
Restriction : (M inContrast < Contrast)
. Parameters (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .string(-array) ; VARIANT ( string )
Parameters to be determined automatically.
Default Value : ’all’
List of values : Parameters ∈ {’all’, ’num_levels’, ’angle_step’, ’scale_step’, ’scale_r_step’,
’scale_c_step’, ’optimization’, ’contrast’, ’contrast_hyst’, ’min_size’, ’min_contrast’}
. ParameterName (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( string )
Name of the automatically determined parameter.
. ParameterValue (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Value of the automatically determined parameter.
Result
If the parameters are valid, the operator DetermineShapeModelParams returns the value TRUE. If necessary
an exception is raised. If the parameters NumLevels and Contrast are chosen such that the model contains too
few points, or the input image does not contain a sufficient number of significant features, the error 8510 is raised.
Parallelization Information
DetermineShapeModelParams is reentrant and processed without parallelization.
Possible Predecessors
DrawRegion, ReduceDomain, Threshold
Possible Successors
CreateShapeModel, CreateScaledShapeModel, CreateAnisoShapeModel
See also
FindShapeModel, FindScaledShapeModel, FindAnisoShapeModel, FindShapeModels,
FindScaledShapeModels, FindAnisoShapeModels
Module
Matching

HALCON 8.0.2
620 CHAPTER 7. MATCHING

[out] VARIANT Row HImageX.FindAnisoShapeModel


([in] HShapeModelX ModelID, [in] double AngleStart, [in] double AngleExtent,
[in] double ScaleRMin, [in] double ScaleRMax, [in] double ScaleCMin,
[in] double ScaleCMax, [in] double MinScore, [in] long NumMatches,
[in] double MaxOverlap, [in] String SubPixel, [in] VARIANT NumLevels,
[in] double Greediness, [out] VARIANT Column, [out] VARIANT Angle,
[out] VARIANT ScaleR, [out] VARIANT ScaleC, [out] VARIANT Score )
[out] VARIANT Row HShapeModelX.FindAnisoShapeModel
([in] HImageX Image, [in] double AngleStart, [in] double AngleExtent,
[in] double ScaleRMin, [in] double ScaleRMax, [in] double ScaleCMin,
[in] double ScaleCMax, [in] double MinScore, [in] long NumMatches,
[in] double MaxOverlap, [in] String SubPixel, [in] VARIANT NumLevels,
[in] double Greediness, [out] VARIANT Column, [out] VARIANT Angle,
[out] VARIANT ScaleR, [out] VARIANT ScaleC, [out] VARIANT Score )
void HOperatorSetX.FindAnisoShapeModel ([in] IHObjectX Image,
[in] VARIANT ModelID, [in] VARIANT AngleStart, [in] VARIANT AngleExtent,
[in] VARIANT ScaleRMin, [in] VARIANT ScaleRMax, [in] VARIANT ScaleCMin,
[in] VARIANT ScaleCMax, [in] VARIANT MinScore, [in] VARIANT NumMatches,
[in] VARIANT MaxOverlap, [in] VARIANT SubPixel, [in] VARIANT NumLevels,
[in] VARIANT Greediness, [out] VARIANT Row, [out] VARIANT Column,
[out] VARIANT Angle, [out] VARIANT ScaleR, [out] VARIANT ScaleC,
[out] VARIANT Score )

Find the best matches of an anisotropic scale invariant shape model in an image.
The operator FindAnisoShapeModel finds the best NumMatches instances of the anisotropic scale invariant
shape model ModelID in the input image Image. The model must have been created previously by calling
CreateAnisoShapeModel or ReadShapeModel.
The position, rotation, and scale in the row and column direction of the found instances of the model are returned
in Row, Column, Angle, ScaleR, and ScaleC. The coordinates Row and Column are the coordinates of the
origin of the shape model in the search image. By default, the origin is the center of gravity of the domain (region)
of the image that was used to create the shape model with CreateAnisoShapeModel. A different origin can
be set with SetShapeModelOrigin.
Note that the coordinates Row and Column do not exactly correspond to the position of the model in the search
image. Thus, you cannot directly use them. Instead, the values are optimized for creating the transformation matrix
with which you can use the results of the matching for various tasks, e.g., to align ROIs for other processing steps.
The example below shows how to create this matrix and use it to display the model at the found position in the
search image and to calculate the exact coordinates.
Additionally, the score of each found instance is returned in Score. The score is a number between 0 and 1, which
is an approximate measure of how much of the model is visible in the image. If, for example, half of the model is
occluded, the score cannot exceed 0.5.
The domain of the image Image determines the search space for the reference point of the model, i.e.,
for the center of gravity of the domain (region) of the image that was used to create the shape model with
CreateAnisoShapeModel. A different origin set with SetShapeModelOrigin is not taken into ac-
count. The model is searched within those points of the domain of the image, in which the model lies completely
within the image. This means that the model will not be found if it extends beyond the borders of the image, even
if it would achieve a score greater than MinScore (see below). This behavior can be changed with SetSystem
(’borderShapeModels’,’true’), which will cause models that extend beyond the image border to be
found if they achieve a score greater than MinScore. Here, points lying outside the image are regarded as being
occluded, i.e., they lower the score. It should be noted that the runtime of the search will increase in this mode.
The parameters AngleStart and AngleExtent determine the range of rotations for which the model is
searched. The parameters ScaleRMin, ScaleRMax, ScaleCMin, and ScaleCMax determine the range of
scales in the row and column directions for which the model is searched. If necessary, both ranges are clipped to the
range given when the model was created with CreateAnisoShapeModel. In particular, this means that the
angle ranges of the model and the search must truly overlap. The angle range in the search is not adapted modulo
2π. To simplify the presentation, all angles in the remainder of the paragraph are given in degrees, whereas they
have to be specified in radians in FindAnisoShapeModel. Hence, if the model, for example, was created with

HALCON/COM Reference Manual, 2008-5-13


7.4. SHAPE-BASED 621

AngleStart = −20◦ and AngleExtent = 40◦ and the angle search space in FindScaledShapeModel
is, for example, set to AngleStart = 350◦ and AngleExtent = 20◦ , the model will not be found, even
though the angle ranges would overlap if they were regarded modulo 360◦ . To find the model, in this example it
would be necessary to select AngleStart = −10◦ .
Furthermore, it should be noted that in some cases instances with a rotation or scale that is slightly outside the
specified range are found. This may happen if the specified range is smaller than the range given when the model
was created.
The parameter MinScore determines what score a potential match must at least have to be regarded as an instance
of the model in the image. The larger MinScore is chosen, the faster the search is. If the model can be expected
never to be occluded in the images, MinScore may be set as high as 0.8 or even 0.9. If the matches are not tracked
to the lowest pyramid level (see below) it might happen that instances with a score slightly below MinScore are
found.
The maximum number of instances to be found can be determined with NumMatches. If more than
NumMatches instances with a score greater than MinScore are found in the image, only the best NumMatches
instances are returned. If fewer than NumMatches are found, only that number is returned, i.e., the parameter
MinScore takes precedence over NumMatches.
If the model exhibits symmetries it may happen that multiple instances with similar positions but different rota-
tions are found in the image. The parameter MaxOverlap determines by what fraction (i.e., a number between
0 and 1) two instances may at most overlap in order to consider them as different instances, and hence to be
returned separately. If two instances overlap each other by more than MaxOverlap only the best instance is
returned. The calculation of the overlap is based on the smallest enclosing rectangle of arbitrary orientation (see
SmallestRectangle2) of the found instances. If MaxOverlap = 0, the found instances may not overlap at
all, while for MaxOverlap = 1 all instances are returned.
The parameter SubPixel determines whether the instances should be extracted with subpixel accuracy. If
SubPixel is set to ’none’ (or ’false’ for backwards compatibility) the model’s pose is only determined with
pixel accuracy and the angle and scale resolution that was specified with CreateAnisoShapeModel. If
SubPixel is set to ’interpolation’ (or ’true’) the position as well as the rotation and scale are determined with
subpixel accuracy. In this mode, the model’s pose is interpolated from the score function. This mode costs almost
no computation time and achieves an accuracy that is high enough for most applications. In some applications,
however, the accuracy requirements are extremely high. In these cases, the model’s pose can be determined
through a least-squares adjustment, i.e., by minimizing the distances of the model points to their corresponding
image points. In contrast to ’interpolation’, this mode requires additional computation time. The different modes
for least-squares adjustment (’least_squares’, ’least_squares_high’, and ’least_squares_very_high’) can be used
to determine the accuracy with which the minimum distance is being searched. The higher the accuracy is cho-
sen, the longer the subpixel extraction will take, however. Usually, SubPixel should be set to ’interpolation’.
If least-squares adjustment is desired, ’least_squares’ should be chosen because this results in the best tradeoff
between runtime and accuracy.
The number of pyramid levels used during the search is determined with NumLevels. If necessary, the number
of levels is clipped to the range given when the shape model was created with CreateAnisoShapeModel.
If NumLevels is set to 0, the number of pyramid levels specified in CreateAnisoShapeModel is used.
Optionally, NumLevels can contain a second value that determines the lowest pyramid level to which the found
matches are tracked. Hence, a value of [4,2] for NumLevels means that the matching starts at the fourth pyramid
level and tracks the matches to the second lowest pyramid level (the lowest pyramid level is denoted by a value
of 1). This mechanism can be used to decrease the runtime of the matching. It should be noted, however, that in
general the accuracy of the extracted pose parameters is lower in this mode than in the normal mode, in which the
matches are tracked to the lowest pyramid level. Hence, if a high accuracy is desired, SubPixel should be set
to at least ’least_squares’. If the lowest pyramid level to use is chosen too large, it may happen that the desired
accuracy cannot be achieved, or that wrong instances of the model are found because the model is not specific
enough on the higher pyramid levels to facilitate a reliable selection of the correct instance of the model. In this
case, the lowest pyramid level to use must be set to a smaller value.
The parameter Greediness determines how “greedily” the search should be carried out. If Greediness = 0,
a safe search heuristic is used, which always finds the model if it is visible in the image. However, the search will
be relatively time consuming in this case. If Greediness = 1, an unsafe search heuristic is used, which may
cause the model not to be found in rare cases, even though it is visible in the image. For Greediness = 1, the
maximum search speed is achieved. In almost all cases, the shape model will always be found for Greediness =
0.9.

HALCON 8.0.2
622 CHAPTER 7. MATCHING

Parameter
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . (multichannel-)image ; HImageX / IHObjectX ( byte, uint2 )
Input image in which the model should be found.
. ModelID (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . shape_model ; HShapeModelX / VARIANT
Handle of the model.
. AngleStart (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; double / VARIANT
Smallest rotation of the model.
Default Value : -0.39
Suggested values : AngleStart ∈ {-3.14, -1.57, -0.78, -0.39, -0.20, 0.0}
. AngleExtent (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; double / VARIANT
Extent of the rotation angles.
Default Value : 0.78
Suggested values : AngleExtent ∈ {6.29, 3.14, 1.57, 0.78, 0.39, 0.0}
Restriction : (AngleExtent ≥ 0)
. ScaleRMin (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Minimum scale of the model in the row direction.
Default Value : 0.9
Suggested values : ScaleRMin ∈ {0.5, 0.6, 0.7, 0.8, 0.9, 1.0}
Restriction : (ScaleRM in > 0)
. ScaleRMax (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Maximum scale of the model in the row direction.
Default Value : 1.1
Suggested values : ScaleRMax ∈ {1.0, 1.1, 1.2, 1.3, 1.4, 1.5}
Restriction : (ScaleRM ax ≥ ScaleRM in)
. ScaleCMin (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Minimum scale of the model in the column direction.
Default Value : 0.9
Suggested values : ScaleCMin ∈ {0.5, 0.6, 0.7, 0.8, 0.9, 1.0}
Restriction : (ScaleCM in > 0)
. ScaleCMax (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Maximum scale of the model in the column direction.
Default Value : 1.1
Suggested values : ScaleCMax ∈ {1.0, 1.1, 1.2, 1.3, 1.4, 1.5}
Restriction : (ScaleCM ax ≥ ScaleCM in)
. MinScore (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Minimum score of the instances of the model to be found.
Default Value : 0.5
Suggested values : MinScore ∈ {0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}
Typical range of values : 0 ≤ MinScore ≤ 0
Minimum Increment : 0.01
Recommended Increment : 0.05
. NumMatches (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of instances of the model to be found.
Default Value : 1
Suggested values : NumMatches ∈ {0, 1, 2, 3, 4, 5, 10, 20}
. MaxOverlap (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Maximum overlap of the instances of the model to be found.
Default Value : 0.5
Suggested values : MaxOverlap ∈ {0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}
Typical range of values : 0 ≤ MaxOverlap ≤ 0
Minimum Increment : 0.01
Recommended Increment : 0.05
. SubPixel (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Subpixel accuracy if not equal to ’none’.
Default Value : ’least_squares’
List of values : SubPixel ∈ {’none’, ’interpolation’, ’least_squares’, ’least_squares_high’,
’least_squares_very_high’}

HALCON/COM Reference Manual, 2008-5-13


7.4. SHAPE-BASED 623

. NumLevels (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )


Number of pyramid levels used in the matching (and lowest pyramid level to use if |NumLevels| = 2).
Default Value : 0
List of values : NumLevels ∈ {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
. Greediness (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
“Greediness” of the search heuristic (0: safe but slow; 1: fast but matches may be missed).
Default Value : 0.9
Suggested values : Greediness ∈ {0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}
Typical range of values : 0 ≤ Greediness ≤ 0
Minimum Increment : 0.01
Recommended Increment : 0.05
. Row (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; VARIANT ( real )
Row coordinate of the found instances of the model.
. Column (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; VARIANT ( real )
Column coordinate of the found instances of the model.
. Angle (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; VARIANT ( real )
Rotation angle of the found instances of the model.
. ScaleR (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real )
Scale of the found instances of the model in the row direction.
. ScaleC (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real )
Scale of the found instances of the model in the column direction.
. Score (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Score of the found instances of the model.
Example

create_aniso_shape_model (ImageReduced, 0, rad(-15), rad(30), 0,


0.9, 1.1, 0, 0.9, 1.1, 0, ’none’,
’use_polarity’, 30, 10, ModelID)
get_shape_model_contours (ModelXLD, ModelID, 1)
find_aniso_shape_model (SearchImage, ModelID, rad(-15), rad(30),
0.9, 1.1, 0.9, 1.1, 0.5, 1, 0.5, ’interpolation’,
0, 0, Row, Column, Angle, ScaleR, ScaleC, Score)
hom_mat2d_identity (HomMat2DIdentity)
hom_mat2d_scale (HomMat2DIdentity, ScaleR, ScaleC, 0, 0, HomMat2DScale)
hom_mat2d_rotate (HomMat2DScale, Angle, 0, 0, HomMat2DRotate)
hom_mat2d_translate (HomMat2DRotate, Row, Column, HomMat2DObject)
affine_trans_contour_xld (ModelXLD, ObjectXLD, HomMat2DObject)
affine_trans_pixel (HomMat2DObject, 0, 0, RowObject, ColObject)

Result
If the parameter values are correct, the operator FindAnisoShapeModel returns the value TRUE.
If the input is empty (no input images are available) the behavior can be set via SetSystem
(’noObjectResult’,<Result>). If necessary, an exception is raised.
Parallelization Information
FindAnisoShapeModel is reentrant and processed without parallelization.
Possible Predecessors
CreateAnisoShapeModel, ReadShapeModel, SetShapeModelOrigin
Possible Successors
ClearShapeModel
See also
SetSystem, GetSystem
Alternatives
FindShapeModel, FindScaledShapeModel, FindShapeModels, FindScaledShapeModels,
FindAnisoShapeModels, BestMatchRotMg
Module
Matching

HALCON 8.0.2
624 CHAPTER 7. MATCHING

[out] VARIANT Row HImageX.FindAnisoShapeModels


([in] HShapeModelX ModelIDs, [in] VARIANT AngleStart,
[in] VARIANT AngleExtent, [in] VARIANT ScaleRMin, [in] VARIANT ScaleRMax,
[in] VARIANT ScaleCMin, [in] VARIANT ScaleCMax, [in] VARIANT MinScore,
[in] VARIANT NumMatches, [in] VARIANT MaxOverlap, [in] VARIANT SubPixel,
[in] VARIANT NumLevels, [in] VARIANT Greediness, [out] VARIANT Column,
[out] VARIANT Angle, [out] VARIANT ScaleR, [out] VARIANT ScaleC,
[out] VARIANT Score, [out] VARIANT Model )
[out] VARIANT Row HShapeModelX.FindAnisoShapeModels
([in] HImageX Image, [in] VARIANT AngleStart, [in] VARIANT AngleExtent,
[in] VARIANT ScaleRMin, [in] VARIANT ScaleRMax, [in] VARIANT ScaleCMin,
[in] VARIANT ScaleCMax, [in] VARIANT MinScore, [in] VARIANT NumMatches,
[in] VARIANT MaxOverlap, [in] VARIANT SubPixel, [in] VARIANT NumLevels,
[in] VARIANT Greediness, [out] VARIANT Column, [out] VARIANT Angle,
[out] VARIANT ScaleR, [out] VARIANT ScaleC, [out] VARIANT Score,
[out] VARIANT Model )
void HOperatorSetX.FindAnisoShapeModels ([in] IHObjectX Image,
[in] VARIANT ModelIDs, [in] VARIANT AngleStart, [in] VARIANT AngleExtent,
[in] VARIANT ScaleRMin, [in] VARIANT ScaleRMax, [in] VARIANT ScaleCMin,
[in] VARIANT ScaleCMax, [in] VARIANT MinScore, [in] VARIANT NumMatches,
[in] VARIANT MaxOverlap, [in] VARIANT SubPixel, [in] VARIANT NumLevels,
[in] VARIANT Greediness, [out] VARIANT Row, [out] VARIANT Column,
[out] VARIANT Angle, [out] VARIANT ScaleR, [out] VARIANT ScaleC,
[out] VARIANT Score, [out] VARIANT Model )

Find the best matches of multiple anisotropic scale invariant shape models.
The operator FindAnisoShapeModels finds the best NumMatches instances of the anisotropic scale invari-
ant shape models that are passed in ModelIDs in the input image Image. The models must have been created
previously by calling CreateAnisoShapeModel or ReadShapeModel.
Hence, in contrast to FindAnisoShapeModel, multiple models can be searched in the same image in one
call. This changes the semantics of all input parameters to some extent. All input parameters must either con-
tain one element, in which case the parameter is used for all models, or must contain the same number of ele-
ments as ModelIDs, in which case each parameter element refers to the corresponding element in ModelIDs.
(NumLevels may also contain either two or twice the number of elements as ModelIDs; see below.) As usual,
the domain of the input image Image is used to restrict the search space for the reference point of the models
ModelIDs. Consistent with the above semantics, the input image Image can therefore contain a single image
object or an image object tuple containing multiple image objects. If Image contains a single image object, its
domain is used as the region of interest for all models in ModelIDs. If Image contains multiple image ob-
jects, each domain is used as the region of interest for the corresponding model in ModelIDs. In this case, the
image matrix of all image objects in the tuple must be identical, i.e., Image cannot be constructed in an arbi-
trary manner using ConcatObj, but must be created from the same image using AddChannels or equivalent
calls. If this is not the case, an error message is returned. The above semantics also hold for the input con-
trol parameters. Hence, for example, MinScore can contain a single value or the same number of values as
ModelIDs. In the first case, the value of MinScore is used for all models in ModelIDs, while in the sec-
ond case the respective value of the elements in MinScore is used for the corresponding model in ModelIDs.
An extension to these semantics holds for NumMatches and MaxOverlap. If NumMatches contains one el-
ement, FindAnisoShapeModels returns the best NumMatches instances of the model irrespective of the
type of the model. If, for example, two models are passed in ModelIDs and NumMatches = 2 is selected, it
can happen that two instances of the first model and no instances of the second model, one instance of the first
model and one instance of the second model, or no instances of the first model and two instances of the second
model are returned. If, on the other hand, NumMatches contains multiple values, the number of instances re-
turned of the different models corresponds to the number specified in the respective entry in NumMatches. If,
for example, NumMatches = [1, 1] is selected, one instance of the first model and one instance of the second
model is returned. For a detailed description of the semantics of NumMatches, see below. A similar extension
of the semantics holds for MaxOverlap. If a single value is passed for MaxOverlap, the overlap is com-
puted for all found instances of the different models, irrespective of the model type, i.e., instances of the same
or of different models that overlap too much are eliminated. If, on the other hand, multiple values are passed in

HALCON/COM Reference Manual, 2008-5-13


7.4. SHAPE-BASED 625

MaxOverlap, the overlap is only computed for found instances of the model that have the same model type,
i.e., only instances of the same model that overlap too much are eliminated. In this mode, models of different
types may overlap completely. For a detailed description of the semantics of MaxOverlap, see below. Hence,
a call to FindAnisoShapeModels with multiple values for ModelIDs, NumMatches and MaxOverlap
has the same effect as multiple independent calls to FindAnisoShapeModel with the respective parameters.
However, a single call to FindAnisoShapeModels is considerably more efficient.
The type of the found instances of the models is returned in Model. The elements of Model are indices into the
tuple ModelIDs, i.e., they can contain values from 0 to |ModelIDs| − 1. Hence, a value of 0 in an element of
Model corresponds to an instance of the first model in ModelIDs.
The position, rotation, and scale in the row and column direction of the found instances of the model are returned
in Row, Column, Angle, ScaleR, and ScaleC. The coordinates Row and Column are the coordinates of the
origin of the shape model in the search image. By default, the origin is the center of gravity of the domain (region)
of the image that was used to create the shape model with CreateAnisoShapeModel. A different origin can
be set with SetShapeModelOrigin.
Note that the coordinates Row and Column do not exactly correspond to the position of the model in the search
image. Thus, you cannot directly use them. Instead, the values are optimized for creating the transformation matrix
with which you can use the results of the matching for various tasks, e.g., to align ROIs for other processing steps.
The example given for FindAnisoShapeModel shows how to create this matrix and use it to display the model
at the found position in the search image and to calculate the exact coordinates.
Additionally, the score of each found instance is returned in Score. The score is a number between 0 and 1, which
is an approximate measure of how much of the model is visible in the image. If, for example, half of the model is
occluded, the score cannot exceed 0.5.
The domain of the image Image determines the search space for the reference point of the model, i.e.,
for the center of gravity of the domain (region) of the image that was used to create the shape model with
CreateAnisoShapeModel. A different origin set with SetShapeModelOrigin is not taken into ac-
count. The model is searched within those points of the domain of the image, in which the model lies completely
within the image. This means that the model will not be found if it extends beyond the borders of the image, even
if it would achieve a score greater than MinScore (see below). This behavior can be changed with SetSystem
(’borderShapeModels’,’true’), which will cause models that extend beyond the image border to be
found if they achieve a score greater than MinScore. Here, points lying outside the image are regarded as being
occluded, i.e., they lower the score. It should be noted that the runtime of the search will increase in this mode.
The parameters AngleStart and AngleExtent determine the range of rotations for which the model is
searched. The parameters ScaleRMin, ScaleRMax, ScaleCMin, and ScaleCMax determine the range of
scales in the row and column directions for which the model is searched. If necessary, both ranges are clipped to the
range given when the model was created with CreateAnisoShapeModel. In particular, this means that the an-
gle ranges of the model and the search must truly overlap. The angle range in the search is not adapted modulo 2π.
To simplify the presentation, all angles in the remainder of the paragraph are given in degrees, whereas they have
to be specified in radians in FindAnisoShapeModels. Hence, if the model, for example, was created with
AngleStart = −20◦ and AngleExtent = 40◦ and the angle search space in FindAnisoShapeModels
is, for example, set to AngleStart = 350◦ and AngleExtent = 20◦ , the model will not be found, even
though the angle ranges would overlap if they were regarded modulo 360◦ . To find the model, in this example it
would be necessary to select AngleStart = −10◦ .
Furthermore, it should be noted that in some cases instances with a rotation or scale that is slightly outside the
specified range are found. This may happen if the specified range is smaller than the range given when the model
was created.
The parameter MinScore determines what score a potential match must at least have to be regarded as an instance
of the model in the image. The larger MinScore is chosen, the faster the search is. If the model can be expected
never to be occluded in the images, MinScore may be set as high as 0.8 or even 0.9. If the matches are not tracked
to the lowest pyramid level (see below) it might happen that instances with a score slightly below MinScore are
found.
The maximum number of instances to be found can be determined with NumMatches. If more than
NumMatches instances with a score greater than MinScore are found in the image, only the best NumMatches
instances are returned. If fewer than NumMatches are found, only that number is returned, i.e., the parameter
MinScore takes precedence over NumMatches.
If the model exhibits symmetries it may happen that multiple instances with similar positions but different rota-
tions are found in the image. The parameter MaxOverlap determines by what fraction (i.e., a number between

HALCON 8.0.2
626 CHAPTER 7. MATCHING

0 and 1) two instances may at most overlap in order to consider them as different instances, and hence to be
returned separately. If two instances overlap each other by more than MaxOverlap only the best instance is
returned. The calculation of the overlap is based on the smallest enclosing rectangle of arbitrary orientation (see
SmallestRectangle2) of the found instances. If MaxOverlap = 0, the found instances may not overlap at
all, while for MaxOverlap = 1 all instances are returned.
The parameter SubPixel determines whether the instances should be extracted with subpixel accuracy. If
SubPixel is set to ’none’ (or ’false’ for backwards compatibility) the model’s pose is only determined with
pixel accuracy and the angle and scale resolution that was specified with CreateAnisoShapeModel. If
SubPixel is set to ’interpolation’ (or ’true’) the position as well as the rotation and scale are determined with
subpixel accuracy. In this mode, the model’s pose is interpolated from the score function. This mode costs almost
no computation time and achieves an accuracy that is high enough for most applications. In some applications,
however, the accuracy requirements are extremely high. In these cases, the model’s pose can be determined
through a least-squares adjustment, i.e., by minimizing the distances of the model points to their corresponding
image points. In contrast to ’interpolation’, this mode requires additional computation time. The different modes
for least-squares adjustment (’least_squares’, ’least_squares_high’, and ’least_squares_very_high’) can be used
to determine the accuracy with which the minimum distance is being searched. The higher the accuracy is cho-
sen, the longer the subpixel extraction will take, however. Usually, SubPixel should be set to ’interpolation’.
If least-squares adjustment is desired, ’least_squares’ should be chosen because this results in the best tradeoff
between runtime and accuracy.
The number of pyramid levels used during the search is determined with NumLevels. If necessary, the number
of levels is clipped to the range given when the shape model was created with CreateAnisoShapeModel.
If NumLevels is set to 0, the number of pyramid levels specified in CreateAnisoShapeModel is used.
Optionally, NumLevels can contain a second value that determines the lowest pyramid level to which the found
matches are tracked. Hence, a value of [4,2] for NumLevels means that the matching starts at the fourth pyramid
level and tracks the matches to the second lowest pyramid level (the lowest pyramid level is denoted by a value
of 1). This mechanism can be used to decrease the runtime of the matching. It should be noted, however, that in
general the accuracy of the extracted pose parameters is lower in this mode than in the normal mode, in which the
matches are tracked to the lowest pyramid level. Hence, if a high accuracy is desired, SubPixel should be set to at
least ’least_squares’. If the lowest pyramid level to use is chosen too large, it may happen that the desired accuracy
cannot be achieved, or that wrong instances of the model are found because the model is not specific enough on
the higher pyramid levels to facilitate a reliable selection of the correct instance of the model. In this case, the
lowest pyramid level to use must be set to a smaller value. If the lowest pyramid level is specified separately for
each model, NumLevels must contain twice the number of elements as ModelIDs. In this case, the number
of pyramid levels and the lowest pyramid level must be specified interleaved in NumLevels. If, for example,
two models are specified in ModelIDs, the number of pyramid levels is 5 for the first model and 4 for the second
model, and the lowest pyramid level is 2 for the first model and 1 for the second model, NumLevels = [5 , 2 , 4 , 1 ]
must be selected. If exactly two models are specified in ModelIDs, a special case occurs. If in this case the lowest
pyramid level is to be specified, the number of pyramid levels and the lowest pyramid level must be specified
explicitly for both models, even if they are identical, because specifying two values in NumLevels is interpreted
as the explicit specification of the number of pyramid levels for the two models.
The parameter Greediness determines how “greedily” the search should be carried out. If Greediness = 0,
a safe search heuristic is used, which always finds the model if it is visible in the image. However, the search will
be relatively time consuming in this case. If Greediness = 1, an unsafe search heuristic is used, which may
cause the model not to be found in rare cases, even though it is visible in the image. For Greediness = 1, the
maximum search speed is achieved. In almost all cases, the shape model will always be found for Greediness =
0.9.
Parameter

. Image (input iconic) . . . . . . . . . . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, uint2 )


Input image in which the models should be found.
. ModelIDs (input control) . . . . . . . . . . . . . . . . shape_model(-array) ; HShapeModelX / VARIANT ( integer )
Handle of the models.
. AngleStart (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad(-array) ; VARIANT ( real )
Smallest rotation of the models.
Default Value : -0.39
Suggested values : AngleStart ∈ {-3.14, -1.57, -0.78, -0.39, -0.20, 0.0}

HALCON/COM Reference Manual, 2008-5-13


7.4. SHAPE-BASED 627

. AngleExtent (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad(-array) ; VARIANT ( real )


Extent of the rotation angles.
Default Value : 0.78
Suggested values : AngleExtent ∈ {6.29, 3.14, 1.57, 0.78, 0.39, 0.0}
Restriction : (AngleExtent ≥ 0)
. ScaleRMin (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( real )
Minimum scale of the models in the row direction.
Default Value : 0.9
Suggested values : ScaleRMin ∈ {0.5, 0.6, 0.7, 0.8, 0.9, 1.0}
Restriction : (ScaleRM in > 0)
. ScaleRMax (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( real )
Maximum scale of the models in the row direction.
Default Value : 1.1
Suggested values : ScaleRMax ∈ {1.0, 1.1, 1.2, 1.3, 1.4, 1.5}
Restriction : (ScaleRM ax ≥ ScaleRM in)
. ScaleCMin (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( real )
Minimum scale of the models in the column direction.
Default Value : 0.9
Suggested values : ScaleCMin ∈ {0.5, 0.6, 0.7, 0.8, 0.9, 1.0}
Restriction : (ScaleCM in > 0)
. ScaleCMax (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( real )
Maximum scale of the models in the column direction.
Default Value : 1.1
Suggested values : ScaleCMax ∈ {1.0, 1.1, 1.2, 1.3, 1.4, 1.5}
Restriction : (ScaleCM ax ≥ ScaleCM in)
. MinScore (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Minimum score of the instances of the models to be found.
Default Value : 0.5
Suggested values : MinScore ∈ {0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}
Typical range of values : 0 ≤ MinScore ≤ 0
Minimum Increment : 0.01
Recommended Increment : 0.05
. NumMatches (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Number of instances of the models to be found.
Default Value : 1
Suggested values : NumMatches ∈ {0, 1, 2, 3, 4, 5, 10, 20}
. MaxOverlap (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Maximum overlap of the instances of the models to be found.
Default Value : 0.5
Suggested values : MaxOverlap ∈ {0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}
Typical range of values : 0 ≤ MaxOverlap ≤ 0
Minimum Increment : 0.01
Recommended Increment : 0.05
. SubPixel (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Subpixel accuracy if not equal to ’none’.
Default Value : ’least_squares’
List of values : SubPixel ∈ {’none’, ’interpolation’, ’least_squares’, ’least_squares_high’,
’least_squares_very_high’}
. NumLevels (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Number of pyramid levels used in the matching (and lowest pyramid level to use if |NumLevels| = 2).
Default Value : 0
List of values : NumLevels ∈ {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

HALCON 8.0.2
628 CHAPTER 7. MATCHING

. Greediness (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )


“Greediness” of the search heuristic (0: safe but slow; 1: fast but matches may be missed).
Default Value : 0.9
Suggested values : Greediness ∈ {0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}
Typical range of values : 0 ≤ Greediness ≤ 0
Minimum Increment : 0.01
Recommended Increment : 0.05
. Row (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; VARIANT ( real )
Row coordinate of the found instances of the models.
. Column (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; VARIANT ( real )
Column coordinate of the found instances of the models.
. Angle (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; VARIANT ( real )
Rotation angle of the found instances of the models.
. ScaleR (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real )
Scale of the found instances of the models in the row direction.
. ScaleC (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real )
Scale of the found instances of the models in the column direction.
. Score (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Score of the found instances of the models.
. Model (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Index of the found instances of the models.
Result
If the parameter values are correct, the operator FindAnisoShapeModels returns the value TRUE.
If the input is empty (no input images are available) the behavior can be set via SetSystem
(’noObjectResult’,<Result>). If necessary, an exception is raised.
Parallelization Information
FindAnisoShapeModels is reentrant and processed without parallelization.
Possible Predecessors
AddChannels, CreateAnisoShapeModel, ReadShapeModel, SetShapeModelOrigin
Possible Successors
ClearShapeModel
See also
SetSystem, GetSystem
Alternatives
FindShapeModels, FindScaledShapeModels, FindShapeModel, FindScaledShapeModel,
FindAnisoShapeModel, BestMatchRotMg
Module
Matching

HALCON/COM Reference Manual, 2008-5-13


7.4. SHAPE-BASED 629

[out] VARIANT Row HImageX.FindScaledShapeModel


([in] HShapeModelX ModelID, [in] double AngleStart, [in] double AngleExtent,
[in] double ScaleMin, [in] double ScaleMax, [in] double MinScore,
[in] long NumMatches, [in] double MaxOverlap, [in] String SubPixel,
[in] VARIANT NumLevels, [in] double Greediness, [out] VARIANT Column,
[out] VARIANT Angle, [out] VARIANT Scale, [out] VARIANT Score )
[out] VARIANT Row HShapeModelX.FindScaledShapeModel
([in] HImageX Image, [in] double AngleStart, [in] double AngleExtent,
[in] double ScaleMin, [in] double ScaleMax, [in] double MinScore,
[in] long NumMatches, [in] double MaxOverlap, [in] String SubPixel,
[in] VARIANT NumLevels, [in] double Greediness, [out] VARIANT Column,
[out] VARIANT Angle, [out] VARIANT Scale, [out] VARIANT Score )
void HOperatorSetX.FindScaledShapeModel ([in] IHObjectX Image,
[in] VARIANT ModelID, [in] VARIANT AngleStart, [in] VARIANT AngleExtent,
[in] VARIANT ScaleMin, [in] VARIANT ScaleMax, [in] VARIANT MinScore,
[in] VARIANT NumMatches, [in] VARIANT MaxOverlap, [in] VARIANT SubPixel,
[in] VARIANT NumLevels, [in] VARIANT Greediness, [out] VARIANT Row,
[out] VARIANT Column, [out] VARIANT Angle, [out] VARIANT Scale,
[out] VARIANT Score )

Find the best matches of a scale invariant shape model in an image.


The operator FindScaledShapeModel finds the best NumMatches instances of the scale invariant shape
model ModelID in the input image Image. The model must have been created previously by calling
CreateScaledShapeModel or ReadShapeModel.
The position, rotation, and scale of the found instances of the model are returned in Row, Column, Angle,
and Scale. The coordinates Row and Column are the coordinates of the origin of the shape model in the
search image. By default, the origin is the center of gravity of the domain (region) of the image that was
used to create the shape model with CreateScaledShapeModel. A different origin can be set with
SetShapeModelOrigin.
Note that the coordinates Row and Column do not exactly correspond to the position of the model in the search
image. Thus, you cannot directly use them. Instead, the values are optimized for creating the transformation matrix
with which you can use the results of the matching for various tasks, e.g., to align ROIs for other processing steps.
The example below shows how to create this matrix and use it to display the model at the found position in the
search image and to calculate the exact coordinates.
Additionally, the score of each found instance is returned in Score. The score is a number between 0 and 1, which
is an approximate measure of how much of the model is visible in the image. If, for example, half of the model is
occluded, the score cannot exceed 0.5.
The domain of the image Image determines the search space for the reference point of the model, i.e.,
for the center of gravity of the domain (region) of the image that was used to create the shape model with
CreateScaledShapeModel. A different origin set with SetShapeModelOrigin is not taken into ac-
count. The model is searched within those points of the domain of the image, in which the model lies completely
within the image. This means that the model will not be found if it extends beyond the borders of the image, even
if it would achieve a score greater than MinScore (see below). This behavior can be changed with SetSystem
(’borderShapeModels’,’true’), which will cause models that extend beyond the image border to be
found if they achieve a score greater than MinScore. Here, points lying outside the image are regarded as being
occluded, i.e., they lower the score. It should be noted that the runtime of the search will increase in this mode.
The parameters AngleStart and AngleExtent determine the range of rotations for which the model is
searched. The parameters ScaleMin and ScaleMax determine the range of scales for which the model
is searched. If necessary, both ranges are clipped to the range given when the model was created with
CreateScaledShapeModel. In particular, this means that the angle ranges of the model and the search
must truly overlap. The angle range in the search is not adapted modulo 2π. To simplify the presentation,
all angles in the remainder of the paragraph are given in degrees, whereas they have to be specified in radians
in FindScaledShapeModel. Hence, if the model, for example, was created with AngleStart = −20◦
and AngleExtent = 40◦ and the angle search space in FindScaledShapeModel is, for example, set to
AngleStart = 350◦ and AngleExtent = 20◦ , the model will not be found, even though the angle ranges

HALCON 8.0.2
630 CHAPTER 7. MATCHING

would overlap if they were regarded modulo 360◦ . To find the model, in this example it would be necessary to
select AngleStart = −10◦ .
Furthermore, it should be noted that in some cases instances with a rotation or scale that is slightly outside the
specified range are found. This may happen if the specified range is smaller than the range given when the model
was created.
The parameter MinScore determines what score a potential match must at least have to be regarded as an instance
of the model in the image. The larger MinScore is chosen, the faster the search is. If the model can be expected
never to be occluded in the images, MinScore may be set as high as 0.8 or even 0.9. If the matches are not tracked
to the lowest pyramid level (see below) it might happen that instances with a score slightly below MinScore are
found.
The maximum number of instances to be found can be determined with NumMatches. If more than
NumMatches instances with a score greater than MinScore are found in the image, only the best NumMatches
instances are returned. If fewer than NumMatches are found, only that number is returned, i.e., the parameter
MinScore takes precedence over NumMatches.
If the model exhibits symmetries it may happen that multiple instances with similar positions but different rota-
tions are found in the image. The parameter MaxOverlap determines by what fraction (i.e., a number between
0 and 1) two instances may at most overlap in order to consider them as different instances, and hence to be
returned separately. If two instances overlap each other by more than MaxOverlap only the best instance is
returned. The calculation of the overlap is based on the smallest enclosing rectangle of arbitrary orientation (see
SmallestRectangle2) of the found instances. If MaxOverlap = 0, the found instances may not overlap at
all, while for MaxOverlap = 1 all instances are returned.
The parameter SubPixel determines whether the instances should be extracted with subpixel accuracy. If
SubPixel is set to ’none’ (or ’false’ for backwards compatibility) the model’s pose is only determined with
pixel accuracy and the angle and scale resolution that was specified with CreateScaledShapeModel. If
SubPixel is set to ’interpolation’ (or ’true’) the position as well as the rotation and scale are determined with
subpixel accuracy. In this mode, the model’s pose is interpolated from the score function. This mode costs almost
no computation time and achieves an accuracy that is high enough for most applications. In some applications,
however, the accuracy requirements are extremely high. In these cases, the model’s pose can be determined
through a least-squares adjustment, i.e., by minimizing the distances of the model points to their corresponding
image points. In contrast to ’interpolation’, this mode requires additional computation time. The different modes
for least-squares adjustment (’least_squares’, ’least_squares_high’, and ’least_squares_very_high’) can be used
to determine the accuracy with which the minimum distance is being searched. The higher the accuracy is cho-
sen, the longer the subpixel extraction will take, however. Usually, SubPixel should be set to ’interpolation’.
If least-squares adjustment is desired, ’least_squares’ should be chosen because this results in the best tradeoff
between runtime and accuracy.
The number of pyramid levels used during the search is determined with NumLevels. If necessary, the number
of levels is clipped to the range given when the shape model was created with CreateScaledShapeModel.
If NumLevels is set to 0, the number of pyramid levels specified in CreateScaledShapeModel is used. If
NumLevels is set to 0, the number of pyramid levels specified in CreateShapeModel is used. Optionally,
NumLevels can contain a second value that determines the lowest pyramid level to which the found matches are
tracked. Hence, a value of [4,2] for NumLevels means that the matching starts at the fourth pyramid level and
tracks the matches to the second lowest pyramid level (the lowest pyramid level is denoted by a value of 1). This
mechanism can be used to decrease the runtime of the matching. It should be noted, however, that in general the
accuracy of the extracted pose parameters is lower in this mode than in the normal mode, in which the matches
are tracked to the lowest pyramid level. Hence, if a high accuracy is desired, SubPixel should be set to at least
’least_squares’. If the lowest pyramid level to use is chosen too large, it may happen that the desired accuracy
cannot be achieved, or that wrong instances of the model are found because the model is not specific enough on the
higher pyramid levels to facilitate a reliable selection of the correct instance of the model. In this case, the lowest
pyramid level to use must be set to a smaller value.
The parameter Greediness determines how “greedily” the search should be carried out. If Greediness = 0,
a safe search heuristic is used, which always finds the model if it is visible in the image. However, the search will
be relatively time consuming in this case. If Greediness = 1, an unsafe search heuristic is used, which may
cause the model not to be found in rare cases, even though it is visible in the image. For Greediness = 1, the
maximum search speed is achieved. In almost all cases, the shape model will always be found for Greediness =
0.9.

HALCON/COM Reference Manual, 2008-5-13


7.4. SHAPE-BASED 631

Parameter
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . (multichannel-)image ; HImageX / IHObjectX ( byte, uint2 )
Input image in which the model should be found.
. ModelID (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . shape_model ; HShapeModelX / VARIANT
Handle of the model.
. AngleStart (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; double / VARIANT
Smallest rotation of the model.
Default Value : -0.39
Suggested values : AngleStart ∈ {-3.14, -1.57, -0.78, -0.39, -0.20, 0.0}
. AngleExtent (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; double / VARIANT
Extent of the rotation angles.
Default Value : 0.78
Suggested values : AngleExtent ∈ {6.29, 3.14, 1.57, 0.78, 0.39, 0.0}
Restriction : (AngleExtent ≥ 0)
. ScaleMin (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Minimum scale of the model.
Default Value : 0.9
Suggested values : ScaleMin ∈ {0.5, 0.6, 0.7, 0.8, 0.9, 1.0}
Restriction : (ScaleM in > 0)
. ScaleMax (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Maximum scale of the model.
Default Value : 1.1
Suggested values : ScaleMax ∈ {1.0, 1.1, 1.2, 1.3, 1.4, 1.5}
Restriction : (ScaleM ax ≥ ScaleM in)
. MinScore (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Minimum score of the instances of the model to be found.
Default Value : 0.5
Suggested values : MinScore ∈ {0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}
Typical range of values : 0 ≤ MinScore ≤ 0
Minimum Increment : 0.01
Recommended Increment : 0.05
. NumMatches (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of instances of the model to be found.
Default Value : 1
Suggested values : NumMatches ∈ {0, 1, 2, 3, 4, 5, 10, 20}
. MaxOverlap (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Maximum overlap of the instances of the model to be found.
Default Value : 0.5
Suggested values : MaxOverlap ∈ {0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}
Typical range of values : 0 ≤ MaxOverlap ≤ 0
Minimum Increment : 0.01
Recommended Increment : 0.05
. SubPixel (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Subpixel accuracy if not equal to ’none’.
Default Value : ’least_squares’
List of values : SubPixel ∈ {’none’, ’interpolation’, ’least_squares’, ’least_squares_high’,
’least_squares_very_high’}
. NumLevels (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Number of pyramid levels used in the matching (and lowest pyramid level to use if |NumLevels| = 2).
Default Value : 0
List of values : NumLevels ∈ {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
. Greediness (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
“Greediness” of the search heuristic (0: safe but slow; 1: fast but matches may be missed).
Default Value : 0.9
Suggested values : Greediness ∈ {0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}
Typical range of values : 0 ≤ Greediness ≤ 0
Minimum Increment : 0.01
Recommended Increment : 0.05

HALCON 8.0.2
632 CHAPTER 7. MATCHING

. Row (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; VARIANT ( real )


Row coordinate of the found instances of the model.
. Column (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; VARIANT ( real )
Column coordinate of the found instances of the model.
. Angle (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; VARIANT ( real )
Rotation angle of the found instances of the model.
. Scale (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real )
Scale of the found instances of the model.
. Score (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Score of the found instances of the model.
Example

create_scaled_shape_model (ImageReduced, 0, rad(-45), rad(180), 0,


0.9, 1.1, 0, ’none’, ’use_polarity’,
30, 10, ModelID)
get_shape_model_contours (ModelXLD, ModelID, 1)
find_scaled_shape_model (SearchImage, ModelID, rad(-45), rad(180),
0.9, 1.1, 0.5, 1, 0.5, ’interpolation’,
0, 0, Row, Column, Angle, Scale, Score)
vector_angle_to_rigid (0, 0, 0, Row, Column, Angle, HomMat2DTmp)
hom_mat2d_scale (HomMat2DTmp, Scale, Scale, Row, Column, HomMat2DObject)
affine_trans_contour_xld (ModelXLD, ObjectXLD, HomMat2DObject)
affine_trans_pixel (HomMat2DObject, 0, 0, RowObject, ColObject)

Result
If the parameter values are correct, the operator FindScaledShapeModel returns the value TRUE.
If the input is empty (no input images are available) the behavior can be set via SetSystem
(’noObjectResult’,<Result>). If necessary, an exception is raised.
Parallelization Information
FindScaledShapeModel is reentrant and processed without parallelization.
Possible Predecessors
CreateScaledShapeModel, ReadShapeModel, SetShapeModelOrigin
Possible Successors
ClearShapeModel
See also
SetSystem, GetSystem
Alternatives
FindShapeModel, FindAnisoShapeModel, FindShapeModels, FindScaledShapeModels,
FindAnisoShapeModels, BestMatchRotMg
Module
Matching

HALCON/COM Reference Manual, 2008-5-13


7.4. SHAPE-BASED 633

[out] VARIANT Row HImageX.FindScaledShapeModels


([in] HShapeModelX ModelIDs, [in] VARIANT AngleStart,
[in] VARIANT AngleExtent, [in] VARIANT ScaleMin, [in] VARIANT ScaleMax,
[in] VARIANT MinScore, [in] VARIANT NumMatches, [in] VARIANT MaxOverlap,
[in] VARIANT SubPixel, [in] VARIANT NumLevels, [in] VARIANT Greediness,
[out] VARIANT Column, [out] VARIANT Angle, [out] VARIANT Scale,
[out] VARIANT Score, [out] VARIANT Model )
[out] VARIANT Row HShapeModelX.FindScaledShapeModels
([in] HImageX Image, [in] VARIANT AngleStart, [in] VARIANT AngleExtent,
[in] VARIANT ScaleMin, [in] VARIANT ScaleMax, [in] VARIANT MinScore,
[in] VARIANT NumMatches, [in] VARIANT MaxOverlap, [in] VARIANT SubPixel,
[in] VARIANT NumLevels, [in] VARIANT Greediness, [out] VARIANT Column,
[out] VARIANT Angle, [out] VARIANT Scale, [out] VARIANT Score,
[out] VARIANT Model )
void HOperatorSetX.FindScaledShapeModels ([in] IHObjectX Image,
[in] VARIANT ModelIDs, [in] VARIANT AngleStart, [in] VARIANT AngleExtent,
[in] VARIANT ScaleMin, [in] VARIANT ScaleMax, [in] VARIANT MinScore,
[in] VARIANT NumMatches, [in] VARIANT MaxOverlap, [in] VARIANT SubPixel,
[in] VARIANT NumLevels, [in] VARIANT Greediness, [out] VARIANT Row,
[out] VARIANT Column, [out] VARIANT Angle, [out] VARIANT Scale,
[out] VARIANT Score, [out] VARIANT Model )

Find the best matches of multiple scale invariant shape models.


The operator FindScaledShapeModels finds the best NumMatches instances of the scale invariant shape
models that are passed in ModelIDs in the input image Image. The models must have been created previously
by calling CreateScaledShapeModel or ReadShapeModel.
Hence, in contrast to FindScaledShapeModel, multiple models can be searched in the same image in one
call. This changes the semantics of all input parameters to some extent. All input parameters must either con-
tain one element, in which case the parameter is used for all models, or must contain the same number of ele-
ments as ModelIDs, in which case each parameter element refers to the corresponding element in ModelIDs.
(NumLevels may also contain either two or twice the number of elements as ModelIDs; see below.) As usual,
the domain of the input image Image is used to restrict the search space for the reference point of the models
ModelIDs. Consistent with the above semantics, the input image Image can therefore contain a single image
object or an image object tuple containing multiple image objects. If Image contains a single image object, its
domain is used as the region of interest for all models in ModelIDs. If Image contains multiple image ob-
jects, each domain is used as the region of interest for the corresponding model in ModelIDs. In this case, the
image matrix of all image objects in the tuple must be identical, i.e., Image cannot be constructed in an arbi-
trary manner using ConcatObj, but must be created from the same image using AddChannels or equivalent
calls. If this is not the case, an error message is returned. The above semantics also hold for the input con-
trol parameters. Hence, for example, MinScore can contain a single value or the same number of values as
ModelIDs. In the first case, the value of MinScore is used for all models in ModelIDs, while in the second
case the respective value of the elements in MinScore is used for the corresponding model in ModelIDs. An
extension to these semantics holds for NumMatches and MaxOverlap. If NumMatches contains one ele-
ment, FindScaledShapeModels returns the best NumMatches instances of the model irrespective of the
type of the model. If, for example, two models are passed in ModelIDs and NumMatches = 2 is selected, it
can happen that two instances of the first model and no instances of the second model, one instance of the first
model and one instance of the second model, or no instances of the first model and two instances of the second
model are returned. If, on the other hand, NumMatches contains multiple values, the number of instances re-
turned of the different models corresponds to the number specified in the respective entry in NumMatches. If,
for example, NumMatches = [1, 1] is selected, one instance of the first model and one instance of the second
model is returned. For a detailed description of the semantics of NumMatches, see below. A similar extension
of the semantics holds for MaxOverlap. If a single value is passed for MaxOverlap, the overlap is com-
puted for all found instances of the different models, irrespective of the model type, i.e., instances of the same
or of different models that overlap too much are eliminated. If, on the other hand, multiple values are passed in
MaxOverlap, the overlap is only computed for found instances of the model that have the same model type,
i.e., only instances of the same model that overlap too much are eliminated. In this mode, models of different
types may overlap completely. For a detailed description of the semantics of MaxOverlap, see below. Hence,

HALCON 8.0.2
634 CHAPTER 7. MATCHING

a call to FindScaledShapeModels with multiple values for ModelIDs, NumMatches and MaxOverlap
has the same effect as multiple independent calls to FindScaledShapeModel with the respective parameters.
However, a single call to FindScaledShapeModels is considerably more efficient.
The type of the found instances of the models is returned in Model. The elements of Model are indices into the
tuple ModelIDs, i.e., they can contain values from 0 to |ModelIDs| − 1. Hence, a value of 0 in an element of
Model corresponds to an instance of the first model in ModelIDs.
The position, rotation, and scale of the found instances of the model are returned in Row, Column, Angle,
and Scale. The coordinates Row and Column are the coordinates of the origin of the shape model in the
search image. By default, the origin is the center of gravity of the domain (region) of the image that was
used to create the shape model with CreateScaledShapeModel. A different origin can be set with
SetShapeModelOrigin.
Note that the coordinates Row and Column do not exactly correspond to the position of the model in the search
image. Thus, you cannot directly use them. Instead, the values are optimized for creating the transformation matrix
with which you can use the results of the matching for various tasks, e.g., to align ROIs for other processing steps.
The example given for FindScaledShapeModel shows how to create this matrix and use it to display the
model at the found position in the search image and to calculate the exact coordinates.
Additionally, the score of each found instance is returned in Score. The score is a number between 0 and 1, which
is an approximate measure of how much of the model is visible in the image. If, for example, half of the model is
occluded, the score cannot exceed 0.5.
The domain of the image Image determines the search space for the reference point of the model, i.e.,
for the center of gravity of the domain (region) of the image that was used to create the shape model with
CreateScaledShapeModel. A different origin set with SetShapeModelOrigin is not taken into ac-
count. The model is searched within those points of the domain of the image, in which the model lies completely
within the image. This means that the model will not be found if it extends beyond the borders of the image, even
if it would achieve a score greater than MinScore (see below). This behavior can be changed with SetSystem
(’borderShapeModels’,’true’), which will cause models that extend beyond the image border to be
found if they achieve a score greater than MinScore. Here, points lying outside the image are regarded as being
occluded, i.e., they lower the score. It should be noted that the runtime of the search will increase in this mode.
The parameters AngleStart and AngleExtent determine the range of rotations for which the model is
searched. The parameters ScaleMin and ScaleMax determine the range of scales for which the model
is searched. If necessary, both ranges are clipped to the range given when the model was created with
CreateScaledShapeModel. In particular, this means that the angle ranges of the model and the search
must truly overlap. The angle range in the search is not adapted modulo 2π. To simplify the presentation, all
angles in the remainder of the paragraph are given in degrees, whereas they have to be specified in radians in
FindScaledShapeModels. Hence, if the model, for example, was created with AngleStart = −20◦
and AngleExtent = 40◦ and the angle search space in FindScaledShapeModels is, for example, set to
AngleStart = 350◦ and AngleExtent = 20◦ , the model will not be found, even though the angle ranges
would overlap if they were regarded modulo 360◦ . To find the model, in this example it would be necessary to
select AngleStart = −10◦ .
Furthermore, it should be noted that in some cases instances with a rotation or scale that is slightly outside the
specified range are found. This may happen if the specified range is smaller than the range given when the model
was created.
The parameter MinScore determines what score a potential match must at least have to be regarded as an instance
of the model in the image. The larger MinScore is chosen, the faster the search is. If the model can be expected
never to be occluded in the images, MinScore may be set as high as 0.8 or even 0.9. If the matches are not tracked
to the lowest pyramid level (see below) it might happen that instances with a score slightly below MinScore are
found.
The maximum number of instances to be found can be determined with NumMatches. If more than
NumMatches instances with a score greater than MinScore are found in the image, only the best NumMatches
instances are returned. If fewer than NumMatches are found, only that number is returned, i.e., the parameter
MinScore takes precedence over NumMatches.
If the model exhibits symmetries it may happen that multiple instances with similar positions but different rota-
tions are found in the image. The parameter MaxOverlap determines by what fraction (i.e., a number between
0 and 1) two instances may at most overlap in order to consider them as different instances, and hence to be
returned separately. If two instances overlap each other by more than MaxOverlap only the best instance is
returned. The calculation of the overlap is based on the smallest enclosing rectangle of arbitrary orientation (see

HALCON/COM Reference Manual, 2008-5-13


7.4. SHAPE-BASED 635

SmallestRectangle2) of the found instances. If MaxOverlap = 0, the found instances may not overlap at
all, while for MaxOverlap = 1 all instances are returned.
The parameter SubPixel determines whether the instances should be extracted with subpixel accuracy. If
SubPixel is set to ’none’ (or ’false’ for backwards compatibility) the model’s pose is only determined with
pixel accuracy and the angle and scale resolution that was specified with CreateScaledShapeModel. If
SubPixel is set to ’interpolation’ (or ’true’) the position as well as the rotation and scale are determined with
subpixel accuracy. In this mode, the model’s pose is interpolated from the score function. This mode costs almost
no computation time and achieves an accuracy that is high enough for most applications. In some applications,
however, the accuracy requirements are extremely high. In these cases, the model’s pose can be determined
through a least-squares adjustment, i.e., by minimizing the distances of the model points to their corresponding
image points. In contrast to ’interpolation’, this mode requires additional computation time. The different modes
for least-squares adjustment (’least_squares’, ’least_squares_high’, and ’least_squares_very_high’) can be used
to determine the accuracy with which the minimum distance is being searched. The higher the accuracy is cho-
sen, the longer the subpixel extraction will take, however. Usually, SubPixel should be set to ’interpolation’.
If least-squares adjustment is desired, ’least_squares’ should be chosen because this results in the best tradeoff
between runtime and accuracy.
The number of pyramid levels used during the search is determined with NumLevels. If necessary, the number
of levels is clipped to the range given when the shape model was created with CreateScaledShapeModel.
If NumLevels is set to 0, the number of pyramid levels specified in CreateScaledShapeModel is used.
Optionally, NumLevels can contain a second value that determines the lowest pyramid level to which the found
matches are tracked. Hence, a value of [4,2] for NumLevels means that the matching starts at the fourth pyramid
level and tracks the matches to the second lowest pyramid level (the lowest pyramid level is denoted by a value
of 1). This mechanism can be used to decrease the runtime of the matching. It should be noted, however, that in
general the accuracy of the extracted pose parameters is lower in this mode than in the normal mode, in which the
matches are tracked to the lowest pyramid level. Hence, if a high accuracy is desired, SubPixel should be set to at
least ’least_squares’. If the lowest pyramid level to use is chosen too large, it may happen that the desired accuracy
cannot be achieved, or that wrong instances of the model are found because the model is not specific enough on
the higher pyramid levels to facilitate a reliable selection of the correct instance of the model. In this case, the
lowest pyramid level to use must be set to a smaller value. If the lowest pyramid level is specified separately for
each model, NumLevels must contain twice the number of elements as ModelIDs. In this case, the number
of pyramid levels and the lowest pyramid level must be specified interleaved in NumLevels. If, for example,
two models are specified in ModelIDs, the number of pyramid levels is 5 for the first model and 4 for the second
model, and the lowest pyramid level is 2 for the first model and 1 for the second model, NumLevels = [5 , 2 , 4 , 1 ]
must be selected. If exactly two models are specified in ModelIDs, a special case occurs. If in this case the lowest
pyramid level is to be specified, the number of pyramid levels and the lowest pyramid level must be specified
explicitly for both models, even if they are identical, because specifying two values in NumLevels is interpreted
as the explicit specification of the number of pyramid levels for the two models.
The parameter Greediness determines how “greedily” the search should be carried out. If Greediness = 0,
a safe search heuristic is used, which always finds the model if it is visible in the image. However, the search will
be relatively time consuming in this case. If Greediness = 1, an unsafe search heuristic is used, which may
cause the model not to be found in rare cases, even though it is visible in the image. For Greediness = 1, the
maximum search speed is achieved. In almost all cases, the shape model will always be found for Greediness =
0.9.
Parameter
. Image (input iconic) . . . . . . . . . . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, uint2 )
Input image in which the models should be found.
. ModelIDs (input control) . . . . . . . . . . . . . . . . shape_model(-array) ; HShapeModelX / VARIANT ( integer )
Handle of the models.
. AngleStart (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad(-array) ; VARIANT ( real )
Smallest rotation of the models.
Default Value : -0.39
Suggested values : AngleStart ∈ {-3.14, -1.57, -0.78, -0.39, -0.20, 0.0}
. AngleExtent (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad(-array) ; VARIANT ( real )
Extent of the rotation angles.
Default Value : 0.78
Suggested values : AngleExtent ∈ {6.29, 3.14, 1.57, 0.78, 0.39, 0.0}
Restriction : (AngleExtent ≥ 0)

HALCON 8.0.2
636 CHAPTER 7. MATCHING

. ScaleMin (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( real )


Minimum scale of the models.
Default Value : 0.9
Suggested values : ScaleMin ∈ {0.5, 0.6, 0.7, 0.8, 0.9, 1.0}
Restriction : (ScaleM in > 0)
. ScaleMax (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( real )
Maximum scale of the models.
Default Value : 1.1
Suggested values : ScaleMax ∈ {1.0, 1.1, 1.2, 1.3, 1.4, 1.5}
Restriction : (ScaleM ax ≥ ScaleM in)
. MinScore (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Minimum score of the instances of the models to be found.
Default Value : 0.5
Suggested values : MinScore ∈ {0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}
Typical range of values : 0 ≤ MinScore ≤ 0
Minimum Increment : 0.01
Recommended Increment : 0.05
. NumMatches (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Number of instances of the models to be found.
Default Value : 1
Suggested values : NumMatches ∈ {0, 1, 2, 3, 4, 5, 10, 20}
. MaxOverlap (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Maximum overlap of the instances of the models to be found.
Default Value : 0.5
Suggested values : MaxOverlap ∈ {0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}
Typical range of values : 0 ≤ MaxOverlap ≤ 0
Minimum Increment : 0.01
Recommended Increment : 0.05
. SubPixel (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Subpixel accuracy if not equal to ’none’.
Default Value : ’least_squares’
List of values : SubPixel ∈ {’none’, ’interpolation’, ’least_squares’, ’least_squares_high’,
’least_squares_very_high’}
. NumLevels (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Number of pyramid levels used in the matching (and lowest pyramid level to use if |NumLevels| = 2).
Default Value : 0
List of values : NumLevels ∈ {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
. Greediness (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
“Greediness” of the search heuristic (0: safe but slow; 1: fast but matches may be missed).
Default Value : 0.9
Suggested values : Greediness ∈ {0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}
Typical range of values : 0 ≤ Greediness ≤ 0
Minimum Increment : 0.01
Recommended Increment : 0.05
. Row (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; VARIANT ( real )
Row coordinate of the found instances of the models.
. Column (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; VARIANT ( real )
Column coordinate of the found instances of the models.
. Angle (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; VARIANT ( real )
Rotation angle of the found instances of the models.
. Scale (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real )
Scale of the found instances of the models.
. Score (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Score of the found instances of the models.
. Model (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Index of the found instances of the models.
Result
If the parameter values are correct, the operator FindScaledShapeModels returns the value TRUE.

HALCON/COM Reference Manual, 2008-5-13


7.4. SHAPE-BASED 637

If the input is empty (no input images are available) the behavior can be set via SetSystem
(’noObjectResult’,<Result>). If necessary, an exception is raised.
Parallelization Information
FindScaledShapeModels is reentrant and processed without parallelization.
Possible Predecessors
AddChannels, CreateScaledShapeModel, ReadShapeModel, SetShapeModelOrigin
Possible Successors
ClearShapeModel
See also
SetSystem, GetSystem
Alternatives
FindShapeModels, FindAnisoShapeModels, FindShapeModel, FindScaledShapeModel,
FindAnisoShapeModel, BestMatchRotMg
Module
Matching

[out] VARIANT Row HImageX.FindShapeModel ([in] HShapeModelX ModelID,


[in] double AngleStart, [in] double AngleExtent, [in] double MinScore,
[in] long NumMatches, [in] double MaxOverlap, [in] String SubPixel,
[in] VARIANT NumLevels, [in] double Greediness, [out] VARIANT Column,
[out] VARIANT Angle, [out] VARIANT Score )
[out] VARIANT Row HShapeModelX.FindShapeModel ([in] HImageX Image,
[in] double AngleStart, [in] double AngleExtent, [in] double MinScore,
[in] long NumMatches, [in] double MaxOverlap, [in] String SubPixel,
[in] VARIANT NumLevels, [in] double Greediness, [out] VARIANT Column,
[out] VARIANT Angle, [out] VARIANT Score )
void HOperatorSetX.FindShapeModel ([in] IHObjectX Image,
[in] VARIANT ModelID, [in] VARIANT AngleStart, [in] VARIANT AngleExtent,
[in] VARIANT MinScore, [in] VARIANT NumMatches, [in] VARIANT MaxOverlap,
[in] VARIANT SubPixel, [in] VARIANT NumLevels, [in] VARIANT Greediness,
[out] VARIANT Row, [out] VARIANT Column, [out] VARIANT Angle,
[out] VARIANT Score )

Find the best matches of a shape model in an image.


The operator FindShapeModel finds the best NumMatches instances of the shape model ModelID in
the input image Image. The model must have been created previously by calling CreateShapeModel or
ReadShapeModel.
The position and rotation of the found instances of the model is returned in Row, Column, and Angle. The
coordinates Row and Column are the coordinates of the origin of the shape model in the search image. By default,
the origin is the center of gravity of the domain (region) of the image that was used to create the shape model with
CreateShapeModel. A different origin can be set with SetShapeModelOrigin.
Note that the coordinates Row and Column do not exactly correspond to the position of the model in the search
image. Thus, you cannot directly use them. Instead, the values are optimized for creating the transformation matrix
with which you can use the results of the matching for various tasks, e.g., to align ROIs for other processing steps.
The example below shows how to create this matrix and use it to display the model at the found position in the
search image and to calculate the exact coordinates.
Additionally, the score of each found instance is returned in Score. The score is a number between 0 and 1, which
is an approximate measure of how much of the model is visible in the image. If, for example, half of the model is
occluded, the score cannot exceed 0.5.
The domain of the image Image determines the search space for the reference point of the model, i.e.,
for the center of gravity of the domain (region) of the image that was used to create the shape model with
CreateShapeModel. A different origin set with SetShapeModelOrigin is not taken into account. The
model is searched within those points of the domain of the image, in which the model lies completely within

HALCON 8.0.2
638 CHAPTER 7. MATCHING

the image. This means that the model will not be found if it extends beyond the borders of the image, even if it
would achieve a score greater than MinScore (see below). This behavior can be changed with SetSystem
(’borderShapeModels’,’true’), which will cause models that extend beyond the image border to be
found if they achieve a score greater than MinScore. Here, points lying outside the image are regarded as being
occluded, i.e., they lower the score. It should be noted that the runtime of the search will increase in this mode.
The parameters AngleStart and AngleExtent determine the range of rotations for which the model is
searched. If necessary, the range of rotations is clipped to the range given when the model was created with
CreateShapeModel. In particular, this means that the angle ranges of the model and the search must truly
overlap. The angle range in the search is not adapted modulo 2π. To simplify the presentation, all angles in the re-
mainder of the paragraph are given in degrees, whereas they have to be specified in radians in FindShapeModel.
Hence, if the model, for example, was created with AngleStart = −20◦ and AngleExtent = 40◦ and the
angle search space in FindShapeModel is, for example, set to AngleStart = 350◦ and AngleExtent =
20◦ , the model will not be found, even though the angle ranges would overlap if they were regarded modulo 360◦ .
To find the model, in this example it would be necessary to select AngleStart = −10◦ .
Furthermore, it should be noted that in some cases instances with a rotation that is slightly outside the specified
range of rotations are found. This may happen if the specified range of rotations is smaller than the range given
when the model was created.
The parameter MinScore determines what score a potential match must at least have to be regarded as an instance
of the model in the image. The larger MinScore is chosen, the faster the search is. If the model can be expected
never to be occluded in the images, MinScore may be set as high as 0.8 or even 0.9. If the matches are not tracked
to the lowest pyramid level (see below) it might happen that instances with a score slightly below MinScore are
found.
The maximum number of instances to be found can be determined with NumMatches. If more than
NumMatches instances with a score greater than MinScore are found in the image, only the best NumMatches
instances are returned. If fewer than NumMatches are found, only that number is returned, i.e., the parameter
MinScore takes precedence over NumMatches.
If the model exhibits symmetries it may happen that multiple instances with similar positions but different rota-
tions are found in the image. The parameter MaxOverlap determines by what fraction (i.e., a number between
0 and 1) two instances may at most overlap in order to consider them as different instances, and hence to be
returned separately. If two instances overlap each other by more than MaxOverlap only the best instance is
returned. The calculation of the overlap is based on the smallest enclosing rectangle of arbitrary orientation (see
SmallestRectangle2) of the found instances. If MaxOverlap = 0, the found instances may not overlap at
all, while for MaxOverlap = 1 all instances are returned.
The parameter SubPixel determines whether the instances should be extracted with subpixel accuracy. If
SubPixel is set to ’none’ (or ’false’ for backwards compatibility) the model’s pose is only determined with
pixel accuracy and the angle resolution that was specified with CreateShapeModel. If SubPixel is set
to ’interpolation’ (or ’true’) the position as well as the rotation are determined with subpixel accuracy. In this
mode, the model’s pose is interpolated from the score function. This mode costs almost no computation time
and achieves an accuracy that is high enough for most applications. In some applications, however, the accuracy
requirements are extremely high. In these cases, the model’s pose can be determined through a least-squares ad-
justment, i.e., by minimizing the distances of the model points to their corresponding image points. In contrast to
’interpolation’, this mode requires additional computation time. The different modes for least-squares adjustment
(’least_squares’, ’least_squares_high’, and ’least_squares_very_high’) can be used to determine the accuracy with
which the minimum distance is being searched. The higher the accuracy is chosen, the longer the subpixel extrac-
tion will take, however. Usually, SubPixel should be set to ’interpolation’. If least-squares adjustment is desired,
’least_squares’ should be chosen because this results in the best tradeoff between runtime and accuracy.
The number of pyramid levels used during the search is determined with NumLevels. If necessary, the num-
ber of levels is clipped to the range given when the shape model was created with CreateShapeModel. If
NumLevels is set to 0, the number of pyramid levels specified in CreateShapeModel is used. Optionally,
NumLevels can contain a second value that determines the lowest pyramid level to which the found matches are
tracked. Hence, a value of [4,2] for NumLevels means that the matching starts at the fourth pyramid level and
tracks the matches to the second lowest pyramid level (the lowest pyramid level is denoted by a value of 1). This
mechanism can be used to decrease the runtime of the matching. It should be noted, however, that in general the
accuracy of the extracted pose parameters is lower in this mode than in the normal mode, in which the matches
are tracked to the lowest pyramid level. Hence, if a high accuracy is desired, SubPixel should be set to at least
’least_squares’. If the lowest pyramid level to use is chosen too large, it may happen that the desired accuracy
cannot be achieved, or that wrong instances of the model are found because the model is not specific enough on the

HALCON/COM Reference Manual, 2008-5-13


7.4. SHAPE-BASED 639

higher pyramid levels to facilitate a reliable selection of the correct instance of the model. In this case, the lowest
pyramid level to use must be set to a smaller value.
The parameter Greediness determines how “greedily” the search should be carried out. If Greediness = 0,
a safe search heuristic is used, which always finds the model if it is visible in the image. However, the search will
be relatively time consuming in this case. If Greediness = 1, an unsafe search heuristic is used, which may
cause the model not to be found in rare cases, even though it is visible in the image. For Greediness = 1, the
maximum search speed is achieved. In almost all cases, the shape model will always be found for Greediness =
0.9.
Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . (multichannel-)image ; HImageX / IHObjectX ( byte, uint2 )


Input image in which the model should be found.
. ModelID (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . shape_model ; HShapeModelX / VARIANT
Handle of the model.
. AngleStart (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; double / VARIANT
Smallest rotation of the model.
Default Value : -0.39
Suggested values : AngleStart ∈ {-3.14, -1.57, -0.78, -0.39, -0.20, 0.0}
. AngleExtent (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; double / VARIANT
Extent of the rotation angles.
Default Value : 0.78
Suggested values : AngleExtent ∈ {6.29, 3.14, 1.57, 0.78, 0.39, 0.0}
Restriction : (AngleExtent ≥ 0)
. MinScore (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Minimum score of the instances of the model to be found.
Default Value : 0.5
Suggested values : MinScore ∈ {0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}
Typical range of values : 0 ≤ MinScore ≤ 0
Minimum Increment : 0.01
Recommended Increment : 0.05
. NumMatches (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of instances of the model to be found.
Default Value : 1
Suggested values : NumMatches ∈ {0, 1, 2, 3, 4, 5, 10, 20}
. MaxOverlap (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Maximum overlap of the instances of the model to be found.
Default Value : 0.5
Suggested values : MaxOverlap ∈ {0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}
Typical range of values : 0 ≤ MaxOverlap ≤ 0
Minimum Increment : 0.01
Recommended Increment : 0.05
. SubPixel (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Subpixel accuracy if not equal to ’none’.
Default Value : ’least_squares’
List of values : SubPixel ∈ {’none’, ’interpolation’, ’least_squares’, ’least_squares_high’,
’least_squares_very_high’}
. NumLevels (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Number of pyramid levels used in the matching (and lowest pyramid level to use if |NumLevels| = 2).
Default Value : 0
List of values : NumLevels ∈ {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
. Greediness (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
“Greediness” of the search heuristic (0: safe but slow; 1: fast but matches may be missed).
Default Value : 0.9
Suggested values : Greediness ∈ {0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}
Typical range of values : 0 ≤ Greediness ≤ 0
Minimum Increment : 0.01
Recommended Increment : 0.05

HALCON 8.0.2
640 CHAPTER 7. MATCHING

. Row (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; VARIANT ( real )


Row coordinate of the found instances of the model.
. Column (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; VARIANT ( real )
Column coordinate of the found instances of the model.
. Angle (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; VARIANT ( real )
Rotation angle of the found instances of the model.
. Score (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Score of the found instances of the model.
Example

create_shape_model (ImageReduced, 0, rad(-45), rad(180), 0,


’none’, ’use_polarity’, 30, 10, ModelID)
get_shape_model_contours (ModelXLD, ModelID, 1)
find_shape_model (SearchImage, ModelID, rad(-45), rad(180),
0.5, 1, 0.5, ’interpolation’,
0, 0, Row, Column, Angle, Score)
vector_angle_to_rigid (0, 0, 0, Row, Column, Angle, HomMat2DObject)
affine_trans_contour_xld (ModelXLD, ObjectXLD, HomMat2DObject)
affine_trans_pixel (HomMat2DObject, 0, 0, RowObject, ColObject)

Result
If the parameter values are correct, the operator FindShapeModel returns the value TRUE. If the input is empty
(no input images are available) the behavior can be set via SetSystem(’noObjectResult’,<Result>).
If necessary, an exception is raised.
Parallelization Information
FindShapeModel is reentrant and processed without parallelization.
Possible Predecessors
CreateShapeModel, ReadShapeModel, SetShapeModelOrigin
Possible Successors
ClearShapeModel
See also
SetSystem, GetSystem
Alternatives
FindScaledShapeModel, FindAnisoShapeModel, FindScaledShapeModels,
FindShapeModels, FindAnisoShapeModels, BestMatchRotMg
Module
Matching

HALCON/COM Reference Manual, 2008-5-13


7.4. SHAPE-BASED 641

[out] VARIANT Row HImageX.FindShapeModels ([in] HShapeModelX ModelIDs,


[in] VARIANT AngleStart, [in] VARIANT AngleExtent, [in] VARIANT MinScore,
[in] VARIANT NumMatches, [in] VARIANT MaxOverlap, [in] VARIANT SubPixel,
[in] VARIANT NumLevels, [in] VARIANT Greediness, [out] VARIANT Column,
[out] VARIANT Angle, [out] VARIANT Score, [out] VARIANT Model )
[out] VARIANT Row HShapeModelX.FindShapeModels ([in] HImageX Image,
[in] VARIANT AngleStart, [in] VARIANT AngleExtent, [in] VARIANT MinScore,
[in] VARIANT NumMatches, [in] VARIANT MaxOverlap, [in] VARIANT SubPixel,
[in] VARIANT NumLevels, [in] VARIANT Greediness, [out] VARIANT Column,
[out] VARIANT Angle, [out] VARIANT Score, [out] VARIANT Model )
void HOperatorSetX.FindShapeModels ([in] IHObjectX Image,
[in] VARIANT ModelIDs, [in] VARIANT AngleStart, [in] VARIANT AngleExtent,
[in] VARIANT MinScore, [in] VARIANT NumMatches, [in] VARIANT MaxOverlap,
[in] VARIANT SubPixel, [in] VARIANT NumLevels, [in] VARIANT Greediness,
[out] VARIANT Row, [out] VARIANT Column, [out] VARIANT Angle,
[out] VARIANT Score, [out] VARIANT Model )

Find the best matches of multiple shape models.


The operator FindShapeModels finds the best NumMatches instances of the shape models that are passed
in the tuple ModelIDs in the input image Image. The models must have been created previously by calling
CreateShapeModel or ReadShapeModel.
Hence, in contrast to FindShapeModel, multiple models can be searched in the same image in one call. This
changes the semantics of all input parameters to some extent. All input parameters must either contain one element,
in which case the parameter is used for all models, or must contain the same number of elements as ModelIDs,
in which case each parameter element refers to the corresponding element in ModelIDs. (NumLevels may also
contain either two or twice the number of elements as ModelIDs; see below.) As usual, the domain of the input
image Image is used to restrict the search space for the reference point of the models ModelIDs. Consistent
with the above semantics, the input image Image can therefore contain a single image object or an image object
tuple containing multiple image objects. If Image contains a single image object, its domain is used as the region
of interest for all models in ModelIDs. If Image contains multiple image objects, each domain is used as the
region of interest for the corresponding model in ModelIDs. In this case, the image matrix of all image objects
in the tuple must be identical, i.e., Image cannot be constructed in an arbitrary manner using ConcatObj,
but must be created from the same image using AddChannels or equivalent calls. If this is not the case, an
error message is returned. The above semantics also hold for the input control parameters. Hence, for example,
MinScore can contain a single value or the same number of values as ModelIDs. In the first case, the value
of MinScore is used for all models in ModelIDs, while in the second case the respective value of the elements
in MinScore is used for the corresponding model in ModelIDs. An extension to these semantics holds for
NumMatches and MaxOverlap. If NumMatches contains one element, FindShapeModels returns the
best NumMatches instances of the model irrespective of the type of the model. If, for example, two models are
passed in ModelIDs and NumMatches = 2 is selected, it can happen that two instances of the first model and no
instances of the second model, one instance of the first model and one instance of the second model, or no instances
of the first model and two instances of the second model are returned. If, on the other hand, NumMatches contains
multiple values, the number of instances returned of the different models corresponds to the number specified
in the respective entry in NumMatches. If, for example, NumMatches = [1, 1] is selected, one instance of
the first model and one instance of the second model is returned. For a detailed description of the semantics of
NumMatches, see below. A similar extension of the semantics holds for MaxOverlap. If a single value is passed
for MaxOverlap, the overlap is computed for all found instances of the different models, irrespective of the model
type, i.e., instances of the same or of different models that overlap too much are eliminated. If, on the other hand,
multiple values are passed in MaxOverlap, the overlap is only computed for found instances of the model that
have the same model type, i.e., only instances of the same model that overlap too much are eliminated. In this mode,
models of different types may overlap completely. For a detailed description of the semantics of MaxOverlap,
see below. Hence, a call to FindShapeModels with multiple values for ModelIDs, NumMatches and
MaxOverlap has the same effect as multiple independent calls to FindShapeModel with the respective
parameters. However, a single call to FindShapeModels is considerably more efficient.
The type of the found instances of the models is returned in Model. The elements of Model are indices into the
tuple ModelIDs, i.e., they can contain values from 0 to |ModelIDs| − 1. Hence, a value of 0 in an element of
Model corresponds to an instance of the first model in ModelIDs.

HALCON 8.0.2
642 CHAPTER 7. MATCHING

The position and rotation of the found instances of the model is returned in Row, Column, and Angle. The
coordinates Row and Column are the coordinates of the origin of the shape model in the search image. By default,
the origin is the center of gravity of the domain (region) of the image that was used to create the shape model with
CreateShapeModel. A different origin can be set with SetShapeModelOrigin.
Note that the coordinates Row and Column do not exactly correspond to the position of the model in the search
image. Thus, you cannot directly use them. Instead, the values are optimized for creating the transformation matrix
with which you can use the results of the matching for various tasks, e.g., to align ROIs for other processing steps.
The example given for FindShapeModel shows how to create this matrix and use it to display the model at the
found position in the search image and to calculate the exact coordinates.
Additionally, the score of each found instance is returned in Score. The score is a number between 0 and 1, which
is an approximate measure of how much of the model is visible in the image. If, for example, half of the model is
occluded, the score cannot exceed 0.5.
The domain of the image Image determines the search space for the reference point of the model, i.e.,
for the center of gravity of the domain (region) of the image that was used to create the shape model with
CreateShapeModel. A different origin set with SetShapeModelOrigin is not taken into account. The
model is searched within those points of the domain of the image, in which the model lies completely within
the image. This means that the model will not be found if it extends beyond the borders of the image, even if it
would achieve a score greater than MinScore (see below). This behavior can be changed with SetSystem
(’borderShapeModels’,’true’), which will cause models that extend beyond the image border to be
found if they achieve a score greater than MinScore. Here, points lying outside the image are regarded as being
occluded, i.e., they lower the score. It should be noted that the runtime of the search will increase in this mode.
The parameters AngleStart and AngleExtent determine the range of rotations for which the model is
searched. If necessary, the range of rotations is clipped to the range given when the model was created with
CreateShapeModel. In particular, this means that the angle ranges of the model and the search must truly over-
lap. The angle range in the search is not adapted modulo 2π. To simplify the presentation, all angles in the remain-
der of the paragraph are given in degrees, whereas they have to be specified in radians in FindShapeModels.
Hence, if the model, for example, was created with AngleStart = −20◦ and AngleExtent = 40◦ and the
angle search space in FindShapeModels is, for example, set to AngleStart = 350◦ and AngleExtent =
20◦ , the model will not be found, even though the angle ranges would overlap if they were regarded modulo 360◦ .
To find the model, in this example it would be necessary to select AngleStart = −10◦ .
Furthermore, it should be noted that in some cases instances with a rotation that is slightly outside the specified
range of rotations are found. This may happen if the specified range of rotations is smaller than the range given
when the model was created.
The parameter MinScore determines what score a potential match must at least have to be regarded as an instance
of the model in the image. The larger MinScore is chosen, the faster the search is. If the model can be expected
never to be occluded in the images, MinScore may be set as high as 0.8 or even 0.9. If the matches are not tracked
to the lowest pyramid level (see below) it might happen that instances with a score slightly below MinScore are
found.
The maximum number of instances to be found can be determined with NumMatches. If more than
NumMatches instances with a score greater than MinScore are found in the image, only the best NumMatches
instances are returned. If fewer than NumMatches are found, only that number is returned, i.e., the parameter
MinScore takes precedence over NumMatches.
If the model exhibits symmetries it may happen that multiple instances with similar positions but different rota-
tions are found in the image. The parameter MaxOverlap determines by what fraction (i.e., a number between
0 and 1) two instances may at most overlap in order to consider them as different instances, and hence to be
returned separately. If two instances overlap each other by more than MaxOverlap only the best instance is
returned. The calculation of the overlap is based on the smallest enclosing rectangle of arbitrary orientation (see
SmallestRectangle2) of the found instances. If MaxOverlap = 0, the found instances may not overlap at
all, while for MaxOverlap = 1 all instances are returned.
The parameter SubPixel determines whether the instances should be extracted with subpixel accuracy. If
SubPixel is set to ’none’ (or ’false’ for backwards compatibility) the model’s pose is only determined with
pixel accuracy and the angle resolution that was specified with CreateShapeModel. If SubPixel is set
to ’interpolation’ (or ’true’) the position as well as the rotation are determined with subpixel accuracy. In this
mode, the model’s pose is interpolated from the score function. This mode costs almost no computation time
and achieves an accuracy that is high enough for most applications. In some applications, however, the accuracy
requirements are extremely high. In these cases, the model’s pose can be determined through a least-squares ad-
justment, i.e., by minimizing the distances of the model points to their corresponding image points. In contrast to

HALCON/COM Reference Manual, 2008-5-13


7.4. SHAPE-BASED 643

’interpolation’, this mode requires additional computation time. The different modes for least-squares adjustment
(’least_squares’, ’least_squares_high’, and ’least_squares_very_high’) can be used to determine the accuracy with
which the minimum distance is being searched. The higher the accuracy is chosen, the longer the subpixel extrac-
tion will take, however. Usually, SubPixel should be set to ’interpolation’. If least-squares adjustment is desired,
’least_squares’ should be chosen because this results in the best tradeoff between runtime and accuracy.
The number of pyramid levels used during the search is determined with NumLevels. If necessary, the num-
ber of levels is clipped to the range given when the shape model was created with CreateShapeModel. If
NumLevels is set to 0, the number of pyramid levels specified in CreateShapeModel is used. Optionally,
NumLevels can contain a second value that determines the lowest pyramid level to which the found matches are
tracked. Hence, a value of [4,2] for NumLevels means that the matching starts at the fourth pyramid level and
tracks the matches to the second lowest pyramid level (the lowest pyramid level is denoted by a value of 1). This
mechanism can be used to decrease the runtime of the matching. It should be noted, however, that in general the
accuracy of the extracted pose parameters is lower in this mode than in the normal mode, in which the matches
are tracked to the lowest pyramid level. Hence, if a high accuracy is desired, SubPixel should be set to at least
’least_squares’. If the lowest pyramid level to use is chosen too large, it may happen that the desired accuracy
cannot be achieved, or that wrong instances of the model are found because the model is not specific enough on the
higher pyramid levels to facilitate a reliable selection of the correct instance of the model. In this case, the lowest
pyramid level to use must be set to a smaller value. If the lowest pyramid level is specified separately for each
model, NumLevels must contain twice the number of elements as ModelIDs. In this case, the number of pyra-
mid levels and the lowest pyramid level must be specified interleaved in NumLevels. If, for example, two models
are specified in ModelIDs, the number of pyramid levels is 5 for the first model and 4 for the second model, and
the lowest pyramid level is 2 for the first model and 1 for the second model, NumLevels = [5 , 2 , 4 , 1 ] must
be selected. If exactly two models are specified in ModelIDs, a special case occurs. If in this case the lowest
pyramid level is to be specified, the number of pyramid levels and the lowest pyramid level must be specified
explicitly for both models, even if they are identical, because specifying two values in NumLevels is interpreted
as the explicit specification of the number of pyramid levels for the two models.
The parameter Greediness determines how “greedily” the search should be carried out. If Greediness = 0,
a safe search heuristic is used, which always finds the model if it is visible in the image. However, the search will
be relatively time consuming in this case. If Greediness = 1, an unsafe search heuristic is used, which may
cause the model not to be found in rare cases, even though it is visible in the image. For Greediness = 1, the
maximum search speed is achieved. In almost all cases, the shape model will always be found for Greediness =
0.9.
Parameter
. Image (input iconic) . . . . . . . . . . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, uint2 )
Input image in which the models should be found.
. ModelIDs (input control) . . . . . . . . . . . . . . . . shape_model(-array) ; HShapeModelX / VARIANT ( integer )
Handle of the models.
. AngleStart (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad(-array) ; VARIANT ( real )
Smallest rotation of the models.
Default Value : -0.39
Suggested values : AngleStart ∈ {-3.14, -1.57, -0.78, -0.39, -0.20, 0.0}
. AngleExtent (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad(-array) ; VARIANT ( real )
Extent of the rotation angles.
Default Value : 0.78
Suggested values : AngleExtent ∈ {6.29, 3.14, 1.57, 0.78, 0.39, 0.0}
Restriction : (AngleExtent ≥ 0)
. MinScore (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Minimum score of the instances of the models to be found.
Default Value : 0.5
Suggested values : MinScore ∈ {0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}
Typical range of values : 0 ≤ MinScore ≤ 0
Minimum Increment : 0.01
Recommended Increment : 0.05
. NumMatches (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Number of instances of the models to be found.
Default Value : 1
Suggested values : NumMatches ∈ {0, 1, 2, 3, 4, 5, 10, 20}

HALCON 8.0.2
644 CHAPTER 7. MATCHING

. MaxOverlap (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )


Maximum overlap of the instances of the models to be found.
Default Value : 0.5
Suggested values : MaxOverlap ∈ {0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}
Typical range of values : 0 ≤ MaxOverlap ≤ 0
Minimum Increment : 0.01
Recommended Increment : 0.05
. SubPixel (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Subpixel accuracy if not equal to ’none’.
Default Value : ’least_squares’
List of values : SubPixel ∈ {’none’, ’interpolation’, ’least_squares’, ’least_squares_high’,
’least_squares_very_high’}
. NumLevels (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Number of pyramid levels used in the matching (and lowest pyramid level to use if |NumLevels| = 2).
Default Value : 0
List of values : NumLevels ∈ {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
. Greediness (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
“Greediness” of the search heuristic (0: safe but slow; 1: fast but matches may be missed).
Default Value : 0.9
Suggested values : Greediness ∈ {0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}
Typical range of values : 0 ≤ Greediness ≤ 0
Minimum Increment : 0.01
Recommended Increment : 0.05
. Row (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; VARIANT ( real )
Row coordinate of the found instances of the models.
. Column (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; VARIANT ( real )
Column coordinate of the found instances of the models.
. Angle (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; VARIANT ( real )
Rotation angle of the found instances of the models.
. Score (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Score of the found instances of the models.
. Model (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Index of the found instances of the models.
Result
If the parameter values are correct, the operator FindShapeModels returns the value TRUE.
If the input is empty (no input images are available) the behavior can be set via SetSystem
(’noObjectResult’,<Result>). If necessary, an exception is raised.
Parallelization Information
FindShapeModels is reentrant and processed without parallelization.
Possible Predecessors
AddChannels, CreateShapeModel, ReadShapeModel, SetShapeModelOrigin
Possible Successors
ClearShapeModel
See also
SetSystem, GetSystem
Alternatives
FindScaledShapeModels, FindAnisoShapeModels, FindShapeModel,
FindScaledShapeModel, FindAnisoShapeModel, BestMatchRotMg
Module
Matching

HALCON/COM Reference Manual, 2008-5-13


7.4. SHAPE-BASED 645

[out] HXLDContX ModelContours HShapeModelX.GetShapeModelContours


([in] long Level )
void HOperatorSetX.GetShapeModelContours
([out] HUntypedObjectX ModelContours, [in] VARIANT ModelID,
[in] VARIANT Level )

Return the contour representation of a shape model.


The operator GetShapeModelContours returns a representation of the shape model ModelID as XLD con-
tours in ModelContours. The parameter Level determines for which pyramid level of the model the contour
representation should be returned. The contours can be used, for example, to visualize the found instances of the
model in an image. It should be noted that the position of ModelContours is normalized such that the reference
point of the model (see SetShapeModelOrigin) lies at the pixel position (0, 0). Hence, the contours simply
need to be translated to the found position in the image (and possibly rotated and scaled around this point).
Parameter
. ModelContours (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . xld_cont ; HXLDContX / HUntypedObjectX
Contour representation of the shape model.
. ModelID (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . shape_model ; HShapeModelX / VARIANT
Handle of the model.
. Level (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Pyramid level for which the contour representation should be returned.
Default Value : 1
Suggested values : Level ∈ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Restriction : (Level ≥ 1)
Result
If the handle of the model is valid, the operator GetShapeModelContours returns the value TRUE. If neces-
sary an exception is raised.
Parallelization Information
GetShapeModelContours is reentrant and processed without parallelization.
Possible Predecessors
CreateShapeModel, CreateScaledShapeModel, CreateAnisoShapeModel, ReadShapeModel
See also
FindShapeModel, FindScaledShapeModel, FindAnisoShapeModel, FindShapeModels,
FindScaledShapeModels, FindAnisoShapeModels
Module
Matching

[out] double Row HShapeModelX.GetShapeModelOrigin


([out] double Column )
void HOperatorSetX.GetShapeModelOrigin ([in] VARIANT ModelID,
[out] VARIANT Row, [out] VARIANT Column )

Return the origin (reference point) of a shape model.


The operator GetShapeModelOrigin returns the origin (reference point) of the shape model ModelID. The
origin is specified relative to the center of gravity of the domain (region) of the image that was used to create the
shape model with CreateShapeModel, CreateScaledShapeModel, or CreateAnisoShapeModel.
Hence, an origin of (0,0) means that the center of gravity of the domain of the model image is used as the origin.
An origin of (-20,-40) means that the origin lies to the upper left of the center of gravity.
Parameter
. ModelID (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . shape_model ; HShapeModelX / VARIANT
Handle of the model.
. Row (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; double / VARIANT
Row coordinate of the origin of the shape model.

HALCON 8.0.2
646 CHAPTER 7. MATCHING

. Column (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; double / VARIANT


Column coordinate of the origin of the shape model.
Result
If the handle of the model is valid, the operator GetShapeModelOrigin returns the value TRUE. If necessary
an exception is raised.
Parallelization Information
GetShapeModelOrigin is reentrant and processed without parallelization.
Possible Predecessors
CreateShapeModel, CreateScaledShapeModel, CreateAnisoShapeModel,
ReadShapeModel, SetShapeModelOrigin
Possible Successors
FindShapeModel, FindScaledShapeModel, FindAnisoShapeModel, FindShapeModels,
FindScaledShapeModels, FindAnisoShapeModels
See also
AreaCenter
Module
Matching

[out] long NumLevels HShapeModelX.GetShapeModelParams


([out] double AngleStart, [out] double AngleExtent, [out] double AngleStep,
[out] VARIANT ScaleMin, [out] VARIANT ScaleMax, [out] VARIANT ScaleStep,
[out] String Metric, [out] long MinContrast )
void HOperatorSetX.GetShapeModelParams ([in] VARIANT ModelID,
[out] VARIANT NumLevels, [out] VARIANT AngleStart, [out] VARIANT AngleExtent,
[out] VARIANT AngleStep, [out] VARIANT ScaleMin, [out] VARIANT ScaleMax,
[out] VARIANT ScaleStep, [out] VARIANT Metric, [out] VARIANT MinContrast )

Return the parameters of a shape model.


The operator GetShapeModelParams returns the parameters of the shape model ModelID that were used
to create it using CreateShapeModel, CreateScaledShapeModel, or CreateAnisoShapeModel.
In particular, this output can be used to check the parameters NumLevels, AngleStep, ScaleStep, and
MinContrast if they were determined automatically during the model creation with CreateShapeModel,
CreateScaledShapeModel, or CreateAnisoShapeModel.
If the shape model was created using CreateShapeModel or CreateScaledShapeModel a single value
is returned in ScaleMin, ScaleMax, and ScaleStep. This parameters corresponds to the isotropic scaling
parameters of the shape model. If the shape model was created using CreateAnisoShapeModel two values
each are returned in the above three parameters. Here, the first value of the respective parameter refers to the
scaling in the row direction, while the second value refers to the scaling in the column direction.
Note that the parameters Optimization and Contrast that also can be determined automatically dur-
ing the model creation cannot be queried by using GetShapeModelParams. If their value is of interest
DetermineShapeModelParams should be used instead.
Parameter
. ModelID (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . shape_model ; HShapeModelX / VARIANT
Handle of the model.
. NumLevels (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of pyramid levels.
. AngleStart (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; double / VARIANT
Smallest rotation of the pattern.
. AngleExtent (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; double / VARIANT
Extent of the rotation angles.
Restriction : (AngleExtent ≥ 0)
. AngleStep (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; double / VARIANT
Step length of the angles (resolution).
Restriction : ((AngleStep ≥ 0) ∧ (AngleStep ≤ (pi/16)))

HALCON/COM Reference Manual, 2008-5-13


7.4. SHAPE-BASED 647

. ScaleMin (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( real )


Minimum scale of the pattern.
Restriction : (ScaleM in > 0)
. ScaleMax (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( real )
Maximum scale of the pattern.
Restriction : (ScaleM ax ≥ ScaleM in)
. ScaleStep (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( real )
Scale step length (resolution).
Restriction : (ScaleStep ≥ 0)
. Metric (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Match metric.
. MinContrast (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; long / VARIANT
Minimum contrast of the objects in the search images.
Result
If the handle of the model is valid, the operator GetShapeModelParams returns the value TRUE. If necessary
an exception is raised.
Parallelization Information
GetShapeModelParams is reentrant and processed without parallelization.
Possible Predecessors
CreateShapeModel, CreateScaledShapeModel, CreateAnisoShapeModel, ReadShapeModel
See also
FindShapeModel, FindScaledShapeModel, FindAnisoShapeModel, FindShapeModels,
FindScaledShapeModels, FindAnisoShapeModels
Module
Matching

[out] HImageX ModelImages HImageX.InspectShapeModel


([out] HRegionX ModelRegions, [in] long NumLevels, [in] VARIANT Contrast )
void HOperatorSetX.InspectShapeModel ([in] IHObjectX Image,
[out] HUntypedObjectX ModelImages, [out] HUntypedObjectX ModelRegions,
[in] VARIANT NumLevels, [in] VARIANT Contrast )

Create the representation of a shape model.


InspectShapeModel creates a representation of a shape model. The operator is particularly useful in or-
der to determine the parameters NumLevels and Contrast, which are used in CreateShapeModel,
CreateScaledShapeModel, or CreateAnisoShapeModel, quickly and conveniently. The repre-
sentation of the model is created on multiple image pyramid levels, where the number of levels is de-
termined by NumLevels. In contrast to CreateShapeModel, CreateScaledShapeModel, and
CreateAnisoShapeModel, the model is only created for the rotation and scale of the object in the input
image, i.e., 0◦ and 1. As output, InspectShapeModel creates an image object ModelImages containing
the images of the individual levels of the image pyramid as well as a region in ModelRegions for each pyra-
mid level that represents the model at the respective pyramid level. The individual objects can be accessed with
SelectObj. If the input image Image has one channel the representation of the model is created with the method
that is used in CreateShapeModel, CreateScaledShapeModel or CreateAnisoShapeModel for
the metrics ’use_polarity’, ’ignore_global_polarity’, and ’ignore_local_polarity’. If the input image has more than
one channel the representation is created with the method that is used for the metric ’ignore_color_polarity’. As
described for CreateShapeModel, CreateScaledShapeModel, and CreateAnisoShapeModel,
the number of pyramid levels should be chosen as large as possible, while taking into account that the model must
be recognizable on the highest pyramid level and must have enough model points. The parameter Contrast
should be chosen such that only the significant features of the template object are used for the model. Contrast
can also contain a tuple with two values. In this case, the model is segmented using a method similar to the
hysteresis threshold method used in EdgesImage. Here, the first element of the tuple determines the lower
threshold, while the second element determines the upper threshold. For more information about the hysteresis
threshold method, see HysteresisThreshold. Optionally, Contrast can contain a third value as the last

HALCON 8.0.2
648 CHAPTER 7. MATCHING

element of the tuple. This value determines a threshold for the selection of significant model components based
on the size of the components, i.e., components that have fewer points than the minimum size thus specified are
suppressed. This threshold for the minimum size is divided by two for each successive pyramid level. If small
model components should be suppressed, but hysteresis thresholding should not be performed, nevertheless three
values must be specified in Contrast. In this case, the first two values can simply be set to identical val-
ues. In its typical use, InspectShapeModel is called interactively multiple times with different parameters
for NumLevels and Contrast, until a satisfactory model is obtained. After this, CreateShapeModel,
CreateScaledShapeModel, or CreateAnisoShapeModel are called with the parameters thus obtained.
Parameter
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . (multichannel-)image ; HImageX / IHObjectX ( byte, uint2 )
Input image.
. ModelImages (output iconic) . . . . . . (multichannel-)image ; HImageX / HUntypedObjectX ( byte, uint2 )
Image pyramid of the input image
. ModelRegions (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX
Model region pyramid
. NumLevels (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of pyramid levels.
Default Value : 4
List of values : NumLevels ∈ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
. Contrast (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( integer )
Threshold or hysteresis thresholds for the contrast of the object in the image and optionally minimum size of
the object parts.
Default Value : 30
Suggested values : Contrast ∈ {10, 20, 30, 40, 60, 80, 100, 120, 140, 160}
Result
If the parameters are valid, the operator InspectShapeModel returns the value TRUE. If necessary an excep-
tion is raised.
Parallelization Information
InspectShapeModel is reentrant and processed without parallelization.
Possible Predecessors
ReduceDomain
Possible Successors
SelectObj
See also
CreateShapeModel, CreateScaledShapeModel, CreateAnisoShapeModel
Module
Foundation

void HShapeModelX.ReadShapeModel ([in] String FileName )


void HOperatorSetX.ReadShapeModel ([in] VARIANT FileName,
[out] VARIANT ModelID )

Read a shape model from a file.


The operator ReadShapeModel reads a shape model, which has been written with WriteShapeModel, from
the file FileName.
Parameter
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.read ; String / VARIANT
File name.
. ModelID (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . shape_model ; HShapeModelX / VARIANT
Handle of the model.
Result
If the file name is valid, the operator ReadShapeModel returns the value TRUE. If necessary an exception is
raised.

HALCON/COM Reference Manual, 2008-5-13


7.4. SHAPE-BASED 649

Parallelization Information
ReadShapeModel is processed completely exclusively without parallelization.
Possible Successors
FindShapeModel, FindScaledShapeModel, FindAnisoShapeModel, FindShapeModels,
FindScaledShapeModels, FindAnisoShapeModels
See also
CreateShapeModel, CreateScaledShapeModel, CreateAnisoShapeModel,
ClearShapeModel
Module
Matching

void HShapeModelX.SetShapeModelOrigin ([in] double Row,


[in] double Column )
void HOperatorSetX.SetShapeModelOrigin ([in] VARIANT ModelID,
[in] VARIANT Row, [in] VARIANT Column )

Set the origin (reference point) of a shape model.


The operator SetShapeModelOrigin sets the origin (reference point) of the shape model ModelID to
a new value. The origin is specified relative to the center of gravity of the domain (region) of the image
that was used to create the shape model with CreateShapeModel, CreateScaledShapeModel, or
CreateAnisoShapeModel. Hence, an origin of (0,0) means that the center of gravity of the domain of the
model image is used as the origin. An origin of (-20,-40) means that the origin lies to the upper left of the center
of gravity.
Parameter

. ModelID (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . shape_model ; HShapeModelX / VARIANT


Handle of the model.
. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; double / VARIANT
Row coordinate of the origin of the shape model.
. Column (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; double / VARIANT
Column coordinate of the origin of the shape model.
Result
If the handle of the model is valid, the operator SetShapeModelOrigin returns the value TRUE. If necessary
an exception is raised.
Parallelization Information
SetShapeModelOrigin is processed completely exclusively without parallelization.
Possible Predecessors
CreateShapeModel, CreateScaledShapeModel, CreateAnisoShapeModel, ReadShapeModel
Possible Successors
FindShapeModel, FindScaledShapeModel, FindAnisoShapeModel, FindShapeModels,
FindScaledShapeModels, FindAnisoShapeModels, GetShapeModelOrigin
See also
AreaCenter
Module
Matching

void HShapeModelX.WriteShapeModel ([in] String FileName )


void HOperatorSetX.WriteShapeModel ([in] VARIANT ModelID,
[in] VARIANT FileName )

Write a shape model to a file.

HALCON 8.0.2
650 CHAPTER 7. MATCHING

The operator WriteShapeModel writes a shape model to the file FileName. The model can be read again
with ReadShapeModel.
Parameter

. ModelID (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . shape_model ; HShapeModelX / VARIANT


Handle of the model.
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.write ; String / VARIANT
File name.
Result
If the file name is valid (write permission), the operator WriteShapeModel returns the value TRUE. If neces-
sary an exception is raised.
Parallelization Information
WriteShapeModel is reentrant and processed without parallelization.
Possible Predecessors
CreateShapeModel, CreateScaledShapeModel, CreateAnisoShapeModel
Module
Matching

HALCON/COM Reference Manual, 2008-5-13


Chapter 8

Matching-3D

void HObjectModel3DX.AffineTransObjectModel3D
([in] HHomMat3dX HomMat3D, [out] long ObjectModel3DIDAffineTrans )
void HOperatorSetX.AffineTransObjectModel3D
([in] VARIANT ObjectModel3DID, [in] VARIANT HomMat3D,
[out] VARIANT ObjectModel3DIDAffineTrans )

Apply an arbitrary affine 3D transformation to a 3D object model.


AffineTransObjectModel3D applies an arbitrary affine 3D transformation, i.e., scaling, rotation, and trans-
lation, to a 3D object model and returns the handle of the transformed 3D object model. The affine transformation
is described by the homogeneous transformation matrix given in HomMat3D.
The transformation matrix can be created using the operators HomMat3dIdentity, HomMat3dScale,
HomMat3dRotate, HomMat3dTranslate, etc., or be the result of PoseToHomMat3d (see
AffineTransPoint3D).
In general, the operator AffineTransObjectModel3D is not necessary in the context of 3D matching. If
a rotation of the 3D object model into a reference orientation should be performed, instead appropriate values
for the parameters RefRotX, RefRotY, RefRotZ, and OrderOfRotation should be passed to the operator
CreateShapeModel3D.
Parameter

. ObjectModel3DID (input control) . . . . . . . . . . . . . . . . object_model_3d ; HObjectModel3DX / VARIANT


Handle of the 3D object model.
. HomMat3D (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . hom_mat3d ; HHomMat3dX / VARIANT ( real )
Transformation matrix.
. ObjectModel3DIDAffineTrans (output control) . . . . . . . . . . . . . . . . . . . . . . number ; long / VARIANT
Handle of the transformed 3D object model.
Result
AffineTransObjectModel3D returns TRUE if all parameters are correct. If necessary, an exception is raised.
Parallelization Information
AffineTransObjectModel3D is processed completely exclusively without parallelization.
Possible Predecessors
ReadObjectModel3DDxf
Possible Successors
ProjectObjectModel3D
See also
AffineTransPoint3D
Module
3D Metrology

651
652 CHAPTER 8. MATCHING-3D

void HMiscX.ClearAllObjectModel3D ( )
void HOperatorSetX.ClearAllObjectModel3D ( )

Free the memory of all 3D object models.


The operator ClearAllObjectModel3D frees the memory of all 3D object models that were created by
ReadObjectModel3DDxf. After calling ClearAllObjectModel3D, no model can be used any longer.
Attention
ClearAllObjectModel3D exists solely for the purpose of implementing the “reset program” functionality in
HDevelop. ClearAllObjectModel3D must not be used in any application.
Result
ClearAllObjectModel3D always returns TRUE.
Parallelization Information
ClearAllObjectModel3D is processed completely exclusively without parallelization.
Possible Predecessors
ReadObjectModel3DDxf
Alternatives
ClearObjectModel3D
Module
3D Metrology

void HMiscX.ClearAllShapeModel3D ( )
void HOperatorSetX.ClearAllShapeModel3D ( )

Free the memory of all 3D shape models.


The operator ClearAllShapeModel3D frees the memory of all 3D shape models that were created by
CreateShapeModel3D. After calling ClearAllShapeModel3D, no model can be used any longer.
Attention
ClearAllShapeModel3D exists solely for the purpose of implementing the “reset program” functionality in
HDevelop. ClearAllShapeModel3D must not be used in any application.
Result
ClearAllShapeModel3D always returns TRUE.
Parallelization Information
ClearAllShapeModel3D is processed completely exclusively without parallelization.
Possible Predecessors
CreateShapeModel3D, ReadShapeModel3D, WriteShapeModel3D
Alternatives
ClearShapeModel3D
Module
3D Metrology

void HOperatorSetX.ClearObjectModel3D ([in] VARIANT ObjectModel3DID )

Free the memory of a 3D object model.


The operator ClearObjectModel3D frees the memory of a 3D object model that was created by
ReadObjectModel3DDxf. After calling ClearObjectModel3D, the model can no longer be used. The
handle ObjectModel3DID becomes invalid.

HALCON/COM Reference Manual, 2008-5-13


653

Parameter

. ObjectModel3DID (input control) . . . . . . . . . . . . . . . . object_model_3d ; HObjectModel3DX / VARIANT


Handle of the 3D object model.
Result
If the handle of the model is valid, the operator ClearObjectModel3D returns the value TRUE. If necessary
an exception is raised.
Parallelization Information
ClearObjectModel3D is processed completely exclusively without parallelization.
Possible Predecessors
ReadObjectModel3DDxf
See also
ClearAllObjectModel3D
Module
3D Metrology

void HOperatorSetX.ClearShapeModel3D ([in] VARIANT ShapeModel3DID )

Free the memory of a 3D shape model.


The operator ClearShapeModel3D frees the memory of a 3D shape model that was created by
CreateShapeModel3D. After calling ClearShapeModel3D, the model can no longer be used. The handle
ShapeModel3DID becomes invalid.
Parameter

. ShapeModel3DID (input control) . . . . . . . . . . . . . . . . . . shape_model_3d ; HShapeModel3DX / VARIANT


Handle of the 3D shape model.
Result
If the handle of the model is valid, the operator ClearShapeModel3D returns the value TRUE. If necessary an
exception is raised.
Parallelization Information
ClearShapeModel3D is processed completely exclusively without parallelization.
Possible Predecessors
CreateShapeModel3D, ReadShapeModel3D, WriteShapeModel3D
See also
ClearAllShapeModel3D
Module
3D Metrology

[out] VARIANT Longitude HMiscX.ConvertPoint3DCartToSpher


([in] VARIANT X, [in] VARIANT Y, [in] VARIANT Z, [in] String EquatPlaneNormal,
[in] String ZeroMeridian, [out] VARIANT Latitude, [out] VARIANT Radius )
void HOperatorSetX.ConvertPoint3DCartToSpher ([in] VARIANT X,
[in] VARIANT Y, [in] VARIANT Z, [in] VARIANT EquatPlaneNormal,
[in] VARIANT ZeroMeridian, [out] VARIANT Longitude, [out] VARIANT Latitude,
[out] VARIANT Radius )

Convert Cartesian coordinates of a 3D point to spherical coordinates.


The operator ConvertPoint3DCartToSpher converts Cartesian coordinates of a 3D point, which are given
in X, Y, and Z, into spherical coordinates. The spherical coordinates are returned in Longitude, Latitude,
and Radius. The Longitude is returned in the range [−π, +π] while the Latitude is returned in the range
[−π/2, +π/2]. Furthermore, the latitude of the north pole is π/2, and hence, the latitude of the south pole is −π/2.

HALCON 8.0.2
654 CHAPTER 8. MATCHING-3D

The orientation of the spherical coordinate system with respect to the Cartesian coordinate system can be specified
with the parameters EquatPlaneNormal and ZeroMeridian.
EquatPlaneNormal determines the normal of the equatorial plane (longitude == 0) pointing to the north pole
(positive latitude) and may take the following values:

’x’: The equatorial plane is the yz plane. The positive x axis points to the north pole.
’-x’: The equatorial plane is the yz plane. The positive x axis points to the south pole.
’y’: The equatorial plane is the xz plane. The positive y axis points to the north pole.
’-y’: The equatorial plane is the xz plane. The positive y axis points to the south pole.
’z’: The equatorial plane is the xy plane. The positive z axis points to the north pole.
’-z’: The equatorial plane is the xy plane. The positive z axis points to the south pole.

The position of the zero meridian can be specified with the parameter ZeroMeridian. For this, the coordinate
axis (lying in the equatorial plane) that points to the zero meridian must be passed. The following values for
ZeroMeridian are valid:

’x’: The positive x axis points in the direction of the zero meridian.
’-x’: The negative x axis points in the direction of the zero meridian.
’y’: The positive y axis points in the direction of the zero meridian.
’-y’: The negative y axis points in the direction of the zero meridian.
’z’: The positive z axis points in the direction of the zero meridian.
’-z’: The negative z axis points in the direction of the zero meridian.

Only reasonable combinations of EquatPlaneNormal and ZeroMeridian are permitted, i.e., the normal
of the equatorial plane must not be parallel to the direction of the zero meridian. For example, the combination
EquatPlaneNormal=’y’ and ZeroMeridian=’-y’ is not permitted.
Note that in order to guarantee a consistent conversion back from spherical to Cartesian coordinates by us-
ing ConvertPoint3DSpherToCart, the same values must be passed for EquatPlaneNormal and
ZeroMeridian as were passed to ConvertPoint3DCartToSpher.
The operator ConvertPoint3DCartToSpher can be used, for example, to convert a given camera position
into spherical coordinates. If multiple camera positions are converted in this way, one obtains a pose range (in
spherical coordinates), which can be passed to CreateShapeModel3D in order to create a 3D shape model.
Parameter

. X (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )


X coordinate of the 3D point.
. Y (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Y coordinate of the 3D point.
. Z (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Z coordinate of the 3D point.
. EquatPlaneNormal (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Normal vector of the equatorial plane (points to the north pole).
Default Value : -y
List of values : EquatPlaneNormal ∈ {’x’, ’y’, ’z’, -x, -y, -z}
. ZeroMeridian (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Coordinate axis in the equatorial plane that points to the zero meridian.
Default Value : -z
List of values : ZeroMeridian ∈ {’x’, ’y’, ’z’, -x, -y, -z}
. Longitude (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad(-array) ; VARIANT ( real )
Longitude of the 3D point.
. Latitude (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad(-array) ; VARIANT ( real )
Latitude of the 3D point.
. Radius (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Radius of the 3D point.

HALCON/COM Reference Manual, 2008-5-13


655

Result
If the parameters are valid, the operator ConvertPoint3DCartToSpher returns the value TRUE. If necessary
an exception is raised.
Parallelization Information
ConvertPoint3DCartToSpher is reentrant and processed without parallelization.
Possible Successors
CreateShapeModel3D, FindShapeModel3D
See also
ConvertPoint3DSpherToCart
Module
3D Metrology

[out] VARIANT X HMiscX.ConvertPoint3DSpherToCart


([in] VARIANT Longitude, [in] VARIANT Latitude, [in] VARIANT Radius,
[in] String EquatPlaneNormal, [in] String ZeroMeridian, [out] VARIANT Y,
[out] VARIANT Z )
void HOperatorSetX.ConvertPoint3DSpherToCart
([in] VARIANT Longitude, [in] VARIANT Latitude, [in] VARIANT Radius,
[in] VARIANT EquatPlaneNormal, [in] VARIANT ZeroMeridian, [out] VARIANT X,
[out] VARIANT Y, [out] VARIANT Z )

Convert spherical coordinates of a 3D point to Cartesian coordinates.


The operator ConvertPoint3DSpherToCart converts the spherical coordinates of a 3D point, which are
given in Longitude, Latitude, and Radius, into the Cartesian coordinates X, Y, and Z. The spherical coor-
dinates Longitude and Latitude must be specified in radians. Furthermore, the Latitude must be within
the range [−π/2, +π/2], where the latitude of the north pole is π/2, and hence, the latitude of the south pole is
−π/2.
The orientation of the spherical coordinate system with respect to the Cartesian coordinate system can be specified
with the parameters EquatPlaneNormal and ZeroMeridian.
EquatPlaneNormal determines the normal of the equatorial plane (longitude == 0) pointing to the north pole
(positive latitude) and may take the following values:

’x’: The equatorial plane is the yz plane. The positive x axis points to the north pole.
’-x’: The equatorial plane is the yz plane. The positive x axis points to the south pole.
’y’: The equatorial plane is the xz plane. The positive y axis points to the north pole.
’-y’: The equatorial plane is the xz plane. The positive y axis points to the south pole.
’z’: The equatorial plane is the xy plane. The positive z axis points to the north pole.
’-z’: The equatorial plane is the xy plane. The positive z axis points to the south pole.

The position of the zero meridian can be specified with the parameter ZeroMeridian. For this, the coordinate
axis (lying in the equatorial plane) that points to the zero meridian must be passed. The following values for
ZeroMeridian are valid:

’x’: The positive x axis points in the direction of the zero meridian.
’-x’: The negative x axis points in the direction of the zero meridian.
’y’: The positive y axis points in the direction of the zero meridian.
’-y’: The negative y axis points in the direction of the zero meridian.
’z’: The positive z axis points in the direction of the zero meridian.
’-z’: The negative z axis points in the direction of the zero meridian.

HALCON 8.0.2
656 CHAPTER 8. MATCHING-3D

Only reasonable combinations of EquatPlaneNormal and ZeroMeridian are permitted, i.e., the normal
of the equatorial plane must not be parallel to the direction of the zero meridian. For example, the combination
EquatPlaneNormal=’y’ and ZeroMeridian=’-y’ is not permitted.
Note that in order to guarantee a consistent conversion back from Cartesian to spherical coordinates by us-
ing ConvertPoint3DCartToSpher, the same values must be passed for EquatPlaneNormal and
ZeroMeridian as were passed to ConvertPoint3DSpherToCart.
The operator ConvertPoint3DSpherToCart can be used, for example, to convert a camera position that
is given in spherical coordinates into Cartesian coordinates. The result can then be utilized to create a complete
camera pose by passing the Cartesian coordinates to CreateCamPoseLookAtPoint.
Parameter
. Longitude (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad(-array) ; VARIANT ( real )
Longitude of the 3D point.
. Latitude (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad(-array) ; VARIANT ( real )
Latitude of the 3D point.
Restriction : (((−(pi)/2) ≤ Latitude) ∧ (Latitude ≤ (pi/2)))
. Radius (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .real(-array) ; VARIANT ( real )
Radius of the 3D point.
. EquatPlaneNormal (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Normal vector of the equatorial plane (points to the north pole).
Default Value : -y
List of values : EquatPlaneNormal ∈ {’x’, ’y’, ’z’, -x, -y, -z}
. ZeroMeridian (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Coordinate axis in the equatorial plane that points to the zero meridian.
Default Value : -z
List of values : ZeroMeridian ∈ {’x’, ’y’, ’z’, -x, -y, -z}
. X (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
X coordinate of the 3D point.
. Y (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Y coordinate of the 3D point.
. Z (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Z coordinate of the 3D point.
Result
If the parameters are valid, the operator ConvertPoint3DSpherToCart returns the value TRUE. If necessary
an exception is raised.
Parallelization Information
ConvertPoint3DSpherToCart is reentrant and processed without parallelization.
Possible Predecessors
GetShapeModel3DParams
See also
ConvertPoint3DCartToSpher
Module
3D Metrology

[out] VARIANT CamPose HPoseX.CreateCamPoseLookAtPoint


([in] VARIANT CamPosX, [in] VARIANT CamPosY, [in] VARIANT CamPosZ,
[in] VARIANT LookAtX, [in] VARIANT LookAtY, [in] VARIANT LookAtZ,
[in] VARIANT RefPlaneNormal, [in] VARIANT CamRoll )
void HOperatorSetX.CreateCamPoseLookAtPoint ([in] VARIANT CamPosX,
[in] VARIANT CamPosY, [in] VARIANT CamPosZ, [in] VARIANT LookAtX,
[in] VARIANT LookAtY, [in] VARIANT LookAtZ, [in] VARIANT RefPlaneNormal,
[in] VARIANT CamRoll, [out] VARIANT CamPose )

Create a 3D camera pose from camera center and viewing direction.

HALCON/COM Reference Manual, 2008-5-13


657

The operator CreateCamPoseLookAtPoint creates a 3D camera pose with respect to a world coordinate
system based on two points and the camera roll angle.
The first of the two points defines the position of the optical center of the camera in the world coordinate system,
i.e., the origin of the camera coordinate system. It is given by its three coordinates CamPosX, CamPosY, and
CamPosZ. The second of the two points defines the viewing direction of the camera. It represents the point in the
world coordinate system at which the camera is to look. It is also specified by its three coordinates LookAtX,
LookAtY, and LookAtZ. Consequently, the second point lies on the z axis of the camera coordinate system.
Finally, the remaining degree of freedom to be specified is a rotation of the camera around its z axis, i.e.,
the roll angle of the camera. To determine this rotation, the normal of a reference plane can be specified in
RefPlaneNormal, which defines the reference orientation of the camera. Finally, the camera roll angle can
be specified in CamRoll, which describes a rotation of the camera around its z axis with respect to its reference
orientation.
The reference plane can be seen as a plane in the world coordinate system that is parallel to the x axis of the
camera (in its reference orientation, i.e., with a roll angle of 0). In an alternative interpretation, the normal vector
of the reference plane projected onto the image plane points upwards, i.e., it is mapped to the negative y axis of the
camera coordinate system. The parameter RefPlaneNormal may take one of the following values:

’x’: The reference plane is the yz plane of the world coordinate system. The projected x axis of the world coordi-
nate system points upwards in the image plane.
’-x’: The reference plane is the yz plane of the world coordinate system. The projected x axis of the world
coordinate system points downwards in the image plane.
’y’: The reference plane is the xz plane of the world coordinate system. The projected y axis of the world coordi-
nate system points upwards in the image plane.
’-y’: The reference plane is the xz plane of the world coordinate system. The projected y axis of the world
coordinate system points downwards in the image plane.
’z’: The reference plane is the xy plane of the world coordinate system. The projected z axis of the world coordi-
nate system points upwards in the image plane.
’-z’: The reference plane is the xy plane of the world coordinate system. The projected z axis of the world
coordinate system points downwards in the image plane.

Alternatively to the above values, an arbitrary normal vector can be specified in RefPlaneNormal, which is not
restricted to the coordinate axes. For this, a tuple of three values representing the three components of the normal
vector must be passed.
Note that the position of the optical center and the point at which the camera looks must differ from each other.
Furthermore, the normal vector of the reference plane and the z axis of the camera must not be parallel. Otherwise,
the camera pose is not well-defined.
CreateCamPoseLookAtPoint is particularly useful if a 3D object model or a 3D shape model should be visu-
alized from a certain camera position. In this case, the pose that is created by CreateCamPoseLookAtPoint
can be passed to ProjectObjectModel3D or ProjectShapeModel3D, respectively.
It is also possible to pass tuples of different length for different input parameters. In this case, internally the
maximum number of parameter values over all input control parameters is computed. This number is taken as
the number of output camera poses. Then, all input parameters can contain a single value or the same number of
values as output camera poses. In the first case, the single value is used for the computation of all camera poses,
while in the second case the respective value of the element in the parameter is used for the computation of the
corresponding camera pose.
Parameter

. CamPosX (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )


X coordinate of the optical center of the camera.
. CamPosY (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Y coordinate of the optical center of the camera.
. CamPosZ (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Z coordinate of the optical center of the camera.
. LookAtX (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
X coordinate of the 3D point to which the camera is directed.

HALCON 8.0.2
658 CHAPTER 8. MATCHING-3D

. LookAtY (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )


Y coordinate of the 3D point to which the camera is directed.
. LookAtZ (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Z coordinate of the 3D point to which the camera is directed.
. RefPlaneNormal (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . .string(-array) ; VARIANT ( string, real )
Normal vector of the reference plane (points up).
Default Value : -y
List of values : RefPlaneNormal ∈ {’x’, ’y’, ’z’, -x, -y, -z}
. CamRoll (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad(-array) ; VARIANT ( real )
Camera roll angle.
Default Value : 0
. CamPose (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pose ; VARIANT ( integer, real )
3D camera pose.
Result
If the parameters are valid, the operator CreateCamPoseLookAtPoint returns the value TRUE. If necessary
an exception is raised. If the parameters are chosen such that the pose is not well defined, the error 8940 is raised.
Parallelization Information
CreateCamPoseLookAtPoint is reentrant and processed without parallelization.
Possible Predecessors
ConvertPoint3DSpherToCart
Alternatives
CreatePose
Module
3D Metrology

void HShapeModel3DX.CreateShapeModel3D
([in] HObjectModel3DX ObjectModel3DID, [in] VARIANT CamParam,
[in] double RefRotX, [in] double RefRotY, [in] double RefRotZ,
[in] String OrderOfRotation, [in] double LongitudeMin,
[in] double LongitudeMax, [in] double LatitudeMin, [in] double LatitudeMax,
[in] double CamRollMin, [in] double CamRollMax, [in] double DistMin,
[in] double DistMax, [in] long MinContrast, [in] VARIANT GenParamNames,
[in] VARIANT GenParamValues )
void HOperatorSetX.CreateShapeModel3D ([in] VARIANT ObjectModel3DID,
[in] VARIANT CamParam, [in] VARIANT RefRotX, [in] VARIANT RefRotY,
[in] VARIANT RefRotZ, [in] VARIANT OrderOfRotation,
[in] VARIANT LongitudeMin, [in] VARIANT LongitudeMax,
[in] VARIANT LatitudeMin, [in] VARIANT LatitudeMax, [in] VARIANT CamRollMin,
[in] VARIANT CamRollMax, [in] VARIANT DistMin, [in] VARIANT DistMax,
[in] VARIANT MinContrast, [in] VARIANT GenParamNames,
[in] VARIANT GenParamValues, [out] VARIANT ShapeModel3DID )

Prepare a 3D object model for matching.


The operator CreateShapeModel3D prepares a 3D object model, which is passed in ObjectModel3DID,
as a 3D shape model used for matching. The 3D object model must previously been read from a file by using
ReadObjectModel3DDxf.
The 3D shape model is generated by computing different views of the 3D object model within a user-specified
pose range. The views are automatically generated by placing virtual cameras around the 3D object model and
projecting the 3D object model into the image plane of each virtual camera position. For each such obtained view
a 2D shape representation is computed. Thus, for the generation of the 3D shape model, no images of the object
are used but only the 3D object model, which is passed in ObjectModel3DID. The shape representations of all
views are stored in the 3D shape model, which is returned in ShapeModel3DID. During the matching process
with FindShapeModel3D, the shape representations are used to find out the best-matching view, from which
the pose is subsequently refined and returned.

HALCON/COM Reference Manual, 2008-5-13


659

In order to create the model views correctly, the camera parameters of the camera that will be used for the matching
must be passed in CamParam. The camera parameters are necessary, for example, to determine the scale of the
projections by using the actual focal length of the camera. Futhermore, they are used to treat radial distortions of the
lens correctly. Consequently, it is essential to calibrate the camera by using CameraCalibration before creat-
ing the 3D shape model. On the one hand, this is necessary to obtain accurate poses from FindShapeModel3D.
On the other hand, this makes the 3D matching applicable even when using lenses with significant radial distor-
tions.
The pose range within which the model views are generated can be specified by the parameters RefRotX,
RefRotY, RefRotZ, OrderOfRotation, LongitudeMin, LongitudeMax, LatitudeMin,
LatitudeMax, CamRollMin, CamRollMax, DistMin, and DistMax. Note that the model will
only be recognized during the matching if it appears within the specified pose range. The parameters are described
in the following:
Before computing the views, the origin of the coordinate system of the 3D object model is moved to the ref-
erence point of the 3D object model, which is the center of the smallest enclosing axis-parallel cuboid and can
be queried by using GetObjectModel3DParams. The virtual cameras, which are used to create the views,
are arranged around the 3D object model in such a way that they all look at the origin of the coordinate system,
i.e., the z axes of the cameras pass through the origin. The pose range can then be specified by restricting the
views to a certain quadrilateral on the sphere around the origin. This naturally leads to the use of the spheri-
cal coordinates longitude, latitude, and radius. The definition of the spherical coordinate system is chosen such
that the equatorial plane corresponds to the xz plane of the Cartesian coordinate system with the y axis pointing
to the south pole (negative latitude) and the negative z axis pointing in the direction of the zero meridian (see
ConvertPoint3DSpherToCart or ConvertPoint3DCartToSpher for further details about the con-
version between Cartesian and spherical coordinates). The advantage of this definition is that a camera with the
pose [0,0,z,0,0,0,0] has its optical center at longitude=0, latitude=0, and radius=z. In this case, the radius represents
the distance of the optical center of the camera to the reference point of the 3D object model.
The longitude range, for which views are to be generated, can be specified by LongitudeMin and
LongitudeMax, both given in radians. Accordingly, the latitude range can be specified by LatitudeMin
and LatitudeMax, also given in radians. The minimum and maximum distance between the camera cen-
ter and the model reference point is specified by DistMin and DistMax. Note that the unit of the distance
must be meters (assuming that the parameter Scale has been correctly set when reading the DXF file with
ReadObjectModel3DDxf). Finally, the minimum and the maximum camera roll angle can be specified in
CamRollMin and CamRollMax. This interval specifies the allowable camera rotation around its z axis with
respect to the 3D object model. If the image plane is parallel to the plane on which the objects reside and if it is
known that the object may rotate in this plane only in a restricted range, then it is reasonable to specify this range
in CamRollMin and CamRollMax. In all other cases the interpretation of the camera roll angle is difficult, and
hence, it is recommended to set this interval to [−π, +π]. Note that the larger the specified pose range is chosen
the more memory the model will consume (except from the range of the camera roll angle) and the slower the
matching will be.
The orientation of the coordinate system of the 3D object model is defined by the coordinates within the DXF
file that was read by using ReadObjectModel3DDxf. Therefore, it is reasonable to previously rotate the 3D
object model into a reference orientation such that the view that corresponds to longitude=0 and latitude=0 is ap-
proximately at the center of the pose range. This can be achieved by passing appropriate values for the reference
orientation in RefRotX, RefRotY, RefRotZ, and OrderOfRotation. The rotation is performed around the
axes of the 3D object model, which origin was set to the reference point. The longitude and latitude range can then
be interpreted as a variation of the 3D object model pose around the reference orientation. There are two possible
ways to specify the reference orientation. The first possibility is to specify three rotation angles in RefRotX,
RefRotY, and RefRotZ and the order in which the three rotations are to be applied in OrderOfRotation,
which can either be ’gba’ or ’abg’. The second possibility is to specify the three components of the Rodriguez
rotation vector in RefRotX, RefRotY, and RefRotZ. In this case, OrderOfRotation must be set to ’ro-
driguez’ (see CreatePose for detailed information about the order of the rotations and the definition of the
Rodriguez vector).
Thus, two transformations are applied to the 3D object model before computing the model views within the pose
range. The first transformation is the translation of the origin of the coordinate systems to the reference point. The
second transformation is the rotation of the 3D object model to the desired reference orientation around the axes
of the reference coordinate system. By combining both transformations one obtains the reference pose of the 3D
shape model. The reference pose of the 3D shape model thus describes the pose of the reference coordinate system
with respect to the coordinate system of the 3D object model defined by the DXF file. Let t = (x, y, z)0 be the
coordinates of the reference point of the 3D object model and R be the rotation matrix containing the reference

HALCON 8.0.2
660 CHAPTER 8. MATCHING-3D

orientation. Then, a point pm given in the 3D object model coordinate system can be transformed to a point pr in
the reference coordinate system of the 3D shape model by applying the following formula:
pr = R · (pm − t)
This transformation can be expressed by a homogeneous 3D transformation matrix or alternatively in terms of a 3D
pose. The latter can be queried by passing ’reference_pose’ for the parameter GenParamNames of the operator
GetShapeModel3DParams. The above formula can be best imagined as a pose of pose type 8, 10, or 12,
depending on the value that was chosen for OrderOfRotation (see CreatePose for detailed information
about the different pose types). Note, however, that GetShapeModel3DParams always returns the pose using
the pose type 0. Finally, poses that are given in one of the two coordinate systems can be transformed to the other
coordinate system by using TransPoseShapeModel3D.
With MinContrast, it can be determined which edge contrast the model must at least have in the recognition
performed by FindShapeModel3D. In other words, this parameter separates the model from the noise in the
image. Therefore, a good choice is the range of gray value changes caused by the noise in the image. If, for
example, the gray values fluctuate within a range of 10 gray levels, MinContrast should be set to 10. If
multichannel images are used for the search images, the noise in one channel must be multiplied by the square root
of the number of channels to determine MinContrast. If, for example, the gray values fluctuate within a range
of 10 gray levels in a single channel and the image is a three-channel image, MinContrast should be set to 17.
If the model should be recognized in very low contrast images, MinContrast must be set to a correspondingly
small value. If the model should be recognized even if it is severely occluded, MinContrast should be slightly
larger than the range of gray value fluctuations created by noise in order to ensure that the pose of the model is
extracted robustly and accurately by FindShapeModel3D.
The parameters described above are application-dependent and must be always specified when creating a 3D
shape model. In addition, there are some generic parameters that can optionally be used to influence the model
creation. For most applications these parameters need not to be specified but can be left at their default values.
If desired, these parameters and their corresponding values can be specified by using GenParamNames and
GenParamValues, respectively. The following values for GenParamNames are possible:

’num_levels’: For efficiency reasons the model views are generated on multiple pyramid levels. On higher levels
fewer views are generated than on lower levels. With the parameter ’num_levels’ the number of pyramid
levels on which model views are generated can be specified. It should be chosen as large as possible because
by this the time necessary to find the model is significantly reduced. On the other hand, the number of
levels must be chosen such that the shape representations of the views on the highest pyramid level are
still recognizable and contain a sufficient number of points (at least four). If not enough model points are
generated for a certain view, the view is deleted from the model and replaced by a view on a lower pyramid
level. If for all views on a pyramid level not enough model points are generated, the number of levels is
reduced internally until for at least one view enough model points are found on the highest pyramid level. If
this procedure would lead to a model with no pyramid levels, i.e., if the number of model points is too small
for all views already on the lowest pyramid level, CreateShapeModel3D returns an error message. If
’num_levels’ is set to ’auto’ (default value), CreateShapeModel3D determines the number of pyramid
levels automatically. In this case all model views on all pyramid levels are automatically checked whether
their shape representations are still recognizable. If the shape representation of a certain view is found to
be not recognizable, the view is deleted from the model and replaced by a view on a lower pyramid level.
Note that if ’num_levels’ is set to ’auto’, the number of pyramid levels can be different for different views.
In rare cases, it might happen that CreateShapeModel3D determines a value for the number of pyramid
levels that is too large or too small. If the number of pyramid levels is chosen too large, the model may
not be recognized in the image or it may be necessary to select very low parameters for MinScore or
Greediness in FindShapeModel3D in order to find the model. If the number of pyramid levels is
chosen too small, the time required to find the model in FindShapeModel3D may increase. In these cases,
the views on the pyramid levels should be checked by using the output of GetShapeModel3DContours.
Suggested values: ’auto’, 3, 4, 5, 6
Default value: ’auto’
’optimization’: For models with particularly large model views, it may be useful to reduce the number of model
points by setting ’optimization’ to a value different from ’none’. If ’optimization’ = ’none’, all model points
are stored. In all other cases, the number of points is reduced according to the value of ’optimization’.
If the number of points is reduced, it may be necessary in FindShapeModel3D to set the parame-
ter Greediness to a smaller value, e.g., 0.7 or 0.8. For models with small model views, the reduction
of the number of model points does not result in a speed-up of the search because in this case usually
significantly more potential instances of the model must be examined. If ’optimization’ is set to ’auto’,

HALCON/COM Reference Manual, 2008-5-13


661

CreateShapeModel3D automatically determines the reduction of the number of model points for each
model view.
List of values: ’auto’, ’none’, ’point_reduction_low’, ’point_reduction_medium’, ’point_reduction_high’
Default value: ’auto’
’metric’: This parameter determines the conditions under which the model is recognized in the image. Cur-
rently, only the metric ’ignore_segment_polarity’ is supported, which recognizes an object even if the con-
trast changes locally.
List of values: ’ignore_segment_polarity’
’min_face_angle’: 3D edges are only included in the shape representations of the views if the angle between
the two 3D faces that are incident with the 3D object model edge is at least ’min_face_angle’. If
’min_face_angle’ is set to 0.0, all edges are included. If ’min_face_angle’ is set to π (equivalent to 180
degrees), only the silhouette of the 3D object model is included. This parameter can be used to suppress
edges within curved surfaces, e.g., the surface of a cylinder or cone. Curved surfaces are approximated by
multiple planar faces. The edges between such neighboring planar faces should not be included in the shape
representation because they also do not appear in real images of the model. Thus, ’min_face_angle’ should
be set sufficiently high to suppress these edges. The effect of different values for ’min_face_angle’ can be in-
spected by using ProjectObjectModel3D before calling CreateShapeModel3D. Note that if edges
that are not visible in the search image are included in the shape representation, the performance (robustness
and speed) of the matching may decrease considerably.
Suggested values: rad(10), rad(20), rad(30), rad(45)
Default value: rad(15)
’min_size’: This value determines a threshold for the selection of significant model components based on the size
of the components, i.e., connected components that have fewer points than the specified minimum size are
suppressed. This threshold for the minimum size is divided by two for each successive pyramid level.
Suggested values: ’auto’, 0, 3, 5, 10, 20
Default value: ’auto’
’model_tolerance’: The parameter specifies the tolerance of the projected 3D object model edges in the image,
given in pixels. The higher the value is chosen, the fewer views need to be generated. Consequently, a higher
value results in models that are less memory consuming and faster to find with FindShapeModel3D. On
the other hand, if the value is chosen too high, the robustness of the matching will decrease. Therefore, this
parameter should only be modified with care. For most applications, a good compromise between speed and
robustness is obtained when setting ’model_tolerance’ to 1.
Suggested values: 0, 1, 2
Default value: 1

Parameter

. ObjectModel3DID (input control) . . . . . . . . . . . . . . . . object_model_3d ; HObjectModel3DX / VARIANT


Handle of the 3D object model.
. CamParam (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Interior camera parameters.
Number of elements : (CamP aram = 8)
. RefRotX (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; double / VARIANT
Reference orientation: Rotation around x-axis or x component of the Rodriguez vector (in radians or without
unit).
Default Value : 0
Suggested values : RefRotX ∈ {-1.57, -0.78, -0.17, 0., 0.17, 0.78, 1.57}
. RefRotY (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; double / VARIANT
Reference orientation: Rotation around y-axis or y component of the Rodriguez vector (in radians or without
unit).
Default Value : 0
Suggested values : RefRotY ∈ {-1.57, -0.78, -0.17, 0., 0.17, 0.78, 1.57}
. RefRotZ (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; double / VARIANT
Reference orientation: Rotation around z-axis or z component of the Rodriguez vector (in radians or without
unit).
Default Value : 0
Suggested values : RefRotZ ∈ {-1.57, -0.78, -0.17, 0., 0.17, 0.78, 1.57}

HALCON 8.0.2
662 CHAPTER 8. MATCHING-3D

. OrderOfRotation (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT


Meaning of the rotation values of the reference orientation.
Default Value : ’gba’
List of values : OrderOfRotation ∈ {’gba’, ’abg’, ’rodriguez’}
. LongitudeMin (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; double / VARIANT
Minimum longitude of the model views.
Default Value : -0.35
Suggested values : LongitudeMin ∈ {-0.78, -0.35, -0.17}
. LongitudeMax (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; double / VARIANT
Maximum longitude of the model views.
Default Value : 0.35
Suggested values : LongitudeMax ∈ {0.17, 0.35, 0.78}
Restriction : (LongitudeM ax ≥ LongitudeM in)
. LatitudeMin (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; double / VARIANT
Minimum latitude of the model views.
Default Value : -0.35
Suggested values : LatitudeMin ∈ {-0.78, -0.35, -0.17}
Restriction : ((−(pi) ≤ LatitudeM in) ∧ (LatitudeM in ≤ pi))
. LatitudeMax (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; double / VARIANT
Maximum latitude of the model views.
Default Value : 0.35
Suggested values : LatitudeMax ∈ {0.17, 0.35, 0.78}
Restriction : (((−(pi) ≤ LatitudeM ax) ∧ (LatitudeM ax ≤ pi)) ∧ (LatitudeM ax ≥ LatitudeM in))
. CamRollMin (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; double / VARIANT
Minimum camera roll angle of the model views.
Default Value : -3.1416
Suggested values : CamRollMin ∈ {-3.14, -1.57, -0.39, 0.0, 0.39, 1.57, 3.14}
. CamRollMax (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; double / VARIANT
Maximum camera roll angle of the model views.
Default Value : 3.1416
Suggested values : CamRollMax ∈ {-3.14, -1.57, -0.39, 0.0, 0.39, 1.57, 3.14}
Restriction : (CamRollM ax ≥ CamRollM in)
. DistMin (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Minimum camera-object-distance of the model views.
Default Value : 0.3
Suggested values : DistMin ∈ {0.05, 0.1, 0.2, 0.5}
Restriction : (DistM in > 0)
. DistMax (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Maximum camera-object-distance of the model views.
Default Value : 0.4
Suggested values : DistMax ∈ {0.1, 0.2, 0.5, 1.0}
Restriction : (DistM ax ≥ DistM in)
. MinContrast (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; long / VARIANT
Minimum contrast of the objects in the search images.
Default Value : 10
Suggested values : MinContrast ∈ {1, 2, 3, 5, 7, 10, 20, 30, 1000, 2000, 5000}
. GenParamNames (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . attribute.name(-array) ; VARIANT ( string )
Names of (optional) parameters for controlling the behavior of the operator.
Default Value : []
List of values : GenParamNames ∈ {’num_levels’, ’optimization’, ’metric’, ’min_face_angle’, ’min_size’,
’model_tolerance’}
. GenParamValues (input control) . . . . . . . . . . . . attribute.name(-array) ; VARIANT ( integer, real, string )
Values of the optional generic parameters.
Default Value : []
Suggested values : GenParamValues ∈ {0, 1, 2, 3, ’auto’, ’none’, ’point_reduction_low’,
’point_reduction_medium’, ’point_reduction_high’, 0.1, 0.2, 0.3, ’ignore_segment_polarity’}
. ShapeModel3DID (output control) . . . . . . . . . . . . . . . . . shape_model_3d ; HShapeModel3DX / VARIANT
Handle of the 3D shape model.

HALCON/COM Reference Manual, 2008-5-13


663

Result
If the parameters are valid, the operator CreateShapeModel3D returns the value TRUE. If necessary an
exception is raised. If the parameters are chosen such that all model views contain too few points, the error 8510
is raised. In the case that the projected model is bigger than twice the image size in at least one model view, the
error 8910 is raised.
Parallelization Information
CreateShapeModel3D is processed completely exclusively without parallelization.
Possible Predecessors
ReadObjectModel3DDxf, ProjectObjectModel3D, GetObjectModel3DParams
Possible Successors
FindShapeModel3D, WriteShapeModel3D, ProjectShapeModel3D, GetShapeModel3DParams,
GetShapeModel3DContours
See also
ConvertPoint3DCartToSpher, ConvertPoint3DSpherToCart,
CreateCamPoseLookAtPoint, TransPoseShapeModel3D
Module
3D Metrology

[out] VARIANT Pose HImageX.FindShapeModel3D


([in] HShapeModel3DX ShapeModel3DID, [in] double MinScore,
[in] double Greediness, [in] VARIANT NumLevels, [in] VARIANT GenParamNames,
[in] VARIANT GenParamValues, [out] VARIANT CovPose, [out] VARIANT Score )
[out] VARIANT Pose HShapeModel3DX.FindShapeModel3D
([in] HImageX Image, [in] double MinScore, [in] double Greediness,
[in] VARIANT NumLevels, [in] VARIANT GenParamNames,
[in] VARIANT GenParamValues, [out] VARIANT CovPose, [out] VARIANT Score )
void HOperatorSetX.FindShapeModel3D ([in] IHObjectX Image,
[in] VARIANT ShapeModel3DID, [in] VARIANT MinScore, [in] VARIANT Greediness,
[in] VARIANT NumLevels, [in] VARIANT GenParamNames,
[in] VARIANT GenParamValues, [out] VARIANT Pose, [out] VARIANT CovPose,
[out] VARIANT Score )

Find the best matches of a 3D shape model in an image.


The operator FindShapeModel3D finds the best matches of the 3D shape model ShapeModel3DID in the
input Image. The 3D shape model must have been created previously by calling CreateShapeModel3D or
ReadShapeModel3D.
The 3D pose of the found instances of the model is returned in Pose. It describes the pose of the 3D object model
in the camera coordinate system. If a pose refinement was applied (see below), additionally the accuracy of the
six pose parameters are returned in CovPose. By default, CovPose contains the 6 standard deviations of the
pose parameters for each match. In contrast, if the generic parameter ’cov_pose_mode’ (see below) was set to
’covariances’, CovPose contains the 36 values of the complete 6 × 6 covariance matrix of the 6 pose parameters.
Note that this reflects only an inner accuracy from which the real accuracy of the pose may differ. Finally, the score
of each found instance is returned in Score. The score is a number between 0 and 1, which is an approximate
measure of how much of the model is visible in the image. If, for example, half of the model is occluded, the score
cannot exceed 0.5.
The domain of the image Image determines the search space for the reference point of the 3D object model.
The parameter MinScore determines what score a potential match must at least have to be regarded as an instance
of the model in the image. The larger MinScore is chosen, the faster the search is. If the model can be expected
never to be occluded in the images, MinScore may be set as high as 0.8 or even 0.9. Note that in images with a
high degree of clutter or strong background texture, MinScore should be set to a value not much lower than 0.7
since otherwise false matches could be found.
The parameter Greediness determines how “greedily” the search should be carried out. If Greediness = 0,
a safe search heuristic is used, which always finds the model if it is visible in the image. However, the search

HALCON 8.0.2
664 CHAPTER 8. MATCHING-3D

will be relatively time consuming in this case. If Greediness = 1, an unsafe search heuristic is used, which
may cause the model not to be found in rare cases, even though it is visible in the image. For Greediness =
1, the maximum search speed is achieved. In almost all cases, the 3D shape model will always be found for
Greediness = 0.9.
The number of pyramid levels used during the search is determined with NumLevels. If necessary, the number
of levels is clipped to the range given when the 3D shape model was created with CreateShapeModel3D. If
NumLevels is set to 0, the number of pyramid levels specified in CreateShapeModel3D is used. Optionally,
NumLevels can contain a second value that determines the lowest pyramid level to which the found matches are
tracked. Hence, a value of [4,2] for NumLevels means that the matching starts at the fourth pyramid level and
tracks the matches to the second lowest pyramid level (the lowest pyramid level is denoted by a value of 1). This
mechanism can be used to decrease the runtime of the matching. If the lowest pyramid level to use is chosen too
large, it may happen that the desired accuracy cannot be achieved, or that wrong instances of the model are found
because the model is not specific enough on the higher pyramid levels to facilitate a reliable selection of the correct
instance of the model. In this case, the lowest pyramid level to use must be set to a smaller value.
In addition to the parameters described above, there are some generic parameters that can optionally be used to in-
fluence the matching. For most applications these parameters need not to be specified but can be left at their default
values. If desired, these parameters and their corresponding values can be specified by using GenParamNames
and GenParamValues, respectively. The following values for GenParamNames are possible:

• If the pose range in which the model is to be searched is smaller than the pose range that was specified during
the model creation with CreateShapeModel3D, the pose range can be restricted appropriately with the
following parameters. If the values lie outside the pose range of the model, the values are automatically
clipped to the pose range of the model.
’longitude_min’: Sets the minimum longitude of the pose range.
Suggested values: rad(-45), rad(-30), rad(-15)
Default value: rad(-180)
’longitude_max’: Sets the maximum longitude of the pose range.
Suggested values: rad(15), rad(30), rad(45)
Default value: rad(180)
’latitude_min’: Sets the minimum latitude of the pose range.
Suggested values: rad(-45), rad(-30), rad(-15)
Default value: rad(-90)
’latitude_max’: Sets the maximum latitude of the pose range.
Suggested values: rad(15), rad(30), rad(45)
Default value: rad(90)
’cam_roll_min’: Sets the minimum camera roll angle of the pose range.
Suggested values: rad(-45), rad(-30), rad(-15)
Default value: rad(-180)
’cam_roll_max’: Sets the maximum camera roll angle of the pose range.
Suggested values: rad(15), rad(30), rad(45)
Default value: rad(180)
’dist_min’: Sets the minimum camera-object-distance of the pose range.
Suggested values: 0.05, 0.1, 0.5, 1.0
Default value: 0
’dist_max’: Sets the maximum camera-object-distance of the pose range.
Suggested values: 0.05, 0.1, 0.5, 1.0
Default value: (∞)
• Further generic parameters that do not concern the pose range can be specified:
’num_matches’: With this parameter the maximum number of instances to be found can be determined.
If more than the specified number of instances with a score greater than MinScore are found in the
image, only the best ’num_matches’ instances are returned. If fewer than ’num_matches’ are found,
only that number is returned, i.e., the parameter MinScore takes precedence over ’num_matches’. If
’num_matches’ is set to 0, all matches that satisfy the score criterion are returned. Note that the more
matches should be found the slower the matching will be.
Suggested values: 0, 1, 2, 3
Default value: 1

HALCON/COM Reference Manual, 2008-5-13


665

’max_overlap’: It may happen that multiple instances with similar positions but with different orientations
are found in the image. The parameter ’max_overlap’ determines by what fraction (i.e., a number be-
tween 0 and 1) two instances may at most overlap in order to consider them as different instances, and
hence to be returned separately. If two instances overlap each other by more than the specified value only
the best instance is returned. The calculation of the overlap is based on the smallest enclosing rectangle
of arbitrary orientation (see SmallestRectangle2) of the found instances. If 0 max _overlap 0 = 0,
the found instances may not overlap at all, while for 0 max _overlap 0 = 1 all instances are returned.
Suggested values: 0.0, 0.2, 0.4, 0.6, 0.8, 1.0
Default value: 0.5
’pose_refinement’: This parameter determines whether the poses of the instances should be refined after
the matching. If ’pose_refinement’ is set to ’none’ the model’s pose is only determined with a limited
accuracy. In this case, the accuracy depends on several sampling steps that are used inside the match-
ing process and, therefore cannot be predicted very well. Therefore, ’pose_refinement’ should only be
set to ’none’ when the computation time is of primary concern and an approximate pose is sufficient.
In all other cases the pose should be determined through a least-squares adjustment, i.e., by minimiz-
ing the distances of the model points to their corresponding image points. In order to achieve a high
accuracy, this refinement is directly performed in 3D. Therefore, the refinement requires additional com-
putation time. The different modes for least-squares adjustment (’least_squares’, ’least_squares_high’,
and ’least_squares_very_high’) can be used to determine the accuracy with which the minimum distance
is searched for. The higher the accuracy is chosen, the longer the pose refinement will take, however.
For most applications ’least_squares_high’ should be chosen because this results in the best tradeoff
between runtime and accuracy.
List of values: ’none’, ’least_squares’, ’least_squares_high’, ’least_squares_very_high’
Default value: ’least_squares_high’
’outlier_suppression’: This parameter only takes effect if ’pose_refinement’ is set to a value other than
’none’, and hence, a least-squares adjustment is performed. Then, in some cases it might be useful
to apply a robust outlier suppression during the least-squares adjustment. This might be necessary, for
example, if a high degree of clutter is present in the image, which prevents the least-squares adjustment
from finding the optimum pose. In this case, ’outlier_suppression’ should be set to either ’medium’
(eliminates a medium proportion of outliers) or ’high’ (eliminates a high proportion of outliers). How-
ever, in most applications, no robust outlier suppression is necessary, and hence, ’pose_refinement’ can
be set to ’none’. It should be noted that activating the outlier suppression comes along with a signifi-
cantly increasing computation time.
List of values: ’none’, ’medium’, ’high’
Default value: ’none’
’cov_pose_mode’: This parameter only takes effect if ’pose_refinement’ is set to a value other than ’none’,
and hence, a least-squares adjustment is performed. ’cov_pose_mode’ determines the mode in which
the accuracies that are computed during the least-squares adjustment are returned in CovPose. If
’cov_pose_mode’ is set to ’standard_deviations’, the 6 standard deviations of the 6 pose parameters
are returned for each match. In contrast, if ’cov_pose_mode’ is set to ’covariances’, CovPose contains
the 36 values of the complete 6 × 6 covariance matrix of the 6 pose parameters.
List of values: ’standard_deviations’, ’covariances’
Default value: ’standard_deviations’
’border_model’: The model is searched within those points of the domain of the image in which the model
lies completely within the image. This means that the model will not be found if it extends beyond
the borders of the image, even if it would achieve a score greater than MinScore. This behavior can
be changed by setting ’border_model’ to ’true’, which will cause models that extend beyond the image
border to be found if they achieve a score greater than MinScore. Here, points lying outside the image
are regarded as being occluded, i.e., they lower the score. It should be noted that the runtime of the
search will increase in this mode.
List of values: ’false’, ’true’
Default value: ’false’

Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . (multichannel-)image ; HImageX / IHObjectX ( byte, uint2 )


Input image in which the model should be found.
. ShapeModel3DID (input control) . . . . . . . . . . . . . . . . . . shape_model_3d ; HShapeModel3DX / VARIANT
Handle of the 3D shape model.

HALCON 8.0.2
666 CHAPTER 8. MATCHING-3D

. MinScore (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT


Minimum score of the instances of the model to be found.
Default Value : 0.7
Suggested values : MinScore ∈ {0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}
Typical range of values : 0 ≤ MinScore ≤ 0
Minimum Increment : 0.01
Recommended Increment : 0.05
. Greediness (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
“Greediness” of the search heuristic (0: safe but slow; 1: fast but matches may be missed).
Default Value : 0.9
Suggested values : Greediness ∈ {0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}
Typical range of values : 0 ≤ Greediness ≤ 0
Minimum Increment : 0.01
Recommended Increment : 0.05
. NumLevels (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Number of pyramid levels used in the matching (and lowest pyramid level to use if |NumLevels| = 2).
Default Value : 0
List of values : NumLevels ∈ {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
. GenParamNames (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . attribute.name(-array) ; VARIANT ( string )
Names of (optional) parameters for controlling the behavior of the operator.
Default Value : []
List of values : GenParamNames ∈ {’longitude_min’, ’longitude_max’, ’latitude_min’, ’latitude_max’,
’cam_roll_min’, ’cam_roll_max’, ’dist_min’, ’dist_max’, ’num_matches’, ’max_overlap’, ’pose_refinement’,
’cov_pose_mode’, ’outlier_suppression’, ’border_model’}
. GenParamValues (input control) . . . . . . . . . . . . attribute.name(-array) ; VARIANT ( integer, real, string )
Values of the optional generic parameters.
Default Value : []
Suggested values : GenParamValues ∈ {-0.78, -0.35, -0.17, 0.0, 0.17, 0.35, 0.78, 0.1, 0.2, 0.5, ’none’,
’false’, ’true’, ’least_squares’, ’least_squares_high’, ’least_squares_very_high’, ’standard_deviations’,
’covariances’, ’medium’, ’high’}
. Pose (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pose ; VARIANT ( integer, real )
3D pose of the 3D shape model.
. CovPose (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
6 standard deviations or 36 covariances of the pose parameters.
. Score (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Score of the found instances of the 3D shape model.
Example

read_object_model_3d_dxf (DXFModelFileName, ’m’, [], [], ObjectModel3DID,


DxfStatus)
CamParam := [0.01221,2791,7.3958e-6,7.4e-6,308.21,245.92,640,480]
create_shape_model_3d (ObjectModel3DID, CamParam, 0, 0, 0, ’gba’,
-rad(20), rad(20), -rad(20), rad(20), 0,
rad(360), 0.15, 0.2, 10, [], [], ShapeModel3DID)
grab_image_async (Image, FGHandle, -1)
find_shape_model_3d (Image, ShapeModel3DID, 0.6, 0.9, 0, [], [],
Pose, CovPose, Score)
project_shape_model_3d (ModelContours, ShapeModel3DID, CamParam,
Pose, ’true’, rad(15))

Result
If the parameter values are correct, the operator FindShapeModel3D returns the value TRUE.
If the input is empty (no input images are available) the behavior can be set via SetSystem
(’noObjectResult’,<Result>). If necessary, an exception is raised.
Parallelization Information
FindShapeModel3D is reentrant and processed without parallelization.

HALCON/COM Reference Manual, 2008-5-13


667

Possible Predecessors
CreateShapeModel3D, ReadShapeModel3D
Possible Successors
ProjectShapeModel3D
See also
ConvertPoint3DCartToSpher, ConvertPoint3DSpherToCart,
CreateCamPoseLookAtPoint, TransPoseShapeModel3D
Module
3D Metrology

void HObjectModel3DX.GetObjectModel3DParams
([in] VARIANT GenParamNames, [out] VARIANT GenParamValues )
void HOperatorSetX.GetObjectModel3DParams
([in] VARIANT ObjectModel3DID, [in] VARIANT GenParamNames,
[out] VARIANT GenParamValues )

Return the parameters of a 3D object model.


The operator GetObjectModel3DParams allows to query parameters of the 3D object model. The names
of the desired parameters are passed in the generic parameter GenParamNames, the corresponding values are
returned in GenParamValues.
The following parameters can be queried:

’reference_point’: 3D coordinates of the reference point of the model. The reference point is the center of the
smallest enclosing axis-parallel cuboid (see parameter ’bounding_box1’).
’bounding_box1’: Smallest enclosing axis-parallel cuboid (min_x, min_y, min_z, max_x, max_y, max_z).

Parameter

. ObjectModel3DID (input control) . . . . . . . . . . . . . . . . object_model_3d ; HObjectModel3DX / VARIANT


Handle of the 3D object model.
. GenParamNames (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . attribute.name(-array) ; VARIANT ( string )
Names of the generic parameters that are to be queried for the 3D object model.
Default Value : ’reference_point’
List of values : GenParamNames ∈ {’reference_point’, ’bounding_box1’}
. GenParamValues (output control) . . . . . . . . . . . attribute.name(-array) ; VARIANT ( integer, string, real )
Values of the generic parameters.
Result
The operator GetObjectModel3DParams returns the value TRUE if the given parameters are correct. Other-
wise, an exception will be raised.
Parallelization Information
GetObjectModel3DParams is reentrant and processed without parallelization.
Possible Predecessors
ReadObjectModel3DDxf
Possible Successors
AffineTransObjectModel3D
Module
3D Metrology

HALCON 8.0.2
668 CHAPTER 8. MATCHING-3D

[out] HXLDContX ModelContours


HShapeModel3DX.GetShapeModel3DContours ([in] long Level,
[in] long View, [out] VARIANT ViewPose )
void HOperatorSetX.GetShapeModel3DContours
([out] HUntypedObjectX ModelContours, [in] VARIANT ShapeModel3DID,
[in] VARIANT Level, [in] VARIANT View, [out] VARIANT ViewPose )

Return the contour representation of a 3D shape model view.


The operator GetShapeModel3DContours returns a representation of a single model view of the 3D shape
model ShapeModel3DID as XLD contours in ModelContours. The parameters Level and View determine
for which model view the contour representation should be returned, where Level denotes the pyramid level and
View denotes the model view on this pyramid level.
The permitted range of values for Level and View can previously be determined by using the operator
GetShapeModel3DParams and passing ’num_views_per_level’ for GenParamNames.
The contours can be used to visualize and rate the 3D shape model that was created with
CreateShapeModel3D. With this it is possible, for example, to decide whether the number of pyramid levels in
the model is appropriate or not. If the contours on the highest pyramid do not show enough details to be representa-
tive for the model view, the number of pyramid levels that are used during the search with FindShapeModel3D
should be adjusted downwards. In contrast, if the contours show too many details even on the highest pyramid
level, a higher number of pyramid levels should be chosen already during the creation of the 3D shape model by
using CreateShapeModel3D.
Additionally, the pose of the selected view is returned in ViewPose. It can be used, for example, to project the 3D
shape model according to the view pose by using ProjectShapeModel3D. The rating of the model contours
that was described above can then be performed by comparing the ModelContours to the projected model.
Note that the position of the contours of the projection and the position of the model contours may slightly differ
because of radial distortions.
Parameter
. ModelContours (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . xld_cont ; HXLDContX / HUntypedObjectX
Contour representation of the model view.
. ShapeModel3DID (input control) . . . . . . . . . . . . . . . . . . shape_model_3d ; HShapeModel3DX / VARIANT
Handle of the 3D shape model.
. Level (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Pyramid level for which the contour representation should be returned.
Default Value : 1
Suggested values : Level ∈ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Restriction : (Level ≥ 1)
. View (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
View for which the contour representation should be returned.
Default Value : 1
Suggested values : View ∈ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Restriction : (V iew ≥ 1)
. ViewPose (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .pose ; VARIANT ( integer, real )
3D pose of the 3D shape model at the current view.
Result
If the parameters are valid, the operator GetShapeModel3DContours returns the value TRUE. If necessary
an exception is raised.
Parallelization Information
GetShapeModel3DContours is reentrant and processed without parallelization.
Possible Predecessors
CreateShapeModel3D, ReadShapeModel3D, GetShapeModel3DParams
Possible Successors
CreateShapeModel3D
Module
3D Metrology

HALCON/COM Reference Manual, 2008-5-13


669

[out] VARIANT GenParamValues HShapeModel3DX.GetShapeModel3DParams


([in] VARIANT GenParamNames )
void HOperatorSetX.GetShapeModel3DParams
([in] VARIANT ShapeModel3DID, [in] VARIANT GenParamNames,
[out] VARIANT GenParamValues )

Return the parameters of a 3D shape model.


The operator GetShapeModel3DParams allows to query parameters of the 3D shape model. The names of the
desired parameters are passed in the generic parameter GenParamNames, the corresponding values are returned
in GenParamValues.
The following parameters can be queried:
’cam_param’: Interior parameters of the camera that is used for the matching.
’ref_rot_x’: Reference orientation: Rotation around x-axis or x component of the Rodriguez vector (in radians or
without unit).
’ref_rot_y’: Reference orientation: Rotation around y-axis or y component of the Rodriguez vector (in radians or
without unit).
’ref_rot_z’: Reference orientation: Rotation around z-axis or z component of the Rodriguez vector (in radians or
without unit).
’order_of_rotation’: Meaning of the rotation values of the reference orientation.
’longitude_min’: Minimum longitude of the model views.
’longitude_max’: Maximum longitude of the model views.
’latitude_min’: Minimum latitude of the model views.
’latitude_max’: Maximum latitude of the model views.
’cam_roll_min’: Minimum camera roll angle of the model views.
’cam_roll_max’: Maximum camera roll angle of the model views.
’dist_min’: Minimum camera-object-distance of the model views.
’dist_max’: Maximum camera-object-distance of the model views.
’min_contrast’: Minimum contrast of the objects in the search images.
’num_levels’: User-specified number of pyramid levels.
’num_levels_max’: Maximum number of used pyramid levels over all model views.
’optimization’: Kind of optimization by reducing the number of model points.
’metric’: Match metric.
’min_face_angle’: Minimum 3D face angle for which 3D object model edges are included in the 3D shape model.
’min_size’: Minimum size of the projected 3D object model edge (in number of pixels) to include the projected
edge in the 3D shape model.
’model_tolerance’: Maximum acceptable tolerance of the projected 3D object model edges (in pixels).
’num_views_per_level’: Number of model views per pyramid level. For each pyramid level the number of views
that are stored in the 3D shape model are returned. Thus, the number of returned elements corresponds to the
number of used pyramid levels, which can be queried with ’num_levels_max’.
’reference_pose’: Reference position and orientation of the 3d shape model. The returned pose describes the pose
of the internally used reference coordinate system of the 3D shape model with respect to the coordinate
system that is used in the underlying 3D object model.
’reference_point’: 3D coordinates of the reference point of the underlying 3D object model.
’bounding_box1’: Smallest enclosing axis-parallel cuboid of the underlying 3D object model in the following
order: [min_x, min_y, min_z, max_x, max_y, max_z].
A detailed description of the parameters can be looked up with the operator CreateShapeModel3D.
It is possible to query the values of several parameters with a single operator call by passing a tuple containing the
names of all desired parameters to GenParamNames. As a result a tuple of the same length with the correspond-
ing values is returned in GenParamValues. Note that this is solely possible for parameters that return only a
single value.

HALCON 8.0.2
670 CHAPTER 8. MATCHING-3D

Parameter
. ShapeModel3DID (input control) . . . . . . . . . . . . . . . . . . shape_model_3d ; HShapeModel3DX / VARIANT
Handle of the 3D shape model.
. GenParamNames (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . attribute.name(-array) ; VARIANT ( string )
Names of the generic parameters that are to be queried for the 3D shape model.
Default Value : ’num_levels_max’
List of values : GenParamNames ∈ {’cam_param’, ’ref_rot_x’, ’ref_rot_y’, ’ref_rot_z’, ’order_of_rotation’,
’longitude_min’, ’longitude_max’, ’latitude_min’, ’latitude_max’, ’cam_roll_min’, ’cam_roll_max’,
’dist_min’, ’dist_max’, ’min_contrast’, ’num_levels’, ’num_levels_max’, ’optimization’, ’metric’,
’min_face_angle’, ’min_size’, ’model_tolerance’, ’num_views_per_level’, ’reference_pose’,
’reference_point’, ’bounding_box1’}
. GenParamValues (output control) . . . . . . . . . . . attribute.name(-array) ; VARIANT ( integer, string, real )
Values of the generic parameters.
Result
If the parameters are valid, the operator GetShapeModel3DParams returns the value TRUE. If necessary an
exception is raised.
Parallelization Information
GetShapeModel3DParams is reentrant and processed without parallelization.
Possible Predecessors
CreateShapeModel3D, ReadShapeModel3D
Possible Successors
FindShapeModel3D
See also
ConvertPoint3DCartToSpher, ConvertPoint3DSpherToCart,
CreateCamPoseLookAtPoint, TransPoseShapeModel3D
Module
3D Metrology

void HObjectModel3DX.ProjectObjectModel3D
([out] HXLDContX ModelContours, [in] VARIANT CamParam, [in] VARIANT Pose,
[in] String HiddenSurfaceRemoval, [in] VARIANT MinFaceAngle )
void HOperatorSetX.ProjectObjectModel3D
([out] HUntypedObjectX ModelContours, [in] VARIANT ObjectModel3DID,
[in] VARIANT CamParam, [in] VARIANT Pose, [in] VARIANT HiddenSurfaceRemoval,
[in] VARIANT MinFaceAngle )

Project the edges of a 3D object model into image coordinates.


The operator ProjectObjectModel3D projects the edges of a 3D object model into the image coordinate sys-
tem and returns the projected edges in ModelContours. The coordinates of the 3D object model are given in the
3D world coordinate system. First, they are transformed into the camera coordinate system using the given Pose.
Then, these coordinates are projected into the image coordinate system based on the interior camera parameters
CamParam.
The interior camera parameters CamParam describe the projection characteristics of the camera (see
WriteCamPar). The Pose describes the position and orientation of the world coordinate system with respect to
the camera coordinate system.
The parameter HiddenSurfaceRemoval can be used to switch on or to switch off the removal of hidden
surfaces. If HiddenSurfaceRemoval is set to ’true’, only those projected edges are returned that are not
hidden by faces of the 3D object model. If HiddenSurfaceRemoval is set to ’false’, all projected edges are
returned. This is faster than a projection with HiddenSurfaceRemoval set to ’true’.
3D edges are only projected if the angle between the two 3D faces that are incident with the 3D edge is at least
MinFaceAngle. If MinFaceAngle is set to 0.0, all edges are projected. If MinFaceAngle is set to π
(equivalent to 180 degrees), only the silhouette of the 3D object model is returned. This parameter can be used to
suppress edges within curved surfaces, e.g., the surface of a cylinder or cone.

HALCON/COM Reference Manual, 2008-5-13


671

Parameter
. ModelContours (output iconic) . . . . . . . . . . . . . . . . . xld_cont(-array) ; HXLDContX / HUntypedObjectX
Projected model contours.
. ObjectModel3DID (input control) . . . . . . . . . . . . . . . . object_model_3d ; HObjectModel3DX / VARIANT
Handle of the 3D object model.
. CamParam (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Interior camera parameters.
. Pose (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pose ; VARIANT ( integer, real )
3D pose of the world coordinate system in camera coordinates.
. HiddenSurfaceRemoval (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Remove hidden surfaces?
Default Value : ’true’
List of values : HiddenSurfaceRemoval ∈ {’true’, ’false’}
. MinFaceAngle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; VARIANT ( integer, real )
Smallest face angle for which the edge is projected.
Default Value : 0.261799
Suggested values : MinFaceAngle ∈ {0.17, 0.26, 0.35}
Result
ProjectObjectModel3D returns TRUE if all parameters are correct. If necessary, an exception is raised.
Parallelization Information
ProjectObjectModel3D is reentrant and processed without parallelization.
Possible Predecessors
ReadObjectModel3DDxf, AffineTransObjectModel3D
Possible Successors
ClearObjectModel3D
See also
ProjectShapeModel3D
Module
3D Metrology

[out] HXLDContX ModelContours HShapeModel3DX.ProjectShapeModel3D


([in] VARIANT CamParam, [in] VARIANT Pose, [in] String HiddenSurfaceRemoval,
[in] VARIANT MinFaceAngle )
void HOperatorSetX.ProjectShapeModel3D
([out] HUntypedObjectX ModelContours, [in] VARIANT ShapeModel3DID,
[in] VARIANT CamParam, [in] VARIANT Pose, [in] VARIANT HiddenSurfaceRemoval,
[in] VARIANT MinFaceAngle )

Project the edges of a 3D shape model into image coordinates.


The operator ProjectShapeModel3D projects the edges of the 3D object model that was used to create
the 3D shape model ShapeModel3DID into the image coordinate system and returns the projected edges in
ModelContours. The coordinates of the 3D object model are given in the 3D world coordinate system. First,
they are transformed into the camera coordinate system using the given Pose. Then, these coordinates are pro-
jected into the image coordinate system based on the interior camera parameters CamParam.
The interior camera parameters CamParam describe the projection characteristics of the camera (see
WriteCamPar). The Pose describes the position and orientation of the world coordinate system with respect to
the camera coordinate system.
The parameter HiddenSurfaceRemoval can be used to switch on or to switch off the removal of hidden
surfaces. If HiddenSurfaceRemoval is set to ’true’, only those projected edges are returned that are not
hidden by faces of the 3D object model. If HiddenSurfaceRemoval is set to ’false’, all projected edges are
returned. This is faster than a projection with HiddenSurfaceRemoval set to ’true’.
3D edges are only projected if the angle between the two 3D faces that are incident with the 3D edge is at least
MinFaceAngle. If MinFaceAngle is set to 0.0, all edges are projected. If MinFaceAngle is set to π

HALCON 8.0.2
672 CHAPTER 8. MATCHING-3D

(equivalent to 180 degrees), only the silhouette of the 3D object model is returned. This parameter can be used to
suppress edges within curved surfaces, e.g., the surface of a cylinder.
ProjectShapeModel3D and ProjectObjectModel3D return the same result if the 3D object model that
was used to create the 3D shape model is passed to ProjectObjectModel3D.
ProjectShapeModel3D is especially useful in order to visualize the matches that are returned by
FindShapeModel3D in the case that the underlying 3D object model is no longer available.
Parameter
. ModelContours (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . xld_cont ; HXLDContX / HUntypedObjectX
Contour representation of the model view.
. ShapeModel3DID (input control) . . . . . . . . . . . . . . . . . . shape_model_3d ; HShapeModel3DX / VARIANT
Handle of the 3D shape model.
. CamParam (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Interior camera parameters.
Number of elements : (CamP aram = 8)
. Pose (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pose ; VARIANT ( integer, real )
3D pose of the 3D shape model in the world coordinate system.
. HiddenSurfaceRemoval (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Remove hidden surfaces?
Default Value : ’true’
List of values : HiddenSurfaceRemoval ∈ {’true’, ’false’}
. MinFaceAngle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; VARIANT ( integer, real )
Smallest face angle for which the edge is displayed
Default Value : 0.261799
Suggested values : MinFaceAngle ∈ {0.17, 0.26, 0.35}
Result
If the parameters are valid, the operator ProjectShapeModel3D returns the value TRUE. If necessary an
exception is raised.
Parallelization Information
ProjectShapeModel3D is reentrant and processed without parallelization.
Possible Predecessors
CreateShapeModel3D, ReadShapeModel3D, GetShapeModel3DParams, FindShapeModel3D
See also
ConvertPoint3DCartToSpher, ConvertPoint3DSpherToCart,
CreateCamPoseLookAtPoint, TransPoseShapeModel3D
Alternatives
ProjectObjectModel3D
Module
3D Metrology

void HObjectModel3DX.ReadObjectModel3DDxf ([in] String FileName,


[in] VARIANT Scale, [in] VARIANT GenParamNames, [in] VARIANT GenParamValues,
[out] VARIANT DxfStatus )
void HOperatorSetX.ReadObjectModel3DDxf ([in] VARIANT FileName,
[in] VARIANT Scale, [in] VARIANT GenParamNames, [in] VARIANT GenParamValues,
[out] VARIANT ObjectModel3DID, [out] VARIANT DxfStatus )

Read a 3D object model from a DXF file.


The operator ReadObjectModel3DDxf reads the contents of the DXF file FileName (DXF version AC1009,
AutoCAD Release 12) and converts them to a 3D object model. The handle of the 3D object model is returned in
ObjectModel3DID. If no absolute path is given in FileName, the DXF file is searched in the current directory
of the HALCON process.
The output parameter DxfStatus contains information about the number of 3D faces that were read and, if
necessary, warnings that parts of the DXF file could not be interpreted.

HALCON/COM Reference Manual, 2008-5-13


673

The operator ReadObjectModel3DDxf supports the following DXF entities:

• POLYLINE
– Polyface meshes
• 3DFACE
• LINE
• CIRCLE
• ARC
• ELLIPSE
• SOLID
• BLOCK
• INSERT

Two-dimensional linear elements like the DXF elements CIRCLE or ELLIPSE are interpreted as faces even if they
are not extruded. If necessary, they are closed. Two-dimensional linear elements that consist of just two points are
not used because they do not define a face. Thus, elements of the type LINE are only used if they are extruded.
The curved surface of extruded DXF entities of the type CIRCLE, ARC, and ELLIPSE is approximated by planar
faces. The accuracy of this approximation can be controlled with the two generic parameters ’min_num_points’
and ’max_approx_error’. The parameter ’min_num_points’ defines the minimum number of sampling points
that are used for the approximation of the DXF element CIRCLE, ARC, or ELLIPSE. Note that the parameter
’min_num_points’ always refers to the full circle or ellipse, respectively, even for ARCs or elliptical arcs, i.e., if
’min_num_points’ is set to 50 and a DXF entity of the type ARC is read that represents a semi-circle, this semi-
circle is approximated by at least 25 sampling points. The parameter ’max_approx_error’ defines the maximum
deviation of the XLD contour from the ideal circle or ellipse, respectively. The determination of this deviation
is carried out in the units used in the DXF file. For the determination of the accuracy of the approximation both
criteria are evaluated. Then, the criterion that leads to the more accurate approximation is used.
Internally, the following default values are used for the generic parameters:

’min_num_points’ = 20
’max_approx_error’ = 0.25

To achieve a more accurate approximation, either the value for ’min_num_points’ must be increased or the value
for ’max_approx_error’ must be decreased.
One possible way to create a suitable DXF file is to create a 3D model of the object with the CAD program
AutoCAD. Ensure that the surface of the object is modelled, not only its edges. Lines that, e.g., define object
edges, will not be used by HALCON, because they do not define the surface of the object. Once the modelling is
completed, you can store the model in DWG format. To convert the DWG file into a DXF file that is suitable for
HALCON’s 3D matching, carry out the following steps:

• Export the 3D CAD model to a 3DS file using the 3dsout command of AutoCAD. This will triangulate the
object’s surface, i.e., the model will only consist of planes. (Users of AutoCAD 2007 or newer versions can
download this command utility from Autodesk’s web site.)
• Open a new empty sheet in AutoCAD.
• Import the 3DS file into this empty sheet with the 3dsin command of AutoCAD.
• Save the object into a DXF R12 file.

Users of other CAD programs should ensure that the surface of the 3D model is triangulated before it is exported
into the DXF file. If the CAD program is not able to carry out the triangulation, it is often possible to save the 3D
model in the proprietary format of the CAD program and to convert it into a suitable DXF file by using a CAD file
format converter that is able to perform the triangulation.

HALCON 8.0.2
674 CHAPTER 8. MATCHING-3D

Parameter
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.read ; String / VARIANT
Name of the DXF file
. Scale (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real, string )
Scale or unit.
Default Value : ’m’
Suggested values : Scale ∈ {’m’, ’cm’, ’mm’, ’microns’, ’µm’, 1.0, 0.01, 0.001, 1.0e-6, 0.0254, 0.3048,
0.9144}
. GenParamNames (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Names of the generic parameters that can be adjusted for the DXF input.
Default Value : []
List of values : GenParamNames ∈ {’min_num_points’, ’max_approx_error’}
. GenParamValues (input control) . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( integer, string, real )
Values of the generic parameters that can be adjusted for the DXF input.
Default Value : []
Suggested values : GenParamValues ∈ {0.1, 0.25, 0.5, 1, 2, 5, 10, 20}
. ObjectModel3DID (output control) . . . . . . . . . . . . . . object_model_3d ; HObjectModel3DX / VARIANT
Handle of the read 3D object model.
. DxfStatus (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Status information.
Result
ReadObjectModel3DDxf returns TRUE if all parameters are correct. If necessary, an exception is raised.
Parallelization Information
ReadObjectModel3DDxf is processed completely exclusively without parallelization.
Possible Successors
AffineTransObjectModel3D, ProjectObjectModel3D
Module
3D Metrology

void HShapeModel3DX.ReadShapeModel3D ([in] String FileName )


void HOperatorSetX.ReadShapeModel3D ([in] VARIANT FileName,
[out] VARIANT ShapeModel3DID )

Read a 3D shape model from a file.


The operator ReadShapeModel3D reads a 3D shape model, which has been written with
WriteShapeModel3D, from the file FileName.
Parameter
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.read ; String / VARIANT
File name.
. ShapeModel3DID (output control) . . . . . . . . . . . . . . . . . shape_model_3d ; HShapeModel3DX / VARIANT
Handle of the 3D shape model.
Result
If the file name is valid, the operator ReadShapeModel3D returns the value TRUE. If necessary an exception
is raised.
Parallelization Information
ReadShapeModel3D is processed completely exclusively without parallelization.
Possible Successors
FindShapeModel3D, GetShapeModel3DParams
See also
CreateShapeModel3D, ClearShapeModel3D
Module
3D Metrology

HALCON/COM Reference Manual, 2008-5-13


675

[out] VARIANT PoseOut HShapeModel3DX.TransPoseShapeModel3D


([in] VARIANT PoseIn, [in] String Transformation )
[out] VARIANT PoseOut HPoseX.TransPoseShapeModel3D
([in] HShapeModel3DX ShapeModel3DID, [in] VARIANT PoseIn,
[in] String Transformation )
void HOperatorSetX.TransPoseShapeModel3D
([in] VARIANT ShapeModel3DID, [in] VARIANT PoseIn,
[in] VARIANT Transformation, [out] VARIANT PoseOut )

Transform a pose that refers to the coordinate system of a 3D object model to a pose that refers to the reference
coordinate system of a 3D shape model and vice versa.
The operator TransPoseShapeModel3D transforms the pose PoseIn into the pose PoseOut by using the
transformation direction specified in Transformation. In the majority of cases, the operator will be used to
transform a camera pose that is given with respect to the source coordinate system to a camera pose that refers to
the target coordinate system.
The pose can be transformed between two coordinate systems. The first coordinate system is the reference coordi-
nate system of the 3D shape model that is passed in ShapeModel3DID. The origin of the reference coordinate
system lies at the reference point of the underlying 3D object model. The orientation of the reference coordi-
nate system is determined by the reference orientation that was specified when creating the 3D shape model with
CreateShapeModel3D.
The second coordinate system is the world coordiante system, i.e., the coordinate system of the 3D object model
that underlies the 3D shape model. This coordinate system is implicitly determined by the coordinates that are
stored in the DXF file that was read by using ReadObjectModel3DDxf.
If Transformation is set to ’ref_to_model’, it is assumed that PoseIn refers to the reference coordinate
system of the 3D shape model. The resulting output pose PoseOut in this case refers to the coordinate system of
the 3D object model.
If Transformation is set to ’model_to_ref’, it is assumed that PoseIn refers to the coordinate system of the
3D object model. The resulting output pose PoseOut in this case refers to the reference coordinate system of the
3D shape model.
The relative pose of the two coordinate systems can be queried by passing ’reference_pose’ for GenParamNames
in the operator GetShapeModel3DParams.
Parameter
. ShapeModel3DID (input control) . . . . . . . . . . . . . . . . . . shape_model_3d ; HShapeModel3DX / VARIANT
Handle of the 3D shape model.
. PoseIn (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pose ; VARIANT ( integer, real )
Pose to be transformed in the source system.
. Transformation (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Direction of the transformation.
Default Value : ’ref_to_model’
List of values : Transformation ∈ {’ref_to_model’, ’model_to_ref’}
. PoseOut (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pose ; VARIANT ( integer, real )
Transformed 3D pose in the target system.
Result
If the parameters are valid, the operator TransPoseShapeModel3D returns the value TRUE. If necessary an
exception is raised.
Parallelization Information
TransPoseShapeModel3D is reentrant and processed without parallelization.
Possible Predecessors
FindShapeModel3D
Alternatives
HomMat3dTranslate, HomMat3dRotate
Module
3D Metrology

HALCON 8.0.2
676 CHAPTER 8. MATCHING-3D

void HShapeModel3DX.WriteShapeModel3D ([in] String FileName )


void HOperatorSetX.WriteShapeModel3D ([in] VARIANT ShapeModel3DID,
[in] VARIANT FileName )

Write a 3D shape model to a file.


The operator WriteShapeModel3D writes a 3D shape model to the file FileName. The model can be read
again with ReadShapeModel3D.
Parameter

. ShapeModel3DID (input control) . . . . . . . . . . . . . . . . . . shape_model_3d ; HShapeModel3DX / VARIANT


Handle of the 3D shape model.
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.write ; String / VARIANT
File name.
Result
If the file name is valid (write permission), the operator WriteShapeModel3D returns the value TRUE. If
necessary an exception is raised.
Parallelization Information
WriteShapeModel3D is reentrant and processed without parallelization.
Possible Predecessors
CreateShapeModel3D
Module
3D Metrology

HALCON/COM Reference Manual, 2008-5-13


Chapter 9

Morphology

9.1 Gray-Values

[out] HImageX ImageRank HImageX.DualRank ([in] String MaskType,


[in] long Radius, [in] long ModePercent, [in] VARIANT Margin )
void HOperatorSetX.DualRank ([in] IHObjectX Image,
[out] HUntypedObjectX ImageRank, [in] VARIANT MaskType, [in] VARIANT Radius,
[in] VARIANT ModePercent, [in] VARIANT Margin )

Opening, Median and Closing with circle or rectangle mask.


The operator DualRank carries out a non-linear transformation of the gray values of all input images (Image).
Circles or squares can be used as structuring elements. The operator DualRank effects two consecutive calls of
RankImage. At the first call the range gray value is calculated with the indicated range (ModePercent).
The result of this calculation is the input of a further call of RankImage, this time using the range value
100−ModePercent.
When filtering different parameters for border treatment (Margin) can be chosen:

gray value Pixels outside of the image edges are assumued


to be constant (with the indicated gray value).
’continued’ Continuation of edge pixels.
’cyclic’ Cyclic continuation of image edges.
’mirrored’ Reflection of pixels at the image edges.

A range filtering is calculated according to the following scheme: The indicated mask is put over the image to be
filtered in such a way that the center of the mask touches all pixels once. For each of these pixels all neighboring
pixels covered by the mask are sorted in an ascending sequence corresponding to their gray values. Each sorted
sequence of gray values contains the same number of gray values like the mask has image points. The n-th highest
element, (= ModePercent, rank values between 0...100 in percent) is selected and set as result gray value in the
corresponding result image.
If ModePercent is 0, then the operator equals to the gray value opening ( GrayOpening). If ModePercent
is 50, the operator results in the median filter, which is applied twice ( MedianImage). The ModePercent
100 in DualRank means that it calculates the gray value closing ( GrayClosing). Choosing parameter values
inside this range results in a smooth transformation of these operators.
Parameter

. Image (input iconic) . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, int2, uint2, int4,
real )
Image to be filtered.
. ImageRank (output iconic) . . . . . . multichannel-image-array ; HImageX / HUntypedObjectX ( byte, int2,
uint2, int4, real )
Filtered Image.

677
678 CHAPTER 9. MORPHOLOGY

. MaskType (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT


Shape of the mask.
Default Value : ’circle’
List of values : MaskType ∈ {’circle’, ’rectangle’}
. Radius (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Radius of the filter mask.
Default Value : 1
Suggested values : Radius ∈ {1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 15, 19, 25, 31, 39, 47, 59}
Typical range of values : 1 ≤ Radius ≤ 1
Minimum Increment : 1
Recommended Increment : 2
. ModePercent (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Filter Mode: 0 corresponds to a gray value opening , 50 corresponds to a median and 100 to a gray values
closing.
Default Value : 10
Suggested values : ModePercent ∈ {0, 2, 5, 10, 15, 20, 40, 50, 60, 80, 85, 90, 95, 98, 100}
Typical range of values : 0 ≤ ModePercent ≤ 0
Minimum Increment : 1
Recommended Increment : 2
. Margin (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( integer, real, string )
Border treatment.
Default Value : ’mirrored’
Suggested values : Margin ∈ {’mirrored’, ’cyclic’, ’continued’, 0, 30, 60, 90, 120, 150, 180, 210, 240, 255}
Example

read_image(Image,’fabrik’)
dual_rank(Image,ImageOpening,’circle’,10,10,’mirrored’)
disp_image(ImageOpening,WindowHandle).

√ Complexity
For each pixel: O( F ∗ 10) with F = area of the structuring element.
Result
If the parameter values are correct the operator DualRank returns the value TRUE. The behavior in case of empty
input (no input images available) is set via the operator SetSystem(’noObjectResult’,<Result>). If
necessary an exception handling is raised.
Parallelization Information
DualRank is reentrant and automatically parallelized (on tuple level, channel level, domain level).
Possible Predecessors
ReadImage
Possible Successors
Threshold, DynThreshold, SubImage, Regiongrowing
See also
GenCircle, GenRectangle1, GrayErosionRect, GrayDilationRect, SigmaImage
Alternatives
RankImage, GrayClosing, GrayOpening, MedianImage
References
W. Eckstein, O. Munkelt “Extracting Objects from Digital Terrain Model” Remote Sensing and Reconstruction for
Threedimensional Objects and Scenes, SPIE Symposium on Optical Science, Engeneering, and Instrumentation,
July 1995, San Diego
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


9.1. GRAY-VALUES 679

void HImageX.GenDiscSe ([in] long Width, [in] long Height,


[in] long Smax )
void HOperatorSetX.GenDiscSe ([out] HUntypedObjectX SE,
[in] VARIANT Width, [in] VARIANT Height, [in] VARIANT Smax )

Generate ellipsoidal structuring elements for gray morphology.


GenDiscSe generates an ellipsoidal structuring element (SE) for gray morphology of images. The parameters
Width and Height determine the length of the two major axes of the ellipse. The value of Smax determines
the maximum gray value of the structuring element. For the generation of arbitrary structuring elements, see
ReadGraySe.
Parameter

. SE (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / HUntypedObjectX ( byte )


Generated structuring element.
. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Width of the structuring element.
Default Value : 5
Suggested values : Width ∈ {0, 1, 2, 3, 4, 5, 10, 15, 20}
Typical range of values : 0 ≤ Width ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 1
. Height (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Height of the structuring element.
Default Value : 5
Suggested values : Height ∈ {0, 1, 2, 3, 4, 5, 10, 15, 20}
Typical range of values : 0 ≤ Height ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 1
. Smax (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Maximum gray value of the structuring element.
Default Value : 0
Suggested values : Smax ∈ {0, 1, 2, 5, 10, 20, 30, 40}
Typical range of values : 0 ≤ Smax ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 1
Result
GenDiscSe returns TRUE if all parameters are correct. If necessary, an exception is raised.
Parallelization Information
GenDiscSe is reentrant and processed without parallelization.
Possible Successors
GrayErosion, GrayDilation, GrayOpening, GrayClosing, GrayTophat, GrayBothat
See also
ReadImage, PaintRegion, PaintGray, CropPart
Alternatives
ReadGraySe
Module
Foundation

HImageX.GrayBothat ([in] HImageX SE )


[out] HImageX ImageBotHat
void HOperatorSetX.GrayBothat ([in] IHObjectX Image, [in] IHObjectX SE,
[out] HUntypedObjectX ImageBotHat )

Perform a gray value bottom hat transformation on an image.

HALCON 8.0.2
680 CHAPTER 9. MORPHOLOGY

GrayBothat applies a gray value bottom hat transformation to the input image Image with the structuring
element SE. The gray value bottom hat transformation of an image i with a structuring element s is defined as

bothat(i, s) = (i • s) − i,

i.e., the difference of the closing of the image with s and the image (see GrayClosing). For the generation of
structuring elements, see ReadGraySe.
Parameter
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte, real )
Input image.
. SE (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte )
Structuring element.
. ImageBotHat (output iconic) . . . . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, real )
Bottom hat image.
Result
GrayBothat returns TRUE if the structuring element is not the empty region. Otherwise, an exception is raised.
Parallelization Information
GrayBothat is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
ReadGraySe, GenDiscSe
Possible Successors
Threshold
See also
GrayTophat, TopHat, GrayErosionRect, SubImage
Alternatives
GrayClosing
Module
Foundation

HImageX.GrayClosing ([in] HImageX SE )


[out] HImageX ImageClosing
void HOperatorSetX.GrayClosing ([in] IHObjectX Image,
[in] IHObjectX SE, [out] HUntypedObjectX ImageClosing )

Perform a gray value closing on an image.


GrayClosing applies a gray value closing to the input image Image with the structuring element SE. The gray
value closing of an image i with a structuring element s is defined as

i • s = (i ⊕ s) s ,

i.e., a dilation of the image with s followed by an erosion with s (see GrayDilation and GrayErosion).
For the generation of structuring elements, see ReadGraySe.
Parameter
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte, real )
Input image.
. SE (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte )
Structuring element.
. ImageClosing (output iconic) . . . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, real )
Gray-closed image.
Result
GrayClosing returns TRUE if the structuring element is not the empty region. Otherwise, an exception is
raised.

HALCON/COM Reference Manual, 2008-5-13


9.1. GRAY-VALUES 681

Parallelization Information
GrayClosing is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
ReadGraySe
See also
Closing, GrayDilation, GrayErosion
Alternatives
DualRank
Module
Foundation

[out] HImageX ImageClosing HImageX.GrayClosingRect


([in] long MaskHeight, [in] long MaskWidth )
void HOperatorSetX.GrayClosingRect ([in] IHObjectX Image,
[out] HUntypedObjectX ImageClosing, [in] VARIANT MaskHeight,
[in] VARIANT MaskWidth )

Perform a gray value closing with a rectangular mask.


GrayClosingRect applies a gray value closing to the input image Image with a rectangular mask of
size (MaskHeight, MaskWidth). The resulting image is returned in ImageClosing. If the parameters
MaskHeight or MaskWidth are even, they are changed to the next larger odd value. At the border of the image
the gray values are mirrored.
The gray value closing of an image i with a rectangular structuring element s is defined as

i ◦ s = (i ⊕ s) s ,

i.e., a dilation of the image with s followed by an erosion with s (see GrayDilationRect and
GrayErosionRect).
Parameter
. Image (input iconic) . . . . . . image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic, int2, int4, real )
Input image.
. ImageClosing (output iconic) . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, direction,
cyclic, int2, int4, real )
Gray-closed image.
. MaskHeight (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; long / VARIANT
Height of the filter mask.
Default Value : 11
Suggested values : MaskHeight ∈ {3, 5, 7, 9, 11, 13, 15}
Typical range of values : 3 ≤ MaskHeight ≤ 3
Minimum Increment : 2
Recommended Increment : 2
Restriction : odd
. MaskWidth (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; long / VARIANT
Width of the filter mask.
Default Value : 11
Suggested values : MaskWidth ∈ {3, 5, 7, 9, 11, 13, 15}
Typical range of values : 3 ≤ MaskWidth ≤ 3
Minimum Increment : 2
Recommended Increment : 2
Restriction : odd
Result
GrayClosingRect returns TRUE if all parameters are correct. If the input is empty the behavior can be set via
SetSystem(’noObjectResult’,<Result>). If necessary, an exception is raised.

HALCON 8.0.2
682 CHAPTER 9. MORPHOLOGY

Parallelization Information
GrayClosingRect is reentrant and automatically parallelized (on tuple level, channel level, domain level).
See also
ClosingRectangle1, GrayDilationRect, GrayErosionRect
Alternatives
GrayClosing, GrayClosingShape
Module
Foundation

[out] HImageX ImageClosing HImageX.GrayClosingShape


([in] VARIANT MaskHeight, [in] VARIANT MaskWidth, [in] String MaskShape )
void HOperatorSetX.GrayClosingShape ([in] IHObjectX Image,
[out] HUntypedObjectX ImageClosing, [in] VARIANT MaskHeight,
[in] VARIANT MaskWidth, [in] VARIANT MaskShape )

Perform a grayvalue closing with a selected mask.


GrayClosingShape applies a gray value closing to the input image Image with the structuring element of
shape MaskShape. The mask’s offset values are 0 and its horizontal and vertical size is defined by MaskHeight
and MaskWidth. The resulting image is returned in ImageClosing.
If the parameters MaskHeight or MaskWidth are of the type integer and are even, they are changed to the next
larger odd value. In contrast, if at least one of the two parameters is of the type float, the input image Image is
transformed with both the next larger and the next smaller odd mask size, and the output image ImageClosing
is interpolated from the two intermediate images. Therefore, note that GrayClosingShape returns different
results for mask sizes of, e.g., 4 and 4.0!
In case of the values ’rhombus’ and ’octagon’ for the MaskShape control parameter, MaskHeight and
MaskWidth must be equal. The parameter value ’octagon’ for MaskShape denotes an equilateral octagonal
mask which is a suitable approximation for a circular structure. At the border of the image the gray values are
mirrored.
The gray value closing of an image i with a structuring element s is defined as

i • s = (i ⊕ s) s ,

i.e., a dilation of the image with s followed by an erosion with s (see GrayDilationShape and
GrayErosionShape).
Attention
Note that GrayClosingShape requires considerably more time for mask sizes of type float than for mask sizes
of type integer. This is especially true for rectangular masks with differnt width and height!
Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte, uint2 )


Image for which the minimum gray values are to be calculated.
. ImageClosing (output iconic) . . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, uint2 )
Image containing the minimum gray values.
. MaskHeight (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; VARIANT ( integer, real )
Height of the filter mask.
Default Value : 11
Suggested values : MaskHeight ∈ {3, 5, 7, 9, 11, 13, 15}
Typical range of values : 1.0 ≤ MaskHeight ≤ 1.0
. MaskWidth (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; VARIANT ( integer, real )
Width of the filter mask.
Default Value : 11
Suggested values : MaskWidth ∈ {3, 5, 7, 9, 11, 13, 15}
Typical range of values : 1.0 ≤ MaskWidth ≤ 1.0

HALCON/COM Reference Manual, 2008-5-13


9.1. GRAY-VALUES 683

. MaskShape (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT


Shape of the mask.
Default Value : ’octagon’
List of values : MaskShape ∈ {’rectangle’, ’rhombus’, ’octagon’}
Result
GrayClosingShape returns TRUE if all parameters are correct.
Parallelization Information
GrayClosingShape is reentrant and automatically parallelized (on tuple level, channel level, domain level).
See also
GrayDilationShape, GrayErosionShape, Closing
Alternatives
GrayClosing
Module
Foundation

HImageX.GrayDilation ([in] HImageX SE )


[out] HImageX ImageDilation
void HOperatorSetX.GrayDilation ([in] IHObjectX Image,
[in] IHObjectX SE, [out] HUntypedObjectX ImageDilation )

Perform a gray value dilation on an image.


GrayDilation applies a gray value dilation to the input image Image with the structuring element SE. The
gray value dilation of an image i with a structuring element s at the pixel position x is defined as:

(i ⊕ s)(x) = max{f (x − z) + s(z)|z ∈ S}

Here, S is the domain of the structuring element s, i.e., the pixels z where s(z) > 0 (see ReadGraySe).
Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte, real )


Input image.
. SE (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte )
Structuring element.
. ImageDilation (output iconic) . . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, real )
Gray-dilated image.
Result
GrayDilation returns TRUE if the structuring element is not the empty region. Otherwise, an exception is
raised.
Parallelization Information
GrayDilation is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
ReadGraySe
Possible Successors
SubImage, GrayErosion
See also
GrayOpening, GrayClosing, Dilation1, GraySkeleton
Alternatives
GrayDilationRect
Module
Foundation

HALCON 8.0.2
684 CHAPTER 9. MORPHOLOGY

[out] HImageX ImageMax HImageX.GrayDilationRect ([in] long MaskHeight,


[in] long MaskWidth )
void HOperatorSetX.GrayDilationRect ([in] IHObjectX Image,
[out] HUntypedObjectX ImageMax, [in] VARIANT MaskHeight,
[in] VARIANT MaskWidth )

Determine the maximum gray value within a rectangle.


GrayDilationRect calculates the maximum gray value of the input image Image within a rectangular mask
of size (MaskHeight, MaskWidth) for each image point. The resulting image is returned in ImageMax. If the
parameters MaskHeight or MaskWidth are even, they are changed to the next larger odd value. At the border
of the image the gray values are mirrored.
Parameter
. Image (input iconic) . . . . . . image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic, int2, int4, real )
Image for which the maximum gray values are to be calculated.
. ImageMax (output iconic) . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, direction, cyclic,
int2, int4, real )
Image containing the maximum gray values.
. MaskHeight (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; long / VARIANT
Height of the filter mask.
Default Value : 11
Suggested values : MaskHeight ∈ {3, 5, 7, 9, 11, 13, 15}
Typical range of values : 3 ≤ MaskHeight ≤ 3
Minimum Increment : 2
Recommended Increment : 2
Restriction : odd
. MaskWidth (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; long / VARIANT
Width of the filter mask.
Default Value : 11
Suggested values : MaskWidth ∈ {3, 5, 7, 9, 11, 13, 15}
Typical range of values : 3 ≤ MaskWidth ≤ 3
Minimum Increment : 2
Recommended Increment : 2
Restriction : odd
Result
GrayDilationRect returns TRUE if all parameters are correct. If the input is empty the behavior can be set
via SetSystem(’noObjectResult’,<Result>). If necessary, an exception is raised.
Parallelization Information
GrayDilationRect is reentrant and automatically parallelized (on tuple level, channel level, domain level).
See also
GraySkeleton
Module
Foundation

[out] HImageX ImageMax HImageX.GrayDilationShape


([in] VARIANT MaskHeight, [in] VARIANT MaskWidth, [in] String MaskShape )
void HOperatorSetX.GrayDilationShape ([in] IHObjectX Image,
[out] HUntypedObjectX ImageMax, [in] VARIANT MaskHeight,
[in] VARIANT MaskWidth, [in] VARIANT MaskShape )

Determine the maximum gray value within a selected mask.


GrayDilationShape calculates the maximum gray value of the input image Image within a mask of shape
MaskShape, vertical size MaskHeight and horizontal size MaskWidth for each image point. The resulting
image is returned in ImageMax.

HALCON/COM Reference Manual, 2008-5-13


9.1. GRAY-VALUES 685

If the parameters MaskHeight or MaskWidth are of the type integer and are even, they are changed to the next
larger odd value. In contrast, if at least one of the two parameters is of the type float, the input image Image is
transformed with both the next larger and the next smaller odd mask size, and the output image ImageMax is
interpolated from the two intermediate images. Therefore, note that GrayDilationShape returns different
results for mask sizes of, e.g., 4 and 4.0!
In case of the values ’rhombus’ und ’octagon’ for the MaskShape control parameter, MaskHeight and
MaskWidth must be equal. The parameter value ’octagon’ for MaskShape denotes an equilateral octagonal
mask which is a suitable approximation for a circular structure. At the border of the image the gray values are
mirrored.
Attention
Note that GrayDilationShape requires considerably more time for mask sizes of type float than for mask
sizes of type integer. This is especially true for rectangular masks with differnt width and height!
Parameter
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte, uint2 )
Image for which the maximum gray values are to be calculated.
. ImageMax (output iconic) . . . . . . . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, uint2 )
Image containing the maximum gray values.
. MaskHeight (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; VARIANT ( integer, real )
Height of the filter mask.
Default Value : 11
Suggested values : MaskHeight ∈ {3, 5, 7, 9, 11, 13, 15}
. MaskWidth (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; VARIANT ( integer, real )
Width of the filter mask.
Default Value : 11
Suggested values : MaskWidth ∈ {3, 5, 7, 9, 11, 13, 15}
. MaskShape (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Shape of the mask.
Default Value : ’octagon’
List of values : MaskShape ∈ {’rectangle’, ’rhombus’, ’octagon’}
Result
GrayDilationShape returns TRUE if all parameters are correct.
Parallelization Information
GrayDilationShape is reentrant and automatically parallelized (on tuple level, channel level, domain level).
See also
GrayOpeningShape, GrayClosingShape, GraySkeleton
Alternatives
GrayDilation, GrayDilationRect
Module
Foundation

HImageX.GrayErosion ([in] HImageX SE )


[out] HImageX ImageErosion
void HOperatorSetX.GrayErosion ([in] IHObjectX Image,
[in] IHObjectX SE, [out] HUntypedObjectX ImageErosion )

Perform a gray value erosion on an image.


GrayErosion applies a gray value erosion to the input image Image with the structuring element SE. The gray
value erosion of an image i with a structuring element s at the pixel position x is defined as:

(i s)(x) = min{f (x + z) − s(z)|z ∈ S}

Here, S is the domain of the structuring element s, i.e., the pixels z where s(z) > 0 (see ReadGraySe).

HALCON 8.0.2
686 CHAPTER 9. MORPHOLOGY

Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte, real )


Input image.
. SE (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte )
Structuring element.
. ImageErosion (output iconic) . . . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, real )
Gray-eroded image.
Result
GrayErosion returns TRUE if the structuring element is not the empty region. Otherwise, an exception is
raised.
Parallelization Information
GrayErosion is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
ReadGraySe
Possible Successors
GrayDilation, SubImage
See also
GrayOpening, GrayClosing, Erosion1, GraySkeleton
Alternatives
GrayErosionRect
Module
Foundation

[out] HImageX ImageMin HImageX.GrayErosionRect ([in] long MaskHeight,


[in] long MaskWidth )
void HOperatorSetX.GrayErosionRect ([in] IHObjectX Image,
[out] HUntypedObjectX ImageMin, [in] VARIANT MaskHeight,
[in] VARIANT MaskWidth )

Determine the minimum gray value within a rectangle.


GrayErosionRect calculates the minimum gray value of the input image Image within a rectangular mask of
size (MaskHeight, MaskWidth) for each image point. The resulting image is returned in ImageMin. If the
parameters MaskHeight or MaskWidth are even, they are changed to the next larger odd value. At the border
of the image the gray values are mirrored.
Parameter

. Image (input iconic) . . . . . . image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic, int2, int4, real )
Image for which the minimum gray values are to be calculated.
. ImageMin (output iconic) . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, direction, cyclic,
int2, int4, real )
Image containing the minimum gray values.
. MaskHeight (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; long / VARIANT
Height of the filter mask.
Default Value : 11
Suggested values : MaskHeight ∈ {3, 5, 7, 9, 11, 13, 15}
Typical range of values : 3 ≤ MaskHeight ≤ 3(lin)
Minimum Increment : 2
Recommended Increment : 2
Restriction : odd

HALCON/COM Reference Manual, 2008-5-13


9.1. GRAY-VALUES 687

. MaskWidth (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; long / VARIANT


Width of the filter mask.
Default Value : 11
Suggested values : MaskWidth ∈ {3, 5, 7, 9, 11, 13, 15}
Typical range of values : 3 ≤ MaskWidth ≤ 3(lin)
Minimum Increment : 2
Recommended Increment : 2
Restriction : odd
Result
GrayErosionRect returns TRUE if all parameters are correct. If the input is empty the behavior can be set via
SetSystem(’noObjectResult’,<Result>). If necessary, an exception is raised.
Parallelization Information
GrayErosionRect is reentrant and automatically parallelized (on tuple level, channel level, domain level).
See also
GrayDilationRect
Module
Foundation

[out] HImageX ImageMin HImageX.GrayErosionShape


([in] VARIANT MaskHeight, [in] VARIANT MaskWidth, [in] String MaskShape )
void HOperatorSetX.GrayErosionShape ([in] IHObjectX Image,
[out] HUntypedObjectX ImageMin, [in] VARIANT MaskHeight,
[in] VARIANT MaskWidth, [in] VARIANT MaskShape )

Determine the minimum gray value within a selected mask.


GrayErosionShape calculates the minimum gray value of the input image Image within a mask of shape
MaskShape, vertical size MaskHeight and horizontal size MaskWidth for each image point. The resulting
image is returned in ImageMin.
If the parameters MaskHeight or MaskWidth are of the type integer and are even, they are changed to the next
larger odd value. In contrast, if at least one of the two parameters is of the type float, the input image Image
is transformed with both the next larger and the next smaller odd mask size, and the output image ImageMin
is interpolated from the two intermediate images. Therefore, note that GrayErosionShape returns different
results for mask sizes of, e.g., 4 and 4.0!
In case of the values ’rhombus’ and ’octagon’ for the MaskShape control parameter, MaskHeight and
MaskWidth must be equal. The parameter value ’octagon’ for MaskShape denotes an equilateral octagonal
mask which is a suitable approximation for a circular structure. At the border of the image the gray values are
mirrored.
Attention
Note that GrayErosionShape requires considerably more time for mask sizes of type float than for mask sizes
of type integer. This is especially true for rectangular masks with differnt width and height!
Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte, uint2 )


Image for which the minimum gray values are to be calculated.
. ImageMin (output iconic) . . . . . . . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, uint2 )
Image containing the minimum gray values.
. MaskHeight (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; VARIANT ( integer, real )
Height of the filter mask.
Default Value : 11
Suggested values : MaskHeight ∈ {3, 5, 7, 9, 11, 13, 15}
. MaskWidth (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; VARIANT ( integer, real )
Width of the filter mask.
Default Value : 11
Suggested values : MaskWidth ∈ {3, 5, 7, 9, 11, 13, 15}

HALCON 8.0.2
688 CHAPTER 9. MORPHOLOGY

. MaskShape (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT


Shape of the mask.
Default Value : ’octagon’
List of values : MaskShape ∈ {’rectangle’, ’rhombus’, ’octagon’}
Result
GrayErosionShape returns TRUE if all parameters are correct.
Parallelization Information
GrayErosionShape is reentrant and automatically parallelized (on tuple level, channel level, domain level).
See also
GrayOpeningShape, GrayClosingShape, GraySkeleton
Alternatives
GrayErosion, GrayErosionRect
Module
Foundation

HImageX.GrayOpening ([in] HImageX SE )


[out] HImageX ImageOpening
void HOperatorSetX.GrayOpening ([in] IHObjectX Image,
[in] IHObjectX SE, [out] HUntypedObjectX ImageOpening )

Perform a gray value opening on an image.


GrayOpening applies a gray value opening to the input image Image with the structuring element SE. The gray
value opening of an image i with a structuring element s is defined as

i ◦ s = (i s) ⊕ s ,

i.e., an erosion of the image with s followed by a dilation with s (see GrayErosion and GrayDilation).
For the generation of structuring elements, see ReadGraySe.
Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte, real )


Input image.
. SE (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte )
Structuring element.
. ImageOpening (output iconic) . . . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, real )
Gray-opened image.
Result
GrayOpening returns TRUE if the structuring element is not the empty region. Otherwise, an exception is
raised.
Parallelization Information
GrayOpening is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
ReadGraySe
See also
Opening, GrayDilation, GrayErosion
Alternatives
DualRank
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


9.1. GRAY-VALUES 689

[out] HImageX ImageOpening HImageX.GrayOpeningRect


([in] long MaskHeight, [in] long MaskWidth )
void HOperatorSetX.GrayOpeningRect ([in] IHObjectX Image,
[out] HUntypedObjectX ImageOpening, [in] VARIANT MaskHeight,
[in] VARIANT MaskWidth )

Perform a gray value opening with a rectangular mask.


GrayOpeningRect applies a gray value opening to the input image Image with a rectangular mask of
size (MaskHeight, MaskWidth). The resulting image is returned in ImageOpening. If the parameters
MaskHeight or MaskWidth are even, they are changed to the next larger odd value. At the border of the image
the gray values are mirrored.
The gray value opening of an image i with a rectangular structuring element s is defined as

i ◦ s = (i s) ⊕ s ,

i.e., an erosion of the image with s followed by a dilation with s (see GrayErosionRect and
GrayDilationRect).
Parameter

. Image (input iconic) . . . . . . image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic, int2, int4, real )
Input image.
. ImageOpening (output iconic) . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, direction,
cyclic, int2, int4, real )
Gray-opened image.
. MaskHeight (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; long / VARIANT
Height of the filter mask.
Default Value : 11
Suggested values : MaskHeight ∈ {3, 5, 7, 9, 11, 13, 15}
Typical range of values : 3 ≤ MaskHeight ≤ 3
Minimum Increment : 2
Recommended Increment : 2
Restriction : odd
. MaskWidth (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; long / VARIANT
Width of the filter mask.
Default Value : 11
Suggested values : MaskWidth ∈ {3, 5, 7, 9, 11, 13, 15}
Typical range of values : 3 ≤ MaskWidth ≤ 3
Minimum Increment : 2
Recommended Increment : 2
Restriction : odd
Result
GrayOpeningRect returns TRUE if all parameters are correct. If the input is empty the behavior can be set via
SetSystem(’noObjectResult’,<Result>). If necessary, an exception is raised.
Parallelization Information
GrayOpeningRect is reentrant and automatically parallelized (on tuple level, channel level, domain level).
See also
OpeningRectangle1, GrayDilationRect, GrayErosionRect
Alternatives
GrayOpening, GrayOpeningShape
Module
Foundation

HALCON 8.0.2
690 CHAPTER 9. MORPHOLOGY

[out] HImageX ImageOpening HImageX.GrayOpeningShape


([in] VARIANT MaskHeight, [in] VARIANT MaskWidth, [in] String MaskShape )
void HOperatorSetX.GrayOpeningShape ([in] IHObjectX Image,
[out] HUntypedObjectX ImageOpening, [in] VARIANT MaskHeight,
[in] VARIANT MaskWidth, [in] VARIANT MaskShape )

Perform a gray value opening with a selected mask.


GrayOpeningShape applies a gray value opening to the input image Image with the structuring element of
shape MaskShape. The mask’s offset values are 0 and its horizontal and vertical size is defined by MaskHeight
and MaskWidth. The resulting image is returned in ImageOpening.
If the parameters MaskHeight or MaskWidth are of the type integer and are even, they are changed to the next
larger odd value. In contrast, if at least one of the two parameters is of the type float, the input image Image is
transformed with both the next larger and the next smaller odd mask size, and the output image ImageOpening
is interpolated from the two intermediate images. Therefore, note that GrayOpeningShape returns different
results for mask sizes of, e.g., 4 and 4.0!
In case of the values ’rhombus’ and ’octagon’ for the MaskShape control parameter, MaskHeight and
MaskWidth must be equal. The parameter value ’octagon’ for MaskShape denotes an equilateral octagonal
mask which is a suitable approximation for a circular structure. At the border of the image the gray values are
mirrored.
The gray value opening of an image i with a structuring element s is defined as

i ◦ s = (i s) ⊕ s ,

i.e., an erosion of the image with s followed by a dilation with s (see GrayErosionShape and
GrayDilationShape).
Attention
Note that GrayOpeningShape requires considerably more time for mask sizes of type float than for mask sizes
of type integer. This is especially true for rectangular masks with differnt width and height!
Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte, uint2 )


Image for which the minimum gray values are to be calculated.
. ImageOpening (output iconic) . . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, uint2 )
Image containing the minimum gray values.
. MaskHeight (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; VARIANT ( integer, real )
Height of the filter mask.
Default Value : 11
Suggested values : MaskHeight ∈ {3, 5, 7, 9, 11, 13, 15}
Typical range of values : 1.0 ≤ MaskHeight ≤ 1.0
. MaskWidth (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; VARIANT ( integer, real )
Width of the filter mask.
Default Value : 11
Suggested values : MaskWidth ∈ {3, 5, 7, 9, 11, 13, 15}
Typical range of values : 1.0 ≤ MaskWidth ≤ 1.0
. MaskShape (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Shape of the mask.
Default Value : ’octagon’
List of values : MaskShape ∈ {’rectangle’, ’rhombus’, ’octagon’}
Result
GrayOpeningShape returns TRUE if all parameters are correct.
Parallelization Information
GrayOpeningShape is reentrant and automatically parallelized (on tuple level, channel level, domain level).
See also
GrayDilationShape, GrayErosionShape, Opening

HALCON/COM Reference Manual, 2008-5-13


9.1. GRAY-VALUES 691

Alternatives
GrayOpening
Module
Foundation

[out] HImageX ImageResult HImageX.GrayRangeRect ([in] long MaskHeight,


[in] long MaskWidth )
void HOperatorSetX.GrayRangeRect ([in] IHObjectX Image,
[out] HUntypedObjectX ImageResult, [in] VARIANT MaskHeight,
[in] VARIANT MaskWidth )

Determine the gray value range within a rectangle.


GrayRangeRect calculates the gray value range, i.e., the difference (max − min) of the maximum and min-
imum gray values, of the input image Image within a rectangular mask of size (MaskHeight, MaskWidth)
for each image point. The resulting image is returned in ImageResult. If the parameters MaskHeight or
MaskWidth are even, they are changed to the next larger odd value. At the border of the image the gray values
are mirrored.
Parameter

. Image (input iconic) . . . . . . image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic, int2, int4, real )
Image for which the gray value range is to be calculated.
. ImageResult (output iconic) . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, direction,
cyclic, int2, int4, real )
Image containing the gray value range.
. MaskHeight (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; long / VARIANT
Height of the filter mask.
Default Value : 11
Suggested values : MaskHeight ∈ {3, 5, 7, 9, 11, 13, 15}
Typical range of values : 3 ≤ MaskHeight ≤ 3(lin)
Minimum Increment : 2
Recommended Increment : 2
Restriction : odd
. MaskWidth (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; long / VARIANT
Width of the filter mask.
Default Value : 11
Suggested values : MaskWidth ∈ {3, 5, 7, 9, 11, 13, 15}
Typical range of values : 3 ≤ MaskWidth ≤ 3(lin)
Minimum Increment : 2
Recommended Increment : 2
Restriction : odd
Result
GrayRangeRect returns TRUE if all parameters are correct. If the input is empty the behavior can be set via
SetSystem(’noObjectResult’,<Result>). If necessary, an exception is raised.
Parallelization Information
GrayRangeRect is reentrant and automatically parallelized (on tuple level, channel level, domain level).
Alternatives
GrayDilationRect, GrayErosionRect, SubImage
Module
Foundation

HALCON 8.0.2
692 CHAPTER 9. MORPHOLOGY

HImageX.GrayTophat ([in] HImageX SE )


[out] HImageX ImageTopHat
void HOperatorSetX.GrayTophat ([in] IHObjectX Image, [in] IHObjectX SE,
[out] HUntypedObjectX ImageTopHat )

Perform a gray value top hat transformation on an image.


GrayTophat applies a gray value top hat transformation to the input image Image with the structuring element
SE. The gray value top hat transformation of an image i with a structuring element s is defined as

tophat(i, s) = i − (i ◦ s),

i.e., the difference of the image and its opening with s (see GrayOpening). For the generation of structuring
elements, see ReadGraySe.
Parameter
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte, real )
Input image.
. SE (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte )
Structuring element.
. ImageTopHat (output iconic) . . . . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, real )
Top hat image.
Result
GrayTophat returns TRUE if the structuring element is not the empty region. Otherwise, an exception is raised.
Parallelization Information
GrayTophat is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
ReadGraySe, GenDiscSe
Possible Successors
Threshold
See also
GrayBothat, TopHat, GrayErosionRect, SubImage
Alternatives
GrayOpening
Module
Foundation

void HImageX.ReadGraySe ([in] String FileName )


void HOperatorSetX.ReadGraySe ([out] HUntypedObjectX SE,
[in] VARIANT FileName )

Load a structuring element for gray morphology.


ReadGraySe loads a structuring element for gray morphology from a file. The file names of these structur-
ing elements must end in ’.gse’ (for gray-scale structuring element). This suffix is automatically appended by
ReadGraySe to the passed file name, and thus must not be passed. The structuring element’s data must be
contained in the file in the following format: The first two numbers in the file determine the width and height of
the structuring element, and determine a rectangle enclosing the structuring element. Both values must be greater
than 0. Then, Width*Height integer numbers follow, with the following interpretation: Values smaller than 0 are
regarded as not belonging to the region of the structuring element, i.e., they are not considered in morphological
operations. This allows the creation of irregularly shaped, not connected structuring elements. All other values
are regarded as the corresponding values for gray morphology. Structuring elements are stored internally as byte-
images, with negative values being mapped to 0, and all other values increased by 1. Thus, normal byte-images
can also be used as structuring elements. However, care should be taken not to use too large images, since the
runtime is proportional to the area of the image times the area of the structuring element.

HALCON/COM Reference Manual, 2008-5-13


9.2. REGION 693

Parameter
. SE (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / HUntypedObjectX ( byte )
Generated structuring element.
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.read ; String / VARIANT
Name of the file containing the structuring element.
Result
ReadGraySe returns TRUE if all parameters are correct. Otherwise, an exception is raised.
Parallelization Information
ReadGraySe is reentrant and processed without parallelization.
Possible Successors
GrayErosion, GrayDilation, GrayOpening, GrayClosing, GrayTophat, GrayBothat
See also
ReadImage, PaintRegion, PaintGray, CropPart
Alternatives
GenDiscSe
Module
Foundation

9.2 Region

[out] HRegionX RegionBottomHat HRegionX.BottomHat


([in] HRegionX StructElement )
void HOperatorSetX.BottomHat ([in] IHObjectX Region,
[in] IHObjectX StructElement, [out] HUntypedObjectX RegionBottomHat )

Compute the bottom hat of regions.


BottomHat computes the Closing of Region with StructElement. The difference between the result of
the closing and the original region is called the bottom hat. In contrast to Closing, which merges regions under
certain circumstances, BottomHat computes the regions generated by such a merge.
The position of StructElement is meaningless, since a closing operation is invariant with respect to the choice
of the reference point.
Structuring elements (StructElement) can be generated with operators such as GenCircle,
GenRectangle1, GenRectangle2, GenEllipse, DrawRegion, GenRegionPolygon,
GenRegionPoints, etc.
Parameter
. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Regions to be processed.
. StructElement (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
Structuring element (position independent).
. RegionBottomHat (output iconic) . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Result of the bottom hat operator.
Example

read_image (Image,’/bilder/name.ext’)
threshold (Image,Regions,128,255)
gen_circle (Circle,0,0,16)
bottom_hat (Regions,Circle,RegionBottomHat).

Result
BottomHat returns TRUE if all parameters are correct. The behavior in case of empty or no input region can be
set via:

HALCON 8.0.2
694 CHAPTER 9. MORPHOLOGY

• no region: SetSystem(’noObjectResult’,<RegionResult>)
• empty region: SetSystem(’emptyRegionResult’,<RegionResult>)

Otherwise, an exception is raised.


Parallelization Information
BottomHat is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection, Union1, Watersheds, ClassNdimNorm, GenCircle,
GenEllipse, GenRectangle1, GenRectangle2, DrawRegion, GenRegionPoints,
GenStructElements, GenRegionPolygonFilled
Possible Successors
ReduceDomain, SelectShape, AreaCenter, Connection
See also
TopHat, MorphHat, GrayBothat, Opening
Alternatives
Closing, Difference
Module
Foundation

HRegionX.Boundary ([in] String BoundaryType )


[out] HRegionX RegionBorder
void HOperatorSetX.Boundary ([in] IHObjectX Region,
[out] HUntypedObjectX RegionBorder, [in] VARIANT BoundaryType )

Reduce a region to its boundary.


Boundary computes the boundary of a region by using morphological operations. The parameter
BoundaryType determines the type of boundary to compute:
’inner’, ’inner_filled’ and ’outer’.
Boundary computes the contour of each input region. The resulting regions consist only of the minimal border
of the input regions. If BoundaryType is set to ’inner’, the contour lies within the original region, if it is set
to ’outer’, it is one pixel outside of the original region. If BoundaryType is set to ’inner_filled’, holes in the
interior of the input region are suppressed.
Parameter

. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Regions for which the boundary is to be computed.
. RegionBorder (output iconic) . . . . . . . . . . . . . . . . . . . . . . . .region(-array) ; HRegionX / HUntypedObjectX
Resulting boundaries.
. BoundaryType (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Boundary type.
Default Value : ’inner’
List of values : BoundaryType ∈ {’inner’, ’outer’, ’inner_filled’}
Complexity
Let F be the area of the input region. Then the runtime complexity for one region is

O(3 F ) .

Result
Boundary returns TRUE if all parameters are correct. The behavior in case of empty or no input region can be
set via:

• no region: SetSystem(’noObjectResult’,<RegionResult>)
• empty region: SetSystem(’emptyRegionResult’,<RegionResult>)

HALCON/COM Reference Manual, 2008-5-13


9.2. REGION 695

Otherwise, an exception is raised.


Parallelization Information
Boundary is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection, Union1, Watersheds, ClassNdimNorm
Possible Successors
ReduceDomain, SelectShape, AreaCenter, Connection
See also
FillUp
Alternatives
DilationCircle, ErosionCircle, Difference
Module
Foundation

[out] HRegionX RegionClosing HRegionX.Closing


([in] HRegionX StructElement )
void HOperatorSetX.Closing ([in] IHObjectX Region,
[in] IHObjectX StructElement, [out] HUntypedObjectX RegionClosing )

Close a region.
A Closing operation is defined as a dilation followed by a Minkowsi subtraction. By applying Closing
to a region, larger structures remain mostly intact, while small gaps between adjacent regions and holes smaller
than StructElement are closed, and the regions’ boundaries are smoothed. All Closing variants share the
property that separate regions are not merged, but remain separate objects. The position of StructElement is
meaningless, since a closing operation is invariant with respect to the choice of the reference point.
Structuring elements (StructElement) can be generated with operators such as GenCircle,
GenRectangle1, GenRectangle2, GenEllipse, DrawRegion, GenRegionPolygon,
GenRegionPoints, etc.
Attention
Closing is applied to each input region separately. If gaps between different regions are to be closed, Union1
or Union2 has to be called first.
Parameter

. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Regions to be closed.
. StructElement (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
Structuring element (position-invariant).
. RegionClosing (output iconic) . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Closed regions.
Complexity
Let F 1 be the area of the input region, and F 2 be the area of the structuring element. Then the runtime complexity
for one region is:
√ √
O(2 · F1 · F 2) .

Result
Closing returns TRUE if all parameters are correct. The behavior in case of empty or no input region can be set
via:

• no region: SetSystem(’noObjectResult’,<RegionResult>)
• empty region: SetSystem(’emptyRegionResult’,<RegionResult>)

HALCON 8.0.2
696 CHAPTER 9. MORPHOLOGY

Otherwise, an exception is raised.


Parallelization Information
Closing is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection, Union1, Watersheds, ClassNdimNorm, GenCircle,
GenEllipse, GenRectangle1, GenRectangle2, DrawRegion, GenRegionPoints,
GenStructElements, GenRegionPolygonFilled
Possible Successors
ReduceDomain, SelectShape, AreaCenter, Connection
See also
Dilation1, Erosion1, Opening, MinkowskiSub1
Alternatives
ClosingCircle, ClosingGolay
Module
Foundation

[out] HRegionX RegionClosing HRegionX.ClosingCircle


([in] VARIANT Radius )
void HOperatorSetX.ClosingCircle ([in] IHObjectX Region,
[out] HUntypedObjectX RegionClosing, [in] VARIANT Radius )

Close a region with a circular structuring element.


ClosingCircle behaves analogously to Closing, i.e., the regions’ boundaries are smoothed and holes
within a region which are smaller than the circular structuring element of radius Radius are closed. The
ClosingCircle operation is defined as a dilation followed by a Minkowski subtraction, both with the same
circular structuring element.
Attention
ClosingCircle is applied to each input region separately. If gaps between different regions are to be closed,
Union1 or Union2 has to be called first.
Parameter

. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Regions to be closed.
. RegionClosing (output iconic) . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Closed regions.
. Radius (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real, integer )
Radius of the circular structuring element.
Default Value : 3.5
Suggested values : Radius ∈ {1.5, 2.5, 3.5, 4.5, 5.5, 7.5, 9.5, 12.5, 15.5, 19.5, 25.5, 33.5, 45.5, 60.5, 110.5}
Typical range of values : 0.5 ≤ Radius ≤ 0.5(lin)
Minimum Increment : 1.0
Recommended Increment : 1.0
Complexity
Let F 1 be the area of the input region. Then the runtime complexity for one region is:

O(4 · F 1 · Radius) .

Result
ClosingCircle returns TRUE if all parameters are correct. The behavior in case of empty or no input region
can be set via:

• no region: SetSystem(’noObjectResult’,<RegionResult>)
• empty region: SetSystem(’emptyRegionResult’,<RegionResult>)

HALCON/COM Reference Manual, 2008-5-13


9.2. REGION 697

Otherwise, an exception is raised.


Parallelization Information
ClosingCircle is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection, Union1, Watersheds, ClassNdimNorm
Possible Successors
ReduceDomain, SelectShape, AreaCenter, Connection
See also
Dilation1, MinkowskiSub1, Erosion1, Opening
Alternatives
RankRegion, FillUp, Closing, ClosingCircle, ClosingGolay
Module
Foundation

[out] HRegionX RegionClosing HRegionX.ClosingGolay


([in] String GolayElement, [in] long Rotation )
void HOperatorSetX.ClosingGolay ([in] IHObjectX Region,
[out] HUntypedObjectX RegionClosing, [in] VARIANT GolayElement,
[in] VARIANT Rotation )

Close a region with an element from the Golay alphabet.


ClosingGolay is defined as a Minkowski addition followed by a Minkowski subtraction. First the Minkowski
addition of the input region (Region) with the structuring element from the Golay alphabet defined by
GolayElement and Rotation is computed. Then the Minkowski subtraction of the result and the structuring
element rotated by 180◦ is performed.
The following structuring elements are available:
’l’, ’m’, ’d’, ’c’, ’e’, ’i’, ’f’, ’f2’, ’h’, ’k’.
The rotation number Rotation determines which rotation of the element should be used, and whether the fore-
ground (even) or background version (odd) of the selected element should be used. The Golay elements, together
with all possible rotations, are described with the operator GolayElements.
ClosingGolay serves to close holes smaller than the structuring element, and to smooth regions’ boundaries.
Attention
Not all values of Rotation are valid for any Golay element. For some of the values of Rotation, the resulting
regions are identical to the input regions.
Parameter

. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Regions to be closed.
. RegionClosing (output iconic) . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Closed regions.
. GolayElement (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Structuring element from the Golay alphabet.
Default Value : ’h’
List of values : GolayElement ∈ {’l’, ’m’, ’d’, ’c’, ’e’, ’i’, ’f’, ’f2’, ’h’, ’k’}
. Rotation (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Rotation of the Golay element. Depending on the element, not all rotations are valid.
Default Value : 0
List of values : Rotation ∈ {0, 2, 4, 6, 8, 10, 12, 14, 1, 3, 5, 7, 9, 11, 13, 15}
Complexity
Let F be the area of an input region. Then the runtime complexity for one region is:

O(6 · F) .

HALCON 8.0.2
698 CHAPTER 9. MORPHOLOGY

Result
ClosingGolay returns TRUE if all parameters are correct. The behavior in case of empty or no input region
can be set via:
• no region: SetSystem(’noObjectResult’,<RegionResult>)
• empty region: SetSystem(’emptyRegionResult’,<RegionResult>)
Otherwise, an exception is raised.
Parallelization Information
ClosingGolay is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection, Union1, Watersheds, ClassNdimNorm
Possible Successors
ReduceDomain, SelectShape, AreaCenter, Connection
See also
ErosionGolay, DilationGolay, OpeningGolay, HitOrMissGolay, ThinningGolay,
ThickeningGolay, GolayElements
Alternatives
Closing
Module
Foundation

[out] HRegionX RegionClosing HRegionX.ClosingRectangle1


([in] VARIANT Width, [in] VARIANT Height )
void HOperatorSetX.ClosingRectangle1 ([in] IHObjectX Region,
[out] HUntypedObjectX RegionClosing, [in] VARIANT Width,
[in] VARIANT Height )

Close a region with a rectangular structuring element.


ClosingRectangle1 performs a DilationRectangle1 followed by an ErosionRectangle1 on the
input region Region. The size of the rectangular structuring element is determined by the parameters Width and
Height. As is the case for all Closing variants, regions’ boundaries are smoothed and holes within a region
which are smaller than the rectangular structuring element are closed.
Attention
ClosingRectangle1 is applied to each input region separately. If gaps between different regions are to be
closed, Union1 or Union2 has to be called first.
Parameter
. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Regions to be closed.
. RegionClosing (output iconic) . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Closed regions.
. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; VARIANT ( integer, real )
Width of the structuring rectangle.
Default Value : 10
Suggested values : Width ∈ {1, 2, 3, 4, 5, 7, 9, 12, 15, 19, 25, 33, 45, 60, 110, 150, 200}
Typical range of values : 1 ≤ Width ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 1
. Height (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; VARIANT ( integer, real )
Height of the structuring rectangle.
Default Value : 10
Suggested values : Height ∈ {1, 2, 3, 4, 5, 7, 9, 12, 15, 19, 25, 33, 45, 60, 110, 150, 200}
Typical range of values : 1 ≤ Height ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 1

HALCON/COM Reference Manual, 2008-5-13


9.2. REGION 699

Complexity
Let F 1 be the area of an input region and H be the height of the rectangle. Then the runtime complexity for one
region is:

O(2 · F 1 · log_2(H)) .

Result
ClosingRectangle1 returns TRUE if all parameters are correct. The behavior in case of empty or no input
region can be set via:

• no region: SetSystem(’noObjectResult’,<RegionResult>)
• empty region: SetSystem(’emptyRegionResult’,<RegionResult>)

Otherwise, an exception is raised.


Parallelization Information
ClosingRectangle1 is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection, Union1, Watersheds, ClassNdimNorm
Possible Successors
ReduceDomain, SelectShape, AreaCenter, Connection
See also
DilationRectangle1, ErosionRectangle1, OpeningRectangle1, GenRectangle1
Alternatives
Closing
Module
Foundation

[out] HRegionX RegionDilation HRegionX.Dilation1


([in] HRegionX StructElement, [in] long Iterations )
void HOperatorSetX.Dilation1 ([in] IHObjectX Region,
[in] IHObjectX StructElement, [out] HUntypedObjectX RegionDilation,
[in] VARIANT Iterations )

Dilate a region.
Dilation1 dilates the input regions with a structuring element. By applying Dilation1 to a region, its
boundary gets smoothed. In the process, the area of the region is enlarged. Furthermore, disconnected regions
may be merged. Such regions, however, remain logically distinct region. The dilation is a set-theoretic region
operation. It uses the union operation.
Let M (StructElement) and R (Region) be two regions, where M is the structuring element and R is the
region to be processed. Furthermore, let m be a point in M . Then the displacement vector ~vm = (dx, dy) is
defined as the difference of the center of gravity of M and the vector m.
~ Let t~vm (R) denote the translation of a
region R by a vector ~v . Then
[
Dilation1(R, M ) := t−~vm (R)
m∈M

For each point m in M a translation of the region R is performed. The union of all these translations is the dilation
of R with M . Dilation1 is similar to the operator MinkowskiAdd1, the difference is that in Dilation1
the structuring element is mirrored at the origin. The position of StructElement is meaningless, since the
displacement vectors are determined with respect to the center of gravity of M .
The parameter Iterations determines the number of iterations which are to be performed with the structuring
element. The result of iteration n − 1 is used as input for iteration n. From the above definition it follows that an
empty region is generated in case of an empty structuring element.

HALCON 8.0.2
700 CHAPTER 9. MORPHOLOGY

Structuring elements (StructElement) can be generated with operators such as GenCircle,


GenRectangle1, GenRectangle2, GenEllipse, DrawRegion, GenRegionPolygon,
GenRegionPoints, etc.
Attention
A dilation always results in enlarged regions. Closely spaced regions which may touch or overlap as a result of
the dilation are still treated as two separate regions. If the desired behavior is to merge them into one region, the
operator Union1 has to be called first.
Parameter

. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Regions to be dilated.
. StructElement (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
Structuring element.
. RegionDilation (output iconic) . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Dilated regions.
. Iterations (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of iterations.
Default Value : 1
Suggested values : Iterations ∈ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 15, 17, 20, 30, 40, 50}
(lin)Minimum Increment : 1
Recommended Increment : 1
Complexity
Let F 1 be the area of the input region, and F 2 be the area of the structuring element. Then the runtime complexity
for one region is:
√ √
O( F 1 · F 2 · Iterations) .

Result
Dilation1 returns TRUE if all parameters are correct. The behavior in case of empty or no input region can be
set via:

• no region: SetSystem(’noObjectResult’,<RegionResult>)
• empty region: SetSystem(’emptyRegionResult’,<RegionResult>)

Otherwise, an exception is raised.


Parallelization Information
Dilation1 is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection, Union1, Watersheds, ClassNdimNorm, GenCircle,
GenEllipse, GenRectangle1, GenRectangle2, DrawRegion, GenRegionPoints,
GenStructElements, GenRegionPolygonFilled
Possible Successors
ReduceDomain, AddChannels, SelectShape, AreaCenter, Connection
See also
Erosion1, Erosion2, Opening, Closing
Alternatives
MinkowskiAdd1, MinkowskiAdd2, Dilation2, DilationGolay, DilationSeq
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


9.2. REGION 701

[out] HRegionX RegionDilation HRegionX.Dilation2


([in] HRegionX StructElement, [in] long Row, [in] long Column,
[in] long Iterations )
void HOperatorSetX.Dilation2 ([in] IHObjectX Region,
[in] IHObjectX StructElement, [out] HUntypedObjectX RegionDilation,
[in] VARIANT Row, [in] VARIANT Column, [in] VARIANT Iterations )

Dilate a region (using a reference point).


Dilation2 dilates the input regions with a structuring element (StructElement) having the reference point
(Row,Column). Dilation2 has a similar effect as Dilation1, the difference is that the reference point of the
structuring element can be chosen arbitrarily. The parameter Iterations determines the number of iterations
which are to be performed with the structuring element. The result of iteration n − 1 is used as input for iteration
n.
An empty region is generated in case of an empty structuring element.
Structuring elements (StructElement) can be generated with operators such as GenCircle,
GenRectangle1, GenRectangle2, GenEllipse, DrawRegion, GenRegionPolygon,
GenRegionPoints, etc.
Attention
A dilation always results in enlarged regions. Closely spaced regions which may touch or overlap as a result of
the dilation are still treated as two separate regions. If the desired behavior is to merge them into one region, the
operator Union1 has to be called first.
Parameter

. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Regions to be dilated.
. StructElement (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
Structuring element.
. RegionDilation (output iconic) . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Dilated regions.
. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; long / VARIANT
Row coordinate of the reference point.
Default Value : 0
. Column (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; long / VARIANT
Column coordinate of the reference point.
Default Value : 0
. Iterations (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of iterations.
Default Value : 1
Suggested values : Iterations ∈ {1, 2, 3, 4, 5, 7, 11, 17, 25, 32, 64, 128}
(lin)Minimum Increment : 1
Recommended Increment : 1
Complexity
Let F 1 be the area of the input region, and F 2 be the area of the structuring element. Then the runtime complexity
for one region is:
√ √
O( F 1 · F 2 · Iterations) .

Result
Dilation2 returns TRUE if all parameters are correct. The behavior in case of empty or no input region can be
set via:

• no region: SetSystem(’noObjectResult’,<RegionResult>)
• empty region: SetSystem(’emptyRegionResult’,<RegionResult>)

Otherwise, an exception is raised.

HALCON 8.0.2
702 CHAPTER 9. MORPHOLOGY

Parallelization Information
Dilation2 is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection, Union1, Watersheds, ClassNdimNorm, GenCircle,
GenEllipse, GenRectangle1, GenRectangle2, DrawRegion, GenRegionPoints,
GenStructElements, GenRegionPolygonFilled
Possible Successors
ReduceDomain, AddChannels, SelectShape, AreaCenter, Connection
See also
Erosion1, Erosion2, Opening, Closing
Alternatives
MinkowskiAdd1, MinkowskiAdd2, Dilation1, DilationGolay, DilationSeq
Module
Foundation

[out] HRegionX RegionDilation HRegionX.DilationCircle


([in] VARIANT Radius )
void HOperatorSetX.DilationCircle ([in] IHObjectX Region,
[out] HUntypedObjectX RegionDilation, [in] VARIANT Radius )

Dilate a region with a circular structuring element.


DilationCircle applies a Minkowski addition with a circular structuring element to the input regions
Region. Because the circular mask is symmetrical, this is identical to a dilation. The size of the circle used
as structuring element is determined by Radius.
The operator results in enlarged regions, smoothed region boundaries, and the holes smaller than the circular mask
in the interior of the region are closed. It is useful to select only values like 3.5, 5.5, etc. for Radius in order
to avoid a translation of a region, because integer radii result in the circle having a non-integer center of gravity
which is rounded to the next integer.
Attention
DilationCircle is applied to each input region separately. If gaps between different regions are to be closed,
Union1 or Union2 has to be called first.
Parameter
. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Regions to be dilated.
. RegionDilation (output iconic) . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Dilated regions.
. Radius (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real, integer )
Radius of the circular structuring element.
Default Value : 3.5
Suggested values : Radius ∈ {1.5, 2.5, 3.5, 4.5, 5.5, 7.5, 9.5, 12.5, 15.5, 19.5, 25.5, 33.5, 45.5, 60.5, 110.5}
Typical range of values : 0.5 ≤ Radius ≤ 0.5(lin)
Minimum Increment : 1.0
Recommended Increment : 1.0
Complexity
Let F 1 be the area of an input region. Then the runtime complexity for one region is:

O(2 · Radius · F 1) .

Result
DilationCircle returns TRUE if all parameters are correct. The behavior in case of empty or no input region
can be set via:

• no region: SetSystem(’noObjectResult’,<RegionResult>)

HALCON/COM Reference Manual, 2008-5-13


9.2. REGION 703

• empty region: SetSystem(’emptyRegionResult’,<RegionResult>)

Otherwise, an exception is raised.


Parallelization Information
DilationCircle is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection, Union1, Watersheds, ClassNdimNorm
Possible Successors
ReduceDomain, SelectShape, AreaCenter, Connection
See also
GenCircle, ErosionCircle, ClosingCircle, OpeningCircle
Alternatives
MinkowskiAdd1, MinkowskiAdd2, ExpandRegion, Dilation1, Dilation2,
DilationRectangle1
Module
Foundation

[out] HRegionX RegionDilation HRegionX.DilationGolay


([in] String GolayElement, [in] long Iterations, [in] long Rotation )
void HOperatorSetX.DilationGolay ([in] IHObjectX Region,
[out] HUntypedObjectX RegionDilation, [in] VARIANT GolayElement,
[in] VARIANT Iterations, [in] VARIANT Rotation )

Dilate a region with an element from the Golay alphabet.


DilationGolay dilates a region with the selected element GolayElement from the Golay alphabet. The
following structuring elements are available:
’l’, ’m’, ’d’, ’c’, ’e’, ’i’, ’f’, ’f2’, ’h’, ’k’.
The rotation number Rotation determines which rotation of the element should be used, and whether the fore-
ground (even) or background version (odd) of the selected element should be used. The Golay elements, together
with all possible rotations, are described with the operator GolayElements. The operator works by shifting
the structuring element over the region to be processed (Region). For all positions of the structuring element that
intersect the region, the corresponding reference point (relative to the structuring element) is added to the output
region. This means that the union of all translations of the structuring element within the region is computed.
The parameter Iterations determines the number of iterations which are to be performed with the structuring
element. The result of iteration n − 1 is used as input for iteration n.
Attention
Not all values of Rotation are valid for any Golay element. For some of the values of Rotation, the resulting
regions are identical to the input regions.
Parameter
. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Regions to be dilated.
. RegionDilation (output iconic) . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Dilated regions.
. GolayElement (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Structuring element from the Golay alphabet.
Default Value : ’h’
List of values : GolayElement ∈ {’l’, ’m’, ’d’, ’c’, ’e’, ’i’, ’f’, ’f2’, ’h’, ’k’}
. Iterations (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of iterations.
Default Value : 1
Suggested values : Iterations ∈ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 15, 17, 20, 30, 40, 50}
(lin)Minimum Increment : 1
Recommended Increment : 1

HALCON 8.0.2
704 CHAPTER 9. MORPHOLOGY

. Rotation (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT


Rotation of the Golay element. Depending on the element, not all rotations are valid.
Default Value : 0
List of values : Rotation ∈ {0, 2, 4, 6, 8, 10, 12, 14, 1, 3, 5, 7, 9, 11, 13, 15}
Complexity
Let F be the area of an input region. Then the runtime complexity for one region is:

O(3 · F) .

Result
DilationGolay returns TRUE if all parameters are correct. The behavior in case of empty or no input region
can be set via:

• no region: SetSystem(’noObjectResult’,<RegionResult>)
• empty region: SetSystem(’emptyRegionResult’,<RegionResult>)

Otherwise, an exception is raised.


Parallelization Information
DilationGolay is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection, Union1, Watersheds, ClassNdimNorm
Possible Successors
ReduceDomain, SelectShape, AreaCenter, Connection
See also
ErosionGolay, OpeningGolay, ClosingGolay, HitOrMissGolay, ThinningGolay,
ThickeningGolay, GolayElements
Alternatives
Dilation1, Dilation2, DilationSeq
Module
Foundation

[out] HRegionX RegionDilation HRegionX.DilationRectangle1


([in] long Width, [in] long Height )
void HOperatorSetX.DilationRectangle1 ([in] IHObjectX Region,
[out] HUntypedObjectX RegionDilation, [in] VARIANT Width,
[in] VARIANT Height )

Dilate a region with a rectangular structuring element.


DilationRectangle1 applies a dilation with a rectangular structuring element to the input regions Region.
The size of the structuring rectangle is Width × Height. The operator results in enlarged regions, and the holes
smaller than the rectangular mask in the interior of the regions are closed.
DilationRectangle1 is a very fast operation because the height of the rectangle enters only logarithmically
into the runtime complexity, while the width does not enter at all. This leads to excellent runtime efficiency, even
in the case of very large rectangles (edge length > 100).
Attention
DilationRectangle1 is applied to each input region separately. If gaps between different regions are to be
closed, Union1 or Union2 has to be called first.
To enlarge a region by the same amount in all directions, Width and Height must be odd. If this is not the case,
the region is dilated by a larger amount at the right or at the bottom, respectively, than at the left or at the top.

HALCON/COM Reference Manual, 2008-5-13


9.2. REGION 705

Parameter

. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Regions to be dilated.
. RegionDilation (output iconic) . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Dilated regions.
. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; long / VARIANT
Width of the structuring rectangle.
Default Value : 11
Suggested values : Width ∈ {1, 2, 3, 4, 5, 11, 15, 21, 31, 51, 71, 101, 151, 201}
Typical range of values : 1 ≤ Width ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 10
. Height (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; long / VARIANT
Height of the structuring rectangle.
Default Value : 11
Suggested values : Height ∈ {1, 2, 3, 4, 5, 11, 15, 21, 31, 51, 71, 101, 151, 201}
Typical range of values : 1 ≤ Height ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 10
Complexity
Let F 1 be the area of an input region and H be the height of the rectangle. Then the runtime complexity for one
region is:

O( F 1 · ld(H)) .

Result
DilationRectangle1 returns TRUE if all parameters are correct. The behavior in case of empty or no input
region can be set via:

• no region: SetSystem(’noObjectResult’,<RegionResult>)
• empty region: SetSystem(’emptyRegionResult’,<RegionResult>)

Otherwise, an exception is raised.


Parallelization Information
DilationRectangle1 is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection, Union1, Watersheds, ClassNdimNorm
Possible Successors
ReduceDomain, SelectShape, AreaCenter, Connection
See also
GenRectangle1, GenRegionPolygonFilled
Alternatives
MinkowskiAdd1, MinkowskiAdd2, ExpandRegion, Dilation1, Dilation2, DilationCircle
Module
Foundation

[out] HRegionX RegionDilation HRegionX.DilationSeq


([in] String GolayElement, [in] long Iterations )
void HOperatorSetX.DilationSeq ([in] IHObjectX Region,
[out] HUntypedObjectX RegionDilation, [in] VARIANT GolayElement,
[in] VARIANT Iterations )

Dilate a region sequentially.

HALCON 8.0.2
706 CHAPTER 9. MORPHOLOGY

DilationSeq computes the sequential dilation of the input region Region with the selected structuring element
GolayElement from the Golay alphabet. This is done by executing the operator DilationGolay with all
rotations of the structuring element Iterations times. The following structuring elements can be selected:
’l’, ’d’, ’c’, ’f’, ’h’, ’k’.
In order to compute the skeleton of a region, usually the elements ’l’ and ’m’ are used. Only the “foreground
elements” (even rotation numbers) are used. The elements ’i’ and ’e’ result in unchanged output regions. The
elements ’l’, ’m’ and ’f2’ are identical for the foreground. The Golay elements, together with all possible rotations,
are described with the operator GolayElements.
Parameter

. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Regions to be dilated.
. RegionDilation (output iconic) . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Dilated regions.
. GolayElement (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Structuring element from the Golay alphabet.
Default Value : ’h’
List of values : GolayElement ∈ {’l’, ’d’, ’c’, ’f’, ’h’, ’k’}
. Iterations (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of iterations.
Default Value : 1
Suggested values : Iterations ∈ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 15, 17, 20, 30, 40, 50}
(lin)Minimum Increment : 1
Recommended Increment : 1
Complexity
Let F be the area of an input region. Then the runtime complexity for one region is:

O(Iterations · 20 · F) .

Result
DilationSeq returns TRUE if all parameters are correct. The behavior in case of empty or no input region can
be set via:

• no region: SetSystem(’noObjectResult’,<RegionResult>)
• empty region: SetSystem(’emptyRegionResult’,<RegionResult>)

Otherwise, an exception is raised.


Parallelization Information
DilationSeq is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection, Union1, Watersheds, ClassNdimNorm
Possible Successors
ReduceDomain, SelectShape, AreaCenter, Connection
See also
ErosionSeq, HitOrMissSeq, ThinningSeq
Alternatives
Dilation1, Dilation2, DilationGolay
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


9.2. REGION 707

[out] HRegionX RegionErosion HRegionX.Erosion1


([in] HRegionX StructElement, [in] long Iterations )
void HOperatorSetX.Erosion1 ([in] IHObjectX Region,
[in] IHObjectX StructElement, [out] HUntypedObjectX RegionErosion,
[in] VARIANT Iterations )

Erode a region.
Erosion1 erodes the input regions with a structuring element. By applying Erosion1 to a region, its boundary
gets smoothed. In the process, the area of the region is reduced. Furthermore, connected regions may be split.
Such regions, however, remain logically one region. The erosion is a set-theoretic region operation. It uses the
intersection operation.
Let M (StructElement) and R (Region) be two regions, where M is the structuring element and R is the
region to be processed. Furthermore, let m be a point in M . Then the displacement vector ~vm = (dx, dy) is
defined as the difference of the center of gravity of M and the vector m.
~ Let t~vm (R) denote the translation of a
region R by a vector ~v . Then
\
Erosion1(R, M ) := t−~vm (R).
m∈M

For each point m in M a translation of the region R is performed. The intersection of all these translations is
the erosion of R with M . Erosion1 is similar to the operator MinkowskiSub1, the difference is that in
Erosion1 the structuring element is mirrored at the origin. The position of StructElement is meaningless,
since the displacement vectors are determined with respect to the center of gravity of M .
The parameter Iterations determines the number of iterations which are to be performed with the structuring
element. The result of iteration n − 1 is used as input for iteration n. From the above definition it follows that the
maximum region is generated in case of an empty structuring element.
Structuring elements (StructElement) can be generated with operators such as GenCircle,
GenRectangle1, GenRectangle2, GenEllipse, DrawRegion, GenRegionPolygon,
GenRegionPoints, etc.
Parameter

. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Regions to be eroded.
. StructElement (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
Structuring element.
. RegionErosion (output iconic) . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Eroded regions.
. Iterations (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of iterations.
Default Value : 1
Suggested values : Iterations ∈ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 15, 17, 20, 30, 40, 50}
(lin)Minimum Increment : 1
Recommended Increment : 1
Complexity
Let F 1 be the area of the input region, and F 2 be the area of the structuring element. Then the runtime complexity
for one region is:
√ √
O( F 1 · F 2 · Iterations) .

Result
Erosion1 returns TRUE if all parameters are correct. The behavior in case of empty or no input region can be
set via:

• no region: SetSystem(’noObjectResult’,<RegionResult>)
• empty region: SetSystem(’emptyRegionResult’,<RegionResult>)

HALCON 8.0.2
708 CHAPTER 9. MORPHOLOGY

Otherwise, an exception is raised.


Parallelization Information
Erosion1 is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Watersheds, ClassNdimNorm, GenCircle, GenEllipse,
GenRectangle1, GenRectangle2, DrawRegion, GenRegionPoints, GenStructElements,
GenRegionPolygonFilled
Possible Successors
Connection, ReduceDomain, SelectShape, AreaCenter
See also
TransposeRegion
Alternatives
MinkowskiSub1, MinkowskiSub2, Erosion2, ErosionGolay, ErosionSeq
Module
Foundation

[out] HRegionX RegionErosion HRegionX.Erosion2


([in] HRegionX StructElement, [in] long Row, [in] long Column,
[in] long Iterations )
void HOperatorSetX.Erosion2 ([in] IHObjectX Region,
[in] IHObjectX StructElement, [out] HUntypedObjectX RegionErosion,
[in] VARIANT Row, [in] VARIANT Column, [in] VARIANT Iterations )

Erode a region (using a reference point).


Erosion2 erodes the input regions with a structuring element (StructElement) having the reference point
(Row,Column). Erosion2 has a similar effect as Erosion1, the difference is that the reference point of the
structuring element can be chosen arbitrarily. The parameter Iterations determines the number of iterations
which are to be performed with the structuring element. The result of iteration n − 1 is used as input for iteration
n.
A maximum region is generated in case of an empty structuring element.
Structuring elements (StructElement) can be generated with operators such as GenCircle,
GenRectangle1, GenRectangle2, GenEllipse, DrawRegion, GenRegionPolygon,
GenRegionPoints, etc.
Parameter

. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Regions to be eroded.
. StructElement (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
Structuring element.
. RegionErosion (output iconic) . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Eroded regions.
. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; long / VARIANT
Row coordinate of the reference point.
Default Value : 0
Typical range of values : 0 ≤ Row ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 1
. Column (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; long / VARIANT
Column coordinate of the reference point.
Default Value : 0
Typical range of values : 0 ≤ Column ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 1

HALCON/COM Reference Manual, 2008-5-13


9.2. REGION 709

. Iterations (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT


Number of iterations.
Default Value : 1
Suggested values : Iterations ∈ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 15, 17, 20, 30, 40, 50}
(lin)Minimum Increment : 1
Recommended Increment : 1
Complexity
Let F 1 be the area of the input region, and F 2 be the area of the structuring element. Then the runtime complexity
for one region is:
√ √
O( F 1 · F 2 · Iterations) .

Result
Erosion2 returns TRUE if all parameters are correct. The behavior in case of empty or no input region can be
set via:

• no region: SetSystem(’noObjectResult’,<RegionResult>)
• empty region: SetSystem(’emptyRegionResult’,<RegionResult>)

Otherwise, an exception is raised.


Parallelization Information
Erosion2 is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Watersheds, ClassNdimNorm, GenCircle, GenEllipse,
GenRectangle1, GenRectangle2, DrawRegion, GenRegionPoints, GenStructElements,
GenRegionPolygonFilled
Possible Successors
ReduceDomain, SelectShape, AreaCenter, Connection
See also
TransposeRegion, GenCircle, GenRectangle2, GenRegionPolygon
Alternatives
MinkowskiSub2, MinkowskiSub1, Erosion1, ErosionGolay, ErosionSeq
Module
Foundation

[out] HRegionX RegionErosion HRegionX.ErosionCircle


([in] VARIANT Radius )
void HOperatorSetX.ErosionCircle ([in] IHObjectX Region,
[out] HUntypedObjectX RegionErosion, [in] VARIANT Radius )

Erode a region with a circular structuring element.


ErosionCircle applies a Minkowski subtraction with a circular structuring element to the input regions
Region. Because the circular mask is symmetrical, this is identical to an erosion. The size of the circle used
as structuring element is determined by Radius.
The operator results in reduced regions, smoothed region boundaries, and the regions smaller than the circular
mask are eliminated. It is useful to select only values like 3.5, 5.5, etc. for Radius in order to avoid a translation
of a region, because integer radii result in a circle having a non-integer center of gravity which is rounded to the
next integer.
Parameter
. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Regions to be eroded.
. RegionErosion (output iconic) . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Eroded regions.

HALCON 8.0.2
710 CHAPTER 9. MORPHOLOGY

. Radius (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real, integer )


Radius of the circular structuring element.
Default Value : 3.5
Suggested values : Radius ∈ {1.5, 2.5, 3.5, 4.5, 5.5, 7.5, 9.5, 12.5, 15.5, 19.5, 25.5, 33.5, 45.5, 60.5, 110.5}
Typical range of values : 0.5 ≤ Radius ≤ 0.5(lin)
Minimum Increment : 1.0
Recommended Increment : 1.0
Complexity
Let F 1 be the area of an input region. Then the runtime complexity for one region is:

O(2 · Radius · F 1) .

Result
ErosionCircle returns TRUE if all parameters are correct. The behavior in case of empty or no input region
can be set via:

• no region: SetSystem(’noObjectResult’,<RegionResult>)
• empty region: SetSystem(’emptyRegionResult’,<RegionResult>)

Otherwise, an exception is raised.


Parallelization Information
ErosionCircle is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Watersheds, ClassNdimNorm
Possible Successors
Connection, ReduceDomain, SelectShape, AreaCenter
See also
GenCircle, DilationCircle, ClosingCircle, OpeningCircle
Alternatives
MinkowskiSub1
Module
Foundation

[out] HRegionX RegionErosion HRegionX.ErosionGolay


([in] String GolayElement, [in] long Iterations, [in] long Rotation )
void HOperatorSetX.ErosionGolay ([in] IHObjectX Region,
[out] HUntypedObjectX RegionErosion, [in] VARIANT GolayElement,
[in] VARIANT Iterations, [in] VARIANT Rotation )

Erode a region with an element from the Golay alphabet.


ErosionGolay erodes a region with the selected element GolayElement from the Golay alphabet. The
following structuring elements are available:
’l’, ’m’, ’d’, ’c’, ’e’, ’i’, ’f’, ’f2’, ’h’, ’k’.
The rotation number Rotation determines which rotation of the element should be used, and whether the fore-
ground (even) or background version (odd) of the selected element should be used. The Golay elements, together
with all possible rotations, are described with the operator GolayElements. The operator works by shifting
the structuring element over the region to be processed (Region). For all positions of the structuring element
fully contained in the region, the corresponding reference point (relative to the structuring element) is added to the
output region. This means that the intersection of all translations of the structuring element within the region is
computed.
The parameter Iterations determines the number of iterations which are to be performed with the structuring
element. The result of iteration n − 1 is used as input for iteration n.

HALCON/COM Reference Manual, 2008-5-13


9.2. REGION 711

Attention
Not all values of Rotation are valid for any Golay element. For some of the values of Rotation, the resulting
regions are identical to the input regions.
Parameter
. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Regions to be eroded.
. RegionErosion (output iconic) . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Eroded regions.
. GolayElement (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Structuring element from the Golay alphabet.
Default Value : ’h’
List of values : GolayElement ∈ {’l’, ’m’, ’d’, ’c’, ’e’, ’i’, ’f’, ’f2’, ’h’, ’k’}
. Iterations (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of iterations.
Default Value : 1
Suggested values : Iterations ∈ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 15, 17, 20, 30, 40, 50}
(lin)Minimum Increment : 1
Recommended Increment : 1
. Rotation (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Rotation of the Golay element. Depending on the element, not all rotations are valid.
Default Value : 0
List of values : Rotation ∈ {0, 2, 4, 6, 8, 10, 12, 14, 1, 3, 5, 7, 9, 11, 13, 15}
Complexity
Let F be the area of an input region. Then the runtime complexity for one region is:

O(3 · F ) .

Result
ErosionGolay returns TRUE if all parameters are correct. The behavior in case of empty or no input region
can be set via:
• no region: SetSystem(’noObjectResult’,<RegionResult>)
• empty region: SetSystem(’emptyRegionResult’,<RegionResult>)
Otherwise, an exception is raised.
Parallelization Information
ErosionGolay is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Watersheds, ClassNdimNorm
Possible Successors
ReduceDomain, SelectShape, AreaCenter, Connection
See also
DilationGolay, OpeningGolay, ClosingGolay, HitOrMissGolay, ThinningGolay,
ThickeningGolay, GolayElements
Alternatives
ErosionSeq, Erosion1, Erosion2
Module
Foundation

[out] HRegionX RegionErosion HRegionX.ErosionRectangle1


([in] long Width, [in] long Height )
void HOperatorSetX.ErosionRectangle1 ([in] IHObjectX Region,
[out] HUntypedObjectX RegionErosion, [in] VARIANT Width,
[in] VARIANT Height )

Erode a region with a rectangular structuring element.

HALCON 8.0.2
712 CHAPTER 9. MORPHOLOGY

ErosionRectangle1 applies an erosion with a rectangular structuring element to the input regions Region.
The size of the structuring rectangle is Width × Height. The operator results in reduced regions, and the areas
smaller than the rectangular mask are eliminated.
ErosionRectangle1 is a very fast operation because the height of the rectangle enters only logarithmically
into the runtime complexity, while the width does not enter at all. This leads to excellent runtime efficiency, even
in the case of very large rectangles (edge length > 100).
Regions containing small connecting strips between large areas are separated only seemingly. They remain logi-
cally one region.
Attention
To reduce a region by the same amount in all directions, Width and Height must be odd. If this is not the case,
the region is eroded by a larger amount at the right or at the bottom, respectively, than at the left or at the top.
Parameter
. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Regions to be eroded.
. RegionErosion (output iconic) . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Eroded regions.
. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; long / VARIANT
Width of the structuring rectangle.
Default Value : 11
Suggested values : Width ∈ {1, 2, 3, 4, 5, 11, 15, 21, 31, 51, 71, 101, 151, 201}
Typical range of values : 1 ≤ Width ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 1
. Height (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; long / VARIANT
Height of the structuring rectangle.
Default Value : 11
Suggested values : Height ∈ {1, 2, 3, 4, 5, 11, 15, 21, 31, 51, 71, 101, 151, 201}
Typical range of values : 1 ≤ Height ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 1
Complexity
Let F 1 be the area of an input region and H be the height of the rectangle. Then the runtime complexity for one
region is:

O( F 1 · ld(H)) .

Result
ErosionRectangle1 returns TRUE if all parameters are correct. The behavior in case of empty or no input
region can be set via:

• no region: SetSystem(’noObjectResult’,<RegionResult>)
• empty region: SetSystem(’emptyRegionResult’,<RegionResult>)

Otherwise, an exception is raised.


Parallelization Information
ErosionRectangle1 is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Watersheds, ClassNdimNorm
Possible Successors
ReduceDomain, SelectShape, AreaCenter, Connection
See also
GenRectangle1
Alternatives
Erosion1, MinkowskiSub1
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


9.2. REGION 713

[out] HRegionX RegionErosion HRegionX.ErosionSeq


([in] String GolayElement, [in] long Iterations )
void HOperatorSetX.ErosionSeq ([in] IHObjectX Region,
[out] HUntypedObjectX RegionErosion, [in] VARIANT GolayElement,
[in] VARIANT Iterations )

Erode a region sequentially.


ErosionSeq computes the sequential erosion of the input region Region with the selected structuring element
GolayElement from the Golay alphabet. This is done by executing the operator ErosionGolay with all
rotations of the structuring element Iterations times. The following structuring elements can be selected:
’l’, ’d’, ’c’, ’f’, ’h’, ’k’.
Only the “foreground elements” (even rotation numbers) are used. The elements ’i’ and ’e’ result in unchanged
output regions. The elements ’l’, ’m’ and ’f2’ are identical for the foreground. The Golay elements, together with
all possible rotations, are described with the operator GolayElements.
Parameter
. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Regions to be eroded.
. RegionErosion (output iconic) . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Eroded regions.
. GolayElement (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Structuring element from the Golay alphabet.
Default Value : ’h’
List of values : GolayElement ∈ {’l’, ’d’, ’c’, ’f’, ’h’, ’k’}
. Iterations (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of iterations.
Default Value : 1
Suggested values : Iterations ∈ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 15, 17, 20, 30, 40, 50}
(lin)Minimum Increment : 1
Recommended Increment : 1
Complexity
Let F be the area of an input region. Then the runtime complexity for one region is:

O(Iterations · 20 · F) .

Result
ErosionSeq returns TRUE if all parameters are correct. The behavior in case of empty or no input region can
be set via:

• no region: SetSystem(’noObjectResult’,<RegionResult>)
• empty region: SetSystem(’emptyRegionResult’,<RegionResult>)

Otherwise, an exception is raised.


Parallelization Information
ErosionSeq is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Watersheds, ClassNdimNorm
Possible Successors
Connection, ReduceDomain, SelectShape, AreaCenter
See also
DilationSeq, HitOrMissSeq, ThinningSeq
Alternatives
ErosionGolay, Erosion1, Erosion2
Module
Foundation

HALCON 8.0.2
714 CHAPTER 9. MORPHOLOGY

[out] HRegionX RegionFitted HRegionX.Fitting


([in] HRegionX StructElements )
void HOperatorSetX.Fitting ([in] IHObjectX Region,
[in] IHObjectX StructElements, [out] HUntypedObjectX RegionFitted )

Perform a closing after an opening with multiple structuring elements.


Fitting performs an Opening and a Closing successively on the input regions. The eight structuring
elements normally used for this operation can be generated with the operator GenStructElements. However,
other user-defined structuring elements can also be used. Let R be the input region(s) and let Mi denote the
structuring elements. Furthermore, let P be the result of the opening and Q be the final result. Then the operator
can be formalized as follows:

n
[
P = (R ◦ Mi )
i=1
\n
Q = (P • Mi )
i=1

Regions larger than the structuring elements are preserved, while small gaps are closed.
Parameter
. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Regions to be processed.
. StructElements (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Structuring elements.
. RegionFitted (output iconic) . . . . . . . . . . . . . . . . . . . . . . . .region(-array) ; HRegionX / HUntypedObjectX
Fitted regions.
Result
Fitting returns TRUE if all parameters are correct. The behavior in case of empty or no input region can be set
via:

• no region: SetSystem(’noObjectResult’,<RegionResult>)
• empty region: SetSystem(’emptyRegionResult’,<RegionResult>)

Otherwise, an exception is raised.


Parallelization Information
Fitting is reentrant and processed without parallelization.
Possible Predecessors
GenStructElements, GenRegionPoints
Possible Successors
ReduceDomain, SelectShape, AreaCenter, Connection
Alternatives
Opening, Closing, Connection, SelectShape
Module
Foundation

void HRegionX.GenStructElements ([in] String Type, [in] long Row,


[in] long Column )
void HOperatorSetX.GenStructElements
([out] HUntypedObjectX StructElements, [in] VARIANT Type, [in] VARIANT Row,
[in] VARIANT Column )

Generate standard structuring elements.

HALCON/COM Reference Manual, 2008-5-13


9.2. REGION 715

GenStructElements serves to generate eight structuring elements normally used in the operator Fitting.
The default value ’noise’ of the parameter Type generates elements especially suited for the elimination of noise.

h h h h x h h h x x h h
x x x h x h h x h h x h
h h h h x h x h h h h x

M1 M2 M3 M4

h h h h h h h x h h x h
x x h h x x x x h h x x
h x h h x h h h h h h h

M5 M6 M7 M8
Parameter

. StructElements (output iconic) . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX


Generated structuring elements.
. Type (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Type of structuring element to generate.
Default Value : ’noise’
List of values : Type ∈ {’noise’}
. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; long / VARIANT
Row coordinate of the reference point.
Default Value : 1
Suggested values : Row ∈ {0, 1, 10, 50, 100, 200, 300, 400}
(lin)
. Column (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; long / VARIANT
Column coordinate of the reference point.
Default Value : 1
Suggested values : Column ∈ {0, 1, 10, 50, 100, 200, 300, 400}
(lin)
Result
GenStructElements returns TRUE if all parameters are correct. Otherwise, an exception is raised.
Parallelization Information
GenStructElements is reentrant and processed without parallelization.
Possible Successors
Fitting, HitOrMiss, Opening, Closing, Erosion2, Dilation2
See also
GolayElements
Module
Foundation

void HRegionX.GolayElements ([out] HRegionX StructElement2,


[in] String GolayElement, [in] long Rotation, [in] long Row,
[in] long Column )
void HOperatorSetX.GolayElements
([out] HUntypedObjectX StructElement1, [out] HUntypedObjectX StructElement2,
[in] VARIANT GolayElement, [in] VARIANT Rotation, [in] VARIANT Row,
[in] VARIANT Column )

Generate the structuring elements of the Golay alphabet.

HALCON 8.0.2
716 CHAPTER 9. MORPHOLOGY

GolayElements generates the structuring elements from the Golay alphabet. The parameter GolayElement
determines the name of the structuring element, while Rotation determines its rotation. The structuring ele-
ments are intended for use in HitOrMiss: In StructElement1 the structuring element for the foreground is
returned, while in StructElement2 the structuring element for the background is returned. Row and Column
determine the reference point of the structuring element.
The rotations are numbered from 0 to 15. This does not mean, however, that there are 16 different rotations: Even
values denote rotations of the foreground elements, while odd values denote rotations of the background elements.
For GolayElements only even values are accepted, and determine the Golay element for StructElement1.
The next larger odd value is used for StructElement2. There are no rotations for the Golay elements ’h’ and ’i’.
Therefore, only the values 0 and 1 are possible as “rotations” (and hence only 0 for GolayElements). The ele-
ment ’e’ has only four possible rotations, and hence the rotation must be between 0 and 7 (for GolayElements
the values 0, 2, 4, or 6 must be used).
The tables below show the elements of the Golay alphabet with all possible rotations. The characters used have
the following meaning:
• Foreground pixel
◦ Background pixel
· Don’t care pixel
The names of the elements and their rotation numbers are displayed below the respective element. The elements
with even number contain the foreground pixels, while the elements with odd numbers contain the background
pixels.
• • •
• • •
• • •
h(0,1)
◦ ◦ ◦
◦ ◦ ◦
◦ ◦ ◦
i(0,1)
· · · ◦ ◦ · ◦ ◦ ◦ · ◦ ◦
◦ • ◦ ◦ • · ◦ • ◦ · • ◦
◦ ◦ ◦ ◦ ◦ · · · · · ◦ ◦
e(0,1) e(2,3) e(4,5) e(6,7)
◦ •
· · ◦ • · ·
◦ ◦ ◦ • · • · ◦ • · ◦ • · • · ◦
· • · • · · • • ◦ · · ◦
• • • • • · ◦ ◦
l(0,1) l(2,3) l(4,5) l(6,7)
• ◦
· · • ◦ · ·
• • • ◦ · • · • ◦ · • ◦ · • •
· • · ◦ · · ◦ • • · · •
◦ ◦ ◦ ◦ ◦ · • •
l(8,9) l(10,11) l(12,13) l(14,15)
• •
• · · · · •
• · · • · • · · • • • · · • · •
• • ◦ · · ◦ · • · ◦ · ·
• · · · · ◦ · ·
m(0,1) m(2,3) m(4,5) m(6,7)

HALCON/COM Reference Manual, 2008-5-13


9.2. REGION 717

· ·
◦ · · · · ◦
· · • · · • · • · ◦ · • · • · ·
◦ • • · · • · • · • · ·
· · • • • • • •
m(8,9) m(10,11) m(12,13) m(14,15)
◦ ◦
◦ · · · · ◦
◦ · · ◦ · • · · ◦ ◦ ◦ · · • · ◦
◦ • • · · • · • · • · ·
◦ · · · · • · ·
d(0,1) d(2,3) d(4,5) d(6,7)
· ·
• · · · · •
· · ◦ · · • · ◦ · • · ◦ · • · ·
• • ◦ · · ◦ · • · ◦ · ·
· · ◦ ◦ ◦ ◦ ◦ ◦
d(8,9) d(10,11) d(12,13) d(14,15)
• •
◦ • ◦ ◦ • ◦
• ◦ ◦ • • • · ◦ • ◦ • ◦ · • • •
◦ • • ◦ · • ◦ • ◦ • · ◦
• ◦ ◦ ◦ ◦ • ◦ ◦
f(0,1) f(2,3) f(4,5) f(6,7)
◦ ◦
• · ◦ ◦ · •
◦ ◦ • ◦ · • • • ◦ • ◦ • • • · ◦
• • ◦ ◦ • ◦ ◦ • ◦ ◦ • ◦
◦ ◦ • • • ◦ • •
f(8,9) f(10,11) f(12,13) f(14,15)
• ◦
◦ · • ◦ · ◦
• • • ◦ · • · • ◦ ◦ • ◦ · • · •
◦ • ◦ ◦ · ◦ ◦ • • ◦ · •
◦ ◦ ◦ ◦ ◦ ◦ • •
f2(0,1) f2(2,3) f2(4,5) f2(6,7)
◦ •
◦ · ◦ • · ◦
◦ ◦ ◦ • · • · ◦ • ◦ ◦ • · • · ◦
◦ • ◦ • · ◦ • • ◦ ◦ · ◦
• • • • • ◦ ◦ ◦
f2(8,9) f2(10,11) f2(12,13) f2(14,15)
• ·
· · • · · ·
• • ◦ · · • · ◦ · · • · · • · •
· • · · · · · • • · · •
· · · · · · ◦ ◦
k(0,1) k(2,3) k(4,5) k(6,7)
· ◦
· · · • · ·
· · · ◦ · • · · ◦ · · • · • · ·
· • · • · · • • · · · ·
◦ • • • • · · ·
k(8,9) k(10,11) k(12,13) k(14,15)

HALCON 8.0.2
718 CHAPTER 9. MORPHOLOGY

• •
• · · · · •
• · · • · ◦ · · • • • · · ◦ · •
• ◦ · · · · · ◦ · · · ·
• · · · · · · ·
c(0,1) c(2,3) c(4,5) c(6,7)
· ·
· · · ·
· ·
· · • · · ◦ • · · · • ◦ · ·
· ◦ • · · • · ◦ · • · ·
· · • • • • • •
c(8,9) c(10,11) c(12,13) c(14,15)
Parameter

. StructElement1 (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX


Structuring element for the foreground.
. StructElement2 (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX
Structuring element for the background.
. GolayElement (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Name of the structuring element.
Default Value : ’l’
List of values : GolayElement ∈ {’l’, ’m’, ’d’, ’c’, ’e’, ’i’, ’f’, ’f2’, ’h’, ’k’}
. Rotation (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Rotation of the Golay element. Depending on the element, not all rotations are valid.
Default Value : 0
List of values : Rotation ∈ {0, 2, 4, 6, 8, 10, 12, 14}
. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; long / VARIANT
Row coordinate of the reference point.
Default Value : 16
Suggested values : Row ∈ {0, 16, 32, 128, 256}
Typical range of values : 0 ≤ Row ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 1
. Column (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; long / VARIANT
Column coordinate of the reference point.
Default Value : 16
Suggested values : Column ∈ {0, 16, 32, 128, 256}
Typical range of values : 0 ≤ Column ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 1
Result
GolayElements returns TRUE if all parameters are correct. Otherwise, an exception is raised.
Parallelization Information
GolayElements is reentrant and processed without parallelization.
Possible Successors
HitOrMiss
See also
DilationGolay, ErosionGolay, OpeningGolay, ClosingGolay, HitOrMissGolay,
ThickeningGolay
Alternatives
GenRegionPoints, GenStructElements, GenRegionPolygonFilled
References
J. Serra: "‘Image Analysis and Mathematical Morphology"’. Volume I. Academic Press, 1982
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


9.2. REGION 719

[out] HRegionX RegionHitMiss HRegionX.HitOrMiss


([in] HRegionX StructElement1, [in] HRegionX StructElement2, [in] long Row,
[in] long Column )
void HOperatorSetX.HitOrMiss ([in] IHObjectX Region,
[in] IHObjectX StructElement1, [in] IHObjectX StructElement2,
[out] HUntypedObjectX RegionHitMiss, [in] VARIANT Row, [in] VARIANT Column )

Hit-or-miss operation for regions.


HitOrMiss performs the hit-or-miss-transformation. First, an erosion with the structuring element
StructElement1 is done on the input region Region. Then an erosion with the structuring element
StructElement2 is performed on the complement of the input region. The intersection of the two resulting
regions is the result RegionHitMiss of HitOrMiss.
The hit-or-miss-transformation selects precisely the points for which the conditions given by the structuring ele-
ments StructElement1 and StructElement2 are fulfilled. StructElement1 determines the condition
for the foreground pixels, while StructElement2 determines the condition for the background pixels. In order
to obtain sensible results, StructElement1 and StructElement2 must fit like key and lock. In any case,
StructElement1 and StructElement2 must be disjunct. Row and Column determine the reference point
of the structuring elements.
Structuring elements (StructElement1, StructElement2) can be generated by calling operators like
GenStructElements, GenRegionPoints, etc.
Parameter
. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Regions to be processed.
. StructElement1 (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
Erosion mask for the input regions.
. StructElement2 (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
Erosion mask for the complements of the input regions.
. RegionHitMiss (output iconic) . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Result of the hit-or-miss operation.
. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; long / VARIANT
Row coordinate of the reference point.
Default Value : 16
Suggested values : Row ∈ {0, 16, 32, 128, 256}
Typical range of values : 0 ≤ Row ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 1
. Column (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; long / VARIANT
Column coordinate of the reference point.
Default Value : 16
Suggested values : Column ∈ {0, 16, 32, 128, 256}
Typical range of values : 0 ≤ Column ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 1
Complexity
Let F be the area of an input region, F 1 the area of the structuring element 1, and F 2 the area of the structuring
element 2. Then the runtime complexity for one object is:
√ √ √ 
O F· F1 + F2 .

Result
HitOrMiss returns TRUE if all parameters are correct. The behavior in case of empty or no input region can be
set via:

• no region: SetSystem(’noObjectResult’,<RegionResult>)
• empty region: SetSystem(’emptyRegionResult’,<RegionResult>)

HALCON 8.0.2
720 CHAPTER 9. MORPHOLOGY

Otherwise, an exception is raised.


Parallelization Information
HitOrMiss is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
GolayElements, GenStructElements, Threshold, Regiongrowing, Connection, Union1,
Watersheds, ClassNdimNorm
Possible Successors
Difference, ReduceDomain, SelectShape, AreaCenter, Connection
See also
Thinning, Thickening, GenRegionPoints, GenRegionPolygonFilled
Alternatives
HitOrMissGolay, HitOrMissSeq, Erosion2, Dilation2
Module
Foundation

[out] HRegionX RegionHitMiss HRegionX.HitOrMissGolay


([in] String GolayElement, [in] long Rotation )
void HOperatorSetX.HitOrMissGolay ([in] IHObjectX Region,
[out] HUntypedObjectX RegionHitMiss, [in] VARIANT GolayElement,
[in] VARIANT Rotation )

Hit-or-miss operation for regions using the Golay alphabet.


HitOrMissGolay performs the hit-or-miss-transformation for the input regions Region (using structur-
ing elements from the Golay alphabet). First, an erosion with the foreground of the structuring element
GolayElement is done on the input region Region. Then an erosion with the background of the structur-
ing element GolayElement is performed on the complement of the input region. The intersection of the two
resulting regions is the result RegionHitMiss of HitOrMissGolay. The following structuring elements are
available:
’l’, ’m’, ’d’, ’c’, ’e’,’i’, ’f’, ’f2’, ’h’, ’k’.
The rotation number Rotation determines which rotation of the element should be used. The hit-or-miss-
transformation selects precisely the points for which the conditions given by the selected Golay element are ful-
filled.
Attention
Not all values of Rotation are valid for any Golay element.
Parameter

. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Regions to be processed.
. RegionHitMiss (output iconic) . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Result of the hit-or-miss operation.
. GolayElement (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Structuring element from the Golay alphabet.
Default Value : ’h’
List of values : GolayElement ∈ {’l’, ’m’, ’d’, ’c’, ’e’, ’i’, ’f’, ’f2’, ’h’, ’k’}
. Rotation (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Rotation of the Golay element. Depending on the element, not all rotations are valid.
Default Value : 0
List of values : Rotation ∈ {0, 2, 4, 6, 8, 10, 12, 14, 1, 3, 5, 7, 9, 11, 13, 15}
Complexity
Let F be the area of an input region. Then the runtime complexity for one region is:

O(6 · F) .

HALCON/COM Reference Manual, 2008-5-13


9.2. REGION 721

Result
HitOrMissGolay returns TRUE if all parameters are correct. The behavior in case of empty or no input region
can be set via:

• no region: SetSystem(’noObjectResult’,<RegionResult>)
• empty region: SetSystem(’emptyRegionResult’,<RegionResult>)

Otherwise, an exception is raised.


Parallelization Information
HitOrMissGolay is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection, Union1, Watersheds, ClassNdimNorm
Possible Successors
ReduceDomain, SelectShape, AreaCenter, Connection
See also
ErosionGolay, DilationGolay, OpeningGolay, ClosingGolay, ThinningGolay,
ThickeningGolay, GolayElements
Alternatives
HitOrMissSeq, HitOrMiss
Module
Foundation

[out] HRegionX RegionHitMiss HRegionX.HitOrMissSeq


([in] String GolayElement )
void HOperatorSetX.HitOrMissSeq ([in] IHObjectX Region,
[out] HUntypedObjectX RegionHitMiss, [in] VARIANT GolayElement )

Hit-or-miss operation for regions using the Golay alphabet (sequential).


HitOrMissGolay performs the hit-or-miss-transformation for the input regions Region using all rotations of
a structuring element from the Golay alphabet. The result of the operator is the union of all intermediate results of
the respective rotations. The following structuring elements are available:
’l’, ’m’, ’d’, ’c’, ’e’, ’i’, ’f’, ’f2’, ’h’, ’k’.
The Golay elements, together with all possible rotations, are described with the operator GolayElements.
Parameter
. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Regions to be processed.
. RegionHitMiss (output iconic) . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Result of the hit-or-miss operation.
. GolayElement (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Structuring element from the Golay alphabet.
Default Value : ’h’
List of values : GolayElement ∈ {’l’, ’m’, ’d’, ’c’, ’e’, ’i’, ’f’, ’f2’, ’h’, ’k’}
Complexity
Let F be the area of an input region, and R be the number of rotations. Then the runtime complexity for one region
is:

O(R · 6 · F) .

Result
HitOrMissSeq returns TRUE if all parameters are correct. The behavior in case of empty or no input region
can be set via:

• no region: SetSystem(’noObjectResult’,<RegionResult>)

HALCON 8.0.2
722 CHAPTER 9. MORPHOLOGY

• empty region: SetSystem(’emptyRegionResult’,<RegionResult>)

Otherwise, an exception is raised.


Parallelization Information
HitOrMissSeq is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection, Union1, Watersheds, ClassNdimNorm
Possible Successors
ReduceDomain, SelectShape, AreaCenter, Connection
See also
ThinningSeq, ThickeningSeq
Alternatives
HitOrMissGolay, HitOrMiss
Module
Foundation

[out] HRegionX RegionMinkAdd HRegionX.MinkowskiAdd1


([in] HRegionX StructElement, [in] long Iterations )
void HOperatorSetX.MinkowskiAdd1 ([in] IHObjectX Region,
[in] IHObjectX StructElement, [out] HUntypedObjectX RegionMinkAdd,
[in] VARIANT Iterations )

Perform a Minkowski addition on a region.


MinkowskiAdd1 dilates the input regions with a structuring element. By applying MinkowskiAdd1 to a
region, its boundary gets smoothed. In the process, the area of the region is enlarged. Furthermore, disconnected
regions may be merged. Such regions, however, remain logically distinct region. The Minkowski addition is a
set-theoretic region operation. It is based on translations and union operations.
Let M (StructElement) and R (Region) be two regions, where M is the structuring element and R is the
region to be processed. Furthermore, let m be a point in M . Then the displacement vector ~vm = (dx, dy) is
defined as the difference of the center of gravity of M and the vector m.
~ Let t~vm (R) denote the translation of a
region R by a vector ~v . Then
[
MinkowskiAdd1(R, M ) := t~vm (R)
m∈M

For each point m in M a translation of the region R is performed. The union of all these translations is the
Minkowski addition of R with M . MinkowskiAdd1 is similar to the operator Dilation1, the difference
is that in Dilation1 the structuring element is mirrored at the origin. The position of StructElement is
meaningless, since the displacement vectors are determined with respect to the center of gravity of M .
The parameter Iterations determines the number of iterations which are to be performed with the structuring
element. The result of iteration n − 1 is used as input for iteration n. From the above definition it follows that an
empty region is generated in case of an empty structuring element.
Structuring elements (StructElement) can be generated with operators such as GenCircle,
GenRectangle1, GenRectangle2, GenEllipse, DrawRegion, GenRegionPolygon,
GenRegionPoints, etc.
Attention
A Minkowski addition always results in enlarged regions. Closely spaced regions which may touch or overlap as
a result of the dilation are still treated as two separate regions. If the desired behavior is to merge them into one
region, the operator Union1 has to be called first.

HALCON/COM Reference Manual, 2008-5-13


9.2. REGION 723

Parameter
. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Regions to be dilated.
. StructElement (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
Structuring element.
. RegionMinkAdd (output iconic) . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Dilated regions.
. Iterations (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of iterations.
Default Value : 1
Suggested values : Iterations ∈ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 15, 17, 20, 30, 40, 50}
(lin)Minimum Increment : 1
Recommended Increment : 1
Complexity
Let F 1 be the area of the input region, and F 2 be the area of the structuring element. Then the runtime complexity
for one region is:
√ √
O( F 1 · F 2 · Iterations) .

Result
MinkowskiAdd1 returns TRUE if all parameters are correct. The behavior in case of empty or no input region
can be set via:

• no region: SetSystem(’noObjectResult’,<RegionResult>)
• empty region: SetSystem(’emptyRegionResult’,<RegionResult>)

Otherwise, an exception is raised.


Parallelization Information
MinkowskiAdd1 is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection, Union1, Watersheds, ClassNdimNorm, GenCircle,
GenEllipse, GenRectangle1, GenRectangle2, DrawRegion, GenRegionPoints,
GenStructElements, GenRegionPolygonFilled
Possible Successors
ReduceDomain, SelectShape, AreaCenter, Connection
See also
TransposeRegion, MinkowskiSub1
Alternatives
MinkowskiAdd2, Dilation1
Module
Foundation

[out] HRegionX RegionMinkAdd HRegionX.MinkowskiAdd2


([in] HRegionX StructElement, [in] long Row, [in] long Column,
[in] long Iterations )
void HOperatorSetX.MinkowskiAdd2 ([in] IHObjectX Region,
[in] IHObjectX StructElement, [out] HUntypedObjectX RegionMinkAdd,
[in] VARIANT Row, [in] VARIANT Column, [in] VARIANT Iterations )

Dilate a region (using a reference point).


MinkowskiAdd2 computes the Minkowski addition of the input regions with a structuring element
(StructElement) having the reference point (Row,Column). MinkowskiAdd2 has a similar effect as
MinkowskiAdd1, the difference is that the reference point of the structuring element can be chosen arbitrarily.

HALCON 8.0.2
724 CHAPTER 9. MORPHOLOGY

The parameter Iterations determines the number of iterations which are to be performed with the structuring
element. The result of iteration n − 1 is used as input for iteration n.
An empty region is generated in case of an empty structuring element.
Structuring elements (StructElement) can be generated with operators such as GenCircle,
GenRectangle1, GenRectangle2, GenEllipse, DrawRegion, GenRegionPolygon,
GenRegionPoints, etc.
Attention
A Minkowski addition always results in enlarged regions. Closely spaced regions which may touch or overlap as
a result of the dilation are still treated as two separate regions. If the desired behavior is to merge them into one
region, the operator Union1 has to be called first.
Parameter
. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Regions to be dilated.
. StructElement (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
Structuring element.
. RegionMinkAdd (output iconic) . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Dilated regions.
. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; long / VARIANT
Row coordinate of the reference point.
Typical range of values : 1 ≤ Row ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 1
. Column (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; long / VARIANT
Column coordinate of the reference point.
Typical range of values : 1 ≤ Column ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 1
. Iterations (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of iterations.
Default Value : 1
Suggested values : Iterations ∈ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 15, 17, 20, 30, 40, 50}
(lin)Minimum Increment : 1
Recommended Increment : 1
Complexity
Let F 1 be the area of the input region, and F 2 be the area of the structuring element. Then the runtime complexity
for one region is:
√ √
O( F 1 · F 2 · Iterations) .

Result
MinkowskiAdd2 returns TRUE if all parameters are correct. The behavior in case of empty or no input region
can be set via:

• no region: SetSystem(’noObjectResult’,<RegionResult>)
• empty region: SetSystem(’emptyRegionResult’,<RegionResult>)

Otherwise, an exception is raised.


Parallelization Information
MinkowskiAdd2 is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection, Union1, Watersheds, ClassNdimNorm, GenCircle,
GenEllipse, GenRectangle1, GenRectangle2, DrawRegion, GenRegionPoints,
GenStructElements, GenRegionPolygonFilled
Possible Successors
ReduceDomain, SelectShape, AreaCenter, Connection

HALCON/COM Reference Manual, 2008-5-13


9.2. REGION 725

See also
TransposeRegion
Alternatives
MinkowskiAdd1, Dilation1
Module
Foundation

[out] HRegionX RegionMinkSub HRegionX.MinkowskiSub1


([in] HRegionX StructElement, [in] long Iterations )
void HOperatorSetX.MinkowskiSub1 ([in] IHObjectX Region,
[in] IHObjectX StructElement, [out] HUntypedObjectX RegionMinkSub,
[in] VARIANT Iterations )

Erode a region.
MinkowskiSub1 computes the Minkowski subtraction of the input regions with a structuring element. By
applying MinkowskiSub1 to a region, its boundary gets smoothed. In the process, the area of the region is
reduced. Furthermore, connected regions may be split. Such regions, however, remain logically one region. The
Minkowski subtraction is a set-theoretic region operation. It uses the intersection operation.
Let M (StructElement) and R (Region) be two regions, where M is the structuring element and R is the
region to be processed. Furthermore, let m be a point in M . Then the displacement vector ~vm = (dx, dy) is
defined as the difference of the center of gravity of M and the vector m.
~ Let t~vm (R) denote the translation of a
region R by a vector ~v . Then
\
MinkowskiSub1(R, M ) := t~vm (R)
m∈M

For each point m in M a translation of the region R is performed. The intersection of all these translations is the
Minkowski subtraction of R with M . MinkowskiSub1 is similar to the operator Erosion1, the difference
is that in Erosion1 the structuring element is mirrored at the origin. The position of StructElement is
meaningless, since the displacement vectors are determined with respect to the center of gravity of M .
The parameter Iterations determines the number of iterations which are to be performed with the structuring
element. The result of iteration n − 1 is used as input for iteration n. From the above definition it follows that the
maximum region is generated in case of an empty structuring element.
Structuring elements (StructElement) can be generated with operators such as GenCircle,
GenRectangle1, GenRectangle2, GenEllipse, DrawRegion, GenRegionPolygon,
GenRegionPoints, etc.
Parameter
. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Regions to be eroded.
. StructElement (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
Structuring element.
. RegionMinkSub (output iconic) . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Eroded regions.
. Iterations (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of iterations.
Default Value : 1
Suggested values : Iterations ∈ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 15, 17, 20, 30, 40, 50}
(lin)Minimum Increment : 1
Recommended Increment : 1
Complexity
Let F 1 be the area of the input region, and F 2 be the area of the structuring element. Then the runtime complexity
for one region is:
√ √
O( F 1 · F 2 · Iterations) .

HALCON 8.0.2
726 CHAPTER 9. MORPHOLOGY

Result
MinkowskiSub1 returns TRUE if all parameters are correct. The behavior in case of empty or no input region
can be set via:

• no region: SetSystem(’noObjectResult’,<RegionResult>)
• empty region: SetSystem(’emptyRegionResult’,<RegionResult>)

Otherwise, an exception is raised.


Parallelization Information
MinkowskiSub1 is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection, Union1, Watersheds, ClassNdimNorm, GenCircle,
GenEllipse, GenRectangle1, GenRectangle2, DrawRegion, GenRegionPoints,
GenStructElements, GenRegionPolygonFilled
Possible Successors
ReduceDomain, SelectShape, AreaCenter, Connection
See also
TransposeRegion
Alternatives
MinkowskiSub2, Erosion1
Module
Foundation

[out] HRegionX RegionMinkSub HRegionX.MinkowskiSub2


([in] HRegionX StructElement, [in] long Row, [in] long Column,
[in] long Iterations )
void HOperatorSetX.MinkowskiSub2 ([in] IHObjectX Region,
[in] IHObjectX StructElement, [out] HUntypedObjectX RegionMinkSub,
[in] VARIANT Row, [in] VARIANT Column, [in] VARIANT Iterations )

Erode a region (using a reference point).


MinkowskiSub2 computes the Minkowski subtraction of the input regions with a structuring element
(StructElement) having the reference point (Row,Column). MinkowskiSub2 has a similar effect as
MinkowskiSub1, the difference is that the reference point of the structuring element can be chosen arbitrarily.
The parameter Iterations determines the number of iterations which are to be performed with the structuring
element. The result of iteration n − 1 is used as input for iteration n.
A maximum region is generated in case of an empty structuring element.
Structuring elements (StructElement) can be generated with operators such as GenCircle,
GenRectangle1, GenRectangle2, GenEllipse, DrawRegion, GenRegionPolygon,
GenRegionPoints, etc.
Parameter
. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Regions to be eroded.
. StructElement (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
Structuring element.
. RegionMinkSub (output iconic) . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Eroded regions.
. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; long / VARIANT
Row coordinate of the reference point.
Default Value : 0
Suggested values : Row ∈ {0, 10, 16, 32, 64, 100, 128}
Typical range of values : 0 ≤ Row ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 1

HALCON/COM Reference Manual, 2008-5-13


9.2. REGION 727

. Column (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; long / VARIANT


Column coordinate of the reference point.
Default Value : 0
Suggested values : Column ∈ {0, 10, 16, 32, 64, 100, 128}
Typical range of values : 0 ≤ Column ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 1
. Iterations (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of iterations.
Default Value : 1
Suggested values : Iterations ∈ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 15, 17, 20, 30, 40, 50}
(lin)Minimum Increment : 1
Recommended Increment : 1
Complexity
Let F 1 be the area of the input region, and F 2 be the area of the structuring element. Then the runtime complexity
for one region is:
√ √
O( F 1 · F 2 · Iterations) .

Result
MinkowskiSub2 returns TRUE if all parameters are correct. The behavior in case of empty or no input region
can be set via:

• no region: SetSystem(’noObjectResult’,<RegionResult>)
• empty region: SetSystem(’emptyRegionResult’,<RegionResult>)

Otherwise, an exception is raised.


Parallelization Information
MinkowskiSub2 is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Watersheds, ClassNdimNorm, GenCircle, GenEllipse,
GenRectangle1, GenRectangle2, DrawRegion, GenRegionPoints, GenStructElements,
GenRegionPolygonFilled
Possible Successors
ReduceDomain, SelectShape, AreaCenter, Connection
See also
GenCircle, GenRectangle2, GenRegionPolygon
Alternatives
MinkowskiSub1, Erosion1, Erosion2, ErosionGolay, ErosionSeq
Module
Foundation

[out] HRegionX RegionMorphHat HRegionX.MorphHat


([in] HRegionX StructElement )
void HOperatorSetX.MorphHat ([in] IHObjectX Region,
[in] IHObjectX StructElement, [out] HUntypedObjectX RegionMorphHat )

Compute the union of BottomHat and TopHat.


MorphHat computes the union of the regions that are removed by an Opening operation with the regions that
are added by a Closing operation. Hence this is the union of the results of TopHat and BottomHat. The
position of StructElement does not influence the result.
Structuring elements (StructElement) can be generated with operators such as GenCircle,
GenRectangle1, GenRectangle2, GenEllipse, DrawRegion, GenRegionPolygon,
GenRegionPoints, etc.

HALCON 8.0.2
728 CHAPTER 9. MORPHOLOGY

Attention
The individual regions are processed separately.
Parameter

. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Regions to be processed.
. StructElement (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
Structuring element (position-invariant).
. RegionMorphHat (output iconic) . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Union of top hat and bottom hat.
Result
MorphHat returns TRUE if all parameters are correct. The behavior in case of empty or no input region can be
set via:

• no region: SetSystem(’noObjectResult’,<RegionResult>)
• empty region: SetSystem(’emptyRegionResult’,<RegionResult>)

Otherwise, an exception is raised.


Parallelization Information
MorphHat is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection, Union1, Watersheds, ClassNdimNorm, GenCircle,
GenEllipse, GenRectangle1, GenRectangle2, DrawRegion, GenRegionPoints,
GenStructElements, GenRegionPolygonFilled
Possible Successors
ReduceDomain, SelectShape, AreaCenter, Connection
See also
Opening, Closing
Alternatives
TopHat, BottomHat, Union2
Module
Foundation

HRegionX.MorphSkeleton ( )
[out] HRegionX RegionSkeleton
void HOperatorSetX.MorphSkeleton ([in] IHObjectX Region,
[out] HUntypedObjectX RegionSkeleton )

Compute the morphological skeleton of a region.


MorphSkeleton computes the skeleton of the input regions (Region) using morphological transformations.
The computation yields a disconnected skeleton (gaps in the diagonals) having a width of one or two pixels. The
calculation uses the Golay element ’h’, i.e., an 8-neighborhood. This is equivalent to the maximum-norm.
Parameter

. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Regions to be processed.
. RegionSkeleton (output iconic) . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Resulting morphological skeleton.
Result
MorphSkeleton returns TRUE if all parameters are correct. The behavior in case of empty or no input region
can be set via:

• no region: SetSystem(’noObjectResult’,<RegionResult>)
• empty region: SetSystem(’emptyRegionResult’,<RegionResult>)

HALCON/COM Reference Manual, 2008-5-13


9.2. REGION 729

Otherwise, an exception is raised.


Parallelization Information
MorphSkeleton is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection, Union1, Watersheds, ClassNdimNorm
Possible Successors
Skeleton, ReduceDomain, SelectShape, AreaCenter, Connection
See also
ThinningSeq, MorphSkiz
Alternatives
Skeleton, Thinning
Module
Foundation

[out] HRegionX RegionSkiz HRegionX.MorphSkiz ([in] VARIANT Iterations1,


[in] VARIANT Iterations2 )
void HOperatorSetX.MorphSkiz ([in] IHObjectX Region,
[out] HUntypedObjectX RegionSkiz, [in] VARIANT Iterations1,
[in] VARIANT Iterations2 )

Thinning of a region.
MorphSkiz first performs a sequential thinning ( ThinningSeq) of the input region with the element ’l’ of
the Golay alphabet. The number of iterations is determined by the parameter Iterations1. Then a sequential
thinning of the resulting region with the element ’e’ of the Golay alphabet is carried out. The number of iterations
for this step is determined by the parameter Iterations2. The skiz operation serves to compute a kind of
skeleton of the input regions, and to prune the branches of the resulting skeleton. If the skiz operation is applied to
the complement of the region, the region and the resulting skeleton are separated.
If very large values or ’maximal’ are passed for Iterations1 or Iterations2, the processing stops if no
more changes occur.
Parameter

. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Regions to be thinned.
. RegionSkiz (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Result of the skiz operator.
. Iterations1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer, string )
Number of iterations for the sequential thinning with the element ’l’ of the Golay alphabet.
Default Value : 100
Suggested values : Iterations1 ∈ {’maximal’, 0, 1, 2, 3, 5, 7, 10, 15, 20, 30, 40, 50, 70, 100, 150, 200,
300, 400}
(lin)Minimum Increment : 1
Recommended Increment : 1
. Iterations2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer, string )
Number of iterations for the sequential thinning with the element ’e’ of the Golay alphabet.
Default Value : 1
Suggested values : Iterations2 ∈ {’maximal’, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 15, 17, 20, 30, 40, 50}
(lin)Minimum Increment : 1
Recommended Increment : 1
Complexity
Let F be the area of the input region. Then the runtime complexity for one region is

O((Iterations1 + Iterations2) · 3 · F) .

HALCON 8.0.2
730 CHAPTER 9. MORPHOLOGY

Result
MorphSkiz returns TRUE if all parameters are correct. The behavior in case of empty or no input region can be
set via:

• no region: SetSystem(’noObjectResult’,<RegionResult>)
• empty region: SetSystem(’emptyRegionResult’,<RegionResult>)

Otherwise, an exception is raised.


Parallelization Information
MorphSkiz is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection, Union1, Watersheds, ClassNdimNorm
Possible Successors
Pruning, ReduceDomain, SelectShape, AreaCenter, Connection, BackgroundSeg,
Complement
See also
Thinning, HitOrMissSeq, Difference
Alternatives
Skeleton, ThinningSeq, MorphSkeleton, Interjacent
Module
Foundation

[out] HRegionX RegionOpening HRegionX.Opening


([in] HRegionX StructElement )
void HOperatorSetX.Opening ([in] IHObjectX Region,
[in] IHObjectX StructElement, [out] HUntypedObjectX RegionOpening )

Open a region.
An Opening operation is defined as an erosion followed by a Minkowsi addition. By applying Opening to a
region, larger structures remain mostly intact, while small structures like lines or points are eliminated. In contrast,
a Closing operation results in small gaps being retained or filled up (see Closing).
Opening serves to eliminate small regions (smaller than StructElement) and to smooth the boundaries of a
region. The position of StructElement is meaningless, since an opening operation is invariant with respect to
the choice of the reference point.
Structuring elements (StructElement) can be generated with operators such as GenCircle,
GenRectangle1, GenRectangle2, GenEllipse, DrawRegion, GenRegionPolygon,
GenRegionPoints, etc.
Parameter

. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Regions to be opened.
. StructElement (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
Structuring element (position-invariant).
. RegionOpening (output iconic) . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Opened regions.
Example

/* Large regions in an aerial picture (beech trees or meadows): */


read_image(Image,’wald1’)
threshold(Image,Light,80,255)
gen_circle(StructElement1,100,100,2)
gen_circle(StructElement2,100,100,20)
/* close the small gap */

HALCON/COM Reference Manual, 2008-5-13


9.2. REGION 731

closing(Light,StructElement1,H)
/* selecting the large regions */
opening(H,StructElement2,Large).

/* Selecting of edges with certain orientation: */


read_image(Image,’fabrik’)
sobel_amp(Image,Sobel,’sum_abs’,3)
threshold(Sobel,Edges,10,255)
gen_rectangle2(StructElement,100,100,3.07819,20,1)
opening(Edges,StructElement,Direction).

Complexity
Let F 1 be the area of the input region, and F 2 be the area of the structuring element. Then the runtime complexity
for one region is:
√ √
O(2 · F1 · F 2) .

Result
Opening returns TRUE if all parameters are correct. The behavior in case of empty or no input region can be set
via:

• no region: SetSystem(’noObjectResult’,<RegionResult>)
• empty region: SetSystem(’emptyRegionResult’,<RegionResult>)

Otherwise, an exception is raised.


Parallelization Information
Opening is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection, Union1, Watersheds, ClassNdimNorm, GenCircle,
GenEllipse, GenRectangle1, GenRectangle2, DrawRegion, GenRegionPoints,
GenStructElements, GenRegionPolygonFilled
Possible Successors
ReduceDomain, SelectShape, AreaCenter, Connection
See also
GenCircle, GenRectangle2, GenRegionPolygon
Alternatives
MinkowskiAdd1, Erosion1, OpeningCircle
Module
Foundation

[out] HRegionX RegionOpening HRegionX.OpeningCircle


([in] VARIANT Radius )
void HOperatorSetX.OpeningCircle ([in] IHObjectX Region,
[out] HUntypedObjectX RegionOpening, [in] VARIANT Radius )

Open a region with a circular structuring element.


OpeningCircle is defined as an erosion followed by a Minkowsi addition with a circular structuring element
(see example). Opening serves to eliminate small regions (smaller than the circular structuring element) and to
smooth the boundaries of a region.

HALCON 8.0.2
732 CHAPTER 9. MORPHOLOGY

Parameter
. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Regions to be opened.
. RegionOpening (output iconic) . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Opened regions.
. Radius (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real, integer )
Radius of the circular structuring element.
Default Value : 3.5
Suggested values : Radius ∈ {1.5, 2.5, 3.5, 4.5, 5.5, 7.5, 9.5, 12.5, 15.5, 19.5, 25.5, 33.5, 45.5, 60.5, 110.5}
Typical range of values : 0.5 ≤ Radius ≤ 0.5(lin)
Minimum Increment : 1.0
Recommended Increment : 1.0
Example

/* Large regions in an aerial picture (beech trees or meadows): */


read_image(Image,’wald1’)
threshold(Image,Light,80,255)
/* close the small gap */
closing_circle(LightH,2)
/* selecting the large regions */
opening_circle(H,Large,20).

Complexity
Let F 1 be the area of the input region. Then the runtime complexity for one region is:

O(4 · F 1 · Radius) .

Result
OpeningCircle returns TRUE if all parameters are correct. The behavior in case of empty or no input region
can be set via:
• no region: SetSystem(’noObjectResult’,<RegionResult>)
• empty region: SetSystem(’emptyRegionResult’,<RegionResult>)
Otherwise, an exception is raised.
Parallelization Information
OpeningCircle is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection, Union1, Watersheds, ClassNdimNorm
Possible Successors
ReduceDomain, SelectShape, AreaCenter, Connection
See also
TransposeRegion
Alternatives
Opening, Dilation1, MinkowskiAdd1, GenCircle
Module
Foundation

[out] HRegionX RegionOpening HRegionX.OpeningGolay


([in] String GolayElement, [in] long Rotation )
void HOperatorSetX.OpeningGolay ([in] IHObjectX Region,
[out] HUntypedObjectX RegionOpening, [in] VARIANT GolayElement,
[in] VARIANT Rotation )

Open a region with an element from the Golay alphabet.

HALCON/COM Reference Manual, 2008-5-13


9.2. REGION 733

OpeningGolay is defined as a Minkowski subtraction followed by a Minkowski addition. First the Minkowski
subtraction of the input region (Region) with the structuring element from the Golay alphabet defined by
GolayElement and Rotation is computed. Then the Minkowski addition of the result and the structuring
element rotated by 180◦ is performed.
The following structuring elements are available:
’l’, ’m’, ’d’, ’c’, ’e’, ’i’, ’f’, ’f2’, ’h’, ’k’.
The rotation number Rotation determines which rotation of the element should be used, and whether the fore-
ground (even) or background version (odd) of the selected element should be used. The Golay elements, together
with all possible rotations, are described with the operator GolayElements.
OpeningGolay serves to eliminate regions smaller than the structuring element, and to smooth regions’ bound-
aries.
Attention
Not all values of Rotation are valid for any Golay element. For some of the values of Rotation, the resulting
regions are identical to the input regions.
Parameter

. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Regions to be opened.
. RegionOpening (output iconic) . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Opened regions.
. GolayElement (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Structuring element from the Golay alphabet.
Default Value : ’h’
List of values : GolayElement ∈ {’l’, ’m’, ’d’, ’c’, ’e’, ’i’, ’f’, ’f2’, ’h’, ’k’}
. Rotation (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Rotation of the Golay element. Depending on the element, not all rotations are valid.
Default Value : 0
List of values : Rotation ∈ {0, 2, 4, 6, 8, 10, 12, 14, 1, 3, 5, 7, 9, 11, 13, 15}
Complexity
Let F be the area of an input region. Then the runtime complexity for one region is:

O(6 · F) .

Result
OpeningGolay returns TRUE if all parameters are correct. The behavior in case of empty or no input region
can be set via:

• no region: SetSystem(’noObjectResult’,<RegionResult>)
• empty region: SetSystem(’emptyRegionResult’,<RegionResult>)

Otherwise, an exception is raised.


Parallelization Information
OpeningGolay is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection, Union1, Watersheds, ClassNdimNorm
Possible Successors
ReduceDomain, SelectShape, AreaCenter, Connection
See also
ErosionGolay, DilationGolay, ClosingGolay, HitOrMissGolay, ThinningGolay,
ThickeningGolay, GolayElements
Alternatives
OpeningSeg, Opening
Module
Foundation

HALCON 8.0.2
734 CHAPTER 9. MORPHOLOGY

[out] HRegionX RegionOpening HRegionX.OpeningRectangle1


([in] VARIANT Width, [in] VARIANT Height )
void HOperatorSetX.OpeningRectangle1 ([in] IHObjectX Region,
[out] HUntypedObjectX RegionOpening, [in] VARIANT Width,
[in] VARIANT Height )

Open a region with a rectangular structuring element.


OpeningRectangle1 performs an ErosionRectangle1 followed by a DilationRectangle1 on the
input region Region. The size of the rectangular structuring element is determined by the parameters Width and
Height. As is the case for all Opening variants, larger structures are preserved, while small regions like lines
or points are eliminated.
Parameter
. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Regions to be opened.
. RegionOpening (output iconic) . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Opened regions.
. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; VARIANT ( integer, real )
Width of the structuring rectangle.
Default Value : 10
Suggested values : Width ∈ {1, 2, 3, 4, 5, 7, 9, 12, 15, 19, 25, 33, 45, 60, 110, 150, 200}
Typical range of values : 1 ≤ Width ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 1
. Height (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; VARIANT ( integer, real )
Height of the structuring rectangle.
Default Value : 10
Suggested values : Height ∈ {1, 2, 3, 4, 5, 7, 9, 12, 15, 19, 25, 33, 45, 60, 110, 150, 200}
Typical range of values : 1 ≤ Height ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 1
Complexity
Let F 1 be the area of an input region and H be the height of the rectangle. Then the runtime complexity for one
region is:

O(2 · F 1 · ld(H)) .

Result
OpeningRectangle1 returns TRUE if all parameters are correct. The behavior in case of empty or no input
region can be set via:

• no region: SetSystem(’noObjectResult’,<RegionResult>)
• empty region: SetSystem(’emptyRegionResult’,<RegionResult>)

Otherwise, an exception is raised.


Parallelization Information
OpeningRectangle1 is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Watersheds, ClassNdimNorm
Possible Successors
ReduceDomain, SelectShape, AreaCenter, Connection
See also
OpeningSeg, OpeningGolay
Alternatives
Opening, GenRectangle1, DilationRectangle1, ErosionRectangle1
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


9.2. REGION 735

[out] HRegionX RegionOpening HRegionX.OpeningSeg


([in] HRegionX StructElement )
void HOperatorSetX.OpeningSeg ([in] IHObjectX Region,
[in] IHObjectX StructElement, [out] HUntypedObjectX RegionOpening )

Separate overlapping regions.


The OpeningSeg operation is defined as a sequence of the following operators: Erosion1, Connection
and Dilation1 (see example). Only one iteration is done in Erosion1 and Dilation1.
OpeningSeg serves to separate overlapping regions whose area of overlap is smaller than StructElement.
It should be noted that the resulting regions can overlap without actually merging (see ExpandRegion).
OpeningSeg uses the center of gravity as the reference point of the structuring element.
Structuring elements (StructElement) can be generated with operators such as GenCircle,
GenRectangle1, GenRectangle2, GenEllipse, DrawRegion, GenRegionPolygon,
GenRegionPoints, etc.
Parameter

. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Regions to be opened.
. StructElement (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
Structuring element (position-invariant).
. RegionOpening (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX
Opened regions.
Example

/* Simulation of opening_seg */
opening_seg(Region,StructElement,RegionOpening):
erosion1(Region,StructElement,H1,1) >
connection(H1,H2)
dilation1(H2,StructElement,RegionOpening,1)
clear_obj([H1,H2]).

Complexity
Let F 1 be the area of the input region, and F 2 be the area of the structuring element. Then the runtime complexity
for one region is:

√ √ √
q
O( F 1 · F 2 · F 1) .

Result
OpeningSeg returns TRUE if all parameters are correct. The behavior in case of empty or no input region can
be set via:

• no region: SetSystem(’noObjectResult’,<RegionResult>)
• empty region: SetSystem(’emptyRegionResult’,<RegionResult>)

Otherwise, an exception is raised.


Parallelization Information
OpeningSeg is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection, Union1, Watersheds, ClassNdimNorm, GenCircle,
GenEllipse, GenRectangle1, GenRectangle2, DrawRegion, GenRegionPoints,
GenStructElements, GenRegionPolygonFilled
Possible Successors
ExpandRegion, ReduceDomain, SelectShape, AreaCenter, Connection

HALCON 8.0.2
736 CHAPTER 9. MORPHOLOGY

Alternatives
Erosion1, Connection, Dilation1
Module
Foundation

HRegionX.Pruning ([in] long Length )


[out] HRegionX RegionPrune
void HOperatorSetX.Pruning ([in] IHObjectX Region,
[out] HUntypedObjectX RegionPrune, [in] VARIANT Length )

Prune the branches of a region.


Pruning removes branches from a skeleton (Region) having a length less than Length. All other branches
are preserved.
Parameter

. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Regions to be processed.
. RegionPrune (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Result of the pruning operation.
. Length (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Length of the branches to be removed.
Default Value : 2
Suggested values : Length ∈ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 15, 17, 20, 30, 40, 50}
Typical range of values : 1 ≤ Length ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 1
Complexity
Let F be the area of the input region. Then the runtime complexity for one region is

O(Length · 3 · F) .

Result
Pruning returns TRUE if all parameters are correct. The behavior in case of empty or no input region can be set
via:

• no region: SetSystem(’noObjectResult’,<RegionResult>)
• empty region: SetSystem(’emptyRegionResult’,<RegionResult>)

Otherwise, an exception is raised.


Parallelization Information
Pruning is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
MorphSkiz, Skeleton, ThinningSeq
Possible Successors
ReduceDomain, SelectShape, AreaCenter, Connection
See also
MorphSkeleton, JunctionsSkeleton
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


9.2. REGION 737

[out] HRegionX RegionThick HRegionX.Thickening


([in] HRegionX StructElement1, [in] HRegionX StructElement2, [in] long Row,
[in] long Column, [in] long Iterations )
void HOperatorSetX.Thickening ([in] IHObjectX Region,
[in] IHObjectX StructElement1, [in] IHObjectX StructElement2,
[out] HUntypedObjectX RegionThick, [in] VARIANT Row, [in] VARIANT Column,
[in] VARIANT Iterations )

Add the result of a hit-or-miss operation to a region.


Thickening performs a thickening of the input regions using morphological operations. The operator first
applies a hit-or-miss-transformation to Region (cf. HitOrMiss), and then adds the detected points to the input
region. The parameter Iterations determines the number of iterations performed.
For the choice of the structuring elements StructElement1 and StructElement2, as well as for Row and
Column, the same restrictions described under HitOrMiss apply.
The structuring elements (StructElement1 and StructElement2) can be generated by calling
GolayElements, for example.
Attention
If the reference point is contained in StructElement1 the input region remains unchanged.
Parameter
. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Regions to be processed.
. StructElement1 (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
Structuring element for the foreground.
. StructElement2 (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
Structuring element for the background.
. RegionThick (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Result of the thickening operator.
. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; long / VARIANT
Row coordinate of the reference point.
Default Value : 16
Suggested values : Row ∈ {0, 2, 4, 8, 16, 32, 128}
Typical range of values : 0 ≤ Row ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 1
. Column (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; long / VARIANT
Column coordinate of the reference point.
Default Value : 16
Suggested values : Column ∈ {0, 2, 4, 8, 16, 32, 128}
Typical range of values : 0 ≤ Column ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 1
. Iterations (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of iterations.
Default Value : 1
Suggested values : Iterations ∈ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 15, 17, 20, 30, 40, 50, 70, 100, 200, 400}
(lin)Minimum Increment : 1
Recommended Increment : 1
Complexity
Let F be the area of an input region, F 1 the area of the structuring element 1, and F 2 the area of the structuring
element 2. Then the runtime complexity for one object is:
 √ √ √ 
O Iterations · F · F1 + F2 .

Result
Thickening returns TRUE if all parameters are correct. The behavior in case of empty or no input region can
be set via:

HALCON 8.0.2
738 CHAPTER 9. MORPHOLOGY

• no region: SetSystem(’noObjectResult’,<RegionResult>)
• empty region: SetSystem(’emptyRegionResult’,<RegionResult>)

Otherwise, an exception is raised.


Parallelization Information
Thickening is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
GolayElements, Threshold, Regiongrowing, Connection, Union1, Watersheds,
ClassNdimNorm, GenCircle, GenEllipse, GenRectangle1, GenRectangle2, DrawRegion,
GenRegionPoints, GenStructElements, GenRegionPolygonFilled
Possible Successors
ReduceDomain, SelectShape, AreaCenter, Connection
See also
HitOrMiss
Alternatives
ThickeningGolay, ThickeningSeq
Module
Foundation

[out] HRegionX RegionThick HRegionX.ThickeningGolay


([in] String GolayElement, [in] long Rotation )
void HOperatorSetX.ThickeningGolay ([in] IHObjectX Region,
[out] HUntypedObjectX RegionThick, [in] VARIANT GolayElement,
[in] VARIANT Rotation )

Add the result of a hit-or-miss operation to a region (using a Golay structuring element).
ThickeningGolay performs a thickening of the input regions using morphological operations and structur-
ing elements from the Golay alphabet. The operator first applies a hit-or-miss-transformation to Region (cf.
HitOrMissGolay), and then adds the detected points to the input region. The following structuring elements
are available:
’l’, ’m’, ’d’, ’c’, ’e’, ’i’, ’f’, ’f2’, ’h’, ’k’.
The rotation number Rotation determines which rotation of the element should be used. The Golay elements,
together with all possible rotations, are described with the operator GolayElements.
Attention
Not all values of Rotation are valid for any Golay element.
Parameter
. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Regions to be processed.
. RegionThick (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Result of the thickening operator.
. GolayElement (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Structuring element from the Golay alphabet.
Default Value : ’h’
List of values : GolayElement ∈ {’l’, ’m’, ’d’, ’c’, ’e’, ’i’, ’f’, ’f2’, ’h’, ’k’}
. Rotation (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Rotation of the Golay element. Depending on the element, not all rotations are valid.
Default Value : 0
List of values : Rotation ∈ {0, 2, 4, 6, 8, 10, 12, 14, 1, 3, 5, 7, 9, 11, 13, 15}
Complexity
Let F be the area of an input region. Then the runtime complexity for one region is:

O(6 · F) .

HALCON/COM Reference Manual, 2008-5-13


9.2. REGION 739

Result
ThickeningGolay returns TRUE if all parameters are correct. The behavior in case of empty or no input region
can be set via:

• no region: SetSystem(’noObjectResult’,<RegionResult>)
• empty region: SetSystem(’emptyRegionResult’,<RegionResult>)

Otherwise, an exception is raised.


Parallelization Information
ThickeningGolay is reentrant and automatically parallelized (on tuple level).
Possible Successors
ReduceDomain, SelectShape, AreaCenter, Connection
See also
ErosionGolay, HitOrMissGolay
Alternatives
Thickening, ThickeningSeq
Module
Foundation

[out] HRegionX RegionThick HRegionX.ThickeningSeq


([in] String GolayElement, [in] long Iterations )
void HOperatorSetX.ThickeningSeq ([in] IHObjectX Region,
[out] HUntypedObjectX RegionThick, [in] VARIANT GolayElement,
[in] VARIANT Iterations )

Add the result of a hit-or-miss operation to a region (sequential).


ThickeningSeq calculates the sequential thickening of the input regions with a structuring element from the
Golay alphabet (GolayElement). To do so, ThickeningSeq calls the operator ThickeningGolay with
all possible rotations of the structuring element Iterations times. The following structuring elements are
available:
’l’, ’m’, ’d’, ’c’, ’e’, ’i’, ’f’, ’f2’, ’h’, ’k’.
The Golay elements, together with all possible rotations, are described with the operator GolayElements. For
all elements of the Golay alphabet, except for ’c’, the foreground and background masks are exchanged in order to
have an effect for them on the outer boundary of the region. The element ’c’ can be used to generate the convex
hull of the input region if enough iterations are performed.
Parameter

. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Regions to be processed.
. RegionThick (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Result of the thickening operator.
. GolayElement (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Structuring element from the Golay alphabet.
Default Value : ’h’
List of values : GolayElement ∈ {’l’, ’m’, ’d’, ’c’, ’e’, ’i’, ’f’, ’f2’, ’h’, ’k’}
. Iterations (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of iterations.
Default Value : 1
Suggested values : Iterations ∈ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 15, 17, 20, 30, 40, 50, 70, 100, 200}
(lin)Minimum Increment : 1
Recommended Increment : 1
Complexity
Let F be the area of an input region. Then the runtime complexity for one region is:

HALCON 8.0.2
740 CHAPTER 9. MORPHOLOGY


O(Iterations · 6 · F) .

Result
ThickeningSeq returns TRUE if all parameters are correct. The behavior in case of empty or no input region
can be set via:

• no region: SetSystem(’noObjectResult’,<RegionResult>)
• empty region: SetSystem(’emptyRegionResult’,<RegionResult>)

Otherwise, an exception is raised.


Parallelization Information
ThickeningSeq is reentrant and automatically parallelized (on tuple level).
Possible Successors
ReduceDomain, SelectShape, AreaCenter, Connection
See also
ErosionGolay, ThinningSeq
Alternatives
ThickeningGolay, Thickening
Module
Foundation

[out] HRegionX RegionThin HRegionX.Thinning


([in] HRegionX StructElement1, [in] HRegionX StructElement2, [in] long Row,
[in] long Column, [in] long Iterations )
void HOperatorSetX.Thinning ([in] IHObjectX Region,
[in] IHObjectX StructElement1, [in] IHObjectX StructElement2,
[out] HUntypedObjectX RegionThin, [in] VARIANT Row, [in] VARIANT Column,
[in] VARIANT Iterations )

Remove the result of a hit-or-miss operation from a region.


Thinning performs a thinning of the input regions using morphological operations. The operator first applies a
hit-or-miss-transformation to Region (cf. HitOrMiss), and then removes the detected points from the input
region. The parameter Iterations determines the number of iterations performed.
For the choice of the structuring elements StructElement1 and StructElement2, as well as for Row and
Column, the same restrictions described under HitOrMiss apply.
Structuring elements (StructElement1, StructElement2) can be generated with operators
such as GenCircle, GenRectangle1, GenRectangle2, GenEllipse, DrawRegion,
GenRegionPolygon, GenRegionPoints, etc.
Parameter
. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Regions to be processed.
. StructElement1 (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
Structuring element for the foreground.
. StructElement2 (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
Structuring element for the background.
. RegionThin (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Result of the thinning operator.
. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; long / VARIANT
Row coordinate of the reference point.
Default Value : 0
Typical range of values : 0 ≤ Row ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 1

HALCON/COM Reference Manual, 2008-5-13


9.2. REGION 741

. Column (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; long / VARIANT


Column coordinate of the reference point.
Default Value : 0
Typical range of values : 0 ≤ Column ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 1
. Iterations (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of iterations.
Default Value : 1
Suggested values : Iterations ∈ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 15, 17, 20, 30, 40, 50}
(lin)Minimum Increment : 1
Recommended Increment : 1
Complexity
Let F be the area of an input region, F 1 the area of the structuring element 1, and F 2 the area of the structuring
element 2. Then the runtime complexity for one object is:
 √ √ √ 
O Iterations · F · F1 + F2 .

Result
Thinning returns TRUE if all parameters are correct. The behavior in case of empty or no input region can be
set via:

• no region: SetSystem(’noObjectResult’,<RegionResult>)
• empty region: SetSystem(’emptyRegionResult’,<RegionResult>)

Otherwise, an exception is raised.


Parallelization Information
Thinning is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection, Union1, Watersheds, ClassNdimNorm, GenCircle,
GenEllipse, GenRectangle1, GenRectangle2, DrawRegion, GenRegionPoints,
GenStructElements, GenRegionPolygonFilled
Possible Successors
ReduceDomain, SelectShape, AreaCenter, Connection
See also
HitOrMiss
Alternatives
ThinningGolay, ThinningSeq
Module
Foundation

[out] HRegionX RegionThin HRegionX.ThinningGolay


([in] String GolayElement, [in] long Rotation )
void HOperatorSetX.ThinningGolay ([in] IHObjectX Region,
[out] HUntypedObjectX RegionThin, [in] VARIANT GolayElement,
[in] VARIANT Rotation )

Remove the result of a hit-or-miss operation from a region (using a Golay structuring element).
ThinningGolay performs a thinning of the input regions using morphological operations and structuring
elements from the Golay alphabet. The operator first applies a hit-or-miss-transformation to Region (cf.
HitOrMissGolay), and then removes the detected points from the input region. The following structuring
elements are available:
’l’, ’m’, ’d’, ’c’, ’e’, ’i’, ’f’, ’f2’, ’h’, ’k’.

HALCON 8.0.2
742 CHAPTER 9. MORPHOLOGY

The rotation number Rotation determines which rotation of the element should be used. The Golay elements,
together with all possible rotations, are described with the operator GolayElements.
Attention
Not all values of Rotation are valid for any Golay element.
Parameter
. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Regions to be processed.
. RegionThin (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Result of the thinning operator.
. GolayElement (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Structuring element from the Golay alphabet.
Default Value : ’h’
List of values : GolayElement ∈ {’l’, ’m’, ’d’, ’c’, ’e’, ’i’, ’f’, ’f2’, ’h’, ’k’}
. Rotation (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Rotation of the Golay element. Depending on the element, not all rotations are valid.
Default Value : 0
List of values : Rotation ∈ {0, 2, 4, 6, 8, 10, 12, 14, 1, 3, 5, 7, 9, 11, 13, 15}
Complexity
Let F be the area of an input region. Then the runtime complexity for one region is:

O(6 · F ) .

Result
ThinningGolay returns TRUE if all parameters are correct. The behavior in case of empty or no input region
can be set via:
• no region: SetSystem(’noObjectResult’,<RegionResult>)
• empty region: SetSystem(’emptyRegionResult’,<RegionResult>)
Otherwise, an exception is raised.
Parallelization Information
ThinningGolay is reentrant and automatically parallelized (on tuple level).
Possible Successors
ReduceDomain, SelectShape, AreaCenter, Connection
See also
ErosionGolay, HitOrMissGolay
Alternatives
ThinningSeq, Thinning
Module
Foundation

[out] HRegionX RegionThin HRegionX.ThinningSeq


([in] String GolayElement, [in] VARIANT Iterations )
void HOperatorSetX.ThinningSeq ([in] IHObjectX Region,
[out] HUntypedObjectX RegionThin, [in] VARIANT GolayElement,
[in] VARIANT Iterations )

Remove the result of a hit-or-miss operation from a region (sequential).


ThinningSeq calculates the sequential thinning of the input regions with a structuring element from the Golay
alphabet (GolayElement). To do so, ThinningSeq calls the operator ThinningGolay with all possible
rotations of the structuring element Iterations times. If Iterations is chosen large enough, the operator
calculates the skeleton of a region if the structuring elements ’l’ or ’m’ are used. For the element ’c’ the background
and foreground are exchanged in order to have an effect on the interior boundary of a region. If a very large value
or ’maximal’ is passed for Iterations the iteration stops if no more changes occur. The following structuring
elements are available:

HALCON/COM Reference Manual, 2008-5-13


9.2. REGION 743

’l’ Skeleton, similar to Skeleton. This structuring element is also used in MorphSkiz.
’m’ A skeleton with many “hairs” and multiple (parallel) branches.
’d’ A skeleton without multiple branches, but with many gaps, similar to MorphSkeleton.
’c’ Uniform erosion of the region.
’e’ One pixel wide lines are shortened. This structuring element is also used in MorphSkiz.
’i’ Isolated points are removed. (Only Iterations = 1 is useful.)
’f’ Y-junctions are eliminated. (Only Iterations = 1 is useful.)
’f2’ One pixel long branches and corners are removed. (Only Iterations = 1 is useful.)
’h’ A kind of inner boundary, which, however, is thicker than the result of Boundary, is generated. (Only
Iterations = 1 is useful.)
’k’ Junction points are eliminated, but also new ones are generated.
The Golay elements, together with all possible rotations, are described with the operator GolayElements.
Parameter
. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Regions to be processed.
. RegionThin (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Result of the thinning operator.
. GolayElement (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Structuring element from the Golay alphabet.
Default Value : ’l’
List of values : GolayElement ∈ {’l’, ’m’, ’d’, ’c’, ’e’, ’i’, ’f’, ’f2’, ’h’, ’k’}
. Iterations (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer, string )
Number of iterations. For ’f’, ’f2’, ’h’ and ’i’ the only useful value is 1.
Default Value : 20
Suggested values : Iterations ∈ {’maximal’, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 15, 20, 30, 40, 50, 70, 100, 150,
200}
(lin)Minimum Increment : 1
Recommended Increment : 1
Complexity
Let F be the area of an input region. Then the runtime complexity for one region is:

O(Iterations · 6 · F ) .

Result
ThinningSeq returns TRUE if all parameters are correct. The behavior in case of empty or no input region can
be set via:
• no region: SetSystem(’noObjectResult’,<RegionResult>)
• empty region: SetSystem(’emptyRegionResult’,<RegionResult>)
Otherwise, an exception is raised.
Parallelization Information
ThinningSeq is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection, Union1, Watersheds, ClassNdimNorm, GenCircle,
GenEllipse, GenRectangle1, GenRectangle2, DrawRegion, GenRegionPoints,
GenStructElements, GenRegionPolygonFilled
Possible Successors
Pruning, ReduceDomain, SelectShape, AreaCenter, Connection, Complement
See also
HitOrMissSeq, ErosionGolay, Difference, ThinningGolay, Thinning, ThickeningSeq
Alternatives
Skeleton, MorphSkiz, ExpandRegion
Module
Foundation

HALCON 8.0.2
744 CHAPTER 9. MORPHOLOGY

[out] HRegionX RegionTopHat HRegionX.TopHat


([in] HRegionX StructElement )
void HOperatorSetX.TopHat ([in] IHObjectX Region,
[in] IHObjectX StructElement, [out] HUntypedObjectX RegionTopHat )

Compute the top hat of regions.


TopHat computes the Opening of Region with StructElement. The difference between the original
region and the result of the opening is called the top hat. In contrast to Opening, which splits regions under
certain circumstances, TopHat computes the regions removed by such a splitting.
The position of StructElement is meaningless, since an opening operation is invariant with respect to the
choice of the reference point.
Structuring elements (StructElement) can be generated with operators such as GenCircle,
GenRectangle1, GenRectangle2, GenEllipse, DrawRegion, GenRegionPolygon,
GenRegionPoints, etc.
Parameter

. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Regions to be processed.
. StructElement (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
Structuring element (position independent).
. RegionTopHat (output iconic) . . . . . . . . . . . . . . . . . . . . . . . .region(-array) ; HRegionX / HUntypedObjectX
Result of the top hat operator.
Result
TopHat returns TRUE if all parameters are correct. The behavior in case of empty or no input region can be set
via:

• no region: SetSystem(’noObjectResult’,<RegionResult>)
• empty region: SetSystem(’emptyRegionResult’,<RegionResult>)

Otherwise, an exception is raised.


Parallelization Information
TopHat is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection, Union1, Watersheds, ClassNdimNorm, GenCircle,
GenEllipse, GenRectangle1, GenRectangle2, DrawRegion, GenRegionPoints,
GenStructElements, GenRegionPolygonFilled
Possible Successors
ReduceDomain, SelectShape, AreaCenter, Connection
See also
BottomHat, MorphHat, GrayTophat, Opening
Alternatives
Opening, Difference
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


Chapter 10

OCR

10.1 Hyperboxes

void HMiscX.CloseAllOcrs ( )
void HOperatorSetX.CloseAllOcrs ( )

Destroy all OCR classificators.


CloseAllOcrs deletes all OCR classificators and frees the used memory space. All the trained data will be lost.
Attention
CloseAllOcrs exists solely for the purpose of implementing the “reset program” functionality in HDevelop.
CloseAllOcrs must not be used in any application.
Result
If it is possible to close the OCR classificators the operator CloseAllOcrs returns the value TRUE. Otherwise
an exception handling is raised.
Parallelization Information
CloseAllOcrs is processed completely exclusively without parallelization.
Alternatives
CloseOcr
Module
OCR/OCV

void HOperatorSetX.CloseOcr ([in] VARIANT OcrHandle )

Deallocation of the memory of an OCR classifier.


The operator CloseOcr deallocates the memory of the classifier having the number OcrHandle. Hereby
all corresponding data will be deleted. However, if necessary, they can be saved in advance using the operator
WriteOcr. The number OcrHandle will be invalid after the call; but later the system can use it again for new
classifiers.
Attention
All data of the classifier will be deleted in main memory (not on the hard disk).
Parameter

. OcrHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ocr_box ; HOcrBoxX / VARIANT


ID of the OCR classifier to be deleted.
Example

745
746 CHAPTER 10. OCR

Result
If the parameter OcrHandle is valid, the operator CloseOcr returns the value TRUE. Otherwise an exception
will be raised.
Parallelization Information
CloseOcr is reentrant and processed without parallelization.
Possible Predecessors
WriteOcrTrainf
Possible Successors
ReadOcr
Module
OCR/OCV

void HOcrBoxX.CreateOcrClassBox ([in] long WidthPattern,


[in] long HeightPattern, [in] long Interpolation, [in] VARIANT Features,
[in] VARIANT Character )
void HOperatorSetX.CreateOcrClassBox ([in] VARIANT WidthPattern,
[in] VARIANT HeightPattern, [in] VARIANT Interpolation,
[in] VARIANT Features, [in] VARIANT Character, [out] VARIANT OcrHandle )

Create a new OCR-classifier.


The operator CreateOcrClassBox creates a new OCR classifier. For a description of this classi-
fier see operator LearnClassBox. This classifier must then be trained with the help of the operators
TraindOcrClassBox or TrainfOcrClassBox.
The parameters WidthPattern and HeightPattern indicate the size of the input-layer of the network. This
size is used for the features ’projection_horizontal’, ’projection_vertical’, ’pixel’, ’pixel_invar’, and ’pixel_binary’
to transform the character to a standard size. The bigger the standard size is, the more characters can be distin-
guished. Hereby the amount of time necessary for the training (as well as the number of training random samples)
and the time necessary for the recognition, however, will increase as well. The parameter Interpolation indi-
cates the interpolation mode concerning the adaptation of characters in the image to the network. For more detailed
information on this parameter see also AffineTransImage. The value 0 results in the same interpolation as
’none’ in AffineTransImage, i.e., no interpolation is performed. For 1, the same behavior as ’constant’ in
AffineTransImage is obtained, i.e., equally weighted interpolation between adjacent pixels is used. Finally,
2 results in the same interpolation as ’weighted’, i.e., Gaussian interpolation between adjacent pixels is used. The
parameter Interpolation must be chosen such that no aliasing occurs when the character is scaled to the stan-
dard size. Typically, this means that Interpolation should be set to 1, except in cases where the characters
are scaled down by a large amount, in which case Interpolation = 2 should be chosen. Interpolation =
0 should only be chosen if the characters will not be scaled.
The parameter Character determines all the characters which have to be recognized. Normally the transmitted
strings consist of one character (e.g. alphabet). But also strings of any length can be learned. The number of
distinguishable characters (number of strings in Character) is limited to 2048.
The parameter Features helps to chose additional features besides gray values in order to recognize characters.
By using ’default’ the features ’ratio’ ans ’pixel_invar’ will be set.
The following features are available:

’ratio’ Ratio of the character.


’width’ Width of the character (not invariant to scaling).
’height’ Height of the character (not invariant to scaling).
’zoom_factor’ Difference in size between the current character and the values of WidthPattern and
HeightPattern (not invariant to scaling).
’foreground’ Relative number of pixels in the foreground.
’foreground_grid_9’ Relative number of foreground pixels in a 3 × 3 grid within the surrounding rectangle of the
character.

HALCON/COM Reference Manual, 2008-5-13


10.1. HYPERBOXES 747

’foreground_grid_16’ Relative number of foreground pixels in a 4 × 4 grid within the surrounding rectangle of
the character.
’anisometry’ Form feature anisometry.
’compactness’ Form feature compactness.
’convexity’ Form feature convexity.
’moments_region_2nd_invar’ Normed 2nd geometric moments of the region. See also
MomentsRegion2NdInvar.
’moments_region_2nd_rel_invar’ Normed 2nd relativ geometric moments of the region. See also
MomentsRegion2NdRelInvar.
’moments_region_3rd_invar’ Normed 3rd geometric moments of the region. See also
MomentsRegion3RdInvar.
’moments_central’ Normed central geometric moments of the region. See also MomentsRegionCentral.
’phi’ Sinus and cosinus of the orientation (angle) of the character.
’num_connect’ Number of connecting components.
’num_holes’ Number of holes.
’projection_horizontal’ Horizontal projection of the gray values.
’projection_horizontal_invar’ Horizontal projection of the gray values with are automatically scaled to maximum
range.
’projection_vertical’ Vertical projection of the gray values.
’projection_vertical_invar’ Vertical projection of the gray values with are automatically scaled to maximum range.
’cooc’ Values of the binary cooccurrence matrix.
’moments_gray_plane’ Normed gray value moments and the angles of the gray value level.
’num_runs’ Number of chords in the region normed to the area.
’chord_histo’ Frequency of the chords per row.
’pixel’ Gray value of the character.
’pixel_invar’ Gray values of the character with automatic maximal scaling of the gray values.
’pixel_binary’ Region of the character as a binary image zoomed to a size of WidthPattern ×
HeightPattern.
’gradient_8dir’ Gradients are computed on the character image. The gradient directions are discretized into 8
directions. The amplitude image is decomposed into 8 channels according to these discretized directions. 25
samples on a 5 × 5 grid are extracted from each channel. These samples are used as features.

Attention

Parameter

. WidthPattern (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT


Width of the input layer of the network.
Default Value : 8
Suggested values : WidthPattern ∈ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 16, 20}
Typical range of values : 1 ≤ WidthPattern ≤ 1
. HeightPattern (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Height of the input layer of the network.
Default Value : 10
Suggested values : HeightPattern ∈ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 16, 20}
Typical range of values : 1 ≤ HeightPattern ≤ 1
. Interpolation (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Interpolation mode concerning scaling of characters.
Default Value : 1
List of values : Interpolation ∈ {0, 1, 2}

HALCON 8.0.2
748 CHAPTER 10. OCR

. Features (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )


Additional features.
Default Value : ’default’
List of values : Features ∈ {’default’, ’zoom_factor’, ’ratio’, ’width’, ’height’, ’foreground’,
’foreground_grid_9’, ’foreground_grid_16’, ’anisometry’, ’compactness’, ’convexity’,
’moments_region_2nd_invar’, ’moments_region_2nd_rel_invar’, ’moments_region_3rd_invar’,
’moments_central’, ’phi’, ’num_connect’, ’num_holes’, ’projection_horizontal’, ’projection_vertical’,
’projection_horizontal_invar’, ’projection_vertical_invar’, ’chord_histo’, ’num_runs’, ’pixel’, ’pixel_invar’,
’pixel_binary’, ’gradient_8dir’, ’cooc’, ’moments_gray_plane’}
. Character (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( string )
All characters of a set.
Default Value : [’a’,’b’,’c’]
. OcrHandle (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ocr_box ; HOcrBoxX / VARIANT
ID of the created OCR classifier.
Example

Result
If the parameters are correct, the operator CreateOcrClassBox returns the value TRUE. Otherwise an excep-
tion will be raised.
Parallelization Information
CreateOcrClassBox is processed completely exclusively without parallelization.
Possible Predecessors
ResetObjDb
Possible Successors
TraindOcrClassBox, TrainfOcrClassBox, InfoOcrClassBox, WriteOcr, OcrChangeChar
See also
AffineTransImage, OcrChangeChar, MomentsRegion2NdInvar,
MomentsRegion2NdRelInvar, MomentsRegion3RdInvar, MomentsRegionCentral
Alternatives
CreateOcrClassMlp, CreateOcrClassSvm
Module
OCR/OCV

[out] VARIANT Class HRegionX.DoOcrMulti ([in] HImageX Image,


[in] HOcrBoxX OcrHandle, [out] VARIANT Confidence )
[out] VARIANT Class HOcrBoxX.DoOcrMulti ([in] HRegionX Character,
[in] HImageX Image, [out] VARIANT Confidence )
void HOperatorSetX.DoOcrMulti ([in] IHObjectX Character,
[in] IHObjectX Image, [in] VARIANT OcrHandle, [out] VARIANT Class,
[out] VARIANT Confidence )

Classify characters.
The operator DoOcrMulti assigns a class to every Character (character). For gray value features the gray
values from the surrounding rectangles of the regions are used. The gray values will be taken from the parameter
Image. For each character the corresponding class will be returned in Class and a confidence value will be
returned in Confidence. The confidence value indicates the similarity between the input pattern and the assigned
character.
Attention

HALCON/COM Reference Manual, 2008-5-13


10.1. HYPERBOXES 749

Parameter

. Character (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Characters to be recognized.
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, uint2 )
Gray values for the characters.
. OcrHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ocr_box ; HOcrBoxX / VARIANT
ID of the OCR classifier.
. Class (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Class (name) of the characters.
Number of elements : (Class = Character)
. Confidence (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Confidence values of the characters.
Number of elements : (Conf idence = Character)
Example

Parallelization Information
DoOcrMulti is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
TraindOcrClassBox, TrainfOcrClassBox, ReadOcr, Connection, SortRegion
See also
WriteOcr
Alternatives
DoOcrSingle
Module
OCR/OCV

[out] VARIANT Classes HRegionX.DoOcrSingle ([in] HImageX Image,


[in] HOcrBoxX OcrHandle, [out] VARIANT Confidences )
[out] VARIANT Classes HOcrBoxX.DoOcrSingle ([in] HRegionX Character,
[in] HImageX Image, [out] VARIANT Confidences )
void HOperatorSetX.DoOcrSingle ([in] IHObjectX Character,
[in] IHObjectX Image, [in] VARIANT OcrHandle, [out] VARIANT Classes,
[out] VARIANT Confidences )

Classify one character.


The operator DoOcrSingle assigns classes to the Character (characters). For gray value features gray
values of the surrounding rectangles of the regions will be used. The gray values will be taken from the paramter
Image. For each character the two classes with the highest confidencenses will be returned in Classes. The
corresponding confidences will be returned in Confidences. The confidence value indicates the similarity
between the input pattern and the assigned character.
Attention

Parameter

. Character (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX


Character to be recognized.
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, uint2 )
Gray values of the characters.
. OcrHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ocr_box ; HOcrBoxX / VARIANT
ID of the OCR classifier.

HALCON 8.0.2
750 CHAPTER 10. OCR

. Classes (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( string )


Classes (names) of the characters.
Number of elements : 2
. Confidences (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Confidence values of the characters.
Number of elements : 2
Example

Result
If the input parameters are correct, the operator DoOcrSingle returns the value TRUE. Otherwise an exception
will be raised.
Parallelization Information
DoOcrSingle is reentrant and processed without parallelization.
Possible Predecessors
TraindOcrClassBox, TrainfOcrClassBox, ReadOcr, Connection, SortRegion
See also
WriteOcr
Alternatives
DoOcrMulti
Module
OCR/OCV

[out] long WidthPattern HOcrBoxX.InfoOcrClassBox


([out] long HeightPattern, [out] long Interpolation, [out] long WidthMaxChar,
[out] long HeightMaxChar, [out] VARIANT Features, [out] VARIANT Characters )
void HOperatorSetX.InfoOcrClassBox ([in] VARIANT OcrHandle,
[out] VARIANT WidthPattern, [out] VARIANT HeightPattern,
[out] VARIANT Interpolation, [out] VARIANT WidthMaxChar,
[out] VARIANT HeightMaxChar, [out] VARIANT Features,
[out] VARIANT Characters )

Get information about an OCR classifier.


The operator InfoOcrClassBox returns some information about an OCR classifier. The parameters are equiv-
alent to those of CreateOcrClassBox. The parameters WidthMaxChar and HeightMaxChar indicate
the extension of the largest trained character. These values can be used to control the segmentation.
Attention

Parameter
. OcrHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ocr_box ; HOcrBoxX / VARIANT
ID of the OCR classifier.
. WidthPattern (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Width of the scaled characters.
. HeightPattern (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Height of the scaled characters.
. Interpolation (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Interpolation mode for scaling the characters.
. WidthMaxChar (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Width of the largest trained character.
. HeightMaxChar (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Height of the largest trained character.

HALCON/COM Reference Manual, 2008-5-13


10.1. HYPERBOXES 751

. Features (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( string )


Used features.
. Characters (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( string )
All characters of the set.
Example

Result
The operator InfoOcrClassBox always returns TRUE.
Parallelization Information
InfoOcrClassBox is reentrant and processed without parallelization.
Possible Predecessors
ReadOcr, CreateOcrClassBox
Possible Successors
WriteOcr
Module
OCR/OCV

void HOcrBoxX.OcrChangeChar ([in] VARIANT Character )


void HOperatorSetX.OcrChangeChar ([in] VARIANT OcrHandle,
[in] VARIANT Character )

Define a new conversion table for the characters.


The operator OcrChangeChar establishes a new look-up table for the characters. Hereby the number of strings
of Character must be the same as of the classifier OcrHandle. In order to enlarge the font, the operator
OcrChangeChar may be used as follows: More characters than actually needed will be indicated when creating
a network using ( CreateOcrClassBox). The last n characters will not be used so far. If more characters are
needed at a later stage, these unused characters will be allocated and then trained with the help of the operator
OcrChangeChar.
Attention

Parameter
. OcrHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ocr_box ; HOcrBoxX / VARIANT
ID of the OCR-network to be changed.
. Character (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( string )
New assign of characters.
Default Value : [’a’,’b’,’c’]
Example

Result
If the number of characters in Character is identical with the number of the characters of the network, the
operator OcrChangeChar returns the value TRUE. Otherwise an exception will be raised.
Parallelization Information
OcrChangeChar is processed completely exclusively without parallelization.
Possible Predecessors
ReadOcr
Possible Successors
DoOcrMulti, DoOcrSingle, WriteOcr
Module
OCR/OCV

HALCON 8.0.2
752 CHAPTER 10. OCR

[out] VARIANT FeatureVector HImageX.OcrGetFeatures


([in] HOcrBoxX OcrHandle )
[out] VARIANT FeatureVector HOcrBoxX.OcrGetFeatures
([in] HImageX Character )
void HOperatorSetX.OcrGetFeatures ([in] IHObjectX Character,
[in] VARIANT OcrHandle, [out] VARIANT FeatureVector )

Access the features which correspond to a character.


The operator OcrGetFeatures calculates the features for the given Character. The type and number of
features is determined by the classifier OcrHandle. FeatureVector contains the same values which are used
inside operators like TraindOcrClassBox or TrainfOcrClassBox.
Parameter

. Character (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, uint2 )


Characters to be trained.
. OcrHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ocr_box ; HOcrBoxX / VARIANT
ID of the desired OCR-classifier.
. FeatureVector (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Feature vector.
Result
If the parameters are correct, the operator OcrGetFeatures returns the value TRUE. Otherwise an exception
will be raised.
Parallelization Information
OcrGetFeatures is reentrant and processed without parallelization.
Possible Predecessors
CreateOcrClassBox, ReadOcr, ReduceDomain, Threshold, Connection
Possible Successors
LearnClassBox
See also
TrainfOcrClassBox, TraindOcrClassBox
Module
OCR/OCV

void HOcrBoxX.ReadOcr ([in] String FileName )


void HOperatorSetX.ReadOcr ([in] VARIANT FileName,
[out] VARIANT OcrHandle )

Read an OCR classifier from a file.


The operator ReadOcr reads an OCR classifier from a file FileName. This file will hereby be searched in
the directory ($HALCONROOT/ocr/) as well as in the currently used directory. If too many classifiers have been
loaded, an error message will be displayed.
Attention

Parameter

. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.read ; String / VARIANT


Name of the OCR classifier file.
Default Value : ’testnet’
. OcrHandle (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ocr_box ; HOcrBoxX / VARIANT
ID of the read OCR classifier.
Example

HALCON/COM Reference Manual, 2008-5-13


10.1. HYPERBOXES 753

Result
If the indicated file is available and the format is correct, the operator ReadOcr returns the value TRUE. Other-
wise an exception will be raised.
Parallelization Information
ReadOcr is processed completely exclusively without parallelization.
Possible Predecessors
ResetObjDb
Possible Successors
DoOcrMulti, DoOcrSingle, TraindOcrClassBox, TrainfOcrClassBox
See also
WriteOcr, DoOcrMulti, TraindOcrClassBox, TrainfOcrClassBox
Module
OCR/OCV

[out] VARIANT Confidence HRegionX.TestdOcrClassBox ([in] HImageX Image,


[in] HOcrBoxX OcrHandle, [in] VARIANT Class )
[out] VARIANT Confidence HOcrBoxX.TestdOcrClassBox
([in] HRegionX Character, [in] HImageX Image, [in] VARIANT Class )
void HOperatorSetX.TestdOcrClassBox ([in] IHObjectX Character,
[in] IHObjectX Image, [in] VARIANT OcrHandle, [in] VARIANT Class,
[out] VARIANT Confidence )

Test an OCR classifier.


The operator TestdOcrClassBox tests the confidence with which a character belongs to a given class. Any
number of regions of an image can be passed. For each character (region) in Character the corresponding
name (class) Class must be specified. The gray values are passed in Image. When the operator has finished the
parameter Confidence provides information about how sure a character belongs to the (arbitrary chosen) class.
Parameter

. Character (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Characters to be tested.
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, uint2 )
Gray values for the characters.
. OcrHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ocr_box ; HOcrBoxX / VARIANT
ID of the desired OCR-classifier.
. Class (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Class (name) of the characters.
Default Value : ’a’
. Confidence (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Confidence for the character to belong to the class.
Result
If the parameters are correct, the operator TestdOcrClassBox returns the value TRUE. Otherwise an exception
will be raised.
Parallelization Information
TestdOcrClassBox is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
ReadOcr, TrainfOcrClassBox, TraindOcrClassBox
Module
OCR/OCV

HALCON 8.0.2
754 CHAPTER 10. OCR

[out] double AvgConfidence HRegionX.TraindOcrClassBox


([in] HImageX Image, [in] HOcrBoxX OcrHandle, [in] VARIANT Class )
[out] double AvgConfidence HOcrBoxX.TraindOcrClassBox
([in] HRegionX Character, [in] HImageX Image, [in] VARIANT Class )
void HOperatorSetX.TraindOcrClassBox ([in] IHObjectX Character,
[in] IHObjectX Image, [in] VARIANT OcrHandle, [in] VARIANT Class,
[out] VARIANT AvgConfidence )

Train an OCR classifier by the input of regions.


The operator TraindOcrClassBox trains the classifier directly via the input of regions in an image. Any
number of regions of an image can be passed. For each character (region) in Character the corresponding
name (class) Class must be specified. The gray values are passed in Image. When the procedure has finished
the parameter AvgConfidence provides information about the success of the training: It contains the average
confidence of the trained characters measured by a re-classification. The confidence of mismatched characters is
set to 0 (thus, the average confidence will be decreased significantly).
Attention

Parameter
. Character (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Characters to be trained.
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, uint2 )
Gray values for the characters.
. OcrHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ocr_box ; HOcrBoxX / VARIANT
ID of the desired OCR-classifier.
. Class (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Class (name) of the characters.
Default Value : ’a’
. AvgConfidence (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Average confidence during a re-classification of the trained characters.
Example

Result
If the parameters are correct, the operator TraindOcrClassBox returns the value TRUE. Otherwise an excep-
tion will be raised.
Parallelization Information
TraindOcrClassBox is processed completely exclusively without parallelization.
Possible Predecessors
CreateOcrClassBox, ReadOcr
Possible Successors
TraindOcrClassBox, WriteOcr, DoOcrMulti, DoOcrSingle
Alternatives
TrainfOcrClassBox
Module
OCR/OCV

[out] double AvgConfidence HOcrBoxX.TrainfOcrClassBox


([in] VARIANT FileName )
void HOperatorSetX.TrainfOcrClassBox ([in] VARIANT OcrHandle,
[in] VARIANT FileName, [out] VARIANT AvgConfidence )

Train an OCR classifier with the help of a training file.

HALCON/COM Reference Manual, 2008-5-13


10.1. HYPERBOXES 755

The operator TrainfOcrClassBox trains the classifier OcrHandle via the indicated training files. Any
number of files can be indicated. The parameter AvgConfidence provides information about the success of
the training: It contains the average confidence of the trained characters measured by a re-classification. The
confidence of mismatched characters is set to 0 (thus, the average confidence will be decreased significantly).
Attention
The names of the characters in the file must fit the network.
Parameter

. OcrHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ocr_box ; HOcrBoxX / VARIANT


ID of the desired OCR-network.
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.read(-array) ; VARIANT ( string )
Name(s) of the training file(s).
Default Value : ’train_ocr’
. AvgConfidence (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Average confidence during a re-classification of the trained characters.
Example

Result
If the file name is correct and the data fit the network, the operator TrainfOcrClassBox returns the value
TRUE. Otherwise an exception will be raised.
Parallelization Information
TrainfOcrClassBox is processed completely exclusively without parallelization.
Possible Predecessors
CreateOcrClassBox, ReadOcr
Possible Successors
TraindOcrClassBox, WriteOcr, DoOcrMulti, DoOcrSingle
Alternatives
TraindOcrClassBox
Module
OCR/OCV

void HOcrBoxX.WriteOcr ([in] String FileName )


void HOperatorSetX.WriteOcr ([in] VARIANT OcrHandle,
[in] VARIANT FileName )

Writing an OCR classifier into a file.


The operator WriteOcr writes the OCR classifier OcrHandle into the file FileName. Since the data of the
classifier will be lost when the program is finished, they have to be stored after the training if the user wants to use
them again at a later execution of the program. The data can then be read with the help of the operator ReadOcr.
The extension will be added automatically to the parameter FileName.
Attention
The output file FileName must be given without extension.
Parameter

. OcrHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ocr_box ; HOcrBoxX / VARIANT


ID of the OCR classifier.
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.write ; String / VARIANT
Name of the file for the OCR classifier (without extension).
Default Value : ’my_ocr’

HALCON 8.0.2
756 CHAPTER 10. OCR

Example

Result
If the parameter OcrHandle is valid and the indicated file can be written, the operator WriteOcr returns the
value TRUE. Otherwise an exception will be raised.
Parallelization Information
WriteOcr is reentrant and processed without parallelization.
Possible Predecessors
TraindOcrClassBox, TrainfOcrClassBox
Possible Successors
DoOcrMulti, DoOcrSingle
See also
ReadOcr, DoOcrMulti, TraindOcrClassBox, TrainfOcrClassBox
Module
OCR/OCV

10.2 Lexica
void HMiscX.ClearAllLexica ( )
void HOperatorSetX.ClearAllLexica ( )

Clear all lexica.


ClearAllLexica clears all lexica and releases their resources. All existing lexicon handles are invalid after
this call, and referring to a lexicon by name in expressions is equally no longer possible.
Attention
ClearAllLexica exists solely for the purpose of implementing the “reset program” functionality in HDevelop.
ClearAllLexica must not be used in any application.
Parallelization Information
ClearAllLexica is processed completely exclusively without parallelization.
See also
ClearLexicon
Module
OCR/OCV

void HOperatorSetX.ClearLexicon ([in] VARIANT LexiconHandle )

Clear a lexicon.
ClearLexicon clears a lexicon and releases its resources.
Parameter

. LexiconHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . lexicon ; HLexiconX / VARIANT


Handle of the lexicon.
Parallelization Information
ClearLexicon is processed completely exclusively without parallelization.
See also
CreateLexicon
Module
OCR/OCV

HALCON/COM Reference Manual, 2008-5-13


10.2. LEXICA 757

void HLexiconX.CreateLexicon ([in] String Name, [in] VARIANT Words )


void HOperatorSetX.CreateLexicon ([in] VARIANT Name,
[in] VARIANT Words, [out] VARIANT LexiconHandle )

Create a lexicon from a tuple of words.


CreateLexicon creates a new lexicon based on a tuple of Words. By specifying a unique textual Name, you
can later refer to the lexicon from syntax expressions like those used, e.g., by DoOcrWordMlp.
Note that lexicon support in HALCON is currently not aimed at natural languages. Rather, it is intended as a
post-processing step in OCR applications that only need to distinguish between a limited set of not more than a
few thousand valid words, e.g., country or product names. MVTec itself does not provide any lexica.
Parameter

. Name (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT


Unique name for the new lexicon.
Default Value : ’lex1’
. Words (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( string )
Word list for the new lexicon.
Default Value : [’word1’,’word2’,’word3’]
. LexiconHandle (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . lexicon ; HLexiconX / VARIANT
Handle of the lexicon.
Parallelization Information
CreateLexicon is processed completely exclusively without parallelization.
Possible Successors
DoOcrWordMlp, DoOcrWordSvm
See also
LookupLexicon, SuggestLexicon
Alternatives
ImportLexicon
Module
OCR/OCV

void HLexiconX.ImportLexicon ([in] String Name, [in] String FileName )


void HOperatorSetX.ImportLexicon ([in] VARIANT Name,
[in] VARIANT FileName, [out] VARIANT LexiconHandle )

Create a lexicon from a text file.


ImportLexicon creates a new lexicon based on a list of words in the file specified by FileName. The format
of the file is a simple text file with one word per line. By specifying a unique textual Name, you can later refer to
the lexicon from syntax expressions like those used, e.g., by DoOcrWordMlp.
Note that lexicon support in HALCON is currently not aimed at natural languages. Rather, it is intended as a
post-processing step in OCR applications that only need to distinguish between a limited set of not more than a
few thousand valid words, e.g., country or product names. MVTec itself does not provide any lexica.
Parameter

. Name (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT


Unique name for the new lexicon.
Default Value : ’lex1’
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.read ; String / VARIANT
Name of a text file containing words for the new lexicon.
Default Value : ’words.txt’
. LexiconHandle (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . lexicon ; HLexiconX / VARIANT
Handle of the lexicon.

HALCON 8.0.2
758 CHAPTER 10. OCR

Parallelization Information
ImportLexicon is processed completely exclusively without parallelization.
Possible Successors
DoOcrWordMlp, DoOcrWordSvm
See also
LookupLexicon, SuggestLexicon
Alternatives
CreateLexicon
Module
OCR/OCV

HLexiconX.InspectLexicon ( )
[out] VARIANT Words
void HOperatorSetX.InspectLexicon ([in] VARIANT LexiconHandle,
[out] VARIANT Words )

Query all words from a lexicon.


InspectLexicon returns a tuple of all words in the lexicon in the parameter Words.
Parameter

. LexiconHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . lexicon ; HLexiconX / VARIANT


Handle of the lexicon.
. Words (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
List of all words.
Parallelization Information
InspectLexicon is reentrant and processed without parallelization.
See also
CreateLexicon
Alternatives
LookupLexicon
Module
OCR/OCV

HLexiconX.LookupLexicon ([in] String Word )


[out] long Found
void HOperatorSetX.LookupLexicon ([in] VARIANT LexiconHandle,
[in] VARIANT Word, [out] VARIANT Found )

Check if a word is contained in a lexicon.


LookupLexicon checks whether Word is contained in the lexicon LexiconHandle, and returns 1 in Found
if the word is found, otherwise 0.
Parameter

. LexiconHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . lexicon ; HLexiconX / VARIANT


Handle of the lexicon.
. Word (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Word to be looked up.
Default Value : ’word’
. Found (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Result of the search.
Parallelization Information
LookupLexicon is reentrant and processed without parallelization.

HALCON/COM Reference Manual, 2008-5-13


10.3. NEURAL-NETS 759

See also
CreateLexicon
Alternatives
SuggestLexicon
Module
OCR/OCV

[out] String Suggestion HLexiconX.SuggestLexicon ([in] String Word,


[out] long NumCorrections )
void HOperatorSetX.SuggestLexicon ([in] VARIANT LexiconHandle,
[in] VARIANT Word, [out] VARIANT Suggestion, [out] VARIANT NumCorrections )

Find a similar word in a lexicon.


SuggestLexicon compares Word to all words in the lexicon and calculates the minimum number of edit
operations NumCorrections required to transform Word into a word from the lexicon. Valid edit operations
are the insertion, deletion and replacement of characters. The most similar word found in the lexicon is returned in
Suggestion. If there are multiple words with the same minimum number of corrections, only the first of those
words is returned.
Parameter
. LexiconHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . lexicon ; HLexiconX / VARIANT
Handle of the lexicon.
. Word (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Word to be looked up.
Default Value : ’word’
. Suggestion (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Most similar word found in the lexicon.
. NumCorrections (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Difference between the words in edit operations.
Parallelization Information
SuggestLexicon is reentrant and processed without parallelization.
See also
CreateLexicon
Alternatives
LookupLexicon
References
Vladimir I. Levenshtein, Binary codes capable of correcting deletions, insertions, and reversals, Doklady Akademii
Nauk SSSR, 163(4):845-848, 1965 (Russian). English translation in Soviet Physics Doklady, 10(8):707-710, 1966.
Module
OCR/OCV

10.3 Neural-Nets
void HMiscX.ClearAllOcrClassMlp ( )
void HOperatorSetX.ClearAllOcrClassMlp ( )

Clear all OCR classifiers.


ClearAllOcrClassMlp clears all OCR classifiers that were created with CreateOcrClassMlp and frees
all memory required for the classifiers. After calling ClearAllOcrClassMlp, no classifiers can be used any
longer.
Attention
ClearAllOcrClassMlp exists solely for the purpose of implementing the “reset program” functionality in
HDevelop. ClearAllOcrClassMlp must not be used in any application.

HALCON 8.0.2
760 CHAPTER 10. OCR

Result
ClearAllOcrClassMlp always returns TRUE.
Parallelization Information
ClearAllOcrClassMlp is processed completely exclusively without parallelization.
Possible Predecessors
DoOcrSingleClassMlp, EvaluateClassMlp
See also
CreateOcrClassMlp, ReadOcrClassMlp, WriteOcrClassMlp, TrainfOcrClassMlp
Alternatives
ClearOcrClassMlp
Module
OCR/OCV

void HOperatorSetX.ClearOcrClassMlp ([in] VARIANT OCRHandle )

Clear an OCR classifier.


ClearOcrClassMlp clears the OCR classifier given by OCRHandle that was created with
CreateOcrClassMlp and frees all memory required for the classifier. After calling ClearOcrClassMlp,
the classifier can no longer be used. The handle OCRHandle becomes invalid.
Parameter
. OCRHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ocr_mlp ; HOcrMlpX / VARIANT
Handle of the OCR classifier.
Result
If OCRHandle is valid, the operator ClearOcrClassMlp returns the value TRUE. If necessary an exception
handling is raised.
Parallelization Information
ClearOcrClassMlp is processed completely exclusively without parallelization.
Possible Predecessors
DoOcrSingleClassMlp, DoOcrMultiClassMlp
See also
CreateOcrClassMlp, ReadOcrClassMlp, WriteOcrClassMlp, TrainfOcrClassMlp
Module
OCR/OCV

void HOcrMlpX.CreateOcrClassMlp ([in] long WidthCharacter,


[in] long HeightCharacter, [in] String Interpolation, [in] VARIANT Features,
[in] VARIANT Characters, [in] long NumHidden, [in] String Preprocessing,
[in] long NumComponents, [in] long RandSeed )
void HOperatorSetX.CreateOcrClassMlp ([in] VARIANT WidthCharacter,
[in] VARIANT HeightCharacter, [in] VARIANT Interpolation,
[in] VARIANT Features, [in] VARIANT Characters, [in] VARIANT NumHidden,
[in] VARIANT Preprocessing, [in] VARIANT NumComponents,
[in] VARIANT RandSeed, [out] VARIANT OCRHandle )

Create an OCR classifier using a multilayer perceptron.


CreateOcrClassMlp creates an OCR classifier that uses a multilayer perceptron (MLP). The handle of the
OCR classifier is returned in OCRHandle.
For a description on how an MLP works, see CreateClassMlp. CreateOcrClassMlp creates an
MLP with OutputFunction = ’softmax’. The length of the feature vector of the MLP (NumInput in
CreateClassMlp) is determined from the features that are used for the OCR, which are passed in Features.

HALCON/COM Reference Manual, 2008-5-13


10.3. NEURAL-NETS 761

The features are described below. The number of units in the hidden layer is determined by NumHidden. The
number of output variables of the MLP (NumOutput in CreateClassMlp) is determined from the names of
the characters to be used in the OCR, which are passed in Characters. As described with CreateClassMlp,
the parameters Preprocessing and NumComponents can be used to specify a preprocessing of the data (i.e.,
the feature vectors). The OCR already approximately normalizes the features. Hence, Preprocessing can
typically be set to ’none’. The parameter RandSeed has the same meaning as in CreateClassMlp.
The features to be used for the classification are determined by Features. Features can contain a tuple
of several feature names. Each of these feature names results in one or more features to be calculated for the
classifier. Some of the feature names compute gray value features (e.g., ’pixel_invar’). Because a classifier requires
a constant number of features (input variables), a character to be classified is transformed to a standard size,
which is determined by WidthCharacter and HeightCharacter. The interpolation to be used for the
transformation is determined by Interpolation. It has the same meaning as in AffineTransImage. The
interpolation should be chosen such that no aliasing effects occur in the transformation. For most applications,
Interpolation = ’constant’ should be used. It should be noted that the size of the transformed character
is not chosen too large, because the generalization properties of the classifier may become bad for large sizes.
In particular, large sizes will lead to the fact that small segmentation errors will have a large influence on the
computed features if gray value features are used. This happens because segmentation errors will change the
smallest enclosing rectangle of the regions, which leads to the fact that the character is zoomed differently than the
characters in the training set. In most applications, sizes between 6 × 8 and 10 × 14 should be used.
The parameter Features can contain the following feature names for the classification of the characters. By
specifying ’default’, the features ’ratio’ and ’pixel_invar’ are selected.

’pixel’ Gray values of the character (WidthCharacter × HeightCharacter features).


’pixel_invar’ Gray values of the character with maximum scaling of the gray values (WidthCharacter ×
HeightCharacter features).
’pixel_binary’ Region of the character as a binary image zoomed to a size of WidthCharacter ×
HeightCharacter (WidthCharacter × HeightCharacter features).
’gradient_8dir’ Gradients are computed on the character image. The gradient directions are discretized into 8
directions. The amplitude image is decomposed into 8 channels according to these discretized directions. 25
samples on a 5 × 5 grid are extracted from each channel. These samples are used as features (200 features).
’projection_horizontal’ Horizontal projection of the gray values (see GrayProjections,
HeightCharacter features).
’projection_horizontal_invar’ Maximally scaled horizontal projection of the gray values (HeightCharacter
features).
’projection_vertical’ Vertical projection of the gray values (see GrayProjections, WidthCharacter fea-
tures).
’projection_vertical_invar’ Maximally scaled vertical projection of the gray values (WidthCharacter fea-
tures).
’ratio’ Aspect ratio of the character (1 feature).
’anisometry’ Anisometry of the character (see Eccentricity, 1 feature).
’width’ Width of the character before scaling the character to the standard size (not scale-invariant, see
SmallestRectangle1, 1 feature).
’height’ Height of the character before scaling the character to the standard size (not scale-invariant, see
SmallestRectangle1, 1 feature).
’zoom_factor’ Difference in size between the character and the values of WidthCharacter and
HeightCharacter (not scale-invariant, 1 feature).
’foreground’ Fraction of pixels in the foreground (1 feature).
’foreground_grid_9’ Fraction of pixels in the foreground in a 3 × 3 grid within the smallest enclosing rectangle of
the character (9 features).
’foreground_grid_16’ Fraction of pixels in the foreground in a 4 × 4 grid within the smallest enclosing rectangle
of the character (16 features).
’compactness’ Compactness of the character (see Compactness, 1 feature).
’convexity’ Convexity of the character (see Convexity, 1 feature).

HALCON 8.0.2
762 CHAPTER 10. OCR

’moments_region_2nd_invar’ Normalized 2nd moments of the character (see MomentsRegion2NdInvar, 3


features).
’moments_region_2nd_rel_invar’ Normalized 2nd relative moments of the character (see
MomentsRegion2NdRelInvar, 2 features).
’moments_region_3rd_invar’ Normalized 3rd moments of the character (see MomentsRegion3RdInvar, 4
features).
’moments_central’ Normalized central moments of the character (see MomentsRegionCentral, 4 features).
’moments_gray_plane’ Normalized gray value moments and the angle of the gray value plane (see
MomentsGrayPlane, 4 features).
’phi’ Sinus and cosinus of the orientation (angle) of the character (see EllipticAxis, 2 feature).
’num_connect’ Number of connected components (see ConnectAndHoles, 1 feature).
’num_holes’ Number of holes (see ConnectAndHoles, 1 feature).
’cooc’ Values of the binary cooccurrence matrix (see GenCoocMatrix, 8 features).
’num_runs’ Number of runs in the region normalized by the area (1 feature).
’chord_histo’ Frequency of the runs per row (HeightCharacter features).

After the classifier has been created, it is trained using TrainfOcrClassMlp. After this, the classifier can be
saved using WriteOcrClassMlp. Alternatively, the classifier can be used immediately after training to classify
characters using DoOcrSingleClassMlp or DoOcrMultiClassMlp.
HALCON provides a number of pretrained OCR classifiers (see Solution Guide I, chapter ’OCR’, section ’Pre-
trained OCR Fonts’). These pretrained OCR classifiers can be read directly with ReadOcrClassMlp and make
it possible to read a wide variety of different fonts without the need to train an OCR classifier. Therefore, it is
recommended to try if one of the pretrained OCR classifiers can be used successfully. If this is the case, it is not
necessary to create and train an OCR classifier.
A comparison of the MLP and the support vector machine (SVM) (see CreateOcrClassSvm) typically shows
that SVMs are generally faster at training, especially for huge training sets, and achieve slightly better recognition
rates than MLPs. The MLP is faster at classification and should therefore be prefered in time critical applications.
Please note that this guideline assumes optimal tuning of the parameters.
Parameter
. WidthCharacter (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Width of the rectangle to which the gray values of the segmented character are zoomed.
Default Value : 8
Suggested values : WidthCharacter ∈ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 16, 20}
Typical range of values : 4 ≤ WidthCharacter ≤ 4
. HeightCharacter (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Height of the rectangle to which the gray values of the segmented character are zoomed.
Default Value : 10
Suggested values : HeightCharacter ∈ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 16, 20}
Typical range of values : 4 ≤ HeightCharacter ≤ 4
. Interpolation (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Interpolation mode for the zooming of the characters.
Default Value : ’constant’
List of values : Interpolation ∈ {’none’, ’constant’, ’weighted’}
. Features (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Features to be used for classification.
Default Value : ’default’
List of values : Features ∈ {’default’, ’pixel’, ’pixel_invar’, ’pixel_binary’, ’gradient_8dir’,
’projection_horizontal’, ’projection_horizontal_invar’, ’projection_vertical’, ’projection_vertical_invar’,
’ratio’, ’anisometry’, ’width’, ’height’, ’zoom_factor’, ’foreground’, ’foreground_grid_9’,
’foreground_grid_16’, ’compactness’, ’convexity’, ’moments_region_2nd_invar’,
’moments_region_2nd_rel_invar’, ’moments_region_3rd_invar’, ’moments_central’, ’moments_gray_plane’,
’phi’, ’num_connect’, ’num_holes’, ’cooc’, ’num_runs’, ’chord_histo’}
. Characters (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( string )
All characters of the character set to be read.
Default Value : [’0’,’1’,’2’,’3’,’4’,’5’,’6’,’7’,’8’,’9’]

HALCON/COM Reference Manual, 2008-5-13


10.3. NEURAL-NETS 763

. NumHidden (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT


Number of hidden units of the MLP.
Default Value : 80
Suggested values : NumHidden ∈ {1, 2, 3, 4, 5, 8, 10, 15, 20, 30, 40, 50, 60, 70, 80, 90, 100, 120, 150}
Restriction : (N umHidden ≥ 1)
. Preprocessing (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Type of preprocessing used to transform the feature vectors.
Default Value : ’none’
List of values : Preprocessing ∈ {’none’, ’normalization’, ’principal_components’,
’canonical_variates’}
. NumComponents (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Preprocessing parameter: Number of transformed features (ignored for Preprocessing = ’none’ and
Preprocessing = ’normalization’).
Default Value : 10
Suggested values : NumComponents ∈ {1, 2, 3, 4, 5, 8, 10, 15, 20, 30, 40, 50, 60, 70, 80, 90, 100}
Restriction : (N umComponents ≥ 1)
. RandSeed (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Seed value of the random number generator that is used to initialize the MLP with random values.
Default Value : 42
. OCRHandle (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ocr_mlp ; HOcrMlpX / VARIANT
Handle of the OCR classifier.
Example

read_image (Image, ’letters’)


* Segment the image.
bin_threshold (Image, Region)
dilation_circle (Region, RegionDilation, 3.5)
connection (RegionDilation, ConnectedRegions)
intersection (ConnectedRegions, Region, RegionIntersection)
sort_region (RegionIntersection, Characters, ’character’, ’true’, ’row’)
* Generate the training file.
Number := |Characters|
Classes := []
for J := 0 to 25 by 1
Classes := [Classes,gen_tuple_const(20,chr(ord(’a’)+J))]
endfor
Classes := [Classes,gen_tuple_const(20,’.’)]
write_ocr_trainf (Characters, Image, Classes, ’letters.trf’)
* Generate and train the classifier.
read_ocr_trainf_names (’letters.trf’, CharacterNames, CharacterCount)
create_ocr_class_mlp (8, 10, ’constant’, ’default’, CharacterNames, 20,
’none’, 81, 42, OCRHandle)
trainf_ocr_class_mlp (OCRHandle, ’letters.trf’, 100, 0.01, 0.01, Error,
ErrorLog)
* Re-classify the characters in the image.
do_ocr_multi_class_mlp (Characters, Image, OCRHandle, Class, Confidence)
clear_ocr_class_mlp (OCRHandle)

Result
If the parameters are valid, the operator CreateOcrClassMlp returns the value TRUE. If necessary an excep-
tion handling is raised.
Parallelization Information
CreateOcrClassMlp is processed completely exclusively without parallelization.
Possible Successors
TrainfOcrClassMlp

HALCON 8.0.2
764 CHAPTER 10. OCR

See also
DoOcrSingleClassMlp, DoOcrMultiClassMlp, ClearOcrClassMlp, CreateClassMlp,
TrainClassMlp, ClassifyClassMlp
Alternatives
CreateOcrClassSvm, CreateOcrClassBox
Module
OCR/OCV

[out] VARIANT Class HRegionX.DoOcrMultiClassMlp ([in] HImageX Image,


[in] HOcrMlpX OCRHandle, [out] VARIANT Confidence )
[out] VARIANT Class HOcrMlpX.DoOcrMultiClassMlp
([in] HRegionX Character, [in] HImageX Image, [out] VARIANT Confidence )
void HOperatorSetX.DoOcrMultiClassMlp ([in] IHObjectX Character,
[in] IHObjectX Image, [in] VARIANT OCRHandle, [out] VARIANT Class,
[out] VARIANT Confidence )

Classify multiple characters with an OCR classifier.


DoOcrMultiClassMlp computes the best class for each of the characters given by the regions Character
and the gray values Image with the OCR classifier OCRHandle and returns the classes in Class and the corre-
sponding confidences (probabilities) of the classes in Confidence. In contrast to DoOcrSingleClassMlp,
DoOcrMultiClassMlp can classify multiple characters in one call, and therefore typically is faster than a
loop that uses DoOcrSingleClassMlp to classify single characters. However, DoOcrMultiClassMlp
can only return the best class of each character. Because the confidences can be interpreted as probabilities (see
ClassifyClassMlp and EvaluateClassMlp), and it is therefore easy to check whether a character has
been classified with too much uncertainty, this is usually not a disadvantage, except in cases where the classes
overlap so much that in many cases the second best class must be examined to be able to decide the class of the
character. In these cases, DoOcrSingleClassMlp should be used. Before calling DoOcrMultiClassMlp,
the classifier must be trained with TrainfOcrClassMlp.
Parameter

. Character (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Characters to be recognized.
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, uint2 )
Gray values of the characters.
. OCRHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ocr_mlp ; HOcrMlpX / VARIANT
Handle of the OCR classifier.
. Class (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Result of classifying the characters with the MLP.
Number of elements : (Class = Character)
. Confidence (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Confidence of the class of the characters.
Number of elements : (Conf idence = Character)
Result
If the parameters are valid, the operator DoOcrMultiClassMlp returns the value TRUE. If necessary an
exception handling is raised.
Parallelization Information
DoOcrMultiClassMlp is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
TrainfOcrClassMlp, ReadOcrClassMlp
See also
CreateOcrClassMlp, ClassifyClassMlp
Alternatives
DoOcrWordMlp, DoOcrSingleClassMlp

HALCON/COM Reference Manual, 2008-5-13


10.3. NEURAL-NETS 765

Module
OCR/OCV

[out] VARIANT Class HRegionX.DoOcrSingleClassMlp ([in] HImageX Image,


[in] HOcrMlpX OCRHandle, [in] VARIANT Num, [out] VARIANT Confidence )
[out] VARIANT Class HOcrMlpX.DoOcrSingleClassMlp
([in] HRegionX Character, [in] HImageX Image, [in] VARIANT Num,
[out] VARIANT Confidence )
void HOperatorSetX.DoOcrSingleClassMlp ([in] IHObjectX Character,
[in] IHObjectX Image, [in] VARIANT OCRHandle, [in] VARIANT Num,
[out] VARIANT Class, [out] VARIANT Confidence )

Classify a single character with an OCR classifier.


DoOcrSingleClassMlp computes the best Num classes of the character given by the region Character
and the gray values Image with the OCR classifier OCRHandle and returns the classes in Class and the
corresponding confidences (probabilities) of the classes in Confidence. Because multiple classes may be
returned by DoOcrSingleClassMlp, Character may only contain a single region (a single character).
If multiple characters should be classified in a single call, DoOcrMultiClassMlp must be used. Because
DoOcrMultiClassMlp typically is faster than a loop with DoOcrSingleClassMlp and because the con-
fidences can be interpreted as probabilities (see ClassifyClassMlp and EvaluateClassMlp), and it
is therefore easy to check whether a character has been classified with too much uncertainty, in most cases
DoOcrMultiClassMlp should be used, unless the second-best class should be examined explicitly. Before
calling DoOcrSingleClassMlp, the classifier must be trained with TrainfOcrClassMlp.
Parameter
. Character (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
Character to be recognized.
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, uint2 )
Gray values of the character.
. OCRHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ocr_mlp ; HOcrMlpX / VARIANT
Handle of the OCR classifier.
. Num (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Number of best classes to determine.
Default Value : 1
Suggested values : Num ∈ {1, 2, 3, 4, 5}
. Class (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Result of classifying the character with the MLP.
. Confidence (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Confidence(s) of the class(es) of the character.
Result
If the parameters are valid, the operator DoOcrSingleClassMlp returns the value TRUE. If necessary an
exception handling is raised.
Parallelization Information
DoOcrSingleClassMlp is reentrant and processed without parallelization.
Possible Predecessors
TrainfOcrClassMlp, ReadOcrClassMlp
See also
CreateOcrClassMlp, ClassifyClassMlp
Alternatives
DoOcrMultiClassMlp
Module
OCR/OCV

HALCON 8.0.2
766 CHAPTER 10. OCR

[out] VARIANT Class HRegionX.DoOcrWordMlp ([in] HImageX Image,


[in] HOcrMlpX OCRHandle, [in] String Expression, [in] long NumAlternatives,
[in] long NumCorrections, [out] VARIANT Confidence, [out] String Word,
[out] double Score )
[out] VARIANT Class HOcrMlpX.DoOcrWordMlp ([in] HRegionX Character,
[in] HImageX Image, [in] String Expression, [in] long NumAlternatives,
[in] long NumCorrections, [out] VARIANT Confidence, [out] String Word,
[out] double Score )
void HOperatorSetX.DoOcrWordMlp ([in] IHObjectX Character,
[in] IHObjectX Image, [in] VARIANT OCRHandle, [in] VARIANT Expression,
[in] VARIANT NumAlternatives, [in] VARIANT NumCorrections,
[out] VARIANT Class, [out] VARIANT Confidence, [out] VARIANT Word,
[out] VARIANT Score )

Classify a related group of characters with an OCR classifier.


DoOcrWordMlp works like DoOcrMultiClassMlp insofar as it computes the best class for each of the
characters given by the regions Character and the gray values Image with the OCR classifier OCRHandle,
and returns the classes in Class and the corresponding confidences (probabilities) of the classes in Confidence.
In contrast to DoOcrMultiClassMlp, DoOcrWordMlp treats the group of characters as an entity which
yields a Word by concatenating the class names for each character region. This allows to restrict the allowed
classification results on a textual level by specifying an Expression describing the expected word.
The Expression may restrict the word to belong to a predefined lexicon created using CreateLexicon
or ImportLexicon, by specifying the name of the lexicon in angular brackets as in ’<mylexicon>’. If the
Expression is of any other form, it is interpreted as a regular expression with the same syntax as specified
for TupleRegexpMatch. Note that you will usually want to use an expression of the form ’^...$’ when using
variable quantifiers like ’*’, to ensure that the entire word is used in the expression. Also note that in contrast to
TupleRegexpMatch, DoOcrWordMlp does not support passing extra options in an expression tuple.
If the word derived from the best class for each character does not match the Expression, DoOcrWordMlp
attempts to correct it by considering the NumAlternatives best classes for each character. The alternatives
used are identical to those returned by DoOcrSingleClassMlp for a single character. It does so by testing
all possible corrections for which the classification result is changed for at most NumCorrections character
regions.
In case the Expression is a lexicon and the above procedure did not yield a result, the most similar word in
the lexicon is returned as long as it requires less than NumCorrections edit operations for the correction (see
SuggestLexicon).
The resulting word is graded by a Score between 0.0 (no correction found) and 1.0 (original word correct), which
is dominated by the number of corrected characters but also adds a minor penalty for ignoring the second best
class or even all best classes (in case of lexica). Note that this is a combinatorial score which does not reflect the
original Confidence of the best Class.
Parameter

. Character (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Characters to be recognized.
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, uint2 )
Gray values of the characters.
. OCRHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ocr_mlp ; HOcrMlpX / VARIANT
Handle of the OCR classifier.
. Expression (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Expression describing the allowed word structure.
. NumAlternatives (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of classes per character considered for the internal word correction.
Default Value : 3
Suggested values : NumAlternatives ∈ {3, 4, 5}

HALCON/COM Reference Manual, 2008-5-13


10.3. NEURAL-NETS 767

. NumCorrections (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT


Maximum number of corrected characters.
Default Value : 2
Suggested values : NumCorrections ∈ {1, 2, 3, 4, 5}
. Class (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Result of classifying the characters with the MLP.
Number of elements : (Class = Character)
. Confidence (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Confidence of the class of the characters.
Number of elements : (Conf idence = Character)
. Word (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Word text after classification and correction.
. Score (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Measure of similarity between corrected word and uncorrected classification results.
Complexity
The complexity of checking all possible corrections is of magnitude O((n ∗ a)min(c,n) ), where a is the number
of alternatives, n is the number of character regions, and c is the number of allowed corrections. However, to
guard against a near-infinite loop in case of large n, c is internally clipped to 5, 3, or 1 if a ∗ n >= 30, 60, or 90,
respectively.
Result
If the parameters are valid, the operator DoOcrMultiClassMlp returns the value TRUE. If necessary an
exception handling is raised.
Parallelization Information
DoOcrWordMlp is reentrant and processed without parallelization.
Possible Predecessors
TrainfOcrClassMlp, ReadOcrClassMlp
See also
CreateOcrClassMlp, ClassifyClassMlp
Alternatives
DoOcrMultiClassMlp
Module
OCR/OCV

[out] VARIANT Features HImageX.GetFeaturesOcrClassMlp


([in] HOcrMlpX OCRHandle, [in] String Transform )
[out] VARIANT Features HOcrMlpX.GetFeaturesOcrClassMlp
([in] HImageX Character, [in] String Transform )
void HOperatorSetX.GetFeaturesOcrClassMlp ([in] IHObjectX Character,
[in] VARIANT OCRHandle, [in] VARIANT Transform, [out] VARIANT Features )

Compute the features of a character.


GetFeaturesOcrClassMlp computes the features of the character given by Character with the
OCR classifier OCRHandle and returns them in Features. In contrast to DoOcrSingleClassMlp
and DoOcrMultiClassMlp, the character is passed as a single image object. Hence, before calling
GetFeaturesOcrClassMlp, ReduceDomain must typically be called. The parameter Transform de-
termines whether the feature transformation specified with Preprocessing in CreateOcrClassMlp for
the classifier should be applied (Transform = ’true’) or whether the untransformed features should be returned
(Transform = ’false’). GetFeaturesOcrClassMlp can be used to inspect the features that are used for
the classification.
Parameter

. Character (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, uint2 )


Input character.

HALCON 8.0.2
768 CHAPTER 10. OCR

. OCRHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ocr_mlp ; HOcrMlpX / VARIANT


Handle of the OCR classifier.
. Transform (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Should the feature vector be transformed with the preprocessing?
Default Value : ’true’
List of values : Transform ∈ {’true’, ’false’}
. Features (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Feature vector of the character.
Result
If the parameters are valid, the operator GetFeaturesOcrClassMlp returns the value TRUE. If necessary an
exception handling is raised.
Parallelization Information
GetFeaturesOcrClassMlp is reentrant and processed without parallelization.
Possible Predecessors
TrainfOcrClassMlp
See also
CreateOcrClassMlp
Module
OCR/OCV

[out] long WidthCharacter HOcrMlpX.GetParamsOcrClassMlp


([out] long HeightCharacter, [out] String Interpolation,
[out] VARIANT Features, [out] VARIANT Characters, [out] long NumHidden,
[out] String Preprocessing, [out] long NumComponents )
void HOperatorSetX.GetParamsOcrClassMlp ([in] VARIANT OCRHandle,
[out] VARIANT WidthCharacter, [out] VARIANT HeightCharacter,
[out] VARIANT Interpolation, [out] VARIANT Features,
[out] VARIANT Characters, [out] VARIANT NumHidden,
[out] VARIANT Preprocessing, [out] VARIANT NumComponents )

Return the parameters of an OCR classifier.


GetParamsOcrClassMlp returns the parameters of an OCR classifier that were specified when the clas-
sifier was created with CreateOcrClassMlp. This is particularly useful if the classifier was read with
ReadOcrClassMlp. The output of GetParamsOcrClassMlp can, for example, be used to check whether a
character to be read is contained in the classifier. For a description of the parameters, see CreateOcrClassMlp.
Parameter

. OCRHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ocr_mlp ; HOcrMlpX / VARIANT


Handle of the OCR classifier.
. WidthCharacter (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Width of the rectangle to which the gray values of the segmented character are zoomed.
. HeightCharacter (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Height of the rectangle to which the gray values of the segmented character are zoomed.
. Interpolation (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Interpolation mode for the zooming of the characters.
. Features (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Features to be used for classification.
. Characters (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( string )
Characters of the character set to be read.
. NumHidden (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of hidden units of the MLP.
. Preprocessing (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Type of preprocessing used to transform the feature vectors.

HALCON/COM Reference Manual, 2008-5-13


10.3. NEURAL-NETS 769

. NumComponents (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT


Preprocessing parameter: Number of transformed features.
Result
If the parameters are valid, the operator GetParamsOcrClassMlp returns the value TRUE. If necessary an
exception handling is raised.
Parallelization Information
GetParamsOcrClassMlp is reentrant and processed without parallelization.
Possible Predecessors
CreateOcrClassMlp, ReadOcrClassMlp
Possible Successors
DoOcrSingleClassMlp, DoOcrMultiClassMlp
See also
TrainfOcrClassMlp, GetParamsClassMlp
Module
OCR/OCV

[out] VARIANT InformationCont HOcrMlpX.GetPrepInfoOcrClassMlp


([in] VARIANT TrainingFile, [in] String Preprocessing,
[out] VARIANT CumInformationCont )
void HOperatorSetX.GetPrepInfoOcrClassMlp ([in] VARIANT OCRHandle,
[in] VARIANT TrainingFile, [in] VARIANT Preprocessing,
[out] VARIANT InformationCont, [out] VARIANT CumInformationCont )

Compute the information content of the preprocessed feature vectors of an OCR classifier.
GetPrepInfoOcrClassMlp computes the information content of the training vectors that have been
transformed with the preprocessing given by Preprocessing. Preprocessing can be set to ’prin-
cipal_components’ or ’canonical_variates’. The OCR classifier OCRHandle must have been created with
CreateOcrClassMlp. The preprocessing methods are described with CreateClassMlp. The informa-
tion content is derived from the variations of the transformed components of the feature vector, i.e., it is computed
solely based on the training data, independent of any error rate on the training data. The information content is
computed for all relevant components of the transformed feature vectors (NumInput for ’principal_components’
and min(NumOutput − 1, NumInput) for ’canonical_variates’, see CreateClassMlp), and is returned in
InformationCont as a number between 0 and 1. To convert the information content into a percentage, it sim-
ply needs to be multiplied by 100. The cumulative information content of the first n components is returned in
the n-th component of CumInformationCont, i.e., CumInformationCont contains the sums of the first n
elements of InformationCont. To use GetPrepInfoOcrClassMlp, a sufficient number of samples must
be stored in the training files given by TrainingFile (see WriteOcrTrainf).
InformationCont and CumInformationCont can be used to decide how many components of the
transformed feature vectors contain relevant information. An often used criterion is to require that the trans-
formed data must represent x% (e.g., 90%) of the total data. This can be decided easily from the first value
of CumInformationCont that lies above x%. The number thus obtained can be used as the value for
NumComponents in a new call to CreateOcrClassMlp. The call to GetPrepInfoOcrClassMlp al-
ready requires the creation of a classifier, and hence the setting of NumComponents in CreateOcrClassMlp
to an initial value. However, if GetPrepInfoOcrClassMlp is called it is typically not known how
many components are relevant, and hence how to set NumComponents in this call. Therefore, the fol-
lowing two-step approach should typically be used to select NumComponents: In a first step, a classi-
fier with the maximum number for NumComponents is created (NumInput for ’principal_components’ and
min(NumOutput − 1, NumInput) for ’canonical_variates’). Then, the training samples are saved in a training
file using WriteOcrTrainf. Subsequently, GetPrepInfoOcrClassMlp is used to determine the infor-
mation content of the components, and with this NumComponents. After this, a new classifier with the desired
number of components is created, and the classifier is trained with TrainfOcrClassMlp.

HALCON 8.0.2
770 CHAPTER 10. OCR

Parameter
. OCRHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ocr_mlp ; HOcrMlpX / VARIANT
Handle of the OCR classifier.
. TrainingFile (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.read(-array) ; VARIANT ( string )
Name(s) of the training file(s).
Default Value : ’ocr.trf’
. Preprocessing (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Type of preprocessing used to transform the feature vectors.
Default Value : ’principal_components’
List of values : Preprocessing ∈ {’principal_components’, ’canonical_variates’}
. InformationCont (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Relative information content of the transformed feature vectors.
. CumInformationCont (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Cumulative information content of the transformed feature vectors.
Example

* Create the initial OCR classifier.


read_ocr_trainf_names (’ocr.trf’, CharacterNames, CharacterCount)
create_ocr_class_mlp (8, 10, ’constant’, ’default’, CharacterNames, 80,
’canonical_variates’, |CharacterNames|, 42, OCRHandle)
* Get the information content of the transformed feature vectors.
get_prep_info_ocr_class_mlp (OCRHandle, ’ocr.trf’, ’canonical_variates’,
InformationCont, CumInformationCont)
* Determine the number of transformed components.
* NumComp = [...]
clear_ocr_class_mlp (OCRHandle)
* Create the final OCR classifier.
create_ocr_class_mlp (8, 10, ’constant’, ’default’, CharacterNames, 80,
’canonical_variates’, NumComp, 42, OCRHandle)
* Train the final classifier.
trainf_ocr_class_mlp (OCRHandle, ’ocr.trf’, 100, 1, 0.01, Error, ErrorLog)
write_ocr_class_mlp (OCRHandle, ’ocr.omc’)
clear_ocr_class_mlp (OCRHandle)

Result
If the parameters are valid, the operator GetPrepInfoOcrClassMlp returns the value TRUE. If necessary an
exception handling is raised.
GetPrepInfoOcrClassMlp may return the error 9211 (Matrix is not positive definite) if Preprocessing
= ’canonical_variates’ is used. This typically indicates that not enough training samples have been stored for each
class.
Parallelization Information
GetPrepInfoOcrClassMlp is reentrant and processed without parallelization.
Possible Predecessors
CreateOcrClassMlp, WriteOcrTrainf, AppendOcrTrainf, WriteOcrTrainfImage
Possible Successors
ClearOcrClassMlp, CreateOcrClassMlp
Module
OCR/OCV

void HOcrMlpX.ReadOcrClassMlp ([in] String FileName )


void HOperatorSetX.ReadOcrClassMlp ([in] VARIANT FileName,
[out] VARIANT OCRHandle )

Read an OCR classifier from a file.

HALCON/COM Reference Manual, 2008-5-13


10.3. NEURAL-NETS 771

ReadOcrClassMlp reads an OCR classifier that has been stored with WriteOcrClassMlp. Since the
training of an OCR classifier can consume a relatively long time, the classifier is typically trained in an
offline process and written to a file with WriteOcrClassMlp. In the online process the classifier is
read with ReadOcrClassMlp and subsequently used for classification with DoOcrSingleClassMlp or
DoOcrMultiClassMlp.
HALCON provides a number of pretrained OCR classifiers (see Solution Guide I, chapter ’OCR’, section ’Pre-
trained OCR Fonts’). These pretrained OCR classifiers make it possible to read a wide variety of different fonts
without the need to train an OCR classifier. Note that the pretrained OCR classifiers were trained with symbols
that are printed dark on light.
Parameter

. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.read ; String / VARIANT


File name.
Suggested values : FileName ∈ {’Document_0-9A-Z.omc’, ’Document_0-9.omc’, ’Document.omc’,
’DotPrint_0-9A-Z.omc’, ’DotPrint_0-9.omc’, ’DotPrint_0-9+.omc’, ’DotPrint.omc’, ’HandWritten_0-9.omc’,
’Industrial_0-9A-Z.omc’, ’Industrial_0-9.omc’, ’Industrial_0-9+.omc’, ’Industrial.omc’, ’MICR.omc’,
’OCRA_0-9A-Z.omc’, ’OCRA_0-9.omc’, ’OCRA.omc’, ’OCRB_0-9A-Z.omc’, ’OCRB_0-9.omc’,
’OCRB.omc’, ’Pharma_0-9A-Z.omc’, ’Pharma_0-9.omc’, ’Pharma_0-9+.omc’, ’Pharma.omc’}
. OCRHandle (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ocr_mlp ; HOcrMlpX / VARIANT
Handle of the OCR classifier.
Result
If the parameters are valid, the operator ReadOcrClassMlp returns the value TRUE. If necessary an exception
handling is raised.
Parallelization Information
ReadOcrClassMlp is processed completely exclusively without parallelization.
Possible Successors
DoOcrSingleClassMlp, DoOcrMultiClassMlp
See also
CreateOcrClassMlp, WriteOcrClassMlp, ReadClassMlp, WriteClassMlp
Module
OCR/OCV

[out] double Error HOcrMlpX.TrainfOcrClassMlp


([in] VARIANT TrainingFile, [in] long MaxIterations,
[in] double WeightTolerance, [in] double ErrorTolerance,
[out] VARIANT ErrorLog )
void HOperatorSetX.TrainfOcrClassMlp ([in] VARIANT OCRHandle,
[in] VARIANT TrainingFile, [in] VARIANT MaxIterations,
[in] VARIANT WeightTolerance, [in] VARIANT ErrorTolerance,
[out] VARIANT Error, [out] VARIANT ErrorLog )

Train an OCR classifier.


TrainfOcrClassMlp trains the OCR classifier OCRHandle with the training characters stored in the OCR
training files given by TrainingFile. The training files must been created, e.g., using WriteOcrTrainf, be-
fore calling TrainfOcrClassMlp. The remaining parameters have the same meaning as in TrainClassMlp
and are described in detail with TrainClassMlp.
Parameter

. OCRHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ocr_mlp ; HOcrMlpX / VARIANT


Handle of the OCR classifier.
. TrainingFile (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.read(-array) ; VARIANT ( string )
Name(s) of the training file(s).
Default Value : ’ocr.trf’

HALCON 8.0.2
772 CHAPTER 10. OCR

. MaxIterations (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT


Maximum number of iterations of the optimization algorithm.
Default Value : 200
Suggested values : MaxIterations ∈ {20, 40, 60, 80, 100, 120, 140, 160, 180, 200, 220, 240, 260, 280,
300}
. WeightTolerance (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Threshold for the difference of the weights of the MLP between two iterations of the optimization algorithm.
Default Value : 1.0
Suggested values : WeightTolerance ∈ {1.0, 0.1, 0.01, 0.001, 0.0001, 0.00001}
Restriction : (W eightT olerance ≥ 1.0e − 8)
. ErrorTolerance (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Threshold for the difference of the mean error of the MLP on the training data between two iterations of the
optimization algorithm.
Default Value : 0.01
Suggested values : ErrorTolerance ∈ {1.0, 0.1, 0.01, 0.001, 0.0001, 0.00001}
Restriction : (ErrorT olerance ≥ 1.0e − 8)
. Error (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Mean error of the MLP on the training data.
. ErrorLog (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Mean error of the MLP on the training data as a function of the number of iterations of the optimization
algorithm.
Example

* Train an OCR classifier


read_ocr_trainf_names (’ocr.trf’, CharacterNames, CharacterCount)
create_ocr_class_mlp (8, 10, ’constant’, ’default’, CharacterNames, 80,
’none’, 81, 42, OCRHandle)
trainf_ocr_class_mlp (OCRHandle, ’ocr.trf’, 100, 1, 0.01, Error, ErrorLog)
write_ocr_class_mlp (OCRHandle, ’ocr.omc’)
clear_ocr_class_mlp (OCRHandle)

Result
If the parameters are valid, the operator TrainfOcrClassMlp returns the value TRUE. If necessary an excep-
tion handling is raised.
TrainfOcrClassMlp may return the error 9211 (Matrix is not positive definite) if Preprocessing =
’canonical_variates’ is used. This typically indicates that not enough training samples have been stored for each
class.
Parallelization Information
TrainfOcrClassMlp is processed completely exclusively without parallelization.
Possible Predecessors
CreateOcrClassMlp, WriteOcrTrainf, AppendOcrTrainf, WriteOcrTrainfImage
Possible Successors
DoOcrSingleClassMlp, DoOcrMultiClassMlp, WriteOcrClassMlp
See also
TrainClassMlp
Alternatives
ReadOcrClassMlp
Module
OCR/OCV

HALCON/COM Reference Manual, 2008-5-13


10.4. SUPPORT-VECTOR-MACHINES 773

void HOcrMlpX.WriteOcrClassMlp ([in] String FileName )


void HOperatorSetX.WriteOcrClassMlp ([in] VARIANT OCRHandle,
[in] VARIANT FileName )

Write an OCR classifier to a file.


WriteOcrClassMlp writes the OCR classifier OCRHandle to the file given by FileName. If a file extension
is not specified in FileName the default extension ’.omc’ is appended to FileName. WriteOcrClassMlp
is typically called after the classifier has been trained with TrainfOcrClassMlp. The classifier can be read
with ReadOcrClassMlp.
Parameter
. OCRHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ocr_mlp ; HOcrMlpX / VARIANT
Handle of the OCR classifier.
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.write ; String / VARIANT
File name.
Result
If the parameters are valid, the operator WriteOcrClassMlp returns the value TRUE. If necessary an exception
handling is raised.
Parallelization Information
WriteOcrClassMlp is reentrant and processed without parallelization.
Possible Predecessors
TrainfOcrClassMlp
Possible Successors
ClearOcrClassMlp
See also
CreateOcrClassMlp, ReadOcrClassMlp, WriteClassMlp, ReadClassMlp
Module
OCR/OCV

10.4 Support-Vector-Machines

void HMiscX.ClearAllOcrClassSvm ( )
void HOperatorSetX.ClearAllOcrClassSvm ( )

Clear all SVM based OCR classifiers.


ClearAllOcrClassSvm clears all SVM-based OCR classifiers that were created with
CreateOcrClassSvm and frees all memory required for the classifiers. After calling
ClearAllOcrClassSvm, no SVM-based classifiers can be used any longer.
Attention
ClearAllOcrClassSvm exists solely for the purpose of implementing the “reset program” functionality in
HDevelop. ClearAllOcrClassSvm must not be used in any application.
Result
ClearAllOcrClassSvm always returns TRUE.
Parallelization Information
ClearAllOcrClassSvm is processed completely exclusively without parallelization.
Possible Predecessors
DoOcrSingleClassSvm
See also
CreateOcrClassSvm, ReadOcrClassSvm, WriteOcrClassSvm, TrainfOcrClassSvm
Alternatives
ClearOcrClassSvm
Module
OCR/OCV

HALCON 8.0.2
774 CHAPTER 10. OCR

void HOperatorSetX.ClearOcrClassSvm ([in] VARIANT OCRHandle )

Clear an SVM-based OCR classifier.


ClearOcrClassSvm clears the OCR classifier given by OCRHandle and frees all memory required for the
classifier. After calling ClearOcrClassSvm, the classifier can no longer be used. The handle OCRHandle
becomes invalid.
Parameter
. OCRHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ocr_svm ; HOcrSvmX / VARIANT
Handle of the OCR classifier.
Result
If OCRHandle is valid the operator ClearOcrClassSvm returns the value TRUE. If necessary, an exception
handling is raised.
Parallelization Information
ClearOcrClassSvm is processed completely exclusively without parallelization.
Possible Predecessors
DoOcrSingleClassSvm, DoOcrMultiClassSvm
See also
CreateOcrClassSvm, ReadOcrClassSvm, WriteOcrClassSvm, TrainfOcrClassSvm
Module
OCR/OCV

void HOcrSvmX.CreateOcrClassSvm ([in] long WidthCharacter,


[in] long HeightCharacter, [in] String Interpolation, [in] VARIANT Features,
[in] VARIANT Characters, [in] String KernelType, [in] double KernelParam,
[in] double Nu, [in] String Mode, [in] String Preprocessing,
[in] long NumComponents )
void HOperatorSetX.CreateOcrClassSvm ([in] VARIANT WidthCharacter,
[in] VARIANT HeightCharacter, [in] VARIANT Interpolation,
[in] VARIANT Features, [in] VARIANT Characters, [in] VARIANT KernelType,
[in] VARIANT KernelParam, [in] VARIANT Nu, [in] VARIANT Mode,
[in] VARIANT Preprocessing, [in] VARIANT NumComponents,
[out] VARIANT OCRHandle )

Create an OCR classifier using a support vector machine.


CreateOcrClassSvm creates an OCR classifier that uses a support vector machine (SVM). The handle of the
OCR classifier is returned in OCRHandle.
For a description on how an SVM works, see CreateClassSvm. CreateOcrClassSvm creates an SVM
for classification with the classification mode given by Mode. The length of the feature vector of the SVM
(NumFeatures in CreateClassSvm) is determined from the features that are used for the OCR, which
are passed in Features. The features are described below. The kernel is parameterized with KernelType,
KernelParam and Nu like in CreateClassSvm. The number of classes of the SVM (NumClasses
in CreateClassSvm) is determined from the names of the characters to be used in the OCR, which are
passed in Characters. As described with CreateClassSvm, the parameters Preprocessing and
NumComponents can be used to specify a preprocessing of the data (i.e., the feature vectors). For the sake
of numerical stability, Preprocessing can typically be set to ’normalization’. In order to speed up classifi-
cation time, ’principal_components’ or ’canonical_variates’ can be used, as the number of input features can be
significantly reduced without deterioration of the recognition rate.
The features to be used for the classification are determined by Features. Features can contain a tuple of
feature names. Each of these feature names results in one or more features to be calculated for the classifier. Some
of the feature names compute gray value features (e.g., ’pixel_invar’). Because a classifier requires a constant num-
ber of features (input variables), a character to be classified is transformed to a standard size, which is determined
by WidthCharacter and HeightCharacter. The interpolation to be used for the transformation is deter-
mined by Interpolation. It has the same meaning as in AffineTransImage. The interpolation should

HALCON/COM Reference Manual, 2008-5-13


10.4. SUPPORT-VECTOR-MACHINES 775

be chosen such that no aliasing effects occur in the transformation. For most applications, Interpolation =
’constant’ should be used. It should be noted that the size of the transformed character is not chosen too large,
because the generalization properties of the classifier may become bad for large sizes. In particular, for large sizes
small segmentation errors will have a large influence on the computed features if gray value features are used. This
happens because segmentation errors will change the smallest enclosing rectangle of the regions, thus the character
is zoomed differently than the characters in the training set. In most applications, sizes between 6 × 8 and 10 × 14
should be used.
The parameter Features can contain the following feature names for the classification of the characters. By
specifying ’default’, the features ’ratio’ and ’pixel_invar’ are selected.

’pixel’ Gray values of the character (WidthCharacter × HeightCharacter features).


’pixel_invar’ Gray values of the character with maximum scaling of the gray values (WidthCharacter ×
HeightCharacter features).
’pixel_binary’ Region of the character as a binary image zoomed to a size of WidthCharacter ×
HeightCharacter (WidthCharacter × HeightCharacter features).
’gradient_8dir’ Gradients are computed on the character image. The gradient directions are discretized into 8
directions. The amplitude image is decomposed into 8 channels according to these discretized directions. 25
samples on a 5 × 5 grid are extracted from each channel. These samples are used as features (200 features).
’projection_horizontal’ Horizontal projection of the gray values (see GrayProjections,
HeightCharacter features).
’projection_horizontal_invar’ Maximally scaled horizontal projection of the gray values (HeightCharacter
features).
’projection_vertical’ Vertical projection of the gray values (see GrayProjections, WidthCharacter fea-
tures).
’projection_vertical_invar’ Maximally scaled vertical projection of the gray values (WidthCharacter fea-
tures).
’ratio’ Aspect ratio of the character (1 feature).
’anisometry’ Anisometry of the character (see Eccentricity, 1 feature).
’width’ Width of the character before scaling the character to the standard size (not scale-invariant, see
SmallestRectangle1, 1 feature).
’height’ Height of the character before scaling the character to the standard size (not scale-invariant, see
SmallestRectangle1, 1 feature).
’zoom_factor’ Difference in size between the character and the values of WidthCharacter and
HeightCharacter (not scale-invariant, 1 feature).
’foreground’ Fraction of pixels in the foreground (1 feature).
’foreground_grid_9’ Fraction of pixels in the foreground in a 3 × 3 grid within the smallest enclosing rectangle of
the character (9 features).
’foreground_grid_16’ Fraction of pixels in the foreground in a 4 × 4 grid within the smallest enclosing rectangle
of the character (16 features).
’compactness’ Compactness of the character (see Compactness, 1 feature).
’convexity’ Convexity of the character (see Convexity, 1 feature).
’moments_region_2nd_invar’ Normalized 2nd moments of the character (see MomentsRegion2NdInvar, 3
features).
’moments_region_2nd_rel_invar’ Normalized 2nd relative moments of the character (see
MomentsRegion2NdRelInvar, 2 features).
’moments_region_3rd_invar’ Normalized 3rd moments of the character (see MomentsRegion3RdInvar, 4
features).
’moments_central’ Normalized central moments of the character (see MomentsRegionCentral, 4 features).
’moments_gray_plane’ Normalized gray value moments and the angle of the gray value plane (see
MomentsGrayPlane, 4 features).
’phi’ Orientation (angle) of the character (see EllipticAxis, 1 feature).
’num_connect’ Number of connected components (see ConnectAndHoles, 1 feature).

HALCON 8.0.2
776 CHAPTER 10. OCR

’num_holes’ Number of holes (see ConnectAndHoles, 1 feature).


’cooc’ Values of the binary cooccurrence matrix (see GenCoocMatrix, 12 features).
’num_runs’ Number of runs in the region normalized by the area (1 feature).
’chord_histo’ Frequency of the runs per row (HeightCharacter features).

After the classifier has been created, it is trained using TrainfOcrClassSvm. After this, the classifier can be
saved using WriteOcrClassSvm. Alternatively, the classifier can be used immediately after training to classify
characters using DoOcrSingleClassSvm or DoOcrMultiClassSvm.
A comparison of SVM and the multi-layer perceptron (MLP) (see CreateOcrClassMlp) typically shows that
SVMs are generally faster at training, especially for huge training sets, and achieve slightly better recognition rates
than MLPs. The MLP is faster at classification and should therefore be prefered in time critical applications. Please
note that this guideline assumes optimal tuning of the parameters.
Parameter
. WidthCharacter (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Width of the rectangle to which the gray values of the segmented character are zoomed.
Default Value : 8
Suggested values : WidthCharacter ∈ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 16, 20}
Typical range of values : 4 ≤ WidthCharacter ≤ 4
. HeightCharacter (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Height of the rectangle to which the gray values of the segmented character are zoomed.
Default Value : 10
Suggested values : HeightCharacter ∈ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 14, 16, 20}
Typical range of values : 4 ≤ HeightCharacter ≤ 4
. Interpolation (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Interpolation mode for the zooming of the characters.
Default Value : ’constant’
List of values : Interpolation ∈ {’none’, ’constant’, ’weighted’}
. Features (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Features to be used for classification.
Default Value : ’default’
List of values : Features ∈ {’default’, ’pixel’, ’pixel_invar’, ’pixel_binary’, ’gradient_8dir’,
’projection_horizontal’, ’projection_horizontal_invar’, ’projection_vertical’, ’projection_vertical_invar’,
’ratio’, ’anisometry’, ’width’, ’height’, ’zoom_factor’, ’foreground’, ’foreground_grid_9’,
’foreground_grid_16’, ’compactness’, ’convexity’, ’moments_region_2nd_invar’,
’moments_region_2nd_rel_invar’, ’moments_region_3rd_invar’, ’moments_central’, ’moments_gray_plane’,
’phi’, ’num_connect’, ’num_holes’, ’cooc’, ’num_runs’, ’chord_histo’}
. Characters (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( string )
All characters of the character set to be read.
Default Value : [’0’,’1’,’2’,’3’,’4’,’5’,’6’,’7’,’8’,’9’]
. KernelType (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
The kernel type.
Default Value : ’rbf’
List of values : KernelType ∈ {’linear’, ’rbf’, ’polynomial_inhomogeneous’, ’polynomial_homogeneous’}
. KernelParam (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Additional parameter for the kernel function.
Default Value : 0.02
Suggested values : KernelParam ∈ {0.01, 0.02, 0.05, 0.1, 0.5}
. Nu (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Regularization constant of the SVM.
Default Value : 0.05
Suggested values : Nu ∈ {0.0001, 0.001, 0.01, 0.05, 0.1, 0.2, 0.3}
Restriction : ((N u > 0.0) ∧ (N u < 1.0))
. Mode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
The mode of the SVM.
Default Value : ’one-versus-one’
List of values : Mode ∈ {’one-versus-all’, ’one-versus-one’}

HALCON/COM Reference Manual, 2008-5-13


10.4. SUPPORT-VECTOR-MACHINES 777

. Preprocessing (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT


Type of preprocessing used to transform the feature vectors.
Default Value : ’normalization’
List of values : Preprocessing ∈ {’none’, ’normalization’, ’principal_components’,
’canonical_variates’}
. NumComponents (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Preprocessing parameter: Number of transformed features (ignored for Preprocessing = ’none’ and
Preprocessing = ’normalization’).
Default Value : 10
Suggested values : NumComponents ∈ {1, 2, 3, 4, 5, 8, 10, 15, 20, 30, 40, 50, 60, 70, 80, 90, 100}
Restriction : (N umComponents ≥ 1)
. OCRHandle (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ocr_svm ; HOcrSvmX / VARIANT
Handle of the OCR classifier.
Example

read_image (Image, ’letters’)


* Segment the image.
bin_threshold (Image, Region)
dilation_circle (Region, RegionDilation, 3.5)
connection (RegionDilation, ConnectedRegions)
intersection (ConnectedRegions, Region, RegionIntersection)
sort_region (RegionIntersection, Characters, ’character’, ’true’, ’row’)
* Generate the training file.
Number := |Characters|
Classes := []
for J := 0 to 25 by 1
Classes := [Classes,gen_tuple_const(20,chr(ord(’a’)+J))]
endfor
Classes := [Classes,gen_tuple_const(20,’.’)]
write_ocr_trainf (Characters, Image, Classes, ’letters.trf’)
* Generate and train the classifier.
read_ocr_trainf_names (’letters.trf’, CharacterNames, CharacterCount)
create_ocr_class_svm (8, 10, ’constant’, ’default’, CharacterNames,
’rbf’, 0.01, 0.01, ’one-versus-all’,
’principal_components’, 10, OCRHandle)
trainf_ocr_class_svm (OCRHandle, ’letters.trf’, 0.001, ’default’)
* Re-classify the characters in the image.
do_ocr_multi_class_svm (Characters, Image, OCRHandle, Class)
clear_ocr_class_svm (OCRHandle)

Result
If the parameters are valid the operator CreateOcrClassSvm returns the value TRUE. If necessary, an excep-
tion handling is raised.
Parallelization Information
CreateOcrClassSvm is processed completely exclusively without parallelization.
Possible Successors
TrainfOcrClassSvm
See also
DoOcrSingleClassSvm, DoOcrMultiClassSvm, ClearOcrClassSvm, CreateClassSvm,
TrainClassSvm, ClassifyClassSvm
Alternatives
CreateOcrClassMlp, CreateOcrClassBox
Module
OCR/OCV

HALCON 8.0.2
778 CHAPTER 10. OCR

[out] VARIANT Class HRegionX.DoOcrMultiClassSvm ([in] HImageX Image,


[in] HOcrSvmX OCRHandle )
[out] VARIANT Class HOcrSvmX.DoOcrMultiClassSvm
([in] HRegionX Character, [in] HImageX Image )
void HOperatorSetX.DoOcrMultiClassSvm ([in] IHObjectX Character,
[in] IHObjectX Image, [in] VARIANT OCRHandle, [out] VARIANT Class )

Classify multiple characters with an SVM-based OCR classifier.


DoOcrMultiClassSvm computes the best class for each of the characters given by the regions Character
and the gray values Image with the SVM-based OCR classifier OCRHandle and returns the classes in Class.
In contrast to DoOcrSingleClassSvm, DoOcrMultiClassSvm can classify multiple characters in one
call, and therefore typically is faster than a loop that uses DoOcrSingleClassSvm to classify single char-
acters. However, DoOcrMultiClassSvm can only return the best class of each character. Before calling
DoOcrMultiClassSvm, the classifier must be trained with TrainfOcrClassSvm.
Parameter

. Character (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Characters to be recognized.
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte )
Gray values of the characters.
. OCRHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ocr_svm ; HOcrSvmX / VARIANT
Handle of the OCR classifier.
. Class (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Result of classifying the characters with the SVM.
Result
If the parameters are valid the operator DoOcrMultiClassSvm returns the value TRUE. If necessary, an ex-
ception handling is raised.
Parallelization Information
DoOcrMultiClassSvm is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
TrainfOcrClassSvm, ReadOcrClassSvm
See also
CreateOcrClassSvm, ClassifyClassSvm
Alternatives
DoOcrSingleClassSvm
Module
OCR/OCV

[out] VARIANT Class HRegionX.DoOcrSingleClassSvm ([in] HImageX Image,


[in] HOcrSvmX OCRHandle, [in] VARIANT Num )
[out] VARIANT Class HOcrSvmX.DoOcrSingleClassSvm
([in] HRegionX Character, [in] HImageX Image, [in] VARIANT Num )
void HOperatorSetX.DoOcrSingleClassSvm ([in] IHObjectX Character,
[in] IHObjectX Image, [in] VARIANT OCRHandle, [in] VARIANT Num,
[out] VARIANT Class )

Classify a single character with an SVM-based OCR classifier.


DoOcrSingleClassSvm computes the best Num classes of the character given by the region Character and
the gray values Image with the OCR classifier OCRHandle and returns the classes in Class. Because multiple
classes may be returned by DoOcrSingleClassSvm, Character may only contain a single region (a single
character). If multiple characters should be classified in a single call, DoOcrMultiClassSvm must be used.
Before calling DoOcrSingleClassSvm, the classifier must be trained with TrainfOcrClassSvm.

HALCON/COM Reference Manual, 2008-5-13


10.4. SUPPORT-VECTOR-MACHINES 779

Parameter
. Character (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
Character to be recognized.
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte )
Gray values of the character.
. OCRHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ocr_svm ; HOcrSvmX / VARIANT
Handle of the OCR classifier.
. Num (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Number of best classes to determine.
Default Value : 1
Suggested values : Num ∈ {1, 2, 3, 4, 5}
. Class (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Result of classifying the character with the SVM.
Result
If the parameters are valid the operator DoOcrSingleClassSvm returns the value TRUE. If necessary, an
exception handling is raised.
Parallelization Information
DoOcrSingleClassSvm is reentrant and processed without parallelization.
Possible Predecessors
TrainfOcrClassSvm, ReadOcrClassSvm
See also
CreateOcrClassSvm, ClassifyClassSvm
Alternatives
DoOcrMultiClassSvm
Module
OCR/OCV

[out] VARIANT Class HRegionX.DoOcrWordSvm ([in] HImageX Image,


[in] HOcrSvmX OCRHandle, [in] String Expression, [in] long NumAlternatives,
[in] long NumCorrections, [out] String Word, [out] double Score )
[out] VARIANT Class HOcrSvmX.DoOcrWordSvm ([in] HRegionX Character,
[in] HImageX Image, [in] String Expression, [in] long NumAlternatives,
[in] long NumCorrections, [out] String Word, [out] double Score )
void HOperatorSetX.DoOcrWordSvm ([in] IHObjectX Character,
[in] IHObjectX Image, [in] VARIANT OCRHandle, [in] VARIANT Expression,
[in] VARIANT NumAlternatives, [in] VARIANT NumCorrections,
[out] VARIANT Class, [out] VARIANT Word, [out] VARIANT Score )

Classify a related group of characters with an OCR classifier.


DoOcrWordSvm works like DoOcrMultiClassSvm insofar as it computes the best class for each of the
characters given by the regions Character and the gray values Image with the OCR classifier OCRHandle,
and returns the results in Class.
In contrast to DoOcrMultiClassSvm, DoOcrWordSvm treats the group of characters as an entity which
yields a Word by concatenating the class names for each character region. This allows to restrict the allowed
classification results on a textual level by specifying an Expression describing the expected word.
The Expression may restrict the word to belong to a predefined lexicon created using CreateLexicon
or ImportLexicon, by specifying the name of the lexicon in angular brackets as in ’<mylexicon>’. If the
Expression is of any other form, it is interpreted as a regular expression with the same syntax as specified
for TupleRegexpMatch. Note that you will usually want to use an expression of the form ’^...$’ when using
variable quantifiers like ’*’, to ensure that the entire word is used in the expression. Also note that in contrast to
TupleRegexpMatch, DoOcrWordSvm does not support passing extra options in an expression tuple.
If the word derived from the best class for each character does not match the Expression, DoOcrWordSvm
attempts to correct it by considering the NumAlternatives best classes for each character. The alternatives

HALCON 8.0.2
780 CHAPTER 10. OCR

used are identical to those returned by DoOcrSingleClassSvm for a single character. It does so by testing
all possible corrections for which the classification result is changed for at most NumCorrections character
regions.
In case the Expression is a lexicon and the above procedure did not yield a result, the most similar word in
the lexicon is returned as long as it requires less than NumCorrections edit operations for the correction (see
SuggestLexicon).
The resulting word is graded by a Score between 0.0 (no correction found) and 1.0 (original word correct), which
is dominated by the number of corrected characters but also adds a minor penalty for ignoring the second best class
or even all best classes (in case of lexica).
Parameter

. Character (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Characters to be recognized.
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, uint2 )
Gray values of the characters.
. OCRHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ocr_svm ; HOcrSvmX / VARIANT
Handle of the OCR classifier.
. Expression (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Expression describing the allowed word structure.
. NumAlternatives (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of classes per character considered for the internal word correction.
Default Value : 3
Suggested values : NumAlternatives ∈ {3, 4, 5}
. NumCorrections (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Maximum number of corrected characters.
Default Value : 2
Suggested values : NumCorrections ∈ {1, 2, 3, 4, 5}
. Class (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Result of classifying the characters with the SVM.
Number of elements : (Class = Character)
. Word (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Word text after classification and correction.
. Score (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Measure of similarity between corrected word and uncorrected classification results.
Complexity
The complexity of checking all possible corrections is of magnitude O((n ∗ a)min(c,n) ), where a is the number
of alternatives, n is the number of character regions, and c is the number of allowed corrections. However, to
guard against a near-infinite loop in case of large n, c is internally clipped to 5, 3, or 1 if a ∗ n >= 30, 60, or 90,
respectively.
Result
If the parameters are valid, the operator DoOcrMultiClassSvm returns the value TRUE. If necessary an
exception handling is raised.
Parallelization Information
DoOcrWordSvm is reentrant and processed without parallelization.
Possible Predecessors
TrainfOcrClassSvm, ReadOcrClassSvm
See also
CreateOcrClassSvm, ClassifyClassSvm
Alternatives
DoOcrMultiClassSvm
Module
OCR/OCV

HALCON/COM Reference Manual, 2008-5-13


10.4. SUPPORT-VECTOR-MACHINES 781

[out] VARIANT Features HImageX.GetFeaturesOcrClassSvm


([in] HOcrSvmX OCRHandle, [in] String Transform )
[out] VARIANT Features HOcrSvmX.GetFeaturesOcrClassSvm
([in] HImageX Character, [in] String Transform )
void HOperatorSetX.GetFeaturesOcrClassSvm ([in] IHObjectX Character,
[in] VARIANT OCRHandle, [in] VARIANT Transform, [out] VARIANT Features )

Compute the features of a character.


GetFeaturesOcrClassSvm computes the features of the character given by Character with the
OCR classifier OCRHandle and returns them in Features. In contrast to DoOcrSingleClassSvm
and DoOcrMultiClassSvm, the character is passed as a single image object. Hence, before calling
GetFeaturesOcrClassSvm, ReduceDomain must typically be called. The parameter Transform de-
termines whether the feature transformation specified with Preprocessing in CreateOcrClassSvm for
the classifier should be applied (Transform = ’true’) or whether the untransformed features should be returned
(Transform = ’false’). GetFeaturesOcrClassSvm can be used to inspect the features that are used for
the classification.
Parameter

. Character (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte )


Input character.
. OCRHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ocr_svm ; HOcrSvmX / VARIANT
Handle of the OCR classifier.
. Transform (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Should the feature vector be transformed with the preprocessing?
Default Value : ’true’
List of values : Transform ∈ {’true’, ’false’}
. Features (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Feature vector of the character.
Result
If the parameters are valid the operator GetFeaturesOcrClassSvm returns the value TRUE. If necessary, an
exception handling is raised.
Parallelization Information
GetFeaturesOcrClassSvm is reentrant and processed without parallelization.
Possible Predecessors
TrainfOcrClassSvm
See also
CreateOcrClassSvm
Module
OCR/OCV

[out] long WidthCharacter HOcrSvmX.GetParamsOcrClassSvm


([out] long HeightCharacter, [out] String Interpolation,
[out] VARIANT Features, [out] VARIANT Characters, [out] String KernelType,
[out] double KernelParam, [out] double Nu, [out] String Mode,
[out] String Preprocessing, [out] long NumComponents )
void HOperatorSetX.GetParamsOcrClassSvm ([in] VARIANT OCRHandle,
[out] VARIANT WidthCharacter, [out] VARIANT HeightCharacter,
[out] VARIANT Interpolation, [out] VARIANT Features,
[out] VARIANT Characters, [out] VARIANT KernelType,
[out] VARIANT KernelParam, [out] VARIANT Nu, [out] VARIANT Mode,
[out] VARIANT Preprocessing, [out] VARIANT NumComponents )

Return the parameters of an OCR classifier.

HALCON 8.0.2
782 CHAPTER 10. OCR

GetParamsOcrClassSvm returns the parameters of an OCR classifier that were specified when the clas-
sifier was created with CreateOcrClassSvm. This is particularly useful if the classifier was read with
ReadOcrClassSvm. The output of GetParamsOcrClassSvm can, for example, be used to check whether a
character to be read is contained in the classifier. For a description of the parameters, see CreateOcrClassSvm.
Parameter

. OCRHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ocr_svm ; HOcrSvmX / VARIANT


Handle of the OCR classifier.
. WidthCharacter (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Width of the rectangle to which the gray values of the segmented character are zoomed.
. HeightCharacter (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Height of the rectangle to which the gray values of the segmented character are zoomed.
. Interpolation (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Interpolation mode for the zooming of the characters.
. Features (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Features to be used for classification.
. Characters (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( string )
Characters of the character set to be read.
. KernelType (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
The kernel type.
. KernelParam (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Additional parameters for the kernel function.
. Nu (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Regularization constant of the SVM.
. Mode (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
The mode of the SVM.
. Preprocessing (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Type of preprocessing used to transform the feature vectors.
. NumComponents (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Preprocessing parameter: Number of transformed features (ignored for Preprocessing = ’none’ and
Preprocessing = ’normalization’).
Result
If the parameters are valid the operator GetParamsOcrClassSvm returns the value TRUE. If necessary, an
exception handling is raised.
Parallelization Information
GetParamsOcrClassSvm is reentrant and processed without parallelization.
Possible Predecessors
CreateOcrClassSvm, ReadOcrClassSvm
Possible Successors
DoOcrSingleClassSvm, DoOcrMultiClassSvm
See also
TrainfOcrClassSvm, GetParamsClassSvm
Module
OCR/OCV

[out] VARIANT InformationCont HOcrSvmX.GetPrepInfoOcrClassSvm


([in] VARIANT TrainingFile, [in] String Preprocessing,
[out] VARIANT CumInformationCont )
void HOperatorSetX.GetPrepInfoOcrClassSvm ([in] VARIANT OCRHandle,
[in] VARIANT TrainingFile, [in] VARIANT Preprocessing,
[out] VARIANT InformationCont, [out] VARIANT CumInformationCont )

Compute the information content of the preprocessed feature vectors of an SVM-based OCR classifier.

HALCON/COM Reference Manual, 2008-5-13


10.4. SUPPORT-VECTOR-MACHINES 783

GetPrepInfoOcrClassSvm computes the information content of the training vectors that have been
transformed with the preprocessing given by Preprocessing. Preprocessing can be set to ’prin-
cipal_components’ or ’canonical_variates’. The OCR classifier OCRHandle must have been created with
CreateOcrClassSvm. The preprocessing methods are described with CreateClassSvm. The information
content is derived from the variations of the transformed components of the feature vector, i.e., it is computed solely
based on the training data, independent of any error rate on the training data. The information content is computed
for all relevant components of the transformed feature vectors (NumFeatures for ’principal_components’ and
min(NumClasses − 1, NumFeatures) for ’canonical_variates’, see CreateClassSvm), and is returned
in InformationCont as a number between 0 and 1. To convert the information content into a percentage, it
simply needs to be multiplied by 100. The cumulative information content of the first n components is returned in
the n-th component of CumInformationCont, i.e., CumInformationCont contains the sums of the first n
elements of InformationCont. To use GetPrepInfoOcrClassSvm, a sufficient number of samples must
be stored in the training files given by TrainingFile (see WriteOcrTrainf).
InformationCont and CumInformationCont can be used to decide how many components of the
transformed feature vectors contain relevant information. An often used criterion is to require that the trans-
formed data must represent x% (e.g., 90%) of the total data. This can be decided easily from the first value
of CumInformationCont that lies above x%. The number thus obtained can be used as the value for
NumComponents in a new call to CreateOcrClassSvm. The call to GetPrepInfoOcrClassSvm al-
ready requires the creation of a classifier, and hence the setting of NumComponents in CreateOcrClassSvm
to an initial value. However, if GetPrepInfoOcrClassSvm is called it is typically not known how
many components are relevant, and hence how to set NumComponents in this call. Therefore, the fol-
lowing two-step approach should typically be used to select NumComponents: In a first step, a classifier
with the maximum number for NumComponents is created (NumFeatures for ’principal_components’ and
min(NumClasses − 1, NumFeatures) for ’canonical_variates’). Then, the training samples are saved in a
training file using WriteOcrTrainf. Subsequently, GetPrepInfoOcrClassSvm is used to determine the
information content of the components, and with this NumComponents. After this, a new classifier with the
desired number of components is created, and the classifier is trained with TrainfOcrClassSvm.
Parameter
. OCRHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ocr_svm ; HOcrSvmX / VARIANT
Handle of the OCR classifier.
. TrainingFile (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.read(-array) ; VARIANT ( string )
Name(s) of the training file(s).
Default Value : ’ocr.trf’
. Preprocessing (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Type of preprocessing used to transform the feature vectors.
Default Value : ’principal_components’
List of values : Preprocessing ∈ {’principal_components’, ’canonical_variates’}
. InformationCont (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Relative information content of the transformed feature vectors.
. CumInformationCont (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Cumulative information content of the transformed feature vectors.
Example

* Create the initial OCR classifier.


read_ocr_trainf_names (’ocr.trf’, CharacterNames, CharacterCount)
create_ocr_class_svm (8, 10, ’constant’, ’default’, CharacterNames,
’rbf’, 0.01, 0.01, ’one-versus-one’,
’principal_components’, 81, OCRHandle)
* Get the information content of the transformed feature vectors.
get_prep_info_ocr_class_svm (OCRHandle, ’ocr.trf’, ’principal_components’,
InformationCont, CumInformationCont)
* Determine the number of transformed components.
* NumComp = [...]
clear_ocr_class_svm (OCRHandle)
* Create the final OCR classifier.
create_ocr_class_svm (8, 10, ’constant’, ’default’, CharacterNames,
’rbf’, 0.01, 0.01,’one-versus-one’,

HALCON 8.0.2
784 CHAPTER 10. OCR

’principal_components’, NumComp, OCRHandle)


* Train the final classifier.
trainf_ocr_class_svm (OCRHandle, ’ocr.trf’, 0.001, ’default’)
write_ocr_class_svm (OCRHandle, ’ocr.osc’)
clear_ocr_class_svm (OCRHandle)

Result
If the parameters are valid the operator GetPrepInfoOcrClassSvm returns the value TRUE. If necessary, an
exception handling is raised.
GetPrepInfoOcrClassSvm may return the error 9211 (Matrix is not positive definite) if Preprocessing
= ’canonical_variates’ is used. This typically indicates that not enough training samples have been stored for each
class.
Parallelization Information
GetPrepInfoOcrClassSvm is reentrant and processed without parallelization.
Possible Predecessors
CreateOcrClassSvm, WriteOcrTrainf, AppendOcrTrainf, WriteOcrTrainfImage
Possible Successors
ClearOcrClassSvm, CreateOcrClassSvm
Module
OCR/OCV

[out] long NumSupportVectors


HOcrSvmX.GetSupportVectorNumOcrClassSvm
([out] VARIANT NumSVPerSVM )
void HOperatorSetX.GetSupportVectorNumOcrClassSvm
([in] VARIANT OCRHandle, [out] VARIANT NumSupportVectors,
[out] VARIANT NumSVPerSVM )

Return the number of support vectors of an OCR classificator.


GetSupportVectorNumOcrClassSvm returns in NumSupportVectors the number of
support vectors that are stored in the support vector machine (SVM) given by OCRHandle.
GetSupportVectorNumOcrClassSvm should be called before the labels of individual support vec-
tors are read out with GetSupportVectorOcrClassSvm, e.g., for visualizing which of the training data
become a SV (see GetSupportVectorOcrClassSvm). The number of SVs in each classifier is listed in
NumSVPerSVM. The reason that its sum differs from the number obtained in NumSupportVectors is that SV
evaluations are reused throughout different binary sub-SVMs.
Parameter
. OCRHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ocr_svm ; HOcrSvmX / VARIANT
OCR handle.
. NumSupportVectors (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Total number of support vectors.
. NumSVPerSVM (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Number of SV of each sub-SVM.
Result
If the parameters are valid the operator GetSampleNumClassSvm returns the value TRUE. If necessary, an
exception handling is raised.
Parallelization Information
GetSupportVectorNumOcrClassSvm is reentrant and processed without parallelization.
Possible Predecessors
TrainfOcrClassSvm
Possible Successors
GetSupportVectorOcrClassSvm

HALCON/COM Reference Manual, 2008-5-13


10.4. SUPPORT-VECTOR-MACHINES 785

See also
CreateOcrClassSvm
Module
OCR/OCV

[out] double Index HOcrSvmX.GetSupportVectorOcrClassSvm


([in] VARIANT IndexSupportVector )
void HOperatorSetX.GetSupportVectorOcrClassSvm
([in] VARIANT OCRHandle, [in] VARIANT IndexSupportVector,
[out] VARIANT Index )

Return the index of a support vector from a trained OCR classifier that is based on support vector machines.
The operator GetSupportVectorOcrClassSvm maps support vectors of a trained SVM-based OCR
classifier (given in OCRHandle) to the original training data set. The index of the SV is specified with
IndexSupportVector. The index is counted from 0, i.e., IndexSupportVector must be a number
between 0 and IndexSupportVectors − 1, where IndexSupportVectors can be determined with
GetSupportVectorNumOcrClassSvm. The index of this SV in the training data is returned in Index.
GetSupportVectorOcrClassSvm can, for example, be used to visualize the support vectors. To do so, the
train file that has been used to train the SVM must be read with ReadOcrTrainf. The value returned in Index
must be incremented by 1 and can then be used to select the support vectors with SelectObj from the training
characters. If more than one train file has been used in TrainfOcrClassSvm Index behaves as if all train
files had been merged into one train file with ConcatOcrTrainf.
Parameter
. OCRHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ocr_svm ; HOcrSvmX / VARIANT
OCR handle.
. IndexSupportVector (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Number of stored support vectors.
. Index (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Index of the support vector in the training set.
Result
If the parameters are valid the operator GetSupportVectorOcrClassSvm returns the value TRUE. If nec-
essary, an exception handling is raised.
Parallelization Information
GetSupportVectorOcrClassSvm is reentrant and processed without parallelization.
Possible Predecessors
TrainfOcrClassSvm, GetSupportVectorNumOcrClassSvm
See also
CreateOcrClassSvm, ReadOcrTrainf, AppendOcrTrainf, ConcatOcrTrainf
Module
OCR/OCV

void HOcrSvmX.ReadOcrClassSvm ([in] String FileName )


void HOperatorSetX.ReadOcrClassSvm ([in] VARIANT FileName,
[out] VARIANT OCRHandle )

Read an SVM-based OCR classifier from a file.


ReadOcrClassSvm reads an OCR classifier that has been stored with WriteOcrClassSvm. Since the
training of an OCR classifier can consume a relatively long time, the classifier is typically trained in an
offline process and written to a file with WriteOcrClassSvm. In the online process the classifier is
read with ReadOcrClassSvm and subsequently used for classification with DoOcrSingleClassSvm or
DoOcrMultiClassSvm.

HALCON 8.0.2
786 CHAPTER 10. OCR

Parameter
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.read ; String / VARIANT
File name.
. OCRHandle (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ocr_svm ; HOcrSvmX / VARIANT
Handle of the OCR classifier.
Result
If the parameters are valid the operator ReadOcrClassSvm returns the value TRUE. If necessary, an exception
handling is raised.
Parallelization Information
ReadOcrClassSvm is processed completely exclusively without parallelization.
Possible Successors
DoOcrSingleClassSvm, DoOcrMultiClassSvm
See also
CreateOcrClassSvm, WriteOcrClassSvm, ReadClassSvm, WriteClassSvm
Module
OCR/OCV

[out] HOcrSvmX OCRHandleReduced HOcrSvmX.ReduceOcrClassSvm


([in] String Method, [in] long MinRemainingSV, [in] double MaxError )
void HOperatorSetX.ReduceOcrClassSvm ([in] VARIANT OCRHandle,
[in] VARIANT Method, [in] VARIANT MinRemainingSV, [in] VARIANT MaxError,
[out] VARIANT OCRHandleReduced )

Approximate a trained SVM-based OCR classifier by a reduced SVM.


ReduceOcrClassSvm reduces the classification time of an SVM based OCR classifier OCRHandle by re-
turning a reduced copy of it in OCRHandleReduced. The parameters Method, MinRemainingSV and
MaxError have the same meaning as in ReduceClassSvm and are described there. Please note that clas-
sification time can also be significantly reduced with a preprocessing step in CreateOcrClassSvm, which
possibly introduces less errors.
Parameter
. OCRHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ocr_svm ; HOcrSvmX / VARIANT
Original handle of SVM-based OCR-classifier.
. Method (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Type of postprocessing to reduce number of SVs.
Default Value : ’bottom_up’
List of values : Method ∈ {’bottom_up’}
. MinRemainingSV (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Minimum number of remaining SVs.
Default Value : 2
Suggested values : MinRemainingSV ∈ {2, 3, 4, 5, 7, 10, 15, 20, 30, 50}
Restriction : (M inRemainingSV ≥ 2)
. MaxError (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Maximum allowed error of reduction.
Default Value : 0.001
Suggested values : MaxError ∈ {0.0001, 0.0002, 0.0005, 0.001, 0.002, 0.005, 0.01, 0.02, 0.05}
Restriction : (M axError > 0.0)
. OCRHandleReduced (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . ocr_svm ; HOcrSvmX / VARIANT
SVMHandle of reduced OCR classifier.
Result
If the parameters are valid the operator ReduceOcrClassSvm returns the value TRUE. If necessary, an excep-
tion handling is raised.
Parallelization Information
ReduceOcrClassSvm is processed completely exclusively without parallelization.

HALCON/COM Reference Manual, 2008-5-13


10.4. SUPPORT-VECTOR-MACHINES 787

Possible Predecessors
TrainfOcrClassSvm, GetSupportVectorNumOcrClassSvm
Possible Successors
DoOcrSingleClassSvm, DoOcrMultiClassSvm, GetSupportVectorOcrClassSvm,
GetSupportVectorNumOcrClassSvm
See also
CreateOcrClassSvm
References
Bernhard Schölkopf, Alexander J.Smola: “Lerning with Kernels”; The MIT Press, London; 1999.
Module
OCR/OCV

void HOcrSvmX.TrainfOcrClassSvm ([in] VARIANT TrainingFile,


[in] double Epsilon, [in] VARIANT TrainMode )
void HOperatorSetX.TrainfOcrClassSvm ([in] VARIANT OCRHandle,
[in] VARIANT TrainingFile, [in] VARIANT Epsilon, [in] VARIANT TrainMode )

Train an OCR classifier.


TrainfOcrClassSvm trains the OCR classifier OCRHandle with the training characters stored in the OCR
training files given by TrainingFile. The training files must been created, e.g., using WriteOcrTrainf,
before calling TrainfOcrClassSvm. The parameters Epsilon and TrainMode have the same meaning as
in TrainClassSvm.
Parameter
. OCRHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ocr_svm ; HOcrSvmX / VARIANT
Handle of the OCR classifier.
. TrainingFile (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.read(-array) ; VARIANT ( string )
Name(s) of the training file(s).
Default Value : ’ocr.trf’
. Epsilon (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Stop parameter for training.
Default Value : 0.001
Suggested values : Epsilon ∈ {0.00001, 0.0001, 0.001, 0.01, 0.1}
. TrainMode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( string, integer )
Mode of training.
Default Value : ’default’
List of values : TrainMode ∈ {’default’, ’add_sv_to_train_set’}
Example

* Train an OCR classifier


read_ocr_trainf_names (’ocr.trf’, CharacterNames, CharacterCount)
create_ocr_class_svm (8, 10, ’constant’, ’default’, CharacterNames,
’rbf’, 0.01, 0.01, ’one-versus-one’,
’normalization’, 81, OCRHandle)
trainf_ocr_class_svm (OCRHandle, ’ocr.trf’, 0.001, ’default’)
write_ocr_class_svm (OCRHandle, ’ocr.osc’)
clear_ocr_class_svm (OCRHandle)

Result
If the parameters are valid the operator TrainfOcrClassSvm returns the value TRUE. If necessary, an excep-
tion handling is raised.
TrainfOcrClassSvm may return the error 9211 (Matrix is not positive definite) if Preprocessing =
’canonical_variates’ is used. This typically indicates that not enough training samples have been stored for each
class.

HALCON 8.0.2
788 CHAPTER 10. OCR

Parallelization Information
TrainfOcrClassSvm is processed completely exclusively without parallelization.
Possible Predecessors
CreateOcrClassSvm, WriteOcrTrainf, AppendOcrTrainf, WriteOcrTrainfImage
Possible Successors
DoOcrSingleClassSvm, DoOcrMultiClassSvm, WriteOcrClassSvm
See also
TrainClassSvm
Alternatives
ReadOcrClassSvm
Module
OCR/OCV

void HOcrSvmX.WriteOcrClassSvm ([in] String FileName )


void HOperatorSetX.WriteOcrClassSvm ([in] VARIANT OCRHandle,
[in] VARIANT FileName )

Write an OCR classifier to a file.


WriteOcrClassSvm writes the OCR classifier OCRHandle to the file given by FileName. If a file extension
is not specified in FileName, the default extension ’.osc’ is appended to FileName. WriteOcrClassSvm
is typically called after the classifier has been trained with TrainfOcrClassSvm. The classifier can be read
with ReadOcrClassSvm.
Parameter

. OCRHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ocr_svm ; HOcrSvmX / VARIANT


Handle of the OCR classifier.
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.write ; String / VARIANT
File name.
Result
If the parameters are valid the operator WriteOcrClassSvm returns the value TRUE. If necessary, an exception
handling is raised.
Parallelization Information
WriteOcrClassSvm is reentrant and processed without parallelization.
Possible Predecessors
TrainfOcrClassSvm
Possible Successors
ClearOcrClassSvm
See also
CreateOcrClassSvm, ReadOcrClassSvm, WriteClassSvm, ReadClassSvm
Module
OCR/OCV

HALCON/COM Reference Manual, 2008-5-13


10.5. TOOLS 789

10.5 Tools
[out] HImageX ImageForeground HRegionX.SegmentCharacters
([in] HImageX Image, [out] HRegionX RegionForeground, [in] String Method,
[in] String EliminateLines, [in] String DotPrint, [in] String StrokeWidth,
[in] VARIANT CharWidth, [in] VARIANT CharHeight, [in] long ThresholdOffset,
[in] long Contrast, [out] long UsedThreshold )
void HOperatorSetX.SegmentCharacters ([in] IHObjectX Region,
[in] IHObjectX Image, [out] HUntypedObjectX ImageForeground,
[out] HUntypedObjectX RegionForeground, [in] VARIANT Method,
[in] VARIANT EliminateLines, [in] VARIANT DotPrint, [in] VARIANT StrokeWidth,
[in] VARIANT CharWidth, [in] VARIANT CharHeight,
[in] VARIANT ThresholdOffset, [in] VARIANT Contrast,
[out] VARIANT UsedThreshold )

Segments characters in a given region of an image.


This operator is used to segment characters in a given Region of an Image. The Region is only used to reduce
the working area. The segmented characters are returned in RegionForeground.
Two different methods to detect the characters are supplied. All segmentation methods assume that the text ist
darker than the background. If this is not the case, please invert the image with InvertImage.
The parameter Method determines the algorithm for text segmentation. The possible values are

’local_contrast_best’ This method extracts text that differ locally from the background. Therefore, it is suited
for images with inhomogeneous illumination. The enhancment of the text borders, leads to a more accurate
determinaton of the outline of the text. Which is especially useful if the background is highly textured.
The parameter Contrast defines the minimum contrast,i.e., the minimum gray value difference between
symobls and background.
’local_auto_shape’ The minimum contrast is estimated automatically such that the number of very small regions
is reduced. This method is especially suitable for noisy images. The parameter ThresholdOffset can
be used to adjust the threshold. Let g(x, y) be the gray value at position (x, y) in the input Image. The
threshold condition is determined by:
g(x, y) ≤ UsedThreshold + ThresholdOffset.

Select EliminateLines if the extraction of characters is disturbed by lines that are horizontal or vertical with
respect to the lines of text and set its value to ’true’. The elimination is influenced by the maximum of CharWidth
and the maximum of CharHeight. For further information see the description of these parameters.
DotPrint: Should be set to ’true’ if dot prints should be read, else to ’false’.
StrokeWidth: Specifies the stroke width of the text. It is used to calculate internally used mask sizes to
determine the characters. This mask sizes are also influenced through the parameters DotPrint, the average
CharWidth, and the average CharHeight.
CharWidth: This can be a tuple with up to three values. The first value is the average width of a character. The
second is the minimum width of a character and the third is the maximum width of a character. If the minimum is
not set or equal -1, the operator automatically sets these value depending on the average CharWidth. The same
is the case if the maximum is not set. Some examples:
[10] sets the average character width to 10, the minimum and maximum are calculated by the operator.
[10,-1,20] sets the average character width to 10, the minimum value is calculated by the system, and the maximum
is set to 20.
[10,5,20] sets the average character width to 10, the minimum to 5, and the maximum to 20.
CharHeight: This can be a tuple with up to three values. The first value is the average height of a character. The
second is the minimum height of a character and the third is the maximum height of a character. If the minimum is
not set or equal -1, the operator automatically sets these value depending on the average CharHeight. The same
is the case if the maximum is not set. Some examples:
[10] sets the average character height to 10, the minimum and maximum are calculated by the operator.
[10,-1,20] sets the average character height to 10, the minimum value is calculated by the system, and the maximum
is set to 20.

HALCON 8.0.2
790 CHAPTER 10. OCR

[10,5,20] this sets the average character height to 10, the minimum to 5, and the maximum to 20.
ThresholdOffset: This parameter can be used to adjust the threshold, which is used when the segmentation
method ’local_auto_shape’ is chosen.
Contrast: Defines the minimum contrast between the text and the background. This parameter is used if the
segmentation method ’local_contrast_best’ is selected.
UsedThreshold: After the execution, this parameter returns the threshold used to segment the characters.
ImageForeground returns the image that was internally used for the segmentation.
Attention

Parameter
. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
Area in the image where the text lines are located.
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, uint2 )
Input image.
. ImageForeground (output iconic) . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX
Image used for the segmentation.
. RegionForeground (output iconic) . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Region of characters.
. Method (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Method to segment the characters.
Default Value : ’local_auto_shape’
List of values : Method ∈ {’local_contrast_best’, ’local_auto_shape’}
. EliminateLines (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Eliminate horizontal and vertical lines?
Default Value : ’false’
List of values : EliminateLines ∈ {’true’, ’false’}
. DotPrint (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Should dot print characters be detected?
Default Value : ’false’
List of values : DotPrint ∈ {’true’, ’false’}
. StrokeWidth (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Stroke width of a character.
Default Value : ’medium’
List of values : StrokeWidth ∈ {’ultra_light’, ’light’, ’medium’, ’bold’}
. CharWidth (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Width of a character.
Default Value : 25
Restriction : (CharW idth ≥ 1)
. CharHeight (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Height of a character.
Default Value : 25
Restriction : (CharHeight ≥ 1)
. ThresholdOffset (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Value to adjust the segmentation.
Default Value : 0
. Contrast (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Minimum gray value difference between text and background.
Default Value : 10
Restriction : (Contrast ≥ 1)
. UsedThreshold (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Threshold used to segment the characters.
Example

read_image (Image, ’dot_print_rotated/dot_print_rotated_’+J$’02d’)

HALCON/COM Reference Manual, 2008-5-13


10.5. TOOLS 791

text_line_orientation (Image, Image, 50, rad(-30), rad(30), OrientationAngle)


rotate_image (Image, ImageRotate, -OrientationAngle/rad(180)*180, ’constant’)
segment_characters (ImageRotate, ImageRotate, ImageForeground, RegionForeground,
’local_auto_shape’, 0, 0, ’medium’, 25, 25, 0, 10, UsedThreshold)

Result
If the input parameters are set correctly, the operator SegmentCharacters returns the value TRUE. Otherwise
an exception will be raised.
Parallelization Information
SegmentCharacters is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
TextLineOrientation
Possible Successors
SelectCharacters, Connection
Alternatives
Threshold
Module
Foundation

[out] HRegionX RegionCharacters HRegionX.SelectCharacters


([in] String DotPrint, [in] String StrokeWidth, [in] VARIANT CharWidth,
[in] VARIANT CharHeight, [in] String Punctuation, [in] String DiacriticMarks,
[in] String PartitionMethod, [in] String PartitionLines,
[in] String FragmentDistance, [in] String ConnectFragments,
[in] long ClutterSizeMax, [in] String StopAfter )
void HOperatorSetX.SelectCharacters ([in] IHObjectX Region,
[out] HUntypedObjectX RegionCharacters, [in] VARIANT DotPrint,
[in] VARIANT StrokeWidth, [in] VARIANT CharWidth, [in] VARIANT CharHeight,
[in] VARIANT Punctuation, [in] VARIANT DiacriticMarks,
[in] VARIANT PartitionMethod, [in] VARIANT PartitionLines,
[in] VARIANT FragmentDistance, [in] VARIANT ConnectFragments,
[in] VARIANT ClutterSizeMax, [in] VARIANT StopAfter )

Selects characters from a given region.


SelectCharacters selects from a given Region the areas which might be characters and returns them in
RegionCharacters. This is done by using features like StrokeWidth, DotPrint, the size of the char-
acters and some more. The given Region should be united, else every Region is processed separately. Thus
do not call Connection before calling SelectCharacters, because then fragments or dots would not be
connected to a character. If you have more than one region with text, you can of course handle them without
merging them. The Region for SelectCharacters typically comes from SegmentCharacters but also
any other segmentation operators can be used.
The process of the selection can be partitioned into four parts. All steps are influenced by the parameters
StrokeWidth, CharHeight, and CharWidth. If you loose small objects like dots, adapt the minimum
CharWidth and the minimum CharHeight. But some parameters affect the result of a certain step in partic-
ular. A closer description follows below. With the parameter StopAfter you can terminate after a specified
step.
In the first step, ’step1_select_candidates’, CharWidth and the CharHeight are used to select the candidates.
The result of this step is also affected by ClutterSizeMax.
In the next step, ’step2_partition_characters’, the parameter PartitionMethod and the parameter
PartitionLines influence the result.
Step three, ’step3_connect_fragments’, uses the the parameters ConnectFragments and DotPrint. If dot-
printed characters have to be detected and some dots are not connected to the character, there are two ways to
overcome this problem: You can increase the FragmentDistance and/or decrease the StrokeWidth.

HALCON 8.0.2
792 CHAPTER 10. OCR

In the last step, ’step4_select_characters’, the result is affected by the parameters DiacriticMarks and
Punctuation.
DotPrint: Should be set to ’true’ if dot prints should be read, else to ’false’.
StrokeWidth: Specifies the stroke width of the text. It is used to calculate internally used mask sizes to
determine the characters. This mask sizes are also influenced through the parameters DotPrint, the average
CharWidth, and the average CharHeight.
CharWidth: This can be a tuple with up to three values. The first value is the average width of a character. The
second is the minimum width of a character and the third is the maximum width of a character. If the minimum is
not set or equal -1, the operator automatically sets these value depending on average CharWidth. The same is
the case if the maximum is not set. Some examples:
[10] sets the average character width to 10, the minimum and maximum are calculated by the operator.
[10,-1,20] sets the average character width to 10, the minimum value is calculated by the system, and the maximum
is set to 20.
[10,5,20] sets the average character width to 10, the minimum to 5, and the maximum to 20.
CharHeight: This can be a tuple with up to three values. The first value is the average height of a character. The
second is the minimum height of a character and the third is the maximum height of a character. If the minimum
is not set or equal -1, the operator automatically sets these value depending on average CharHeight. The same
is the case if the maximum is not set. Some examples:
[10] sets the average character height to 10, the minimum and maximum are calculated by the operator.
[10,-1,20] sets the average character height to 10 the minimum value is calculated by the system and the maximum
is set to 20.
[10,5,20] this sets the average character height to 10, the minimum to 5 and the maximum to 20.
Punctuation: Set this parameter to ’true’ if the operator also has to detect punctuation marks (e.g. .,:’‘"),
otherwise they will be suppressed.
DiacriticMarks: Set this parameter to ’true’ if the text in your application contains diacritic marks (e.g. â,é,ö),
or to ’false’ to suppress them.
PartitionMethod: If neighboring characters are printed close to each other, they may be partly merged. With
this parameter you can specify the method to partition such characters. The possible values are ’none’, which
means no partitioning is perfomed. ’fixed_width’ means that the partitioning assumes a constant character width.
If the width of the extracted region is well above the average CharWidth, the region ist split into parts that have
the given average CharWidth. The partitioning starts at the left border of the region. ’variable_width’ means
that the characters are partitioned at the position where they have the thinnest connection. This method can be
selected for characters that are printed with a variable-width font or if many consecutive characters are extracted as
one symbol. It could be helpful to call TextLineSlant and/or use TextLineOrientation before calling
SelectCharacters.
PartitionLines: If some text lines or some characters of different text lines are connected, set this parameter
to ’true’.
FragmentDistance: This parameter influences the connection of character fragments. If too much is con-
nected, set the parameter to ’narrow’ or ’medium’. In the case that more fragments should be connected, set
the parameter to ’medium’ or ’wide’. The connection is also influenced by the maximum of CharWidth and
CharHeight. See also ConnectFragments.
ConnectFragments: Set this parameter to ’true’ if the extracted symbols are fragmented, i.e., if a symbol is
not extracted as one region but broken up into several parts. See also FragmentDistance and StopAfter in
the step ’step3_connect_fragments’.
ClutterSizeMax: If the extracted characters contain clutter, i.e., small regions near the actual symbols, increase
this value. If parts of the symbols are missing, decrease this value.
StopAfter: Use this parameter in the case the operator does not produce the desired results. By modifying this
value the operator stops after the execution of the selected step and provides the corresponding results. To end on
completion, set StopAfter to ’completion’.
Attention

HALCON/COM Reference Manual, 2008-5-13


10.5. TOOLS 793

Parameter

. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Region of text lines in which to select the characters.
. RegionCharacters (output iconic) . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Selected characters.
. DotPrint (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Should dot print characters be detected?
Default Value : ’false’
List of values : DotPrint ∈ {’true’, ’false’}
. StrokeWidth (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Stroke width of a character.
Default Value : ’medium’
List of values : StrokeWidth ∈ {’ultra_light’, ’light’, ’medium’, ’bold’}
. CharWidth (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Width of a character.
Default Value : 25
Restriction : (CharW idth ≥ 1)
. CharHeight (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Height of a character.
Default Value : 25
Restriction : (CharHeight ≥ 1)
. Punctuation (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Add punctuation?
Default Value : ’false’
List of values : Punctuation ∈ {’true’, ’false’}
. DiacriticMarks (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Exist diacritic marks?
Default Value : ’false’
List of values : DiacriticMarks ∈ {’true’, ’false’}
. PartitionMethod (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Method to partition neighbored characters.
Default Value : ’none’
List of values : PartitionMethod ∈ {’none’, ’fixed_width’, ’variable_width’}
. PartitionLines (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Should lines be partitioned?
Default Value : ’false’
List of values : PartitionLines ∈ {’true’, ’false’}
. FragmentDistance (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Distance of fragments.
Default Value : ’medium’
List of values : FragmentDistance ∈ {’narrow’, ’medium’, ’wide’}
. ConnectFragments (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Connect fragments?
Default Value : ’false’
List of values : ConnectFragments ∈ {’true’, ’false’}
. ClutterSizeMax (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Maximum size of clutter.
Default Value : 0
Restriction : (0 < ClutterSizeM ax)
. StopAfter (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Stop execution after this step.
Default Value : ’completion’
List of values : StopAfter ∈ {’step1_select_candidates’, ’step2_partition_characters’,
’step3_connect_fragments’, ’step4_select_characters’, ’completion’}
Example

HALCON 8.0.2
794 CHAPTER 10. OCR

read_image (Image, ’dot_print_rotated/dot_print_rotated_’+J$’02d’)


text_line_orientation (Image, Image, 50, rad(-30), rad(30), OrientationAngle)
rotate_image (Image, ImageRotate, -OrientationAngle/rad(180)*180, ’constant’)
segment_characters (ImageRotate, ImageRotate, ImageForeground, RegionForeground, ’local_
select_characters (RegionForeground, RegionCharacters, 1, ’ultra_light’, [60,1,100], [60

Result
If the input parameters are set correctly, the operator SelectCharacters returns the value TRUE. Otherwise
an exception will be raised.
Parallelization Information
SelectCharacters is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
SegmentCharacters, TextLineSlant
Possible Successors
DoOcrSingle, DoOcrMulti
Alternatives
Connection
Module
Foundation

[out] VARIANT OrientationAngle HRegionX.TextLineOrientation


([in] HImageX Image, [in] long CharHeight, [in] double OrientationFrom,
[in] double OrientationTo )
void HOperatorSetX.TextLineOrientation ([in] IHObjectX Region,
[in] IHObjectX Image, [in] VARIANT CharHeight, [in] VARIANT OrientationFrom,
[in] VARIANT OrientationTo, [out] VARIANT OrientationAngle )

Determines the orientation of a text line or paragraph.


TextLineOrientation determines the orientation of a single text line or a paragraph in relation to
the horizontal image axis. If the orientation of a single text line should be determined, the range for the
OrientationFrom and OrientationTo should be in the interval from -pi/4 to pi/4.
The parameter Region specifies the area of the image in which the text lines are located. The Region is only
used to reduce the working area. To determine the slant, the gray values inside that area are used. The text lines are
segmented by the operator TextLineOrientation itself. If more than one region is passed, the numerical
values of the orientation angle are stored in a tuple, the position of a value in the tuple corresponding to the position
of the region in the input tuple.
CharHeight specifies the approximately height of the existing text lines in the region Region. It´s assumed,
that the text lines are darker than the background.
The search area can be restricted by the parameters OrientationFrom and OrientationTo, whereby also
the runtime of the operator is influenced.
With the calculated angle OrientationAngle and operators like AffineTransImage, the region Region
of the image Image can be rotated such, that the text lines lie horizontally in the image. This may simplify the
character segmentation for OCR applications.
Attention

Parameter

. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Area of text lines.
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, uint2 )
Input image.

HALCON/COM Reference Manual, 2008-5-13


10.5. TOOLS 795

. CharHeight (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT


Height of the text lines.
Default Value : 25
Restriction : (CharHeight ≥ 1)
. OrientationFrom (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; double / VARIANT
Minimum rotation of the text lines.
Default Value : -0.523599
Typical range of values : -1.570796 ≤ OrientationFrom ≤ -1.570796
Restriction : (((−(pi)/2) ≤ OrientationF rom) ∧ (OrientationF rom ≤ OrientationT o))
. OrientationTo (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; double / VARIANT
Maximum rotation of the text lines.
Default Value : 0.523599
Typical range of values : -1.570796 ≤ OrientationTo ≤ -1.570796
Restriction : (((−(pi)/2) ≤ OrientationT o) ∧ (OrientationT o ≤ (pi/2)))
. OrientationAngle (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad(-array) ; VARIANT ( real )
Calculated rotation angle of the text lines.
Example

read_image(Image,’letters’)
text_line_orientation(Image,Image,50,rad(-80),rad(80),OrientationAngle)
rotate_image(Image,ImageRotate,-OrientationAngle/rad(180)*180,’constant’)

Result
If the input parameters are set correctly, the operator TextLineOrientation returns the value TRUE. Other-
wise an exception will be raised.
Parallelization Information
TextLineOrientation is reentrant and automatically parallelized (on tuple level).
Possible Successors
RotateImage, AffineTransImage, AffineTransImageSize
Module
Foundation

[out] VARIANT SlantAngle HRegionX.TextLineSlant ([in] HImageX Image,


[in] long CharHeight, [in] double SlantFrom, [in] double SlantTo )
void HOperatorSetX.TextLineSlant ([in] IHObjectX Region,
[in] IHObjectX Image, [in] VARIANT CharHeight, [in] VARIANT SlantFrom,
[in] VARIANT SlantTo, [out] VARIANT SlantAngle )

Determines the slant of characters of a text line or paragraph.


TextLineSlant determines the slant of a single text line or a paragraph.
The parameter Region specifies the area of the image in which the text lines are located. The Region is only
used to reduce the working area. To determine the slant, the gray values inside that area are used. The text lines
are segmented by the operator TextLineSlant itself. If more than one region is passed, the numerical values
of the orientation angle are stored in a tuple, the position of a value in the tuple corresponding to the position of
the region in the input tuple.
CharHeight specifies the approximately high of the existing text lines in the region Region. It´s assumed, that
the text lines are darker than the background.
The search area can be restricted by the parameters SlantFrom and SlantTo, whereby also the runtime of the
operator is influenced.
With the calculated slant angle SlantAngle and operators for affine transformations, the slant can be removed
from the characters. This may simplify the character separation for OCR applications. To work correctly all
characters of a region should have nearly the same slant.

HALCON 8.0.2
796 CHAPTER 10. OCR

Attention

Parameter
. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Area of text lines.
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, uint2 )
Input image.
. CharHeight (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Height of the text lines.
Default Value : 25
Restriction : (CharHeight ≥ 1)
. SlantFrom (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; double / VARIANT
Minimum slant of the characters
Default Value : -0.523599
Typical range of values : -0.785398 ≤ SlantFrom ≤ -0.785398
Restriction : (((−(pi)/4) ≤ SlantF rom) ∧ (SlantF rom ≤ SlantT o))
. SlantTo (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; double / VARIANT
Maximum slant of the characters
Default Value : 0.523599
Typical range of values : -0.785398 ≤ SlantTo ≤ -0.785398
Restriction : (((−(pi)/4) ≤ SlantT o) ∧ (SlantT o ≤ (pi/4)))
. SlantAngle (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad(-array) ; VARIANT ( real )
Calculated slant of the characters in the region
Example

hom_mat2d_identity(HomMat2DIdentity)
read_image(Image,’dot_print_slanted’)
/* correct slant */
text_line_slant(Image,Image,50,rad(-45),rad(45),SlantAngle)
hom_mat2d_slant(HomMat2DIdentity,-SlantAngle,’x’,0,0,HomMat2DSlant)
affine_trans_image(Image,Image,HomMat2DSlant,’constant’,’true’)

Result
If the input parameters are set correctly, the operator TextLineSlant returns the value TRUE. Otherwise an
exception will be raised.
Parallelization Information
TextLineSlant is reentrant and automatically parallelized (on tuple level).
Possible Successors
HomMat2dSlant, AffineTransImage, AffineTransImageSize
Module
Foundation

10.6 Training-Files

void HRegionX.AppendOcrTrainf ([in] HImageX Image, [in] VARIANT Class,


[in] String FileName )
void HOperatorSetX.AppendOcrTrainf ([in] IHObjectX Character,
[in] IHObjectX Image, [in] VARIANT Class, [in] VARIANT FileName )

Add characters to a training file.


The operator AppendOcrTrainf serves to prepare the training with the operator TrainfOcrClassBox.
Hereby regions, representing characters, including their gray values (region and pixel) and the corresponding class

HALCON/COM Reference Manual, 2008-5-13


10.6. TRAINING-FILES 797

name will be written into a file. An arbitrary number of regions within one image is supported. For each character
(region) in Character the corresponding class name must be specified in Class. The gray values are passed via
the parameter Image. In contrast to the operator WriteOcrTrainf the characters are appended to an existing
file using the same training file format as this file. If the file does not exist, a new file is generated. In this case, the
file format can be chosen by the parameter ’ocr_trainf_version’ of the operator SetSystem. If no file extension
is specified in FileName, the extension ’.trf’ is appended to the name.
Parameter
. Character (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Characters to be trained.
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, uint2 )
Gray values of the characters.
. Class (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Class (name) of the characters.
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.write ; String / VARIANT
Name of the training file.
Default Value : ’train_ocr’
Result
If the parameters are correct, the operator AppendOcrTrainf returns the value TRUE. Otherwise an exception
will be raised.
Parallelization Information
AppendOcrTrainf is processed completely exclusively without parallelization.
Possible Predecessors
Threshold, Connection, CreateOcrClassBox, ReadOcr
Possible Successors
TrainfOcrClassBox, InfoOcrClassBox, WriteOcr, DoOcrMulti, DoOcrSingle
Alternatives
WriteOcrTrainf, WriteOcrTrainfImage
Module
OCR/OCV

void HMiscX.ConcatOcrTrainf ([in] VARIANT SingleFiles,


[in] String ComposedFile )
void HOperatorSetX.ConcatOcrTrainf ([in] VARIANT SingleFiles,
[in] VARIANT ComposedFile )

Concat training files.


The operator ConcatOcrTrainf stores all characters which are contained in the files SingleFiles into a
new file with the name ComposedFile. The file format can be defined by the parameter ’ocr_trainf_version’ of
the operator SetSystem. If no file extension is specified in ComposedFile, the extension ’.trf’ is appended
to the file name.
Parameter
. SingleFiles (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.read(-array) ; VARIANT ( string )
Name of the single training files.
Default Value : ”
. ComposedFile (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.write ; String / VARIANT
Name of the composed training file.
Default Value : ’all_characters’
Result
If the parameters are correct, the operator ConcatOcrTrainf returns the value TRUE. Otherwise an exception
will be raised.
Parallelization Information
ConcatOcrTrainf is processed completely exclusively without parallelization.

HALCON 8.0.2
798 CHAPTER 10. OCR

Possible Predecessors
WriteOcrTrainf, AppendOcrTrainf
Possible Successors
TrainfOcrClassBox, InfoOcrClassBox, WriteOcr, DoOcrMulti, DoOcrSingle
Module
OCR/OCV

void HImageX.ReadOcrTrainf ([in] VARIANT TrainFileNames,


[out] VARIANT CharacterNames )
void HOperatorSetX.ReadOcrTrainf ([out] HUntypedObjectX Characters,
[in] VARIANT TrainFileNames, [out] VARIANT CharacterNames )

Read training characters from files and convert to images.


ReadOcrTrainf reads all characters from the specified file names and converts them into images. The domain
is defined according to the foreground of the characters (as specified in WriteOcrTrainf). The names of the
characters are returned in CharacterNames. If more than one file name is given the files are processed in the
order the file names.
Parameter
. Characters (output iconic) . . . . . . . . . . . . . . . . . . . . . image ; HImageX / HUntypedObjectX ( byte, uint2 )
Images read from file.
. TrainFileNames (input control) . . . . . . . . . . . . . . . . . . . . . . . . . filename.read(-array) ; VARIANT ( string )
Names of the training files.
Default Value : ”
. CharacterNames (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( string )
Names of the read characters.
Result
If the parameter values are correct the operator ReadOcrTrainf returns the value TRUE. Otherwise an excep-
tion handling is raised.
Parallelization Information
ReadOcrTrainf is reentrant and processed without parallelization.
Possible Predecessors
WriteOcrTrainf
Possible Successors
DispImage, SelectObj, ZoomImageSize
See also
TrainfOcrClassBox
Alternatives
ReadOcrTrainfSelect
Module
OCR/OCV

[out] VARIANT CharacterNames HMiscX.ReadOcrTrainfNames


([in] VARIANT TrainFileNames, [out] VARIANT CharacterCount )
void HOperatorSetX.ReadOcrTrainfNames ([in] VARIANT TrainFileNames,
[out] VARIANT CharacterNames, [out] VARIANT CharacterCount )

Query which characters are stored in a training file.


ReadOcrTrainfNames extracts the names and frequency of all characters in the specified training files.

HALCON/COM Reference Manual, 2008-5-13


10.6. TRAINING-FILES 799

Parameter
. TrainFileNames (input control) . . . . . . . . . . . . . . . . . . . . . . . . . filename.read(-array) ; VARIANT ( string )
Names of the training files.
Default Value : ”
. CharacterNames (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Names of the read characters.
. CharacterCount (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Number of the characters.
Result
If the parameter values are correct the operator ReadOcrTrainfNames returns the value TRUE. Otherwise an
exception handling is raised.
Parallelization Information
ReadOcrTrainfNames is reentrant and processed without parallelization.
Possible Predecessors
WriteOcrTrainf
See also
TrainfOcrClassBox
Module
OCR/OCV

void HImageX.ReadOcrTrainfSelect ([in] VARIANT TrainFileNames,


[in] VARIANT SearchNames, [out] VARIANT FoundNames )
void HOperatorSetX.ReadOcrTrainfSelect
([out] HUntypedObjectX Characters, [in] VARIANT TrainFileNames,
[in] VARIANT SearchNames, [out] VARIANT FoundNames )

Read training specific characters from files and convert to images.


ReadOcrTrainfSelect reads the characters given in SearchNames from the specified files and converts
them into images. It works simimalr to ReadOcrTrainf but here the characters which are extracted can be
specified.
Parameter
. Characters (output iconic) . . . . . . . . . . . . . . . . . . . . . image ; HImageX / HUntypedObjectX ( byte, uint2 )
Images read from file.
. TrainFileNames (input control) . . . . . . . . . . . . . . . . . . . . . . . . . filename.read(-array) ; VARIANT ( string )
Names of the training files.
Default Value : ”
. SearchNames (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Names of the characters to be extracted.
Default Value : ’0’
. FoundNames (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Names of the read characters.
Result
If the parameter values are correct the operator ReadOcrTrainfSelect returns the value TRUE. Otherwise
an exception handling is raised.
Parallelization Information
ReadOcrTrainfSelect is reentrant and processed without parallelization.
Possible Predecessors
WriteOcrTrainf
Possible Successors
DispImage, SelectObj, ZoomImageSize
See also
TrainfOcrClassBox

HALCON 8.0.2
800 CHAPTER 10. OCR

Alternatives
ReadOcrTrainf
Module
OCR/OCV

void HRegionX.WriteOcrTrainf ([in] HImageX Image, [in] VARIANT Class,


[in] String FileName )
void HOperatorSetX.WriteOcrTrainf ([in] IHObjectX Character,
[in] IHObjectX Image, [in] VARIANT Class, [in] VARIANT FileName )

Storing of trained characters into a file.


The operator WriteOcrTrainf serves to prepare the training with the operator TrainfOcrClassBox.
Hereby regions, representing characters, including their gray values (region and pixel) and the corresponding class
name will be written into a file. An arbitrary number of regions within one image is supported. For each character
(region) in Character the corresponding class name must be specified in Class. The gray values are passed
via the parameter Image. If no file extension is specified in FileName the extension ’.trf’ is appended to the file
name. The version of the file format used for writing data can be defined by the parameter ’ocr_trainf_version’ of
the operator SetSystem.
Attention

Parameter
. Character (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Characters to be trained.
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, uint2 )
Gray values of the characters.
. Class (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Class (name) of the characters.
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.write ; String / VARIANT
Name of the training file.
Default Value : ’train_ocr’
Example

Result
If the parameters are correct, the operator WriteOcrTrainf returns the value TRUE. Otherwise an exception
will be raised.
Parallelization Information
WriteOcrTrainf is reentrant and processed without parallelization.
Possible Predecessors
Threshold, Connection, CreateOcrClassBox, ReadOcr
Possible Successors
TrainfOcrClassBox, InfoOcrClassBox, WriteOcr, DoOcrMulti, DoOcrSingle
Module
OCR/OCV

void HImageX.WriteOcrTrainfImage ([in] VARIANT Class,


[in] String FileName )
void HOperatorSetX.WriteOcrTrainfImage ([in] IHObjectX Character,
[in] VARIANT Class, [in] VARIANT FileName )

Write characters into a training file.

HALCON/COM Reference Manual, 2008-5-13


10.6. TRAINING-FILES 801

The operator WriteOcrTrainfImage is used to prepare the training with the operator
TrainfOcrClassBox. Hereby regions, representing characters, including their gray values (region and
pixel) and the corresponding class name will be written into a file. An arbitrary number of regions within one
image is supported. For each character (region) in Character the corresponding class name must be specified
in Class. If no file extension is specified in FileName the extension ’.trf’ is appended to the file name. In
contrast to WriteOcrTrainf one image per character is passed. The domain of this image defines the pixels
which belong to the character. The file format can be defined by the parameter ’ocr_trainf_version’ of the operator
SetSystem.
Parameter

. Character (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte, uint2 )


Characters to be trained.
. Class (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Class (name) of the characters.
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.write ; String / VARIANT
Name of the training file.
Default Value : ’train_ocr’
Result
If the parameters are correct, the operator WriteOcrTrainfImage returns the value TRUE. Otherwise an
exception will be raised.
Parallelization Information
WriteOcrTrainfImage is reentrant and processed without parallelization.
Possible Predecessors
Threshold, Connection, CreateOcrClassBox, ReadOcr
Possible Successors
TrainfOcrClassBox, InfoOcrClassBox, WriteOcr, DoOcrMulti, DoOcrSingle
Alternatives
WriteOcrTrainf, AppendOcrTrainf
Module
OCR/OCV

HALCON 8.0.2
802 CHAPTER 10. OCR

HALCON/COM Reference Manual, 2008-5-13


Chapter 11

Object

11.1 Information
[out] long Number HObjectX.CountObj ( )
void HOperatorSetX.CountObj ([in] IHObjectX Objects,
[out] VARIANT Number )

Number of objects in a tuple.


The operator CountObj determines for the object parameter Objects the number of objects it contains. In
this connection it should be noted that object is not the same as connection component (see Connection). For
example, the number of objects of a region not consisting of three connected parts is 1.
Attention
In Prolog and Lisp the length of the list is not necessarily identical with the number of objects. This is the case
when object keys are contained which were created in the compact mode (keys from compact and normal mode
can be used as a mixture). See in this connection SetSystem(::’compactObject’,<true/false>:).
Parameter
. Objects (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . object ; IHObjectX
Objects to be examined.
. Number (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of objects in the tuple Objects.
Complexity
Runtime complexity: O(|Objects|).
Result
If the surrogates are correct, i.e. all objects are present in the HALCON operator data base, the operator
CountObj returns the value TRUE. The behavior in case of empty input (no input objects available) is set via the
operator SetSystem(::’noObjectResult’,<Result>:).
Parallelization Information
CountObj is reentrant and processed without parallelization.
See also
CopyObj, ObjToInteger, Connection, SetSystem
Module
Foundation

[out] VARIANT Information HObjectX.GetChannelInfo ([in] String Request,


[in] VARIANT Channel )
void HOperatorSetX.GetChannelInfo ([in] IHObjectX Object,
[in] VARIANT Request, [in] VARIANT Channel, [out] VARIANT Information )

Informations about the components of an image object.

803
804 CHAPTER 11. OBJECT

The operator GetChannelInfo gives information about the components of an image object. The following
requests (Request) are currently possible:

’creator’ Output of the names of the procedures which initially created the image components (not the object).
’type’ Output of the type of image component (’byte’, ’int1’, ’int2’, ’uint2’ ’int4’, ’real’, ’direction’, ’cyclic’,
’complex’, ’vector_field’). The component 0 is of type ’region’ or ’xld’.

In the tuple Channel the numbers of the components about which information is required are stated. After
carrying out GetChannelInfo, Information contains a tuple of strings (one string per entry in Channel)
with the required information.
Parameter

. Object (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . object ; IHObjectX


Image object to be examined.
. Request (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Required information about object components.
Default Value : ’creator’
List of values : Request ∈ {’creator’, ’type’}
. Channel (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . channel(-array) ; VARIANT ( integer )
Components to be examined (0 for region/XLD).
Default Value : 0
Suggested values : Channel ∈ {0, 1, 2, 3, 4, 5, 6, 7, 8}
. Information (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Requested information.
Result
If the parameters are correct the operator GetChannelInfo returns the value TRUE. Otherwise an exception is
raised.
Parallelization Information
GetChannelInfo is reentrant and processed without parallelization.
Possible Predecessors
ReadImage
See also
CountRelation
Module
Foundation

HObjectX.GetObjClass ( )
[out] VARIANT Class
void HOperatorSetX.GetObjClass ([in] IHObjectX Object,
[out] VARIANT Class )

Name of the class of an image object.


GetObjClass returns the name of the corresponding class to each object. The following classes are possible:

’image’ Object with region (definition domain) and at least one channel.
’region’ Object with a region without gray values.
’xld_cont’ XLD object as contour
’xld_poly’ XLD object as polygon
’xld_parallel’ XLD object with parallel polygons

HALCON/COM Reference Manual, 2008-5-13


11.1. INFORMATION 805

Parameter
. Object (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . object(-array) ; IHObjectX
Image objects to be examined.
. Class (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Name of class.
Result
If the parameter values are correct the operator GetObjClass returns the value TRUE. Otherwise an exception
is raised.
Parallelization Information
GetObjClass is reentrant and automatically parallelized (on tuple level).
Possible Successors
DispImage, DispRegion, DispXld
See also
GetChannelInfo, CountRelation
Module
Foundation

[out] long IsEqual HObjectX.TestEqualObj ([in] IHObjectX Objects2 )


void HOperatorSetX.TestEqualObj ([in] IHObjectX Objects1,
[in] IHObjectX Objects2, [out] VARIANT IsEqual )

Compare image objects regarding equality.


The operator TestEqualObj compares the regions and gray value components of all objects of the two input
parameters. The n-th object in Objects1 is compared to the n-th object in Objects2 (for all n). If all corre-
sponding regions are equal and the number of regions is also identical the parameter IsEqual is set to TRUE,
otherwise FALSE.
Attention
Image matrices and XLDs are not compared regarding their contents. Thus, two images or XLDs, respectively,
are “equal” if they are at the same place in the storage. If the input parameters are empty and the behavior was set
via the operator SetSystem(::’noObjectResult’,’true’:), the parameter IsEqual is set to TRUE,
since all input (= empty set) is equal.
Parameter
. Objects1 (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . object ; IHObjectX
Test objects.
. Objects2 (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . object ; IHObjectX
Comparative objects.
. IsEqual (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
boolean result value.
Complexity √ √
If F is the area of a region the runtime complexity is O(1) or O( F ) if the result is TRUE and O( F ) if the
result is FALSE.
Result
The operator TestEqualObj returns the value TRUE if the parameters are correct. The behav-
ior in case of empty input (no input objects available) is set via the operator SetSystem(::
’noObjectResult’,<Result>:). If the number of objects differs an exception is raised. Else
TestEqualObj returns TRUE
Parallelization Information
TestEqualObj is reentrant and processed without parallelization.
See also
TestEqualRegion
Module
Foundation

HALCON 8.0.2
806 CHAPTER 11. OBJECT

HObjectX.TestObjDef ( )
[out] long IsDefined
void HOperatorSetX.TestObjDef ([in] IHObjectX Object,
[out] VARIANT IsDefined )

Test whether an object is already deleted.


The operator TestObjDef checks whether the object still exists in the HALCON operator data base (i.e. whether
the surrogate is still valid). Is that the case IsDefined is set to TRUE, else FALSE. This check especially makes
sense before deleting an object if it is not sure that the object has already been deleted by a prior deleting operator
( ClearObj).
Attention
The parameter IsDefined can be TRUE even if the object was already deleted because the surrogates of deleted
objects are re-used for new objects. In this context see the example.
Parameter

. Object (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . object ; IHObjectX


Object to be checked.
. IsDefined (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
boolean result value.
Complexity
The runtime complexity is O(1).
Result
The operator TestObjDef returns the value TRUE if the parameters are correct. The behavior in case of empty
input (no input objects available) is set via the operator SetSystem(::’noObjectResult’,<Result>:
).
Parallelization Information
TestObjDef is reentrant and processed without parallelization.
Possible Predecessors
ClearObj, GenCircle, GenRectangle1
See also
SetCheck, ClearObj, ResetObjDb
Module
Foundation

11.2 Manipulation

void HOperatorSetX.ClearObj ([in] IHObjectX Objects )

Delete an iconic object from the HALCON database.


ClearObj deletes iconic objects, which are no longer needed, from the HALCON database. It should be noted
that ClearObj is the only way to delete objects from the database, and hence to reclaim their memory, in
HALCON/C. In all other HALCON language interfaces, ClearObj must not be used because objects are
destroyed automatically through appropriate destructors.
Images and regions are normally used by several iconic objects at the same time (uses less memory!). This has the
consequence that a region or an image is only deleted if all objects using it have been deleted.
The operator ResetObjDb can be used to reset the system and clear all remaining iconic objects.
Attention
Regarding the use of local variables: Because only local variables are deleted on exit of a subroutine, while the
HALCON database is not updated, it is necessary to clear local objects before exiting the subroutine.

HALCON/COM Reference Manual, 2008-5-13


11.2. MANIPULATION 807

Parameter
. Objects (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . object(-array) ; IHObjectX
Objects to be deleted.
Result
ClearObj returns TRUE if all objects are contained in the HALCON database. If not all objects are valid
(e.g., already cleared), an exception is raised, which also clears all valid objects. The operator SetCheck(::
’˜clear’:) can be used to suppress the raising of this exception. If the input is empty the behavior can be set
via SetSystem(::’noObjectResult’,<Result>:). If necessary, an exception is raised.
Parallelization Information
ClearObj is reentrant and processed without parallelization.
Possible Predecessors
TestObjDef
See also
TestObjDef, SetCheck
Alternatives
ResetObjDb
Module
Foundation

[out] HObjectX ObjectsConcat HObjectX.ConcatObj


([in] IHObjectX Objects2 )
void HOperatorSetX.ConcatObj ([in] IHObjectX Objects1,
[in] IHObjectX Objects2, [out] HUntypedObjectX ObjectsConcat )

Concatenate two iconic object tuples.


ConcatObj concatenates the two tuples of iconic objects Objects1 and Objects2 into a new object tuple
ObjectsConcat. Hence, this tuple contains all the objects of the two input tuples:
ObjectsConcat = [Objects1,Objects2]
In ObjectsConcat the objects of Objects1 are stored first, followed by the objects of Objects2. The order
of the objects is preserved. As usual, only the objects are copied, and not the corresponding images and regions,
i.e., no new memory is allocated. ConcatObj is designed especially for HALCON/C. In languages like C++ it
is not needed.
ConcatObj should not be confused with Union1 or Union2, in which regions are merged, i.e., in which the
number of objects is modified.
ConcatObj can be used to concatenate objects of different image object types (e.g., images and XLD contours)
into a single object. This is only recommended if it is necessary to accumulate in a single object variable, for
example, the results of an image processing sequence. It should be noted that the only operators that can handle
such object tuples of mixed type are ConcatObj, CopyObj, SelectObj, and DispObj. For technical
reasons, object tuples of mixed type must not be created in HDevelop.
Parameter
. Objects1 (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . object(-array) ; IHObjectX
Object tuple 1.
. Objects2 (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . object(-array) ; IHObjectX
Object tuple 2.
. ObjectsConcat (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . object ; HObjectX / HUntypedObjectX
Concatenated objects.
Complexity
Runtime complexity: O(|Objects1| + |Objects2|);
Memory complexity of the result objects: O(|Objects1| + |Objects2|)
Result
ConcatObj returns TRUE if all objects are contained in the HALCON database. If the input is empty the

HALCON 8.0.2
808 CHAPTER 11. OBJECT

behavior can be set via SetSystem(::’noObjectResult’,<Result>:). If necessary, an exception is


raised.
Parallelization Information
ConcatObj is reentrant and processed without parallelization.
See also
CountObj, CopyObj, SelectObj, DispObj
Module
Foundation

[out] HObjectX ObjectsSelected HObjectX.CopyObj ([in] long Index,


[in] long NumObj )
void HOperatorSetX.CopyObj ([in] IHObjectX Objects,
[out] HUntypedObjectX ObjectsSelected, [in] VARIANT Index,
[in] VARIANT NumObj )

Copy an iconic object in the HALCON database.


CopyObj copies NumObj iconic objects beginning with index Index (starting with 1) from the iconic input
object tuple Objects to the output object ObjectsSelected. If -1 is passed for NumObj all objects beginning
with Index are copied. No new storage is allocated for the regions and images. Instead, new objects containing
references to the existing objects are created. The number of objects in an object tuple can be queried with the
operator CountObj.
Parameter
. Objects (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . object(-array) ; IHObjectX
Objects to be copied.
. ObjectsSelected (output iconic) . . . . . . . . . . . . . . . . . . . . object(-array) ; HObjectX / HUntypedObjectX
Copied objects.
. Index (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Starting index of the objects to be copied.
Default Value : 1
Suggested values : Index ∈ {1, 2, 3, 4, 5, 10, 20, 50, 100, 200, 500, 1000, 2000, 5000}
Restriction : (Objects ≤ number)
. NumObj (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of objects to be copied or -1.
Default Value : 1
Suggested values : NumObj ∈ {-1, 1, 2, 3, 4, 5, 10, 20, 50, 100, 200, 500, 1000, 2000, 5000}
Restriction : ((Objects ≤ number) ∧ (N umObj 6= 0))
Example

/* Access all regions */

count_obj(Regions,Num)
for(1,Num,i)
copy_obj(Regions,Single,i,1)
get_region_polygon(Single,5.0,Line,Column)
disp_polygon(WindowHandle,Line,Column)
clear_obj(Single)
loop().

Complexity
Runtime complexity: O(|Objects| + NumObj);
Memory complexity of the result object: O(NumObj)
Result
CopyObj returns TRUE if all objects are contained in the HALCON database and all parameters are correct.

HALCON/COM Reference Manual, 2008-5-13


11.2. MANIPULATION 809

If the input is empty the behavior can be set via SetSystem(::’noObjectResult’,<Result>:). If


necessary, an exception is raised.
Parallelization Information
CopyObj is reentrant and processed without parallelization.
Possible Predecessors
CountObj
See also
CountObj, ConcatObj, ObjToInteger, CopyImage
Alternatives
SelectObj
Module
Foundation

void HObjectX.GenEmptyObj ( )
void HOperatorSetX.GenEmptyObj ([out] HUntypedObjectX EmptyObject )

Create an empty object tuple.


The operator GenEmptyObj creates an empty tuple. This means that the output parameter does not contain any
objects. Thus, the operator CountObj returns 0. However, ClearObj can be called for the output. It should
be noted that no objects must not be confused with an empty region. In case of an empty region, i.e. a region with
0 pixels CountObj returns the value 1.
Parameter

. EmptyObject (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . object ; HObjectX / HUntypedObjectX


No objects.
Parallelization Information
GenEmptyObj is reentrant and processed without parallelization.
Module
Foundation

void HObjectX.IntegerToObj ([in] VARIANT SurrogateTuple )


void HOperatorSetX.IntegerToObj ([out] HUntypedObjectX Objects,
[in] VARIANT SurrogateTuple )

Convert an “integer number” into an iconic object.


IntegerToObj is the inverse operator to ObjToInteger. All surrogates of objects passed in
SurrogateTuple are stored as objects. In contrast to ObjToInteger, the objects are duplicated.
IntegerToObj is intended especially for use in HALCON/C, because iconic objects and control parameters
are treated differently in C.
Attention
The objects are duplicated in the database.
Parameter

. Objects (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . object(-array) ; HObjectX / HUntypedObjectX


Created objects.
. SurrogateTuple (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pointer(-array) ; VARIANT ( integer )
Tuple of object surrogates.
Result
IntegerToObj returns TRUE if all parameters are correct, i.e., if they are valid object keys. If the input is empty
the behavior can be set via SetSystem(::’noObjectResult’,<Result>:). If necessary, an exception
is raised.

HALCON 8.0.2
810 CHAPTER 11. OBJECT

Parallelization Information
IntegerToObj is reentrant and processed without parallelization.
See also
ObjToInteger
Module
Foundation

[out] VARIANT SurrogateTuple HObjectX.ObjToInteger ([in] long Index,


[in] long Number )
void HOperatorSetX.ObjToInteger ([in] IHObjectX Objects,
[in] VARIANT Index, [in] VARIANT Number, [out] VARIANT SurrogateTuple )

Convert an iconic object into an “integer number.”


ObjToInteger stores Number, starting at index Index, of the database keys of the input object Objects as
integer numbers in the output parameter SurrogateTuple. If -1 is passed for Number all objects beginning
with Index are copied. This facilitates a direct access to an arbitrary element of Objects. In conjunction with
CountObj (returns the number of objects in Objects) the elements of Objects can be processed successively.
The objects are not duplicated by ObjToInteger and thus must not be cleared by ClearObj.
Attention
The objects’ data is not duplicated.
Parameter
. Objects (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . object(-array) ; IHObjectX
Objects for which the surrogates are to be returned.
. Index (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Starting index of the surrogates to be returned.
Default Value : 1
. Number (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of surrogates to be returned.
Default Value : -1
Restriction : ((N umber + Index) ∨ (Objects ≤ number))
. SurrogateTuple (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pointer(-array) ; VARIANT ( integer )
Tuple containing the surrogates.
Example

/* Access the i-th element: */


obj_to_integer(Objects,i,1,Surrogat).

Complexity
Runtime complexity: O(|Objects| + Number)
Result
ObjToInteger returns TRUE if all parameters are correct. If the input is empty the behavior can be set via
SetSystem(::’noObjectResult’,<Result>:). If necessary, an exception is raised.
Parallelization Information
ObjToInteger is reentrant and processed without parallelization.
Possible Predecessors
TestObjDef
See also
IntegerToObj, CountObj
Alternatives
CopyObj, SelectObj, CopyImage, GenImageProto
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


11.2. MANIPULATION 811

HObjectX.SelectObj ([in] VARIANT Index )


[out] HObjectX ObjectSelected
void HOperatorSetX.SelectObj ([in] IHObjectX Objects,
[out] HUntypedObjectX ObjectSelected, [in] VARIANT Index )

Select objects from an object tuple.


SelectObj copies the iconic objects with the indices given by Index (starting with 1) from the iconic input
object tuple Objects to the output object ObjectSelected. No new storage is allocated for the regions and
images. Instead, new objects containing references to the existing objects are created. The number of objects in an
object tuple can be queried with the operator CountObj.
Parameter

. Objects (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . object(-array) ; IHObjectX


Input objects.
. ObjectSelected (output iconic) . . . . . . . . . . . . . . . . . . . . . object(-array) ; HObjectX / HUntypedObjectX
Selected objects.
. Index (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Indices of the objects to be selected.
Default Value : 1
Suggested values : Index ∈ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 50, 100, 200, 500, 1000, 2000, 5000}
Restriction : (Index ≥ 1)
Complexity
Runtime complexity: O(|Objects|)
Result
SelectObj returns TRUE if all objects are contained in the HALCON database and all parameters are correct.
If the input is empty the behavior can be set via SetSystem(::’noObjectResult’,<Result>:). If
necessary, an exception is raised.
Parallelization Information
SelectObj is reentrant and processed without parallelization.
Possible Predecessors
CountObj
See also
CountObj, ConcatObj, ObjToInteger
Alternatives
CopyObj
Module
Foundation

HALCON 8.0.2
812 CHAPTER 11. OBJECT

HALCON/COM Reference Manual, 2008-5-13


Chapter 12

Regions

12.1 Access
[out] long Row HRegionX.GetRegionChain ([out] long Column,
[out] VARIANT Chain )
void HOperatorSetX.GetRegionChain ([in] IHObjectX Region,
[out] VARIANT Row, [out] VARIANT Column, [out] VARIANT Chain )

Contour of an object as chain code.


The operator GetRegionChain returns the contour of a region. A contour is a series of pixels describing the
outline of the region. The contour “lies on” the region. It starts at the smallest line number; in that line at the pixel
with the largest column index. The rotation occurs clockwise. Holes of the region are ignored. The direction code
(chain code) is defined as follows:

3 2 1
4 ∗ 0
5 6 7

The operator GetRegionChain returns the code in the form of a tuple. In case of an empty region the parame-
ters Row and Column are zero and Chain is the empty tuple.
Attention
Holes of the region are ignored. Only one region may be passed, and it must have exactly one connection compo-
nent.
Parameter

. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX


Region to be transformed.
. Row (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . chain.begin.y ; long / VARIANT
Line of starting point.
. Column (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . chain.begin.x ; long / VARIANT
Column of starting point.
. Chain (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . chain.code ; VARIANT ( integer )
Direction code of the contour (from starting point).
Typical range of values : 0 ≤ Chain ≤ 0
Result
The operator GetRegionChain normally returns the value TRUE. If more than one connection component
is passed an exception handling is caused. The behavior in case of empty input (no input regions available) is
set via the operator SetSystem(’noObjectResult’,<Result>). The behavior in case of empty region
(the region is the empty set) is set via the operator SetSystem(’emptyRegionResult’,<Result>). If
necessary an exception handling is raised.

813
814 CHAPTER 12. REGIONS

Parallelization Information
GetRegionChain is reentrant and processed without parallelization.
Possible Predecessors
SobelAmp, Threshold, Skeleton, EdgesImage, GenRectangle1, GenCircle
Possible Successors
ApproxChain, ApproxChainSimple
See also
CopyObj, GetRegionContour, GetRegionPolygon
Module
Foundation

HRegionX.GetRegionContour ([out] VARIANT Columns )


[out] VARIANT Rows
void HOperatorSetX.GetRegionContour ([in] IHObjectX Region,
[out] VARIANT Rows, [out] VARIANT Columns )

Access the contour of an object.


The operator GetRegionContour returns the contour of a region. A contour is a result of line (Rows) and
column coordinates (Columns), describing the boundary of the region. The contour lies on the region. It starts
at the smallest line number. In that line at the pixel with the largest column index. The rotation direction is
clockwise. The first pixel of the contour is identical with the last. Holes of the region are ignored. The operator
GetRegionContour returns the coordinates in the form of tuples. An empty region is passed as empty tuple.
Attention
Holes of the region are ignored. Only one region may be passed, and this region must have exactly one connection
component.
Parameter

. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX


Output region.
. Rows (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . contour.y ; VARIANT ( integer )
Line numbers of the contour pixels.
. Columns (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . contour.x ; VARIANT ( integer )
Column numbers of the contour pixels.
Number of elements : (Columns = Rows)
Result
The operator GetRegionContour normally returns the value TRUE. If more than one connection component
is passed an exception handling is caused. The behavior in case of empty input (no input regions available) is set
via the operator SetSystem(’noObjectResult’,<Result>).
Parallelization Information
GetRegionContour is reentrant and processed without parallelization.
Possible Predecessors
SobelAmp, Threshold, Skeleton, EdgesImage, GenRectangle1, GenCircle
See also
CopyObj, GetRegionChain, GetRegionPolygon
Module
Foundation

HRegionX.GetRegionConvex ([out] VARIANT Columns )


[out] VARIANT Rows
void HOperatorSetX.GetRegionConvex ([in] IHObjectX Region,
[out] VARIANT Rows, [out] VARIANT Columns )

Access convex hull as contour.

HALCON/COM Reference Manual, 2008-5-13


12.1. ACCESS 815

The operator GetRegionConvex returns the convex hull of a region as polygon. The polygon is the minimum
result of line (Rows) and column coordinates (Columns) describing the hull of the region. The polygon pixels
lie on the region. The polygon starts at the smallest line number; in this line at the pixel with the largest column
index. The rotation direction is clockwise. The first pixel of the polygon is identical with the last. The operator
GetRegionConvex returns the coordinates in the form of tuples. An empty region is passed as empty tuple.
Parameter

. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX


Output region.
. Rows (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . contour.y ; VARIANT ( integer )
Line numbers of contour pixels.
. Columns (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . contour.x ; VARIANT ( integer )
Column numbers of the contour pixels.
Number of elements : (Columns = Rows)
Result
The operator GetRegionConvex returns the value TRUE.
Parallelization Information
GetRegionConvex is reentrant and processed without parallelization.
Possible Predecessors
Threshold, Skeleton, DynThreshold
Possible Successors
DispPolygon
See also
SelectObj, GetRegionContour
Alternatives
ShapeTrans
Module
Foundation

HRegionX.GetRegionPoints ([out] VARIANT Columns )


[out] VARIANT Rows
void HOperatorSetX.GetRegionPoints ([in] IHObjectX Region,
[out] VARIANT Rows, [out] VARIANT Columns )

Access the pixels of a region.


The operator GetRegionPoints returns the region data in the form of coordinate lists. The coordinates are
sorted in the following order:

(r1 , c1 ) ≤ (r2 , c2 ) := (r1 < r2 ) ∨ (r1 = r2 ) ∧ (c1 ≤ c2)

GetRegionPoints returns the coordinates in the form of tuples. An empty region is passed as empty tuple.
Attention
Only one region may be passed.
Parameter

. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX


This region is accessed.
. Rows (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . coordinates.y ; VARIANT ( integer )
Line numbers of the pixels in the region
. Columns (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . coordinates.x ; VARIANT ( integer )
Column numbers of the pixels in the region.
Number of elements : (Columns = Rows)

HALCON 8.0.2
816 CHAPTER 12. REGIONS

Result
The operator GetRegionPoints normally returns the value TRUE. If more than one connection component is
passed an exception handling is caused. The behavior in case of empty input (no input regions available) is set via
the operator SetSystem(’noObjectResult’,<Result>).
Parallelization Information
GetRegionPoints is reentrant and processed without parallelization.
Possible Predecessors
SobelAmp, Threshold, Connection
See also
CopyObj, GenRegionPoints
Alternatives
GetRegionRuns
Module
Foundation

[out] VARIANT Rows HRegionX.GetRegionPolygon ([in] VARIANT Tolerance,


[out] VARIANT Columns )
void HOperatorSetX.GetRegionPolygon ([in] IHObjectX Region,
[in] VARIANT Tolerance, [out] VARIANT Rows, [out] VARIANT Columns )

Polygon approximation of a region.


The operator GetRegionPolygon calculates a polygon to approximate the edge of a region. A polygon is
a sequence of line (Rows) and column coordinates (Columns). It describes the contour of the region. Only
the base points of the polygon are returned. The parameter Tolerance indicates how large the maximum dis-
tance between the polygon and the edge of the region may be. Holes of the region are ignored. The operator
GetRegionPolygon returns the coordinates in the form of tuples.
Attention
Holes of the region are ignored. Only one region may be passed, and this region must have exactly one connection
component.
Parameter

. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX


Region to be approximated.
. Tolerance (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Maximum distance between the polygon and the edge of the region.
Default Value : 5.0
Suggested values : Tolerance ∈ {0.0, 2.0, 5.0, 10.0}
(lin)Minimum Increment : 0.01
Recommended Increment : 1.0
. Rows (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . polygon.y ; VARIANT ( integer )
Line numbers of the base points of the contour.
. Columns (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . polygon.x ; VARIANT ( integer )
Column numbers of the base points of the contour.
Number of elements : (Columns = Rows)
Result
The operator GetRegionPolygon normally returns the value TRUE. If more than one connection component
is passed an exception handling is caused. The behavior in case of empty input (no input regions available) is set
via the operator SetSystem(’noObjectResult’,<Result>).
Parallelization Information
GetRegionPolygon is reentrant and processed without parallelization.
Possible Predecessors
SobelAmp, Threshold, Skeleton, EdgesImage

HALCON/COM Reference Manual, 2008-5-13


12.1. ACCESS 817

See also
CopyObj, GenRegionPolygon, DispPolygon, GetRegionChain, GetRegionContour,
SetLineApprox
Module
Foundation

[out] VARIANT Row HRegionX.GetRegionRuns ([out] VARIANT ColumnBegin,


[out] VARIANT ColumnEnd )
void HOperatorSetX.GetRegionRuns ([in] IHObjectX Region,
[out] VARIANT Row, [out] VARIANT ColumnBegin, [out] VARIANT ColumnEnd )

Access the runlength coding of a region.


The operator GetRegionRuns returns the region data in the form of chord tuples. The chord representation is
caused by examining a region line by line with ascending line number (= from “top” to “bottom”). Every line is
passed from left to right (ascending column number); storing all starting and ending points of region segments (=
chords). Thus a region can be described by a sequence of chords, a chord being defined by line number, starting
and ending points (column number). The operator GetRegionRuns returns the three components of the chords
in the form of tuples. In case of an empty region three empty tuples are returned.
Attention
Only one region may be passed.
Parameter

. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX


Output region.
. Row (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . chord.y ; VARIANT ( integer )
Line numbers of the chords.
. ColumnBegin (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . chord.x1 ; VARIANT ( integer )
Column numbers of the starting points of the chords.
Number of elements : (ColumnBegin = Row)
. ColumnEnd (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . chord.x2 ; VARIANT ( integer )
Column numbers of the ending points of the chords.
Number of elements : (ColumnEnd = Row)
Result
The operator GetRegionRuns normally returns the value TRUE. If more than one region is passed an excep-
tion handling is caused. The behavior in case of empty input (no input regions available) is set via the operator
SetSystem(’noObjectResult’,<Result>).
Parallelization Information
GetRegionRuns is reentrant and processed without parallelization.
Possible Predecessors
Threshold, Connection
See also
CopyObj, GenRegionRuns
Alternatives
GetRegionPoints
Module
Foundation

HALCON 8.0.2
818 CHAPTER 12. REGIONS

12.2 Creation
void HRegionX.GenCheckerRegion ([in] long WidthRegion,
[in] long HeightRegion, [in] long WidthPattern, [in] long HeightPattern )
void HOperatorSetX.GenCheckerRegion
([out] HUntypedObjectX RegionChecker, [in] VARIANT WidthRegion,
[in] VARIANT HeightRegion, [in] VARIANT WidthPattern,
[in] VARIANT HeightPattern )

Create a checkered region.


The operator GenCheckerRegion returns a checkered region. Every black field of the checkerboard belongs
to the region. The horizontal and vertical expansion of the region is limited by WidthRegion, HeightRegion
respectively, the size of the fields of the checkerboard by WidthPattern × HeightPattern.
Attention
If a very small pattern is chosen (WidthPattern < 4) the created region requires much storage.
Parameter
. RegionChecker (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX
Created checkerboard region.
. WidthRegion (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; long / VARIANT
Largest occurring x value of the region.
Default Value : 511
Suggested values : WidthRegion ∈ {10, 20, 31, 63, 127, 255, 300, 400, 511}
Typical range of values : 1 ≤ WidthRegion ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 10
Restriction : (W idthRegion ≥ 1)
. HeightRegion (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; long / VARIANT
Largest occurring y value of the region.
Default Value : 511
Suggested values : HeightRegion ∈ {10, 20, 31, 63, 127, 255, 300, 400, 511}
Typical range of values : 1 ≤ HeightRegion ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 10
Restriction : (HeightRegion ≥ 1)
. WidthPattern (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; long / VARIANT
Width of a field of the checkerboard.
Default Value : 64
Suggested values : WidthPattern ∈ {1, 2, 4, 8, 16, 20, 32, 64, 100, 128, 200, 300, 500}
Typical range of values : 1 ≤ WidthPattern ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 10
Restriction : ((W idthP attern > 0) ∧ (W idthP attern < W idthRegion))
. HeightPattern (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; long / VARIANT
Height of a field of the checkerboard.
Default Value : 64
Suggested values : HeightPattern ∈ {1, 2, 4, 8, 16, 20, 32, 64, 100, 128, 200, 300, 500}
Typical range of values : 1 ≤ HeightPattern ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 10
Restriction : ((HeightP attern > 0) ∧ (HeightP attern < HeightRegion))
Example

gen_checker_region(Checker,512,512,32,64:)
set_draw(WindowHandle,’fill’)
set_part(WindowHandle,0,0,511,511)
disp_region(Checker,WindowHandle)

HALCON/COM Reference Manual, 2008-5-13


12.2. CREATION 819

Complexity
The required storage (in bytes) for the region is:
O((WidthRegion ∗ HeightRegion)/WidthPattern)
Result
The operator GenCheckerRegion returns the value TRUE if the parameter values are correct. Otherwise an ex-
ception handling is raised. The clipping according to the current image format is set via the operator SetSystem
(’clipRegion’,<’true’/’false’>).
Parallelization Information
GenCheckerRegion is reentrant and processed without parallelization.
Possible Successors
PaintRegion
See also
HammingChangeRegion, ReduceDomain
Alternatives
GenGridRegion, GenRegionPolygonFilled, GenRegionPoints, GenRegionRuns,
GenRectangle1, ConcatObj, GenRandomRegion, GenRandomRegions
Module
Foundation

void HRegionX.GenCircle ([in] VARIANT Row, [in] VARIANT Column,


[in] VARIANT Radius )
void HOperatorSetX.GenCircle ([out] HUntypedObjectX Circle,
[in] VARIANT Row, [in] VARIANT Column, [in] VARIANT Radius )

Create a circle.
The operator GenCircle generates one or more circles described by the center and Radius. If several circles
shall be generated the coordinates must be passed in the form of tuples.
GenCircle only creates symmetric circles. To achieve this, the radius is rounded internally to a multiple of 0.5.
If an integer number is specified for the radius (i.e., 1, 2, 3, ...) an even diameter is obtained, and hence the circle
can only be symmetric with respect to a center with coordinates that have a fractional part of 0.5. Consequently,
internally the coordinates of the center are adapted to the closest coordinates that have a fractional part of 0.5. Here,
integer coordinates are rounded down to the next smaller values with a fractional part of 0.5. For odd diameters
(i.e., radius = 1.5, 2.5, 3.5, ...), the circle can only be symmetric with respect to a center with integer coordinates.
Hence, internally the coordinates of the center are rounded to the nearest integer coordinates. It should be noted
that the above algorithm may lead to the fact that circles with an even diameter are not contained in circles with
the next larger odd diameter, even if the coordinates specified in Row and Column are identical.
If the circle extends beyond the image edge it is clipped to the current image format if the value of the system flag
’clip_region’ is set to ’true’ ( SetSystem).
Parameter

. Circle (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX


Generated circle.
. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . circle.center.y(-array) ; VARIANT ( integer, real )
Line index of center.
Default Value : 200.0
Suggested values : Row ∈ {0.0, 10.0, 50.0, 100.0, 200.0, 300.0}
Typical range of values : 1.0 ≤ Row ≤ 1.0(lin)
Minimum Increment : 1.0
Recommended Increment : 10.0

HALCON 8.0.2
820 CHAPTER 12. REGIONS

. Column (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . circle.center.x(-array) ; VARIANT ( integer, real )


Column index of center.
Default Value : 200.0
Suggested values : Column ∈ {0.0, 10.0, 50.0, 100.0, 200.0, 300.0}
Typical range of values : 1.0 ≤ Column ≤ 1.0(lin)
Minimum Increment : 1.0
Recommended Increment : 10.0
. Radius (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . circle.radius(-array) ; VARIANT ( integer, real )
Radius of circle.
Default Value : 100.5
Suggested values : Radius ∈ {1.0, 1.5, 2.0, 2.5, 3, 3.5, 4, 4.5, 5.5, 6.5, 7.5, 9.5, 11.5, 15.5, 20.5, 25.5, 31.5,
50.5}
Typical range of values : 1.0 ≤ Radius ≤ 1.0(lin)
Minimum Increment : 1.0
Recommended Increment : 10.0
Restriction : (Radius > 0.0)
Example

open_window(0,0,-1,-1,’root’,’visible’,’’,WindowHandle)
read_image(Image,’meer’)
gen_circle(Circle,300.0,200.0,150.5)
reduce_domain(Image,Circle,Mask)
disp_color(Mask,WindowHandle).

Complexity
Runtime complexity: O(Radius ∗ 2)
Storage complexity (byte): O(Radius ∗ 8)
Result
If the parameter values are correct, the operator GenCircle returns the value TRUE. Otherwise an exception
handling is raised. The clipping according to the current image format is set via the operator SetSystem
(’clipRegion’,<’true’/’false’>). If an empty region is created by clipping (the circle is completely
outside of the image format) the operator SetSystem(’storeEmptyRegion’,<true/false>) deter-
mines whether the empty region is put out.
Parallelization Information
GenCircle is reentrant and processed without parallelization.
Possible Successors
PaintRegion, ReduceDomain
See also
DispCircle, SetShape, SmallestCircle, ReduceDomain
Alternatives
GenEllipse, GenRegionPolygonFilled, GenRegionPoints, GenRegionRuns, DrawCircle
Module
Foundation

void HRegionX.GenEllipse ([in] VARIANT Row, [in] VARIANT Column,


[in] VARIANT Phi, [in] VARIANT Radius1, [in] VARIANT Radius2 )
void HOperatorSetX.GenEllipse ([out] HUntypedObjectX Ellipse,
[in] VARIANT Row, [in] VARIANT Column, [in] VARIANT Phi, [in] VARIANT Radius1,
[in] VARIANT Radius2 )

Create an ellipse.
The operator GenEllipse generates one or more ellipses with the center (Row, Column), the orientation Phi
and the half-radii Radius1 and Radius2. The angle is indicated in arc measure according to the x axis in
mathematically positive direction. More than one region can be created by passing tuples of parameter values.

HALCON/COM Reference Manual, 2008-5-13


12.2. CREATION 821

The center must be located within the image coordinates. The coordinate system runs from (0,0) (upper left corner)
to (Width-1,Height-1). See GetSystem and ResetObjDb in this context. If the ellipse reaches beyond the
edge of the image it is clipped to the current image format according to the value of the system flag ’clip_region’ (
SetSystem).
Parameter
. Ellipse (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Created ellipse(s).
. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ellipse.center.y(-array) ; VARIANT ( integer, real )
Line index of center.
Default Value : 200.0
Suggested values : Row ∈ {0.0, 10.0, 20.0, 50.0, 100.0, 256.0, 300.0, 400.0}
Typical range of values : 1.0 ≤ Row ≤ 1.0(lin)
Minimum Increment : 1.0
Recommended Increment : 10.0
. Column (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ellipse.center.x(-array) ; VARIANT ( integer, real )
Column index of center.
Default Value : 200.0
Suggested values : Column ∈ {0.0, 10.0, 20.0, 50.0, 100.0, 256.0, 300.0, 400.0}
Typical range of values : 1.0 ≤ Column ≤ 1.0(lin)
Minimum Increment : 1.0
Recommended Increment : 10.0
. Phi (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ellipse.angle.rad(-array) ; VARIANT ( integer, real )
Orientation of the longer radius (Radius1).
Default Value : 0.0
Suggested values : Phi ∈ {-1.178097, -0.785398, -0.392699, 0.0, 0.392699, 0.785398, 1.178097}
Typical range of values : -1.178097 ≤ Phi ≤ -1.178097(lin)
Minimum Increment : 0.01
Recommended Increment : 0.1
. Radius1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . ellipse.radius1(-array) ; VARIANT ( integer, real )
Longer radius.
Default Value : 100.0
Suggested values : Radius1 ∈ {2.0, 5.0, 10.0, 20.0, 50.0, 100.0, 256.0, 300.0, 400.0}
Typical range of values : 1.0 ≤ Radius1 ≤ 1.0(lin)
Minimum Increment : 1.0
Recommended Increment : 10.0
Restriction : (Radius1 > 0)
. Radius2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . ellipse.radius2(-array) ; VARIANT ( integer, real )
Shorter radius.
Default Value : 60.0
Suggested values : Radius2 ∈ {1.0, 2.0, 4.0, 5.0, 10.0, 20.0, 50.0, 100.0, 256.0, 300.0, 400.0}
Typical range of values : 1.0 ≤ Radius2 ≤ 1.0(lin)
Minimum Increment : 1.0
Recommended Increment : 10.0
Restriction : ((Radius2 > 0) ∧ (Radius2 ≤ Radius1))
Example

open_window(0,0,-1,-1,’root’,’visible’,’’,WindowHandle)
set_insert(WindowHandle,’xor’)
repeat()
get_mbutton(WindowHandle,Row,Column,Button)
gen_ellipse(Ellipse,Row,Column,Column / 300.0,
(Row mod 100)+1,(Column mod 50) + 1)
disp_region(Ellipse,WindowHandle)
clear_obj(Ellipse)
until(Button = 1).

Complexity
Runtime complexity: O(Radius1 ∗ 2)

HALCON 8.0.2
822 CHAPTER 12. REGIONS

Storage complexity (byte): O(Radius1 ∗ 8)


Result
If the parameter values are correct, the operator GenEllipse returns the value TRUE. Otherwise an exception
handling is raised. The clipping according to the current image format is set via the operator SetSystem
(’clipRegion’,<’true’/’false’>).
Parallelization Information
GenEllipse is reentrant and processed without parallelization.
Possible Successors
PaintRegion, ReduceDomain
See also
DispEllipse, SetShape, SmallestCircle, ReduceDomain
Alternatives
GenCircle, GenRegionPolygonFilled, DrawEllipse
Module
Foundation

void HRegionX.GenEmptyRegion ( )
void HOperatorSetX.GenEmptyRegion
([out] HUntypedObjectX EmptyRegion )

Create an empty region.


The operator GenEmptyRegion creates an empty region. This means that the output parameter contains an
object. Thus, CountObj returns 1. The area of the region is 0. Most of the shape features are undefined (0). It
should be noted that an empty region must not be confused with the empty tuple.
Parameter
. EmptyRegion (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX
Empty region (no pixels).
Parallelization Information
GenEmptyRegion is reentrant and processed without parallelization.
Module
Foundation

void HRegionX.GenGridRegion ([in] VARIANT RowSteps,


[in] VARIANT ColumnSteps, [in] String Type, [in] long Width,
[in] long Height )
void HOperatorSetX.GenGridRegion ([out] HUntypedObjectX RegionGrid,
[in] VARIANT RowSteps, [in] VARIANT ColumnSteps, [in] VARIANT Type,
[in] VARIANT Width, [in] VARIANT Height )

Create a region from lines or pixels.


The operator GenGridRegion creates a grid constructed of lines (Type = ’lines’) or pixels (Type = ’points’).
In case of ’lines’ continuous lines are returned, in case of ’points’ only the intersections of the lines. Starting from
the pixel (0,0) to the pixel (Height-1,Width-1) the grid is built up at stepping width RowSteps in line direction
and ColumnSteps in column direction. In the ’lines’ mode RowSteps, ColumnSteps respectively, can be
set to zero. In this case only columns, lines respectively, are created.
Attention
If a very small pattern is chosen (RowSteps < 4 or ColumnSteps < 4) the created region requires much
storage.
In the ’points’ mode RowSteps and ColumnSteps must not be set to zero.

HALCON/COM Reference Manual, 2008-5-13


12.2. CREATION 823

Parameter

. RegionGrid (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX


Created lines/pixel region.
. RowSteps (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; VARIANT ( real, integer )
Step width in line direction or zero.
Default Value : 10
Suggested values : RowSteps ∈ {0, 2, 3, 4, 5, 7, 10, 15, 20, 30, 50, 100}
Typical range of values : 0 ≤ RowSteps ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 10
Restriction : ((RowSteps > 1) ∨ (RowSteps = 0))
. ColumnSteps (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; VARIANT ( real, integer )
Step width in column direction or zero.
Default Value : 10
Suggested values : ColumnSteps ∈ {0, 2, 3, 4, 5, 7, 10, 15, 20, 30, 50, 100}
Typical range of values : 0 ≤ ColumnSteps ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 10
Restriction : ((ColumnSteps > 1) ∨ (ColumnSteps = 0))
. Type (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Type of created pattern.
Default Value : ’lines’
List of values : Type ∈ {’lines’, ’points’}
. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; long / VARIANT
Maximum width of pattern.
Default Value : 512
Suggested values : Width ∈ {128, 256, 512, 1024}
Typical range of values : 1 ≤ Width ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 10
Restriction : (W idth ≥ 1)
. Height (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; long / VARIANT
Maximum height of pattern.
Default Value : 512
Suggested values : Height ∈ {128, 256, 512, 1024}
Typical range of values : 1 ≤ Height ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 10
Restriction : (Height ≥ 1)
Example

read_image(Image,’fabrik’)
gen_grid_region(Raster,10,10,’lines’,512,512)
reduce_domain(Image,Raster,Mask)
sobel_amp(Mask,GridSobel,’sum_abs’,3)
disp_image(GridSobel,WindowHandle).

Complexity
The necessary storage (in bytes) for the region is:
O((ImageW idth/ColumnSteps) ∗ (ImageHeight/RowSteps))
Result
If the parameter values are correct the operator GenGridRegion returns the value TRUE. Otherwise an excep-
tion handling is raised. The clipping according to the current image format is set via the operator SetSystem
(’clipRegion’,<’true’/’false’>).
Parallelization Information
GenGridRegion is reentrant and processed without parallelization.

HALCON 8.0.2
824 CHAPTER 12. REGIONS

Possible Successors
ReduceDomain, PaintRegion
See also
GenCheckerRegion, ReduceDomain
Alternatives
GenRegionLine, GenRegionPolygon, GenRegionPoints, GenRegionRuns
Module
Foundation

void HRegionX.GenRandomRegion ([in] long Width, [in] long Height )


void HOperatorSetX.GenRandomRegion
([out] HUntypedObjectX RegionRandom, [in] VARIANT Width,
[in] VARIANT Height )

Create a random region.


The operator GenRandomRegion returns a random region. During this process every pixel in the image area
[0 . . . Width − 1][0 . . . Height − 1] is adapted into the region with the probability 0.5. The created region can be
imagined as the threshold formation in an image with noise.
This procedure is particularly important for the creation of uncorrelated binary patterns. The random pattern is
created by the C function “nrand48()”.
Attention
If Width and Height are chosen large (> 100) the created region may require much storage space due to the
internally used runlength coding. The gray values of the output region are undefined.
Parameter

. RegionRandom (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX


Created random region with expansion Width x Height.
. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; long / VARIANT
Maximum horizontal expansion of random region.
Default Value : 128
Suggested values : Width ∈ {16, 32, 50, 64, 100, 128, 256, 300, 400, 512}
Typical range of values : 1 ≤ Width ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 10
Restriction : (W idth > 0)
. Height (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; long / VARIANT
Maximum vertical expansion of random region.
Default Value : 128
Suggested values : Height ∈ {16, 32, 50, 64, 100, 128, 256, 300, 400, 512}
Typical range of values : 1 ≤ Height ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 10
Restriction : (Height > 0)
Complexity
The worst case for the storage complexity for the created region (in byte) is: O(W idth ∗ Height ∗ 2).
Result
If the parameter values are correct, the operator GenRandomRegion returns the value TRUE. Otherwise an ex-
ception handling is raised. The clipping according to the current image format is set via the operator SetSystem
(’clipRegion’,<’true’/’false’>).
Parallelization Information
GenRandomRegion is reentrant and processed without parallelization.
Possible Successors
PaintRegion, ReduceDomain

HALCON/COM Reference Manual, 2008-5-13


12.2. CREATION 825

See also
GenCheckerRegion, HammingChangeRegion, AddNoiseDistribution, AddNoiseWhite,
ReduceDomain
Module
Foundation

void HRegionX.GenRandomRegions ([in] String Type,


[in] VARIANT WidthMin, [in] VARIANT WidthMax, [in] VARIANT HeightMin,
[in] VARIANT HeightMax, [in] VARIANT PhiMin, [in] VARIANT PhiMax,
[in] long NumRegions, [in] long Width, [in] long Height )
void HOperatorSetX.GenRandomRegions ([out] HUntypedObjectX Regions,
[in] VARIANT Type, [in] VARIANT WidthMin, [in] VARIANT WidthMax,
[in] VARIANT HeightMin, [in] VARIANT HeightMax, [in] VARIANT PhiMin,
[in] VARIANT PhiMax, [in] VARIANT NumRegions, [in] VARIANT Width,
[in] VARIANT Height )

Create random regions like circles, rectangles and ellipses.


The operator GenRandomRegion generates circles, rectangles and ellipses whose parameters are determined at
random. In each case only one lower, upper limit respectively, is given. The position is always random and cannot
be determined by parameters. The parameter NumRegions indicates how many regions shall be created.
Parameter

. Regions (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX


Created regions.
. Type (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Type of regions to be created.
Default Value : ’circle’
List of values : Type ∈ {’circle’, ’ring’, ’ellipse’, ’rectangle1’, ’rectangle2’}
. WidthMin (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Minimum width of the region.
Default Value : 10.0
Suggested values : WidthMin ∈ {1.0, 3.0, 5.0, 10.0, 20.0, 40.0, 80.0}
Typical range of values : 1.0 ≤ WidthMin ≤ 1.0(lin)
Minimum Increment : 1.0
Recommended Increment : 10.0
Restriction : (W idthM in > 0)
. WidthMax (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Maximum width of the region.
Default Value : 20.0
Suggested values : WidthMax ∈ {1.0, 3.0, 5.0, 10.0, 20.0, 40.0, 80.0}
Typical range of values : 1.0 ≤ WidthMax ≤ 1.0(lin)
Minimum Increment : 1.0
Recommended Increment : 10.0
Restriction : (W idthM ax > 0)
. HeightMin (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Minimum height of the region.
Default Value : 10.0
Suggested values : HeightMin ∈ {1.0, 3.0, 5.0, 10.0, 20.0, 40.0, 80.0}
Typical range of values : 1.0 ≤ HeightMin ≤ 1.0(lin)
Minimum Increment : 1.0
Recommended Increment : 10.0
Restriction : (HeightM in > 0)

HALCON 8.0.2
826 CHAPTER 12. REGIONS

. HeightMax (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )


Maximum height of the region.
Default Value : 30.0
Suggested values : HeightMax ∈ {1.0, 3.0, 5.0, 10.0, 20.0, 40.0, 80.0}
Typical range of values : 1.0 ≤ HeightMax ≤ 1.0(lin)
Minimum Increment : 1.0
Recommended Increment : 10.0
Restriction : (HeightM ax > 0)
. PhiMin (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Minimum rotation angle of the region.
Default Value : -0.7854
Suggested values : PhiMin ∈ {0.0, 0.1, 0.3, 0.6, 0.9, 1.2, 1.5}
Typical range of values : 0.0 ≤ PhiMin ≤ 0.0(lin)
Minimum Increment : 0.001
Recommended Increment : 0.10
Restriction : (P hiM in > 0)
. PhiMax (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Maximum rotation angle of the region.
Default Value : 0.7854
Suggested values : PhiMax ∈ {0.0, 0.1, 0.3, 0.6, 0.9, 1.2, 1.5}
Typical range of values : 0.0 ≤ PhiMax ≤ 0.0(lin)
Minimum Increment : 0.001
Recommended Increment : 0.10
Restriction : (P hiM ax > 0)
. NumRegions (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of regions.
Default Value : 100
Suggested values : NumRegions ∈ {1, 5, 20, 100, 200, 500, 1000, 2000}
Typical range of values : 1 ≤ NumRegions ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 10
Restriction : (N umRegions > 0)
. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Maximum horizontal expansion.
Default Value : 512
Suggested values : Width ∈ {128, 256, 512, 1024}
Typical range of values : 1 ≤ Width ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 10
Restriction : (W idth > 0)
. Height (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Maximum vertical expansion.
Default Value : 512
Suggested values : Height ∈ {128, 256, 512, 1024}
Typical range of values : 1 ≤ Height ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 10
Restriction : (Height > 0)
Result
If the parameter values are correct GenRandomRegions returns the value TRUE. Otherwise an exception han-
dling is raised. The clipping according to the current image format is determined by the operator SetSystem
(’clipRegion’,<’true’/’false’>).
Parallelization Information
GenRandomRegions is reentrant and processed without parallelization.
Possible Successors
PaintRegion
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


12.2. CREATION 827

void HRegionX.GenRectangle1 ([in] VARIANT Row1, [in] VARIANT Column1,


[in] VARIANT Row2, [in] VARIANT Column2 )
void HOperatorSetX.GenRectangle1 ([out] HUntypedObjectX Rectangle,
[in] VARIANT Row1, [in] VARIANT Column1, [in] VARIANT Row2,
[in] VARIANT Column2 )

Create a rectangle parallel to the coordinate axes.


The operator GenRectangle1 generates one or more rectangles parallel to the coordinate axes which are de-
scribed by the upper left corner (Row1, Column1) and the lower right corner (Row2, Column2). More than one
region can be created by passing a tuple of corner points. The coordinate system runs from (0,0) (upper left corner)
to (Width-1,Height-1). See GetSystem and ResetObjDb in this context.
Parameter
. Rectangle (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Created rectangle.
. Row1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.origin.y(-array) ; VARIANT ( integer, real )
Line of upper left corner point.
Default Value : 30.0
Suggested values : Row1 ∈ {0.0, 10.0, 20.0, 50.0, 100.0, 200.0}
(lin)Minimum Increment : 1.0
Recommended Increment : 10.0
. Column1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.origin.x(-array) ; VARIANT ( integer, real )
Column of upper left corner point.
Default Value : 20.0
Suggested values : Column1 ∈ {0.0, 10.0, 20.0, 50.0, 100.0, 200.0}
(lin)Minimum Increment : 1.0
Recommended Increment : 10.0
. Row2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.corner.y(-array) ; VARIANT ( integer, real )
Line of lower right corner point.
Default Value : 100.0
Suggested values : Row2 ∈ {10.0, 20.0, 50.0, 100.0, 200.0, 300.0, 400.0, 500.0, 511.0}
(lin)Minimum Increment : 1.0
Recommended Increment : 10.0
Restriction : (Row2 ≥ Row1)
. Column2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.corner.x(-array) ; VARIANT ( integer, real )
Column of lower right corner point.
Default Value : 200.0
Suggested values : Column2 ∈ {10.0, 20.0, 50.0, 100.0, 200.0, 300.0, 400.0, 500.0, 511.0}
(lin)Minimum Increment : 1.0
Recommended Increment : 10.0
Restriction : (Column2 ≥ Column1)
Example

/* Contrast improvement in a rectangular region of interest */

read_image(Image,’fabrik’)
open_window(0,0,-1,-1,’root’,’visible’,’’,WindowHandle)
disp_image(Image,WindowHandle)
draw_rectangle1(WindowHandle,Row1,Column1,Row2,Column2)
gen_rectangle1(Rectangle,Row1,Column1,Row2,Column2)
reduce_domain(Image,Rectangle,Mask)
emphasize(Mask,Emphasize,9,9,1.0)
disp_image(Emphasize,WindowHandle).

Result
If the parameter values are correct, the operator GenRectangle1 returns the value TRUE. Otherwise an excep-
tion handling is raised. The clipping according to the current image format is set via the operator SetSystem
(’clipRegion’,<’true’/’false’>).

HALCON 8.0.2
828 CHAPTER 12. REGIONS

Parallelization Information
GenRectangle1 is reentrant and processed without parallelization.
Possible Successors
PaintRegion, ReduceDomain
See also
DrawRectangle1, ReduceDomain, SmallestRectangle1
Alternatives
GenRectangle2, GenRegionPolygon, FillUp, GenRegionRuns, GenRegionPoints,
GenRegionLine
Module
Foundation

void HRegionX.GenRectangle2 ([in] VARIANT Row, [in] VARIANT Column,


[in] VARIANT Phi, [in] VARIANT Length1, [in] VARIANT Length2 )
void HOperatorSetX.GenRectangle2 ([out] HUntypedObjectX Rectangle,
[in] VARIANT Row, [in] VARIANT Column, [in] VARIANT Phi, [in] VARIANT Length1,
[in] VARIANT Length2 )

Create a rectangle of any orientation.


The operator GenRectangle2 generates one or more rectangles with the center (Row, Column) , the orientation
Phi and the half edge lengths Length1 and Length2. The orientation is given in arc measure and indicates
the angle between the horizontal axis and Length1 (mathematically positive). The coordinate system runs from
(0,0) (upper left corner) to (Width-1,Height-1). See GetSystem and ResetObjDb in this context. More than
one region can be created by passing one tuple of corner points.
Attention
The gray values of the output objects are undefined.
Parameter
. Rectangle (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Created rectangle.
. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .rectangle2.center.y(-array) ; VARIANT ( integer, real )
Line index of the center.
Default Value : 50.0
Suggested values : Row ∈ {10.0, 20.0, 50.0, 100.0, 200.0, 300.0, 400.0, 500.0}
(lin)Minimum Increment : 1.0
Recommended Increment : 10.0
. Column (input control) . . . . . . . . . . . . . . . . . . . . . . . . . rectangle2.center.x(-array) ; VARIANT ( integer, real )
Column index of the center.
Default Value : 100.0
Suggested values : Column ∈ {10.0, 20.0, 50.0, 100.0, 200.0, 300.0, 400.0, 500.0}
(lin)Minimum Increment : 1.0
Recommended Increment : 10.0
. Phi (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle2.angle.rad(-array) ; VARIANT ( integer, real )
Angle of longitudinal axis to the horizontal (in radians).
Default Value : 0.0
Suggested values : Phi ∈ {-1.178097, -0.785398, -0.392699, 0.0, 0.392699, 0.785398, 1.178097}
Typical range of values : -1.178097 ≤ Phi ≤ -1.178097(lin)
Minimum Increment : 0.001
Recommended Increment : 0.1
Restriction : (((−(pi)/2) < P hi) ∧ (P hi ≤ (pi/2)))

HALCON/COM Reference Manual, 2008-5-13


12.2. CREATION 829

. Length1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . rectangle2.hwidth(-array) ; VARIANT ( integer, real )


Half width.
Default Value : 200.0
Suggested values : Length1 ∈ {3.0, 5.0, 10.0, 15.0, 20.0, 50.0, 100.0, 200.0, 300.0, 500.0}
(lin)Minimum Increment : 1.0
Recommended Increment : 10.0
. Length2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . rectangle2.hheight(-array) ; VARIANT ( integer, real )
Half height.
Default Value : 100.0
Suggested values : Length2 ∈ {1.0, 2.0, 3.0, 5.0, 10.0, 15.0, 20.0, 50.0, 100.0, 200.0}
(lin)Minimum Increment : 1.0
Recommended Increment : 10.0
Result
If the parameter values are correct the operator GenRectangle2 returns the value TRUE. Otherwise an excep-
tion handling is raised. The clipping according to the current image format is set via the operator SetSystem
(’clipRegion’,<’true’/’false’>).
Parallelization Information
GenRectangle2 is reentrant and processed without parallelization.
Possible Successors
PaintRegion, ReduceDomain
See also
DrawRectangle2, ReduceDomain, SmallestRectangle2, GenEllipse
Alternatives
GenRectangle1, GenRegionPolygonFilled, GenRegionPolygon, GenRegionPoints, FillUp
Module
Foundation

[out] HRegionX Region HXLDContX.GenRegionContourXld


([in] String Mode )
void HOperatorSetX.GenRegionContourXld ([in] IHObjectX Contour,
[out] HUntypedObjectX Region, [in] VARIANT Mode )

Create a region from an XLD contour.


GenRegionContourXld creates a region Region from a subpixel XLD contour Contour. The contour is
sampled according to the Bresenham algorithm and influenced by the parameter neighborhood of the operator
SetSystem. Open contours are closed before converting them to regions. Finally, the parameter Mode defines
whether the region is filled up (filled) or returned by its contour (margin).
Please note that the coordinates of the contour points are rounded to their nearest integer pixel coordinates dur-
ing the conversion. This may lead to unexpected results when passing the contour obtained by the operator
GenContourRegionXld to GenRegionContourXld: When setting Mode of GenContourRegionXld
to border, the input region of GenContourRegionXld and the output region of GenRegionContourXld
differ. For example, let us assume that the input region of GenContourRegionXld consists of the single pixel
(1,1). Then, the resulting contour that is obtained when calling GenContourRegionXld with Mode set to
border consists of the five points (0.5,0.5), (0.5,1.5), (1.5,1.5), (1.5,0.5), and (0.5,0.5). Consequently, when pass-
ing this contour again to GenRegionContourXld, the resulting region consists of the points (1,1), (1,2), (2,2),
and (2,1).
Parameter

. Contour (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xld_cont ; HXLDContX / IHObjectX


Input contour.
. Region (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX
Created region.

HALCON 8.0.2
830 CHAPTER 12. REGIONS

. Mode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT


Fill mode of the region.
Default Value : ’filled’
Suggested values : Mode ∈ {’filled’, ’margin’}
Parallelization Information
GenRegionContourXld is reentrant and processed without parallelization.
Possible Predecessors
GenContourPolygonXld, GenContourPolygonRoundedXld
See also
SetSystem
Alternatives
GenRegionPolygon, GenRegionPolygonXld
Module
Foundation

void HRegionX.GenRegionHisto ([in] VARIANT Histogram, [in] long Row,


[in] long Column, [in] long Scale )
[out] HRegionX Region HHistogramX.GenRegionHisto
([in] VARIANT Histogram, [in] long Row, [in] long Column, [in] long Scale )
void HOperatorSetX.GenRegionHisto ([out] HUntypedObjectX Region,
[in] VARIANT Histogram, [in] VARIANT Row, [in] VARIANT Column,
[in] VARIANT Scale )

Convert a histogram into a region.


GenRegionHisto converts a histogram created with GrayHisto into a region. The effect of the three control
parameters is the same as in DispImage and SetPaint.
Parameter

. Region (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX


Region containing the histogram.
. Histogram (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . histogram ; VARIANT ( integer )
Input histogram.
. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; long / VARIANT
Row coordinate of the center of the histogram.
Default Value : 255
Suggested values : Row ∈ {100, 200, 255, 300, 400}
Typical range of values : 0 ≤ Row ≤ 0
. Column (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; long / VARIANT
Column coordinate of the center of the histogram.
Default Value : 255
Suggested values : Column ∈ {100, 200, 255, 300, 400}
Typical range of values : 0 ≤ Column ≤ 0
. Scale (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Scale factor for the histogram.
Default Value : 1
List of values : Scale ∈ {1, 2, 3, 4, 5, 6, 7}
Typical range of values : 1 ≤ Scale ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 1
Result
GenRegionHisto returns TRUE if all parameters are correct. If necessary, an exception handling is raised.
Parallelization Information
GenRegionHisto is reentrant and processed without parallelization.

HALCON/COM Reference Manual, 2008-5-13


12.2. CREATION 831

Possible Predecessors
GrayHisto
See also
DispChannel, SetPaint
Module
Foundation

void HRegionX.GenRegionHline ([in] VARIANT Orientation,


[in] VARIANT Distance )
void HOperatorSetX.GenRegionHline ([out] HUntypedObjectX Regions,
[in] VARIANT Orientation, [in] VARIANT Distance )

Store input lines described in Hesse normal shape as regions.


The operator GenRegionHline stores the lines described in Hesse normal shape as regions. A line is deter-
mined by the distance from the line to the origin (Distance, corresponds to the length of the normal vector)
and the direction of the normal vector (Orientation, corresponds to the orientation of the line ±π/2). The
directions were defined in such a way that at Orientation = 0 the normal vector lies in the direction of the X
axis, which corresponds to a vertical line. At Orientation = π/2 the normal vector points in the direction of
the Y axis, i.e. a horizontal line is described.
Attention
The lines are clipped to the current maximum image format.
Parameter

. Regions (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX


Created regions (one for every line), clipped to maximum image format.
Number of elements : (Regions = Distance)
. Orientation (input control) . . . . . . . . . . . . . . . . . . hesseline.angle.rad(-array) ; VARIANT ( integer, real )
Orientation of the normal vector in radians.
Default Value : 0.0
Suggested values : Orientation ∈ {-0.78, 0.0, 0.78, 1.57}
(lin)Recommended Increment : 0.02
Number of elements : (Orientation = Distance)
. Distance (input control) . . . . . . . . . . . . . . . . . . . . . . . .hesseline.distance(-array) ; VARIANT ( integer, real )
Distance from the line to the coordinate origin (0.0).
Default Value : 200
Suggested values : Distance ∈ {10, 50, 100, 200, 300, 400}
(lin)Recommended Increment : 1
Result
The operator GenRegionHline always returns the value TRUE.
Parallelization Information
GenRegionHline is reentrant and processed without parallelization.
See also
HoughLines
Alternatives
GenRegionLine
Module
Foundation

HALCON 8.0.2
832 CHAPTER 12. REGIONS

void HRegionX.GenRegionLine ([in] VARIANT BeginRow,


[in] VARIANT BeginCol, [in] VARIANT EndRow, [in] VARIANT EndCol )
void HOperatorSetX.GenRegionLine ([out] HUntypedObjectX RegionLines,
[in] VARIANT BeginRow, [in] VARIANT BeginCol, [in] VARIANT EndRow,
[in] VARIANT EndCol )

Store input lines as regions.


The operator GenRegionLine stores the given lines (with starting point [BeginRow,BeginCol] and ending
point [EndRow, EndCol]) as region.
Attention

Parameter

. RegionLines (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX


Created regions.
. BeginRow (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.begin.y(-array) ; VARIANT ( integer )
Line coordinates of the starting points of the input lines.
Default Value : 100
Suggested values : BeginRow ∈ {10, 50, 100, 200, 300, 400}
(lin)Minimum Increment : 1
Recommended Increment : 1
. BeginCol (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.begin.x(-array) ; VARIANT ( integer )
Column coordinates of the starting points of the input lines.
Default Value : 50
Suggested values : BeginCol ∈ {10, 50, 100, 200, 300, 400}
(lin)Minimum Increment : 1
Recommended Increment : 1
. EndRow (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.end.y(-array) ; VARIANT ( integer )
Line coordinates of the ending points of the input lines.
Default Value : 150
Suggested values : EndRow ∈ {50, 100, 200, 300, 400, 500}
(lin)Minimum Increment : 1
Recommended Increment : 1
. EndCol (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.end.x(-array) ; VARIANT ( integer )
Column coordinates of the ending points of the input lines.
Default Value : 250
Suggested values : EndCol ∈ {50, 100, 200, 300, 400, 500}
(lin)Minimum Increment : 1
Recommended Increment : 1
Result
The operator GenRegionLine always returns the value TRUE. The clipping according to the current image
format is determined by the operator SetSystem(’clipRegion’,<’true’/’false’>).
Parallelization Information
GenRegionLine is reentrant and processed without parallelization.
Possible Predecessors
SplitSkeletonLines
Alternatives
GenRegionHline
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


12.2. CREATION 833

void HRegionX.GenRegionPoints ([in] VARIANT Rows,


[in] VARIANT Columns )
void HOperatorSetX.GenRegionPoints ([out] HUntypedObjectX Region,
[in] VARIANT Rows, [in] VARIANT Columns )

Store individual pixels as image region.


The operator GenRegionPoints creates a region described by a number of pixels. The pixels do not have to
be stored in a fixed order, but the best runtime behavior is obtained when the pixels are stored in ascending order.
The order is as follows:

(l1 , c1 ) ≤ (l2 , c2 ) := (l1 < l2 ) ∨ (l1 = l2 ) ∧ (c1 ≤ c2 )

The indicated coordinates stand for two consecutive pixels in the tupel.
Attention

Parameter

. Region (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX


Created region.
. Rows (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . coordinates.y(-array) ; VARIANT ( integer )
Lines of the pixels in the region.
Default Value : 100
Suggested values : Rows ∈ {0, 10, 30, 50, 100, 200, 300, 500}
(lin)Minimum Increment : 1
Recommended Increment : 1
. Columns (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .coordinates.x(-array) ; VARIANT ( integer )
Columns of the pixels in the region.
Default Value : 100
Suggested values : Columns ∈ {0, 10, 30, 50, 100, 200, 300, 500}
(lin)Minimum Increment : 1
Recommended Increment : 1
Number of elements : (Columns = Rows)
Complexity
F shall be the number of pixels. If the pixels are sorted in ascending order the runtime complexity is: O(F ),
otherwise O(log(F ) ∗ F ).
Result
The operator GenRegionPoints returns the value TRUE if the pixels are located within the image format.
Otherwise an exception handling is raised. The clipping according to the current image format is set via the operator
SetSystem(’clipRegion’,<’true’/’false’>). If an empty region is created (by the clipping or by
an empty input) the operator SetSystem(’storeEmptyRegion’,<true/false>) determines whether
the region is returned or an empty object tuple.
Parallelization Information
GenRegionPoints is reentrant and processed without parallelization.
Possible Predecessors
GetRegionPoints
Possible Successors
PaintRegion, ReduceDomain
See also
ReduceDomain
Alternatives
GenRegionPolygon, GenRegionRuns, GenRegionLine
Module
Foundation

HALCON 8.0.2
834 CHAPTER 12. REGIONS

void HRegionX.GenRegionPolygon ([in] VARIANT Rows,


[in] VARIANT Columns )
void HOperatorSetX.GenRegionPolygon ([out] HUntypedObjectX Region,
[in] VARIANT Rows, [in] VARIANT Columns )

Store a polygon as an image object.


The operator GenRegionPolygon creates a region from a polygon row described by a series of line and
column coordinates. The created region consists of the pixels of the routes defined thereby, wherein it is linearily
interpolated between the base points.
Attention
The region is not automatically closed and not filled. The gray values of the output regions are undefined.
Parameter

. Region (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX


Created region.
. Rows (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . polygon.y ; VARIANT ( integer )
Line indices of the base points of the region contour.
Default Value : 100
Suggested values : Rows ∈ {0, 10, 30, 50, 100, 200, 300, 500}
(lin)Minimum Increment : 1
Recommended Increment : 1
. Columns (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . polygon.x ; VARIANT ( integer )
Colum indices of the base points of the region contour.
Default Value : 100
Suggested values : Columns ∈ {0, 10, 30, 50, 100, 200, 300, 500}
(lin)Minimum Increment : 1
Recommended Increment : 1
Number of elements : (Columns = Rows)
Example

/* Polygon-approximation*/
get_region_polygon(Region,7,Row,Column)
/* store it as a region */
gen_region_polygon(Pol,Row,Column)
/* fill up the hole */
fill_up(Pol,Filled).

Result
If the base points are correct the operator GenRegionPolygon returns the value TRUE. Otherwise an exception
handling is raised. The clipping according to the current image format is set via the operator SetSystem
(’clipRegion’,<’true’/’false’>). If an empty region is created (by the clipping or by an empty
input) the operator SetSystem(’storeEmptyRegion’,<true/false>) determines whether the region
is returned or an empty object tuple.
Parallelization Information
GenRegionPolygon is reentrant and processed without parallelization.
Possible Predecessors
GetRegionPolygon, DrawPolygon
See also
FillUp, ReduceDomain, GetRegionPolygon, DrawPolygon
Alternatives
GenRegionPolygonFilled, GenRegionPoints, GenRegionRuns
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


12.2. CREATION 835

void HRegionX.GenRegionPolygonFilled ([in] VARIANT Rows,


[in] VARIANT Columns )
void HOperatorSetX.GenRegionPolygonFilled
([out] HUntypedObjectX Region, [in] VARIANT Rows, [in] VARIANT Columns )

Store a polygon as a “filled” region.


The operator GenRegionPolygonFilled creates a region from a polygon containing the corner points of the
region (line and column coordinates) either clockwise or anti-clockwise. Contrary to GenRegionPolygon a
“filled” region is returned here.
Attention

Parameter

. Region (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX


Created region.
. Rows (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . polygon.y ; VARIANT ( integer )
Line indices of the base points of the region contour.
Default Value : 100
Suggested values : Rows ∈ {0, 10, 30, 50, 100, 200, 300, 500}
(lin)Minimum Increment : 1
Recommended Increment : 1
. Columns (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . polygon.x ; VARIANT ( integer )
Column indices of the base points of the region contour.
Default Value : 100
Suggested values : Columns ∈ {0, 10, 30, 50, 100, 200, 300, 500}
(lin)Minimum Increment : 1
Recommended Increment : 1
Number of elements : (Columns = Rows)
Result
If the base points are correct the operator GenRegionPolygonFilled returns the value TRUE. Otherwise
an exception handling is raised. The clipping according to the current image format is set via the operator
SetSystem(’clipRegion’,<’true’/’false’>). If an empty region is created (by the clipping or by
an empty input) the operator SetSystem(’storeEmptyRegion’,<true/false>) determines whether
the region is returned or an empty object tuple.
Parallelization Information
GenRegionPolygonFilled is reentrant and processed without parallelization.
Possible Predecessors
GetRegionPolygon, DrawPolygon
See also
GenRegionPolygon, ReduceDomain, GetRegionPolygon, GenRegionRuns
Alternatives
GenRegionPolygon, GenRegionPoints, DrawPolygon
Module
Foundation

[out] HRegionX Region HXLDPolyX.GenRegionPolygonXld


([in] String Mode )
void HOperatorSetX.GenRegionPolygonXld ([in] IHObjectX Polygon,
[out] HUntypedObjectX Region, [in] VARIANT Mode )

Create a region from an XLD polygon.


GenRegionPolygonXld creates a region Region from a subpixel XLD polygon Polygon. The polygon
is sampled according to the Bresenham algorithm and influenced by the parameter neighborhood of the operator

HALCON 8.0.2
836 CHAPTER 12. REGIONS

SetSystem. Open polygons are closed before converting them to regions. Finally, the parameter Mode defines
whether the region is filled up (filled) or returned by its contour (margin).
Parameter

. Polygon (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xld_poly ; HXLDPolyX / IHObjectX


Input polygon.
. Region (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX
Created region.
. Mode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Fill mode of the region.
Default Value : ’filled’
Suggested values : Mode ∈ {’filled’, ’margin’}
Parallelization Information
GenRegionPolygonXld is reentrant and processed without parallelization.
Possible Predecessors
GenPolygonsXld
See also
SetSystem
Alternatives
GenRegionPolygon, GenRegionContourXld
Module
Foundation

void HRegionX.GenRegionRuns ([in] VARIANT Row, [in] VARIANT ColumnBegin,


[in] VARIANT ColumnEnd )
void HOperatorSetX.GenRegionRuns ([out] HUntypedObjectX Region,
[in] VARIANT Row, [in] VARIANT ColumnBegin, [in] VARIANT ColumnEnd )

Create an image region from a runlength coding.


The operator GenRegionRuns creates a region described by the input runlength structure. The runlength rep-
resentation is created by examining a region line by line with ascending line number (= from “top” to “bottom”).
Every line runs through from left to right (ascending column number). All starting and ending points being stored
by region segments (=runs). Thus a region can be described by a sequence of runs, a run being defined by line
number as well as starting and ending points (column number).
The storing is fastest when the runs are sorted. The order is as follows:

(l1 , b1 , e1 ) ≤ (l2 , b2 , e2 ) := (l1 < l2 ) ∨ (l1 = l2 ) ∧ (b1 ≤ b2 )

.
Attention

Parameter

. Region (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX


Created region.
. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . chord.y(-array) ; VARIANT ( integer )
Lines of the runs.
Default Value : 100
Suggested values : Row ∈ {0, 50, 100, 200, 300, 500}
(lin)Minimum Increment : 1
Recommended Increment : 10

HALCON/COM Reference Manual, 2008-5-13


12.2. CREATION 837

. ColumnBegin (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . chord.x1(-array) ; VARIANT ( integer )


Columns of the starting points of the runs.
Default Value : 50
Suggested values : ColumnBegin ∈ {0, 50, 100, 200, 300, 500}
(lin)Minimum Increment : 1
Recommended Increment : 10
Number of elements : (ColumnBegin = Row)
. ColumnEnd (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . chord.x2(-array) ; VARIANT ( integer )
Columns of the ending points of the runs.
Default Value : 200
Suggested values : ColumnEnd ∈ {50, 100, 200, 300, 500}
(lin)Minimum Increment : 1
Recommended Increment : 10
Restriction : (ColumnEnd ≥ ColumnBegin)
Number of elements : (ColumnEnd = Row)
Complexity
F shall be the number of pixels. If the pixels are sorted in ascending order the runtime complexity is: O(F ),
otherwise it is O(log(F ) ∗ F ).
Result
If the data is correct the operator GenRegionRuns returns the value TRUE, otherwise an exception han-
dling is raised. The clipping according to the current image format is set via the operator SetSystem
(’clipRegion’,<’true’/’false’>). If an empty region is created (by the clipping or by an empty
input) the operator SetSystem(’storeEmptyRegion’,<true/false>) determines whether the region
is returned or an empty object tuple.
Parallelization Information
GenRegionRuns is reentrant and processed without parallelization.
Possible Predecessors
GetRegionRuns
See also
ReduceDomain
Alternatives
GenRegionPoints, GenRegionPolygon, GenRegionLine, GenRegionPolygonFilled
Module
Foundation

HImageX.LabelToRegion ( )
[out] HRegionX Regions
void HOperatorSetX.LabelToRegion ([in] IHObjectX LabelImage,
[out] HUntypedObjectX Regions )

Extract regions with equal gray values from an image.


LabelToRegion segments an image into regions of equal gray value. One output region is generated for each
gray value occuring in the image. This is similar to calling Threshold multiple times, and accumulating
the results with ConcatObj. Another related operator is Regiongrowing. However, LabelToRegion
does not perform a Connection operation on the resulting regions, i.e., they may be disconnected. A typical
application of LabelToRegion is the segmentation of label images, hence its name.
The number of output regions is limited by the system parameter ’max_outp_obj_par’, which can be read via
GetSystem(::’max_outp_obj_par’:<Anzahl>).

Attention
LabelToRegion is not implemented for images of type ’real’. The input images must not contain negative gray
values.

HALCON 8.0.2
838 CHAPTER 12. REGIONS

Parameter

. LabelImage (input iconic) . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte, int2, int4 )


Label image.
. Regions (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX
Regions having a constant gray value.
Complexity
Let x1 be the minimum x-coordinate, x2 the maximum x-coordinate, y1 be the minimum y-coordinate, and y2 the
maximum y-coordinate of a particular gray value. Furthermore, let N be the number of different gray values in the
image. Then the runtime complexity is O(N ∗ (x2 − x1 + 1) ∗ (y2 − y1 + 1))
Result
LabelToRegion returns TRUE if the gray values lie within a correct range. The behavior with respect to
the input images and output regions can be determined by setting the values of the flags ’no_object_result’,
’empty_region_result’, and ’store_empty_region’ with SetSystem. If necessary, an exception is raised.
Parallelization Information
LabelToRegion is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
MinMaxGray, SobelAmp, BinomialFilter, GaussImage, ReduceDomain, DiffOfGauss
Possible Successors
Connection, Dilation1, Erosion1, Opening, Closing, RankRegion, ShapeTrans, Skeleton
See also
Threshold, ConcatObj, Regiongrowing, RegionToLabel
Module
Foundation

12.3 Features
[out] VARIANT Area HRegionX.AreaCenter ([out] VARIANT Row,
[out] VARIANT Column )
void HOperatorSetX.AreaCenter ([in] IHObjectX Regions,
[out] VARIANT Area, [out] VARIANT Row, [out] VARIANT Column )

Area and center of regions.


The operator AreaCenter calculates the area and the center of the input regions. The area is defined as the
number of pixels of a region. The center is calculated as the mean value of the line or column coordinates,
respectively, of all pixels.
If more than one region is passed the results are stored in tuples, the index of a value in the tuple corresponding to
the index of the input region. In case of empty region all parameters have the value 0.0 if no other behavior was
set (see SetSystem).
Parameter

. Regions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Region(s) to be examined.
. Area (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Area of the region.
. Row (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( real )
Line index of the center.
. Column (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( real )
Column index of the center.
Complexity√
If F is the area of a region the mean runtime complexity is O( F ).
Result
The operator AreaCenter returns the value TRUE if the input is not empty. The behavior in case of empty

HALCON/COM Reference Manual, 2008-5-13


12.3. FEATURES 839

input (no input regions available) is set via the operator SetSystem(’noObjectResult’,<Result>).
The behavior in case of empty region (the region is the empty set) is set via SetSystem
(’emptyRegionResult’,<Result>). If necessary an exception handling is raised.
Parallelization Information
AreaCenter is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection
See also
SelectShape
Module
Foundation

HRegionX.Circularity ( )
[out] VARIANT Circularity
void HOperatorSetX.Circularity ([in] IHObjectX Regions,
[out] VARIANT Circularity )

Shape factor for the circularity (similarity to a circle) of a region.


The operator Circularity calculates the similarity of the input region with a circle.

Calculation: If F is the area of the region and max is the maximum distance from the center to all contour pixels,
the shape factor C is defined as:
F
C=
(max2 ∗ π)

The shape factor C of a circle is 1. If the region is long or has holes C is smaller than 1. The operator
Circularity especially responds to large bulges, holes and unconnected regions.
In case of an empty region the operator Circularity returns the value 0 (if no other behavior was set (see
SetSystem)). If more than one region is passed the numerical values of the shape factor are stored in a tuple, the
position of a value in the tuple corresponding to the position of the region in the input tuple.
Parameter

. Regions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Region(s) to be examined.
. Circularity (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Roundness of the input region(s).
Restriction : ((0 ≤ Circularity) ∧ (Circularity ≤ 1.0))
Example

/* Comparison between shape factors of rectangle, circle and ellipse: */


gen_rectangle1(R1,10,10,20,20)
gen_rectangle2(R2,100,100,0.0,100,20)
gen_ellipse(E100,100,0.0,100,20)
gen_circle(,C,100,100,20)
circularity([R1,R2,E,C],M)
fwrite_string(FileId,[’quadrate: ’,M[1]])
fnew_line(FileId)
fwrite_string(FileId,[’rectangle: ’,M[2]])
fnew_line(FileId)
fwrite_string(FileId,[’ellipse: ’,M[3]])
fnew_line(FileId)
fwrite_string(FileId,[’circle: ’,M[4]])
fnew_line(FileId)

HALCON 8.0.2
840 CHAPTER 12. REGIONS

Result
The operator Circularity returns the value TRUE if the input is not empty. The behavior in case of empty
input (no input regions available) is set via the operator SetSystem(’noObjectResult’,<Result>).
The behavior in case of empty region (the region is the empty set) is set via SetSystem
(’emptyRegionResult’,<Result>). If necessary an exception handling is raised.
Parallelization Information
Circularity is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection
See also
AreaCenter, SelectShape
Alternatives
Roundness, Compactness, Convexity, Eccentricity
Module
Foundation

[out] VARIANT Compactness HRegionX.Compactness ( )


void HOperatorSetX.Compactness ([in] IHObjectX Regions,
[out] VARIANT Compactness )

Shape factor for the compactness of a region.


The operator Compactness calculates the compactness of the input regions.

Calculation: If L is the length of the contour (see Contlength) and F the area of the region the shape factor
C is defined as:
L2
C=
4F π
The shape factor C of a circle is 1. If the region is long or has holes C is larger than 1. The operator
Compactness responds to the course of the contour (roughness) and to holes. In case of an empty region
the operator Compactness returns the value 0 if no other behavior was set (see SetSystem). If more than
one region is passed the numerical values of the shape factor are stored in a tuple, the position of a value in the
tuple corresponding to the position of the region in the input tuple.
Attention

Parameter

. Regions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Region(s) to be examined.
. Compactness (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Compactness of the input region(s).
Restriction : ((Compactness ≥ 1.0) ∨ (Compactness = 0))
Result
The operator Compactness returns the value TRUE if the input is not empty. The behavior in case of empty
input (no input regions available) is set via the operator SetSystem(’noObjectResult’,<Result>).
The behavior in case of empty region (the region is the empty set) is set via SetSystem
(’emptyRegionResult’,<Result>). If necessary an exception handling is raised.
Parallelization Information
Compactness is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection
See also
Contlength, AreaCenter, SelectShape

HALCON/COM Reference Manual, 2008-5-13


12.3. FEATURES 841

Alternatives
Compactness, Convexity, Eccentricity
Module
Foundation

[out] VARIANT NumConnected HRegionX.ConnectAndHoles


([out] VARIANT NumHoles )
void HOperatorSetX.ConnectAndHoles ([in] IHObjectX Regions,
[out] VARIANT NumConnected, [out] VARIANT NumHoles )

Number of connection components and holes


The operator ConnectAndHoles calculates the number of connection components and the number of holes of
each region of Regions.
If more than one region is passed the numerical values of the output control parameters NumConnected and
NumHoles are each stored in a tuple, the position of a value in the tuple corresponding to the position of the
region in the input tuple.
Attention

Parameter
. Regions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Region(s) to be examined.
. NumConnected (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Number of connection components of a region.
. NumHoles (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Number of holes of a region.
Result
The operator ConnectAndHoles returns the value TRUE if the input is not empty. The be-
havior in case of empty input (no input regions available) is set via the operator SetSystem
(’noObjectResult’,<Result>). The behavior in case of empty region (the region is the empty set) is
set via SetSystem(’emptyRegionResult’,<Result>).
Parallelization Information
ConnectAndHoles is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection
See also
Connection, FillUp, FillUpShape, Union1
Alternatives
EulerNumber
Module
Foundation

HRegionX.Contlength ( )
[out] VARIANT ContLength
void HOperatorSetX.Contlength ([in] IHObjectX Regions,
[out] VARIANT ContLength )

Contour length of a region.


The operator Contlength calculates the total length of the contour (sum of all connection components of
the region) for each region of Regions. The distance between √ two neighboring contour points parallel to the
coordinate axes is rated 1, the distance in the diagonal is rated 2. If more than one region is passed the numerical
values of the contour length are stored in a tuple, the position of a value in the tuple corresponding to the position
of the region in the input tuple. In case of an empty region the operator Contlength returns the value 0.

HALCON 8.0.2
842 CHAPTER 12. REGIONS

Attention
The contour of holes is not calculated.
Parameter

. Regions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Region(s) to be examined.
. ContLength (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Contour length of the input region(s).
Restriction : (ContLength ≥ 0)
Result
The operator Contlength returns the value TRUE if the input is not empty. The behavior in case of empty
input (no input regions available) is set via the operator SetSystem(’noObjectResult’,<Result>). If
necessary an exception handling is raised.
Parallelization Information
Contlength is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection
Possible Successors
GetRegionContour
See also
AreaCenter, GetRegionContour
Alternatives
Compactness
Module
Foundation

HRegionX.Convexity ( )
[out] VARIANT Convexity
void HOperatorSetX.Convexity ([in] IHObjectX Regions,
[out] VARIANT Convexity )

Shape factor for the convexity of a region.


The operator Convexity calculates the convexity of each input region of Regions.

Calculation: If Fc is the area of the convex hull and Fo the original area of the region the shape factor C is defined
as:

Fo
C=
Fc
The shape factor C is 1 if the region is convex (e.g., rectangle, circle etc.). If there are indentations or holes C is
smaller than 1.
In case of an empty region the operator Convexity returns the value 0 (if no other behavior was set (see
SetSystem)). If more than one region is passed the numerical values of the contour length are stored in a tuple,
the position of a value in the tuple corresponding to the position of the region in the input tuple.
Attention

Parameter

. Regions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Region(s) to be examined.
. Convexity (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Convexity of the input region(s).
Restriction : (Convexity ≤ 1)

HALCON/COM Reference Manual, 2008-5-13


12.3. FEATURES 843

Result
The operator Convexity returns the value TRUE if the input is not empty. The behavior in case of empty
input (no input regions available) is set via the operator SetSystem(’noObjectResult’,<Result>).
The behavior in case of empty region (the region is the empty set) is set via SetSystem
(’emptyRegionResult’,<Result>). If necessary an exception handling is raised.
Parallelization Information
Convexity is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection
See also
SelectShape, AreaCenter, ShapeTrans
Module
Foundation

[out] VARIANT Row1 HRegionX.DiameterRegion ([out] VARIANT Column1,


[out] VARIANT Row2, [out] VARIANT Column2, [out] VARIANT Diameter )
void HOperatorSetX.DiameterRegion ([in] IHObjectX Regions,
[out] VARIANT Row1, [out] VARIANT Column1, [out] VARIANT Row2,
[out] VARIANT Column2, [out] VARIANT Diameter )

Maximal distance between two boundary points of a region.


The operator DiameterRegion calculates the maximal distance between two boundary points of a region. The
coordinates of these two extremes and the distance between them will be returned.
Attention
If the region is empty, the results of Row1, Column1, Row2 and Column2 (all of them = 0) may lead to confu-
sion.
Parameter

. Regions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Regions to be examined.
. Row1 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.begin.y(-array) ; VARIANT ( integer )
Row index of the first extreme point.
. Column1 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.begin.x(-array) ; VARIANT ( integer )
Column index of the first extreme point.
. Row2 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.end.y(-array) ; VARIANT ( integer )
Row index of the second extreme point.
. Column2 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.end.x(-array) ; VARIANT ( integer )
Column index of the second extreme point.
. Diameter (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( real )
Distance of the two extreme points.
Complexity √
If F is the area of a region, the runtime complexity amounts to O( F ) on average.
Result
The operator DiameterRegion returns the value TRUE, if the input is not empty. The reaction to
empty input (no input regions are available) may be determined with the help of the operator SetSystem
(’noObjectResult’,<Result>). The reaction concerning an empty region (region is the empty set) will be
determined by the operator SetSystem(’emptyRegionResult’,<Result>). If necessary an exception
handling is raised.
Parallelization Information
DiameterRegion is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection, RunlengthFeatures

HALCON 8.0.2
844 CHAPTER 12. REGIONS

Possible Successors
DispLine
Alternatives
SmallestRectangle2
Module
Foundation

[out] VARIANT Anisometry HRegionX.Eccentricity ([out] VARIANT Bulkiness,


[out] VARIANT StructureFactor )
void HOperatorSetX.Eccentricity ([in] IHObjectX Regions,
[out] VARIANT Anisometry, [out] VARIANT Bulkiness,
[out] VARIANT StructureFactor )

Shape features derived from the ellipse parameters.


The operator Eccentricity calculates three shape features derived from the geometric moments.
Definition: If the parameters Ra, Rb and the area A of the region are given (see EllipticAxis), the following
applies:
Ra
Anisometry =
Rb
π · Ra · Rb
Bulkiness =
A
StructureFactor = Anisometry · Bulkiness − 1

If more than one region is passed the results are stored in tuples, the index of a value in the tuple corresponding to
the index of a region in the input.
In case of empty region all parameters have the value 0.0 if no other behavior was set (see SetSystem).
Attention
It should be noted that, like for all region-moments-based operators, the region’s pixels are regarded as math-
ematical, infinitely small points that are represented by the center of the pixels (see the documentation of
EllipticAxis). This can lead to non-empty regions that have Rb = 0. In these cases, the output features
that require a division by Rb are set to 0. In particular, regions that contain a single point or regions whose points
lie exactly on a straight line (e.g., one pixel high horizontal regions or one pixel wide vertical regions) have an
anisometry of 0.
Parameter

. Regions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Region(s) to be examined.
. Anisometry (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Shape feature (in case of a circle = 1.0).
Restriction : (Anisometry ≥ 1.0)
. Bulkiness (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Calculated shape feature.
. StructureFactor (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Calculated shape feature.
Complexity √
If F is the area of the region the mean runtime complexity is O( F ).
Result
The operator Eccentricity returns the value TRUE if the input is not empty. The behavior in case of empty
input (no input regions available) is set via the operator SetSystem(’noObjectResult’,<Result>).
The behavior in case of empty region (the region is the empty set) is set via SetSystem
(’emptyRegionResult’,<Result>). If necessary an exception handling is raised.
Parallelization Information
Eccentricity is reentrant and automatically parallelized (on tuple level).

HALCON/COM Reference Manual, 2008-5-13


12.3. FEATURES 845

Possible Predecessors
Threshold, Regiongrowing, Connection
See also
EllipticAxis, MomentsRegion2Nd, SelectShape, AreaCenter
Module
Foundation

[out] VARIANT Ra HRegionX.EllipticAxis ([out] VARIANT Rb,


[out] VARIANT Phi )
void HOperatorSetX.EllipticAxis ([in] IHObjectX Regions,
[out] VARIANT Ra, [out] VARIANT Rb, [out] VARIANT Phi )

Parameters of the equivalent ellipse.


The operator EllipticAxis calculates the radii and the orientation of the ellipse having the “same orientation”
and the “same side relation” as the input region. Several input regions can be passed in Regions as tuples. The
length of the main radius Ra and the secondary radius Rb as well as the orientation of the main axis with regard to
the horizontal (Phi) are determined. The angle is indicated in arc measure.
Calculation:
If the moments M20 , M02 and M11 are normalized and passed to the area (see MomentsRegion2Nd), the radii
Ra and Rb are calculated as:
q p
8(M20 + M02 + (M20 − M02 )2 + 4M11 2 )
Ra =
2
q p
8(M20 + M02 − (M20 − M02 )2 + 4M11 2 )
Rb =
2
The orientation Phi is defined by:

Phi = −0.5atan2(2M11 , M02 − M20 )

If more than one region is passed the results are stored in tuples, the index of a value in the tuple corresponding to
the index of a region in the input.
In case of empty region all parameters have the value 0.0 if no other behavior was set (see SetSystem
(’noObjectResult’,<Result>)).
Attention
It should be noted that, like for all region-moments-based operators, the region’s pixels are regarded as mathemat-
ical, infinitely small points that are represented by the center of the pixels. This means that Ra and Rb can assume
the value 0. In particular, for an empty region and a region containing a single point Ra = Rb = 0 is returned.
Furthermore, for regions whose points lie exactly on a straight line (e.g., one pixel high horizontal regions or one
pixel wide vertical regions), Rb = 0 is returned.
Parameter

. Regions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Region(s) to be examined.
. Ra (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Main radius (normalized to the area).
Restriction : (Ra ≥ 0.0)
. Rb (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Secondary radius (normalized to the area).
Restriction : ((Rb ≥ 0.0) ∧ (Rb ≤ Ra))
. Phi (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Angle between main radius and x axis (arc measure).
Restriction : (((−(pi)/2) < P hi) ∧ (P hi ≤ (pi/2)))

HALCON 8.0.2
846 CHAPTER 12. REGIONS

Example

read_image(Image,’fabrik’)
open_window(0,0,-1,-1,’root’,’visible’,’’,WindowHandle)
regiongrowing(Image,Seg,5,5,6,100)
elliptic_axis(Seg,Ra,Rb,Phi)
area_center(Seg,_,Row,Column)
gen_ellipse(Ellipses,Row,Column,Phi,Ra,Rb)
set_draw(WindowHandle,’margin’)
disp_region(Ellipses,WindowHandle)

Complexity√
If F is the area of a region the mean runtime complexity is O( F ).
Result
The operator EllipticAxis returns the value TRUE if the input is not empty. The behavior in case of empty
input (no input regions available) is set via the operator SetSystem(’noObjectResult’,<Result>).
The behavior in case of empty region (the region is the empty set) is set via SetSystem
(’emptyRegionResult’,<Result>). If necessary an exception handling is raised.
Parallelization Information
EllipticAxis is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection
Possible Successors
GenEllipse
See also
MomentsRegion2Nd, SelectShape, SetShape
Alternatives
SmallestRectangle2, OrientationRegion
References
R. Haralick, L. Shapiro “Computer and Robot Vision” Addison-Wesley, 1992, pp. 73-75
Module
Foundation

HRegionX.EulerNumber ( )
[out] VARIANT EulerNumber
void HOperatorSetX.EulerNumber ([in] IHObjectX Regions,
[out] VARIANT EulerNumber )

Calculate the Euler number.


The procedure EulerNumber calculates the Euler number, i.e., the difference between the number of connection
components and the number of holes.
If more than one region is passed the results are stored in tuples, the index of a value in the tuple corresponding to
the index of a region in the input.
Parameter

. Regions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Region(s) to be examined.
. EulerNumber (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Calculated Euler number.
Result
The operator EulerNumber returns the value TRUE if the input is not empty. The behavior in case of empty
input (no input regions available) is set via the operator SetSystem(’noObjectResult’,<Result>).

HALCON/COM Reference Manual, 2008-5-13


12.3. FEATURES 847

The behavior in case of empty region (the region is the empty set) is set via SetSystem
(’emptyRegionResult’,<Result>). If necessary an exception handling is raised.
Parallelization Information
EulerNumber is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection
Alternatives
ConnectAndHoles
Module
Foundation

[out] VARIANT RegionIndex1 HRegionX.FindNeighbors


([in] HRegionX Regions2, [in] long MaxDistance, [out] VARIANT RegionIndex2 )
void HOperatorSetX.FindNeighbors ([in] IHObjectX Regions1,
[in] IHObjectX Regions2, [in] VARIANT MaxDistance,
[out] VARIANT RegionIndex1, [out] VARIANT RegionIndex2 )

Search direct neighbors.


The operator FindNeighbors determines neighboring regions with Regions1 and Regions2 containing
the regions to be examined. Regions1 can have three different states:

• Regions1 is empty:
In this case all regions in Regions2 are permutatively checked for neighborhood.
• Regions1 consists of one region:
The regions of Regions1 are compared to all regions in Regions2.
• Regions1 consists of the same number of regions as Regions2:
Here all regions at the n-th position in Regions1 and Regions2 are checked for the neighboring relation.

The operator FindNeighbors uses the chessboard distance between neighboring regions. It can be specified
by the parameter MaxDistance. Neighboring regions are located at the n-th position in RegionIndex1 and
RegionIndex2, i.e., the region with index RegionIndex1[n] from Regions1 is the neighbor of the region
with index RegionIndex2[n] from Regions2.
Attention
Covered regions are not found!
Parameter
. Regions1 (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Starting regions.
. Regions2 (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Comparative regions.
. MaxDistance (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Maximal distance of regions.
Default Value : 1
Suggested values : MaxDistance ∈ {1, 2, 3, 4, 5, 6, 7, 8, 10, 15, 20, 50}
Typical range of values : 1 ≤ MaxDistance ≤ 1
Minimum Increment : 1
Recommended Increment : 1
. RegionIndex1 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Indices of the found regions from Regions1.
. RegionIndex2 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Indices of the found regions from Regions2.
Result
The operator FindNeighbors returns the value TRUE if the input is not empty. The behavior in case of empty
input (no input regions available) is set via the operator SetSystem(’noObjectResult’,<Result>).

HALCON 8.0.2
848 CHAPTER 12. REGIONS

The behavior in case of empty region (the region is the empty set) is set via SetSystem
(’emptyRegionResult’,<Result>). If necessary an exception handling is raised.
Parallelization Information
FindNeighbors is reentrant and processed without parallelization.
Possible Predecessors
Threshold, Regiongrowing, Connection
See also
SpatialRelation, SelectRegionSpatial, ExpandRegion, DistanceTransform,
Interjacent, Boundary
Module
Foundation

[out] VARIANT Index HRegionX.GetRegionIndex ([in] long Row,


[in] long Column )
void HOperatorSetX.GetRegionIndex ([in] IHObjectX Regions,
[in] VARIANT Row, [in] VARIANT Column, [out] VARIANT Index )

Index of all regions containing a given pixel.


The operator GetRegionIndex returns the index of all regions in Regions (range of values: 1 to n) containing
the test pixel (Row,Column), i.e.:

|Regions[n] ∩ {(Row, Column)}| =


6 ∅

The returned indices can be used, e.g., in SelectObj to select the regions containing the test pixel.
Attention
If the regions overlap more than one region might contain the pixel. In this case all these regions are returned. If
no region contains the indicated pixel the empty tuple (= no region) is returned.
Parameter
. Regions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
Regions to be examined.
. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; long / VARIANT
Line index of the test pixel.
Default Value : 100
(lin)
. Column (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; long / VARIANT
Column index of the test pixel.
Default Value : 100
(lin)
. Index (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Index of the regions containing the test pixel.
Complexity √
If F is the area of the region and N is the number of regions the mean runtime complexity is O(ln( F ) ∗ N ).
Result
The operator GetRegionIndex returns the value TRUE if the parameters are correct. The be-
havior in case of empty input (no input regions available) is set via the operator SetSystem
(’noObjectResult’,<Result>). If necessary an exception handling is raised.
Parallelization Information
GetRegionIndex is reentrant and processed without parallelization.
Possible Predecessors
Threshold, Regiongrowing, Connection
See also
GetMbutton, GetMposition, TestRegionPoint

HALCON/COM Reference Manual, 2008-5-13


12.3. FEATURES 849

Alternatives
SelectRegionPoint
Module
Foundation

[out] VARIANT Thickness HRegionX.GetRegionThickness


([out] VARIANT Histogramm )
void HOperatorSetX.GetRegionThickness ([in] IHObjectX Region,
[out] VARIANT Thickness, [out] VARIANT Histogramm )

Access the thickness of a region along the main axis.


The operator GetRegionThickness calculates the thickness of the regions along the main axis (see
EllipticAxis) for each pixel of the section. The thickness at one point on the main axis is defined as the
distance between the intersections of the contour with the plumb on the main axis in the respective point which are
the furthest apart. Additionally the operator GetRegionThickness returns the Histogramm of the thick-
nesses of the region. The length of the histogram corresponds to the largest occurring thickness in the observed
region.
Attention
Only one region may be passed. If the region has several connection components, only the first one is investigated.
All other components are ignored.
Parameter
. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
Region to be analysed.
. Thickness (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Thickness of the region along its main axis.
. Histogramm (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Histogram of the thickness of the region along its main axis.
Result
The operator GetRegionThickness returns the value TRUE if exactly one region is passed. The
behavior in case of empty input (no input regions available) is set via the operator SetSystem
(’noObjectResult’,<Result>).
Parallelization Information
GetRegionThickness is reentrant and processed without parallelization.
Possible Predecessors
SobelAmp, Threshold, Connection, SelectShape, SelectObj
See also
CopyObj, EllipticAxis
Module
Foundation

[out] VARIANT Distance HRegionX.HammingDistance


([in] HRegionX Regions2, [out] VARIANT Similarity )
void HOperatorSetX.HammingDistance ([in] IHObjectX Regions1,
[in] IHObjectX Regions2, [out] VARIANT Distance, [out] VARIANT Similarity )

Hamming distance between two regions.


The operator HammingDistance returns the hamming distance between two regions, i.e., the number of pixels
of the regions which are different (Distance), i.e., the number of pixels contained in one region but not in the
other:

Distance = |Regions1 ∩ Regions2| + |Regions2 ∩ Regions1|

HALCON 8.0.2
850 CHAPTER 12. REGIONS

The parameter Similarity describes the similarity between the two regions based on the hamming distance
Distance:

Distance
Similarity = 1 −
|Regions1| + |Regions2|

If both regions are empty Similarity is set to 0. The regions with the same index from both input parameters
are always compared.
Attention
In both input parameters the same number of regions must be passed.
Parameter
. Regions1 (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Regions to be examined.
. Regions2 (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Comparative regions.
. Distance (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Hamming distance of two regions.
Restriction : (Distance ≥ 0)
. Similarity (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Similarity of two regions.
Restriction : ((0 ≤ Similarity) ∧ (Similarity ≤ 1))
Complexity√
If F is the area of a region the mean runtime complexity is O( F ).
Result
hamming_distance returns the value TRUE if the number of objects in both parameters is the same and is
not 0. The behavior in case of empty input (no input objects available) is set via the operator SetSystem
(’noObjectResult’,<Result>). The behavior in case of empty region (the region is the empty set) is
set via SetSystem(’emptyRegionResult’,<Result>). If necessary an exception handling handling is
raised.
Parallelization Information
HammingDistance is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection
See also
HammingChangeRegion
Alternatives
Intersection, Complement, AreaCenter
Module
Foundation

[out] VARIANT Distance HRegionX.HammingDistanceNorm


([in] HRegionX Regions2, [in] VARIANT Norm, [out] VARIANT Similarity )
void HOperatorSetX.HammingDistanceNorm ([in] IHObjectX Regions1,
[in] IHObjectX Regions2, [in] VARIANT Norm, [out] VARIANT Distance,
[out] VARIANT Similarity )

Hamming distance between two regions using normalization.


The operator HammingDistanceNorm returns the hamming distance between two regions, i.e., the number of
pixels of the regions which are different (Distance). Before calculating the difference the region in Regions1
is normalized onto the regions in Regions2. The result is the number of pixels contained in one region but not
in the other:

Distance = |N orm(Regions1) ∩ Regions2| + |Regions2 ∩ N orm(Regions1)|

HALCON/COM Reference Manual, 2008-5-13


12.3. FEATURES 851

The parameter Similarity describes the similarity between the two regions based on the hamming distance
Distance:

Distance
Similarity = 1 −
|N orm(Regions1)| + |Regions2|

The following types of normalization are available:

’center’: The region is moved so that both regions have the save center of gravity.

If both regions are empty Similarity is set to 0. The regions with the same index from both input parameters
are always compared.
Attention
In both input parameters the same number of regions must be passed.
Parameter

. Regions1 (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Regions to be examined.
. Regions2 (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Comparative regions.
. Norm (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Type of normalization.
Default Value : ’center’
List of values : Norm ∈ {’center’}
. Distance (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Hamming distance of two regions.
Restriction : (Distance ≥ 0)
. Similarity (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Similarity of two regions.
Restriction : ((0 ≤ Similarity) ∧ (Similarity ≤ 1))
Complexity√
If F is the area of a region the mean runtime complexity is O( F ).
Result
hamming_distance_norm returns the value TRUE if the number of objects in both parameters is the same and
is not 0. The behavior in case of empty input (no input objects available) is set via the operator SetSystem
(’noObjectResult’,<Result>). The behavior in case of empty region (the region is the empty set) is set
via SetSystem(’emptyRegionResult’,<Result>). If necessary an exception handling is raised.
Parallelization Information
HammingDistanceNorm is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection
See also
HammingChangeRegion
Alternatives
Intersection, Complement, AreaCenter
Module
Foundation

[out] VARIANT Row HRegionX.InnerCircle ([out] VARIANT Column,


[out] VARIANT Radius )
void HOperatorSetX.InnerCircle ([in] IHObjectX Regions,
[out] VARIANT Row, [out] VARIANT Column, [out] VARIANT Radius )

Largest inner circle of a region.

HALCON 8.0.2
852 CHAPTER 12. REGIONS

The operator InnerCircle determines the largest inner circle of a region. This is the biggest discrete circle
region that completely fits into the region. For this circle the center (Row, Column) and the radius (Radius) are
calculated. If the position of the circle is ambiguous, the "first possible" position (as far upper left as possible) is
returned.
The output of the procedure is chosen in such a way that it can be used as an input for the HALCON procedures
DispCircle, GenCircle, and GenEllipseContourXld.
If several regions are passed in Regions corresponding tuples are returned as output parameters. In case of an
empty input region all parameters have the value 0.0 if no other behavior was set with SetSystem.
Attention
If several inner circles are present at a region only the most upper left solution is returned.
Parameter

. Regions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Regions to be examined.
. Row (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . circle.center.y(-array) ; VARIANT ( real )
Line index of the center.
. Column (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . circle.center.x(-array) ; VARIANT ( real )
Column index of the center.
. Radius (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . circle.radius(-array) ; VARIANT ( real )
Radius of the inner circle.
Restriction : (Radius ≥ 0)
Example

read_image(Image,’fabrik’)
open_window(0,0,-1,-1,’root’,’visible’,’’,WindowHandle)
regiongrowing(Image,Seg,5,5,6,100)
select_shape(Seg,H,’area’,’and’,100,2000)
inner_circle(H,Row,Column,Radius)
gen_circle(Circles,Row,Column,Radius:)
set_draw(WindowHandle,’margin’)
disp_region(Circles,WindowHandle)

Complexity √
If F is the area of the region and R is the radius of the inner circle the runtime complexity is O( F ∗ R).
Result
The operator InnerCircle returns the value TRUE if the input is not empty. The behavior in case of empty
input (no input regions available) is set via the operator SetSystem(’noObjectResult’,<Result>), the
behavior in case of empty region is set via SetSystem(’emptyRegionResult’,<Result>). If necessary
an exception handling is raised.
Parallelization Information
InnerCircle is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection, RunlengthFeatures
Possible Successors
GenCircle, DispCircle
See also
SetShape, SelectShape, SmallestCircle
Alternatives
ErosionCircle, InnerRectangle1
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


12.3. FEATURES 853

[out] VARIANT Row1 HRegionX.InnerRectangle1 ([out] VARIANT Column1,


[out] VARIANT Row2, [out] VARIANT Column2 )
void HOperatorSetX.InnerRectangle1 ([in] IHObjectX Regions,
[out] VARIANT Row1, [out] VARIANT Column1, [out] VARIANT Row2,
[out] VARIANT Column2 )

Largest inner rectangle of a region.


The operator InnerRectangle1 determines the largest axis-parallel rectangle that fits into a region. The
rectangle is described by the coordinates of the corner pixels (Row1, Column1, Row2, Column2).
If more than one region is passed in Regions the results are stored in tuples, the index of a value in the tuple
corresponding to the index of the input region. For empty regions all parameters have the value 0 if no other
behavior was set (see SetSystem).
Parameter

. Regions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Region to be examined.
. Row1 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.origin.y(-array) ; VARIANT ( integer )
Row coordinate of the upper left corner point.
. Column1 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . .rectangle.origin.x(-array) ; VARIANT ( integer )
Column coordinate of the upper left corner point.
. Row2 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.corner.y(-array) ; VARIANT ( integer )
Row coordinate of the lower right corner point.
. Column2 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.corner.x(-array) ; VARIANT ( integer )
Column coordinate of the lower right corner point.
Result
The operator InnerRectangle1 returns the value TRUE if the input is not empty. The be-
havior in case of empty input (no input regions available) is set via the operator SetSystem
(’noObjectResult’,<Result>). The behavior in case of empty region (the region is the empty set) is
set via SetSystem(’noObjectResult’,<Result>). If necessary an exception handling is raised.
Parallelization Information
InnerRectangle1 is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection
Possible Successors
DispRectangle1, GenRectangle1
See also
SmallestRectangle1, SelectShape
Alternatives
InnerCircle
Module
Foundation

[out] VARIANT M11 HRegionX.MomentsRegion2Nd ([out] VARIANT M20,


[out] VARIANT M02, [out] VARIANT Ia, [out] VARIANT Ib )
void HOperatorSetX.MomentsRegion2Nd ([in] IHObjectX Regions,
[out] VARIANT M11, [out] VARIANT M20, [out] VARIANT M02, [out] VARIANT Ia,
[out] VARIANT Ib )

Geometric moments of regions.


The operator MomentsRegion2Nd calculates the moments (M20, M02) and the product of inertia of the axes
through the center parallel to the coordinate axes (M11). Furthermore the main axes of inertia (Ia, Ib) are
calculated.

HALCON 8.0.2
854 CHAPTER 12. REGIONS

Calculation: Z0 and S0 are the coordinates of the center of a region R with the area F . Then the moments Mij
are defined by: X
Mij = (Z0 − Z)i (S0 − S)j
(Z,S)∈R

wherein Z and S run through all pixels of the region R.


Furthermore,
M 20 + M 02
h=
2
then Ia and Ib are defined by:
p
Ia = h + h2 − M 20 ∗ M 02 + M 112

p
Ib = h − h2 − M 20 ∗ M 02 + M 112

If more than one region is passed the results are stored in tuples, the index of a value in the tuple corresponding to
the index of a region in the input.
In case of empty region all parameters have the value 0.0 if no other behavior was set (see SetSystem).
Attention

Parameter

. Regions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Regions to be examined.
. M11 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Product of inertia of the axes through the center parallel to the coordinate axes.
. M20 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Moment of 2nd order (line-dependent).
. M02 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Moment of 2nd order (column-dependent).
. Ia (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
The one main axis of inertia.
. Ib (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
The other main axis of inertia.
Complexity √
If F is the area of the region the mean runtime complexity is O( F ).
Result
The operator MomentsRegion2Nd returns the value TRUE if the input is not empty. The be-
havior in case of empty input (no input regions available) is set via the operator SetSystem
(’noObjectResult’,<Result>). The behavior in case of empty region (region is the empty set) is set
via SetSystem(’emptyRegionResult’,<Result>). If necessary an exception handling is raised.
Parallelization Information
MomentsRegion2Nd is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection
See also
EllipticAxis
Alternatives
MomentsRegion2NdInvar
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


12.3. FEATURES 855

[out] VARIANT M11 HRegionX.MomentsRegion2NdInvar ([out] VARIANT M20,


[out] VARIANT M02 )
void HOperatorSetX.MomentsRegion2NdInvar ([in] IHObjectX Regions,
[out] VARIANT M11, [out] VARIANT M20, [out] VARIANT M02 )

Geometric moments of regions.


The operator MomentsRegion2NdInvar calculates the scaled moments (M20, M02) and the procut of inertia
of the axes through the center parallel to the coordinate axes (M11).

Calculation: Z0 and S0 are the coordinates of the center of a region R with the area F . Then the moments Mij
are defined by:
1 X
Mij = 2 (Z0 − Z)i (S0 − S)j
F
(Z,S)∈R

wherein Z and S run through all pixels of the region R.

If more than one region is passed the results are stored in tuples, the index of a value in the tuple corresponding to
the index of a region in the input.
In case of empty region all parameters have the value 0.0 if no other behavior was set (see SetSystem).
Attention

Parameter

. Regions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Regions to be examined.
. M11 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Product of inertia of the axes through the center parallel to the coordinate axes.
. M20 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Moment of 2nd order (line-dependent).
. M02 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Moment of 2nd order (column-dependent).
Complexity √
If F is the area of the region the mean runtime complexity is O( F ).
Result
The operator MomentsRegion2NdInvar returns the value TRUE if the input is not empty. The
behavior in case of empty input (no input regions available) is set via the operator SetSystem
(’noObjectResult’,<Result>). The behavior in case of empty region (the region is the empty set) is
set via SetSystem(’emptyRegionResult’,<Result>). If necessary an exception handling is raised.
Parallelization Information
MomentsRegion2NdInvar is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection
See also
EllipticAxis
Alternatives
MomentsRegion2Nd
Module
Foundation

HALCON 8.0.2
856 CHAPTER 12. REGIONS

[out] VARIANT PHI1 HRegionX.MomentsRegion2NdRelInvar


([out] VARIANT PHI2 )
void HOperatorSetX.MomentsRegion2NdRelInvar
([in] IHObjectX Regions, [out] VARIANT PHI1, [out] VARIANT PHI2 )

Geometric moments of regions.


The operator MomentsRegion2NdRelInvar calculates the scaled relative moments (PHI1, PHI2).

Calculation: The moments P HI1 and P HI2 are defined by:

P HI1 = M20 + M02

P HI2 = (M20 + M02 )2 + M11


2

If more than one region is passed the results are stored in tuples, the index of a value in the tuple corresponding to
the index of a region in the input.
In case of empty region all parameters have the value 0.0 if no other behavior was set (see SetSystem).
Attention

Parameter

. Regions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Regions to be examined.
. PHI1 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Moment of 2nd order.
. PHI2 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Moment of 2nd order.
Result
The operator MomentsRegion2NdRelInvar returns the value TRUE if the input is not empty. The
behavior in case of empty input (no input regions available) is set via the operator SetSystem
(’noObjectResult’,<Result>). The behavior in case of empty region (the region is the empty set) is
set via SetSystem(’emptyRegionResult’,<Result>). If necessary an exception handling is raised.
Parallelization Information
MomentsRegion2NdRelInvar is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection
See also
EllipticAxis
Alternatives
MomentsRegion2Nd
Module
Foundation

[out] VARIANT M21 HRegionX.MomentsRegion3Rd ([out] VARIANT M12,


[out] VARIANT M03, [out] VARIANT M30 )
void HOperatorSetX.MomentsRegion3Rd ([in] IHObjectX Regions,
[out] VARIANT M21, [out] VARIANT M12, [out] VARIANT M03, [out] VARIANT M30 )

Geometric moments of regions.


The operator MomentsRegion3Rd calculates the translation-invariant central moments (M21, M12, M03, M30)
of order (p + q).

HALCON/COM Reference Manual, 2008-5-13


12.3. FEATURES 857

Calculation: x and y are the coordinates of the center of a region R with the area Z. Then the moments Mpq are
defined by: X
Mpq = M Z(xi , yi )(xi − x)p (yi − y)q
i=1
m10 m01
wherein are x = m00 and y = m00 .

If more than one region is passed the results are stored in tuples, the index of a value in the tuple corresponding to
the index of a region in the input.
In case of empty region all parameters have the value 0.0 if no other behavior was set (see SetSystem).
Attention

Parameter
. Regions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Regions to be examined.
. M21 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Moment of 3rd order (line-dependent).
. M12 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Moment of 3rd order (column-dependent).
. M03 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Moment of 3rd order (column-dependent).
. M30 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Moment of 3rd order (line-dependent).
Complexity √
If Z is the area of the region the mean runtime complexity is O( Z).
Result
The operator MomentsRegion3Rd returns the value TRUE if the input is not empty. The be-
havior in case of empty input (no input regions available) is set via the operator SetSystem
(’noObjectResult’,<Result>). The behavior in case of empty region (the region is the empty set) is
set via SetSystem(’emptyRegionResult’,<Result>). If necessary an exception handling is raised.
Parallelization Information
MomentsRegion3Rd is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection
See also
EllipticAxis
Alternatives
MomentsRegion2Nd
Module
Foundation

[out] VARIANT M21 HRegionX.MomentsRegion3RdInvar ([out] VARIANT M12,


[out] VARIANT M03, [out] VARIANT M30 )
void HOperatorSetX.MomentsRegion3RdInvar ([in] IHObjectX Regions,
[out] VARIANT M21, [out] VARIANT M12, [out] VARIANT M03, [out] VARIANT M30 )

Geometric moments of regions.


The operator MomentsRegion3RdInvar calculates the scale-invariant moments (M21, M12, M03, M30).

Calculation: Then the moments Mij are defined by:


µpq
Mpq =
µ3

HALCON 8.0.2
858 CHAPTER 12. REGIONS

wobei p + q >= 2 und µ = µ00 = m00 sind.


wherein are p + q >= 2 and µ = µ00 = m00 .

If more than one region is passed the results are stored in tuples, the index of a value in the tuple corresponding to
the index of a region in the input.
In case of empty region all parameters have the value 0.0 if no other behavior was set (see SetSystem).
Attention

Parameter
. Regions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Regions to be examined.
. M21 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Moment of 3rd order (line-dependent).
. M12 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Moment of 3rd order (column-dependent).
. M03 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Moment of 3rd order (column-dependent).
. M30 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Moment of 3rd order (line-dependent).
Complexity √
If Z is the area of the region the mean runtime complexity is O( Z).
Result
The operator MomentsRegion3RdInvar returns the value TRUE if the input is not empty. The
behavior in case of empty input (no input regions available) is set via the operator SetSystem
(’noObjectResult’,<Result>). The behavior in case of empty region (the region is the empty set) is
set via SetSystem(’emptyRegionResult’,<Result>). If necessary an exception handling is raised.
Parallelization Information
MomentsRegion3RdInvar is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection
See also
EllipticAxis
Alternatives
MomentsRegion2Nd
Module
Foundation

[out] VARIANT I1 HRegionX.MomentsRegionCentral ([out] VARIANT I2,


[out] VARIANT I3, [out] VARIANT I4 )
void HOperatorSetX.MomentsRegionCentral ([in] IHObjectX Regions,
[out] VARIANT I1, [out] VARIANT I2, [out] VARIANT I3, [out] VARIANT I4 )

Geometric moments of regions.


The operator MomentsRegionCentral calculates the central moments (I1, I2, I3, I4).
Calculation: Then the moments Ii are defined by:
I1 = µ20 µ02 − µ211
I2 = (µ30 µ03 − µ21 µ12 )2 − 4(µ30 µ12 − µ221 )(µ21 µ03 − µ212 )
I3 = µ20 (µ21 µ03 − µ212 ) − µ11 (µ30 µ03 − µ21 µ12 ) + µ02 (µ30 µ12 − µ221 )
I4 = µ230 µ302 − 6µ30 µ21 µ11 µ202 + 6µ30 µ12 µ02 (2µ211 − µ20 µ02 )
+µ30 µ03 (6µ20 µ11 µ02 − 8µ311 ) + 9µ221 µ20 µ202 − 18µ21 µ12 µ20 µ11 µ02
+6µ21 µ03 µ20 (2µ211 − µ20 µ02 ) + 9µ212 µ220 µ02 − 6µ12 µ03 µ11 µ220 + µ203 µ320

HALCON/COM Reference Manual, 2008-5-13


12.3. FEATURES 859

If more than one region is passed the results are stored in tuples, the index of a value in the tuple corresponding to
the index of a region in the input.
In case of empty region all parameters have the value 0.0 if no other behavior was set (see SetSystem).
Attention

Parameter
. Regions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Regions to be examined.
. I1 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Moment of 2nd order.
. I2 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Moment of 2nd order.
. I3 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Moment of 2nd order.
. I4 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Moment of 3rd order.
Complexity √
If Z is the area of the region the mean runtime complexity is O( Z).
Result
The operator MomentsRegionCentral returns the value TRUE if the input is not empty. The
behavior in case of empty input (no input regions available) is set via the operator SetSystem
(’noObjectResult’,<Result>). The behavior in case of empty region (the region is the empty set) is
set via SetSystem(’emptyRegionResult’,<Result>). If necessary an exception handling is raised.
Parallelization Information
MomentsRegionCentral is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection
See also
EllipticAxis
Alternatives
MomentsRegion2Nd
Module
Foundation

[out] VARIANT PSI1 HRegionX.MomentsRegionCentralInvar


([out] VARIANT PSI2, [out] VARIANT PSI3, [out] VARIANT PSI4 )
void HOperatorSetX.MomentsRegionCentralInvar
([in] IHObjectX Regions, [out] VARIANT PSI1, [out] VARIANT PSI2,
[out] VARIANT PSI3, [out] VARIANT PSI4 )

Geometric moments of regions.


The operator MomentsRegionCentralInvar calculates the moments (PSI1, PSI2, PSI3, PSI4) that are
invariant under translation and general linear transformations.
Calculation: Then the moments ψi are defined by:
I1
ψ1 =
µ4
I2
ψ2 = 1
µ 0
I3
ψ3 = 7
µ
I4
ψ4 = 1
µ 1

HALCON 8.0.2
860 CHAPTER 12. REGIONS

If more than one region is passed the results are stored in tuples, the index of a value in the tuple corresponding to
the index of a region in the input.
In case of empty region all parameters have the value 0.0 if no other behavior was set (see SetSystem).
Attention

Parameter
. Regions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Regions to be examined.
. PSI1 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Moment of 2nd order.
. PSI2 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Moment of 2nd order.
. PSI3 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Moment of 2nd order.
. PSI4 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Moment of 2nd order.
Complexity √
If Z is the area of the region the mean runtime complexity is O( Z).
Result
The operator MomentsRegionCentralInvar returns the value TRUE if the input is not empty.
The behavior in case of empty input (no input regions available) is set via the operator SetSystem
(’noObjectResult’,<Result>). The behavior in case of empty region (the region is the empty set) is
set via SetSystem(’emptyRegionResult’,<Result>). If necessary an exception handling is raised.
Parallelization Information
MomentsRegionCentralInvar is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection
See also
EllipticAxis
Alternatives
MomentsRegion2Nd
Module
Foundation

HRegionX.OrientationRegion ( )
[out] VARIANT Phi
void HOperatorSetX.OrientationRegion ([in] IHObjectX Regions,
[out] VARIANT Phi )

Orientation of a region.
The operator OrientationRegion calculates the orientation of the region. The operator is based on
EllipticAxis. In addition the point on the contour with maximal distance to the center of gravity is cal-
culated. If the column coordinate of this point is less than the column coordinate of the center of gravity the value
of π is added to the angle.
If more than one region is passed the results are stored in tuples, the index of a value in the tuple corresponding to
the index of a region in the input.
In case of empty region all parameters have the value 0.0 if no other behavior was set (see SetSystem
(’noObjectResult’,<Result>)).
Attention

HALCON/COM Reference Manual, 2008-5-13


12.3. FEATURES 861

Parameter

. Regions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Region(s) to be examined.
. Phi (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Orientation of region (arc measure).
Restriction : ((−(pi) ≤ P hi) ∧ (P hi < pi))
Complexity√
If F is the area of a region the mean runtime complexity is O( F ).
Result
The operator OrientationRegion returns the value TRUE if the input is not empty. The be-
havior in case of empty input (no input regions available) is set via the operator SetSystem
(’noObjectResult’,<Result>). The behavior in case of empty region (the region is the empty set) is
set via SetSystem(’emptyRegionResult’,<Result>). If necessary an exception handling is raised.
Parallelization Information
OrientationRegion is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection
Possible Successors
DispArrow
See also
MomentsRegion2Nd, LineOrientation
Alternatives
EllipticAxis, SmallestRectangle2
Module
Foundation

HRegionX.Rectangularity ( )
[out] VARIANT Rectangularity
void HOperatorSetX.Rectangularity ([in] IHObjectX Regions,
[out] VARIANT Rectangularity )

Shape factor for the rectangularity of a region.


The operator Rectangularity calculates the rectangularity of the input regions.
To determine the rectangularity, first a rectangle is computed that has the same first and second order moments
as the input region. The computation of the rectangularity measure is finally based on the area of the difference
between the computed rectangle and the input region normalized with respect to the area of the rectangle.
For rectangles Rectangularity returns the value 1. The more the input region deviates from a perfect rectan-
gle, the less the returned value for Rectangularity will be.
In case of an empty region the operator Rectangularity returns the value 0 (if no other behavior was set (see
SetSystem)). If more than one region is passed the numerical values of the rectangularity are stored in a tuple,
the position of a value in the tuple corresponding to the position of the region in the input tuple.
Attention
For input regions which orientation cannot be computed by using second order moments (as it is the case for
square regions, for example), the returned Rectangularity is underestimated by up to 10% depending on the
orientation of the input region.
Parameter

. Regions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Region(s) to be examined.
. Rectangularity (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Rectangularity of the input region(s).
Restriction : ((0 ≤ Rectangularity) ∧ (Rectangularity ≤ 1.0))

HALCON 8.0.2
862 CHAPTER 12. REGIONS

Result
The operator Rectangularity returns the value TRUE if the input is not empty. The be-
havior in case of empty input (no input regions available) is set via the operator SetSystem
(’noObjectResult’,<Result>). The behavior in case of empty region (the region is the empty set) is
set via SetSystem(’emptyRegionResult’,<Result>). If necessary an exception handling is raised.
Parallelization Information
Rectangularity is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection
See also
Contlength, AreaCenter, SelectShape
Alternatives
Circularity, Compactness, Convexity, Eccentricity
References
P. L. Rosin: “Measuring rectangularity”; Machine Vision and Applications; vol. 11; pp. 191-196; Springer-Verlag,
1999.
Module
Foundation

[out] VARIANT Distance HRegionX.Roundness ([out] VARIANT Sigma,


[out] VARIANT Roundness, [out] VARIANT Sides )
void HOperatorSetX.Roundness ([in] IHObjectX Regions,
[out] VARIANT Distance, [out] VARIANT Sigma, [out] VARIANT Roundness,
[out] VARIANT Sides )

Shape factors from contour.


The operator Roundness examines the distance between the contour and the center of the area. In particular
the mean distance (Distance), the deviation from the mean distance (Sigma) and two shape features derived
therefrom are determined. Roundness is the relation between mean value and standard deviation, and Sides
indicates the number of polygon pieces if a regular polygon is concerned.
The contour for calculating the features is determined depending on the global neighborhood (see SetSystem).
Calculation:
If p is the center of the area, p_i the pixels and F the area of the contour.
1 X
Distance = ||p − p_i||
F
1 X 2
Sigma2 = (||p − p_i|| − Distance)
F
Sigma
Roundness = 1 −
Distance
 0.4724
Distance
Sides = 1.4111
Sigma

If more than one region is passed the results are stored in tuples, the index of a value in the tuple corresponding to
the index of a region in the input.
In case of empty region all parameters have the value 0.0 if no other behavior was set (see SetSystem).
Attention

HALCON/COM Reference Manual, 2008-5-13


12.3. FEATURES 863

Parameter
. Regions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Region(s) to be examined.
. Distance (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Mean distance from the center.
Restriction : (Distance ≥ 0.0)
. Sigma (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Standard deviation of Distance.
Restriction : (Sigma ≥ 0.0)
. Roundness (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Shape factor for roundness.
Restriction : (Roundness ≤ 1.0)
. Sides (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Number of polygon sides.
Restriction : (Sides ≥ 0)
Complexity√
If F is the area of a region the mean runtime complexity is O( F ).
Result
The operator Roundness returns the value TRUE if the input is not empty. The behavior in case of empty
input (no input regions available) is set via the operator SetSystem(’noObjectResult’,<Result>),
the behavior in case of empty region is set via SetSystem(’emptyRegionResult’,<Result>). If
necessary an exception handling is raised.
Parallelization Information
Roundness is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection
See also
Contlength
Alternatives
Compactness
References
R. Haralick, L. Shapiro “Computer and Robot Vision” Addison-Wesley, 1992, pp. 61
Module
Foundation

[out] VARIANT Foreground HRegionX.RunlengthDistribution


([out] VARIANT Background )
void HOperatorSetX.RunlengthDistribution ([in] IHObjectX Region,
[out] VARIANT Foreground, [out] VARIANT Background )

Distribution of runs needed for runlength encoding of a region.


The operator RunlengthDistribution calculates the distribution of the runs of a region of the fore- and
background. The frequency of the occurrence of a certain length is calculated. Runs of infinite length are not
counted. Therefore the background are the holes of the region. As many values are passed as set by the maximum
length of fore- or background, respectively. The length of both tuples usually differs. The first entry of the tuples is
always 0 (no runs of the length 0). If there are no blanks the empty tuple is passed at Background. Analogously
the empty tuple is passed in case of an empty region at Foreground.
Parameter
. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
Region to be examined.
. Foreground (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Length distribution of the region (foreground).

HALCON 8.0.2
864 CHAPTER 12. REGIONS

. Background (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )


Length distribution of the background.
Complexity
If n is the number of runs of the region the runtime complexity is O(n).
Result
The operator RunlengthDistribution returns the value TRUE if the input is not empty. The
behavior in case of empty input (no input regions available) is set via the operator SetSystem
(’noObjectResult’,<Result>). If more than one region is passed an exception handling is raised.
Parallelization Information
RunlengthDistribution is reentrant and processed without parallelization.
Possible Predecessors
Threshold, SelectObj
See also
RunlengthFeatures
Alternatives
RunlengthFeatures
Module
Foundation

[out] VARIANT NumRuns HRegionX.RunlengthFeatures


([out] VARIANT KFactor, [out] VARIANT LFactor, [out] VARIANT MeanLength,
[out] VARIANT Bytes )
void HOperatorSetX.RunlengthFeatures ([in] IHObjectX Regions,
[out] VARIANT NumRuns, [out] VARIANT KFactor, [out] VARIANT LFactor,
[out] VARIANT MeanLength, [out] VARIANT Bytes )

Characteristic values for runlength coding of regions.


The operator RunlengthFeatures calculates for every input region from Regions the number of runs neces-
sary for storing this region with the aid of runlength coding. Furthermore the so-called "‘K-factor"’ is determined,
which indicates by how much the number of runs differs from the ideal of the square in which this value is 1.0.
The K-factor (KFactor) is calculated according to the formula:

NumRuns
KFactor = √
Area

wherein Area indicates the area of the region. It should be noted that the K-factor can be smaller than 1.0 (in case
of long horizontal regions).
The L-factor (LFactor) indicates the mean number of runs for each line index occurring in the region.
MeanLength indicates the mean length of the runs. The parameter Bytes indicates how many bytes are neces-
sary for coding the region with runlengths.
Attention
All features calculated by the operator RunlengthFeatures are not rotation invariant because the runlength
coding depends on the direction. The operator RunlengthFeatures does not serve for calculating shape
features but for controlling and analysing the efficiency of the runlength coding.
Parameter
. Regions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Regions to be examined.
. NumRuns (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Number of runs.
Restriction : (0 ≤ N umRuns)
. KFactor (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Storing factor in relation to a square.
Restriction : (0 ≤ KF actor)

HALCON/COM Reference Manual, 2008-5-13


12.3. FEATURES 865

. LFactor (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )


Mean number of runs per line.
Restriction : (0 ≤ LF actor)
. MeanLength (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Mean length of runs.
Restriction : (0 ≤ M eanLength)
. Bytes (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Number of bytes necessary for coding the region.
Restriction : (0 ≤ Bytes)
Complexity
The mean runtime complexity is O(1).
Result
The operator RunlengthFeatures returns the value TRUE if the input is not empty. If necessary an exception
handling is raised.
Parallelization Information
RunlengthFeatures is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection, RunlengthFeatures
See also
RunlengthFeatures, RunlengthDistribution
Module
Foundation

[out] HRegionX DestRegions HRegionX.SelectRegionPoint ([in] long Row,


[in] long Column )
void HOperatorSetX.SelectRegionPoint ([in] IHObjectX Regions,
[out] HUntypedObjectX DestRegions, [in] VARIANT Row, [in] VARIANT Column )

Choose all regions containing a given pixel.


The operator SelectRegionPoint selects all regions from Regions containing the test pixel
(Row,Column), i.e.:

|Regions[n] ∩ {(Row, Column)}| = 1

Attention
If the regions overlap more than one region might contain the pixel. In this case all these regions are returned. If
no region contains the indicated pixel the empty tuple (= no region) is returned.
Parameter
. Regions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
Regions to be examined.
. DestRegions (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX
All regions containing the test pixel.
. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; long / VARIANT
Line index of the test pixel.
Default Value : 100
. Column (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; long / VARIANT
Column index of the test pixel.
Default Value : 100
Example

read_image(Image,’fabrik’)
open_window(0,0,-1,-1,’root’,’visible’,’’,WindowHandle)

HALCON 8.0.2
866 CHAPTER 12. REGIONS

disp_image(Image)
regiongrowing(Image,Seg,3,3,5,0)
set_color(WindowHandle,’red’)
set_draw(WindowHandle,’margin’)
Button := 1
while (Button = 1)
fwrite_string(FileId,’Select the region with the mouse (End right button)’)
fnew_line(FileId)
get_mbutton(WindowHandle,Row,Column,Button)
select_region_point(Seg,Single,Row,Column)
disp_region(Single,WindowHandle)
endwhile

Complexity √
If F is the area of the region and N is the number of regions, the mean runtime complexity is O(ln( F ) ∗ N ).
Result
The operator SelectRegionPoint returns the value TRUE if the parameters are correct. The
behavior in case of empty input (no input regions available) is set via the operator SetSystem
(’noObjectResult’,<Result>). If necessary an exception handling is raised.
Parallelization Information
SelectRegionPoint is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection
See also
GetMbutton, GetMposition
Alternatives
TestRegionPoint
Module
Foundation

[out] VARIANT RegionIndex1 HRegionX.SelectRegionSpatial


([in] HRegionX Regions2, [in] String Direction, [out] VARIANT RegionIndex2 )
void HOperatorSetX.SelectRegionSpatial ([in] IHObjectX Regions1,
[in] IHObjectX Regions2, [in] VARIANT Direction, [out] VARIANT RegionIndex1,
[out] VARIANT RegionIndex2 )

Pose relation of regions.


The operator SelectRegionSpatial chooses the regions from Regions2 which are sufficient for the neigh-
boring relation Direction. The regions to be examined have to be passed in Regions1 or Regions2, re-
spectively. Regions1 can have three different states:

• Regions1 is empty:
In this case all regions in Regions2 are permutatively checked for neighborhood.
• Regions1 consists of one region:
The regions of Regions1 are compared to all regions in Regions2.
• Regions1 consists of the same number of regions as Regions2:
The regions at the n-th position in Regions1 and Regions2 are each checked for a neighboring relation.

Possible values for Direction are:

’left’: Regions2 is left of Regions1


’right’: Regions2 is right of Regions1
’above’: Regions2 is above Regions1

HALCON/COM Reference Manual, 2008-5-13


12.3. FEATURES 867

’below’: Regions2 is below Regions1

The operator SelectRegionSpatial calculates the centers of the regions to be compared and decides ac-
cording to the angle between the center straight lines and the x axis whether the direction relation is fulfilled. The
relation is fulfilled within the area of -45 degree to +45 degree around the coordinate axes. Thus, the direction
relation can be understood in such a way that the center of the second region must be located left (or right, above,
below) of the center of the first region. The indices of the regions fulfilling the direction relation are located at the
n-th position in RegionIndex1 and RegionIndex2, i.e., the region with the index RegionIndex2[n] has
the indicated relation with the region with the index RegionIndex1[n]. Access to regions via the index can be
obtained via the operator CopyObj.
Attention

Parameter
. Regions1 (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Starting regions
. Regions2 (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Comparative regions
. Direction (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Desired neighboring relation.
Default Value : ’left’
List of values : Direction ∈ {’left’, ’right’, ’above’, ’below’}
. RegionIndex1 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Indices in the input tuples (Regions1 or Regions2), respectively.
. RegionIndex2 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Indices in the input tuples (Regions1 or Regions2), respectively.
Result
The operator SelectRegionSpatial returns the value TRUE if Regions2 is not empty. The behav-
ior in case of empty parameter Regions2 (no input regions available) is set via the operator SetSystem
(’noObjectResult’,<Result>). The behavior in case of empty region (the region is the empty set) is set
via SetSystem(’emptyRegionResult’,<Result>). If necessary an exception handling is raised.
Parallelization Information
SelectRegionSpatial is reentrant and processed without parallelization.
Possible Predecessors
Threshold, Regiongrowing, Connection
See also
SpatialRelation, FindNeighbors, CopyObj, ObjToInteger
Alternatives
AreaCenter, Intersection
Module
Foundation

[out] HRegionX SelectedRegions HRegionX.SelectShape


([in] VARIANT Features, [in] String Operation, [in] VARIANT Min,
[in] VARIANT Max )
void HOperatorSetX.SelectShape ([in] IHObjectX Regions,
[out] HUntypedObjectX SelectedRegions, [in] VARIANT Features,
[in] VARIANT Operation, [in] VARIANT Min, [in] VARIANT Max )

Choose regions with the aid of shape features.


The operator SelectShape chooses regions according to shape. For each input region from Regions the
indicated features (Features) are calculated. If each (Operation = ’and’) or at least one (Operation = ’or’)
of the calculated features is within the default limits (Min,Max) the region is adapted into the output (duplicated).
Condition: M ini ≤ F eaturei (Object) ≤ M axi
Possible values for Features:

HALCON 8.0.2
868 CHAPTER 12. REGIONS

’area’: Area of the object


’row’: Row index of the center
’column’: Column index of the center
’width’: Width of the region
’height’: Height of the region
’row1’: Row index of upper left corner
’column1’: Column index of upper left corner
’row2’: Row index of lower right corner
’column2’: Column index of lower right corner
’circularity’: Circularity (see Circularity)
’compactness’: Compactness (see Compactness)
’contlength’: Total length of contour (see operator Contlength)
’convexity’: Convexity (see Convexity)
’rectangularity’: Rectangularity (see Rectangularity)
’ra’: Main radius of the equivalent ellipse (see EllipticAxis)
’rb’: Secondary radius of the equivalent ellipse (see EllipticAxis)
’phi’: Orientation of the equivalent ellipse (see EllipticAxis)
’anisometry:’ Anisometry (see Eccentricity)
’bulkiness:’ Bulkiness (see operator Eccentricity)
’struct_factor:’ Structur Factor (see operator Eccentricity)
’outer_radius’: Radius of smallest surrounding circle (see SmallestCircle)
’inner_radius’: Radius of largest inner circle (see InnerCircle)
’inner_width’: Width of the largest axis-parallel rectangle that fits into the region (see InnerRectangle1)
’inner_height’: Height of the largest axis-parallel rectangle that fits into the region (see InnerRectangle1)
’dist_mean’: Mean distance from the region border to the center (see operator Roundness)
’dist_deviation:’ Deviation of the distance from the region border from the center (see operator Roundness)
’roundness’: Roundness (see operator Roundness)
’num_sides’: Number of polygon sides (see operator Roundness)
’connect_num’: Number of connection components (see operator ConnectAndHoles)
’holes_num’: Number of holes (see operator ConnectAndHoles)
’max_diameter’: Maximum diameter of the region (see operator DiameterRegion)
’orientation’: Orientation of the region (see operator OrientationRegion)
’euler_number’: Euler number (see operator EulerNumber)
’rect2_phi’: Orientation of the smallest surrounding rectangle (see operator SmallestRectangle2)
’rect2_len1’: Half the length of the smallest surrounding rectangle (see operator SmallestRectangle2)
’rect2_len2’: Half the width of the smallest surrounding rectangle (see operator SmallestRectangle2)
’moments_m11’: Geometric moments of the region (see operator MomentsRegion2Nd)
’moments_m20’: Geometric moments of the region (see operator MomentsRegion2Nd)
’moments_m02’: Geometric moments of the region (see operator MomentsRegion2Nd)
’moments_ia’: Geometric moments of the region (see operator MomentsRegion2Nd)
’moments_ib’: Geometric moments of the region (see operator MomentsRegion2Nd)
’moments_m11_invar’: Geometric moments of the region (see operator MomentsRegion2NdInvar)
’moments_m20_invar’: Geometric moments of the region (see operator MomentsRegion2NdInvar)
’moments_m02_invar’: Geometric moments of the region (see operator MomentsRegion2NdInvar)
’moments_phi1’: Geometric moments of the region (see operator MomentsRegion2NdRelInvar)

HALCON/COM Reference Manual, 2008-5-13


12.3. FEATURES 869

’moments_phi2’: Geometric moments of the region (see operator MomentsRegion2NdRelInvar)


’moments_m21’: Geometric moments of the region (see operator MomentsRegion3Rd)
’moments_m12’: Geometric moments of the region (see operator MomentsRegion3Rd)
’moments_m03’: Geometric moments of the region (see operator MomentsRegion3Rd)
’moments_m30’: Geometric moments of the region (see operator MomentsRegion3Rd)
’moments_m21_invar’: Geometric moments of the region (see operator MomentsRegion3RdInvar)
’moments_m12_invar’: Geometric moments of the region (see operator MomentsRegion3RdInvar)
’moments_m03_invar’: Geometric moments of the region (see operator MomentsRegion3RdInvar)
’moments_m30_invar’: Geometric moments of the region (see operator MomentsRegion3RdInvar)
’moments_i1’: Geometric moments of the region (see operator MomentsRegionCentral)
’moments_i2’: Geometric moments of the region (see operator MomentsRegionCentral)
’moments_i3’: Geometric moments of the region (see operator MomentsRegionCentral)
’moments_i4’: Geometric moments of the region (see operator MomentsRegionCentral)
’moments_psi1’: Geometric moments of the region (see operator MomentsRegionCentralInvar)
’moments_psi2’: Geometric moments of the region (see operator MomentsRegionCentralInvar)
’moments_psi3’: Geometric moments of the region (see operator MomentsRegionCentralInvar)
’moments_psi4’: Geometric moments of the region (see operator MomentsRegionCentralInvar)

If only one feature (Features) is used the value of Operation is meaningless. Several features are processed
in the sequence in which they are entered.
Attention

Parameter

. Regions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX


Regions to be examined.
. SelectedRegions (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX
Regions fulfilling the condition.
. Features (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Shape features to be checked.
Default Value : ’area’
List of values : Features ∈ {’area’, ’row’, ’column’, ’width’, ’height’, ’row1’, ’column1’, ’row2’,
’column2’, ’circularity’, ’compactness’, ’contlength’, ’convexity’, ’rectangularity’, ’ra’, ’rb’, ’phi’,
’anisometry’, ’bulkiness’, ’struct_factor’, ’outer_radius’, ’inner_radius’, ’inner_width’, ’inner_height’,
’max_diameter’, ’dist_mean’, ’dist_deviation’, ’roundness’, ’num_sides’, ’orientation’, ’connect_num’,
’holes_num’, ’euler_number’, ’rect2_phi’, ’rect2_len1’, ’rect2_len2’, ’moments_m11’, ’moments_m20’,
’moments_m02’, ’moments_ia’, ’moments_ib’, ’moments_m11_invar’, ’moments_m20_invar’,
’moments_m02_invar’, ’moments_phi1’, ’moments_phi2’, ’moments_m21’, ’moments_m12’,
’moments_m03’, ’moments_m30’, ’moments_m21_invar’, ’moments_m12_invar’, ’moments_m03_invar’,
’moments_m30_invar’, ’moments_i1’, ’moments_i2’, ’moments_i3’, ’moments_i4’, ’moments_psi1’,
’moments_psi2’, ’moments_psi3’, ’moments_psi4’}
. Operation (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Linkage type of the individual features.
Default Value : ’and’
List of values : Operation ∈ {’and’, ’or’}
. Min (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( integer, real, string )
Lower limits of the features or ’min’.
Default Value : 150.0
Typical range of values : 0.0 ≤ Min ≤ 0.0
Minimum Increment : 0.001
Recommended Increment : 1.0

HALCON 8.0.2
870 CHAPTER 12. REGIONS

. Max (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( integer, real, string )


Upper limits of the features or ’max’.
Default Value : 99999.0
Typical range of values : 0.0 ≤ Max ≤ 0.0
Minimum Increment : 0.001
Recommended Increment : 1.0
Restriction : (M ax ≥ M in)
Example

/* where are the eyes of the ape ? */


read_image(Image’affe’)
threshold(Image,S1,160,255)
connection(S1,S2)
select_shape(S2,Eyes,[’area’,’anisometry’],’and’,[500,1.0],[50000,1.7])
disp_region(Eyes,WindowHandle)

Result
The operator SelectShape returns the value TRUE if the input is not empty. The behavior in case of empty
input (no input objects available) is set via the operator SetSystem(’noObjectResult’,<Result>).
The behavior in case of empty region (the region is the empty set) is set via SetSystem
(’emptyRegionResult’,<Result>). If necessary an exception handling is raised.
Parallelization Information
SelectShape is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection, RunlengthFeatures
Possible Successors
SelectShape, SelectGray, ShapeTrans, ReduceDomain, CountObj
See also
AreaCenter, Circularity, Compactness, Contlength, Convexity, Rectangularity,
EllipticAxis, Eccentricity, InnerCircle, SmallestCircle, SmallestRectangle1,
SmallestRectangle2, InnerRectangle1, Roundness, ConnectAndHoles, DiameterRegion,
OrientationRegion, MomentsRegion2Nd, MomentsRegion2NdInvar,
MomentsRegion2NdRelInvar, MomentsRegion3Rd, MomentsRegion3RdInvar,
MomentsRegionCentral, MomentsRegionCentralInvar, SelectObj
Alternatives
SelectShapeStd
Module
Foundation

[out] HRegionX SelectedRegions HRegionX.SelectShapeProto


([in] HRegionX Pattern, [in] VARIANT Feature, [in] VARIANT Min,
[in] VARIANT Max )
void HOperatorSetX.SelectShapeProto ([in] IHObjectX Regions,
[in] IHObjectX Pattern, [out] HUntypedObjectX SelectedRegions,
[in] VARIANT Feature, [in] VARIANT Min, [in] VARIANT Max )

Choose regions having a certain relation to each other.


The operator SelectShapeProto selects regions based on certain relations between the regions. Every region
from Regions is compared to the union of regions from Pattern. The limits (Min and Max) are specified
absolutely or in percent (0..100), depending on the feature. Possible values for Feature are:

’distance_dilate’ The minimum distance in the maximum norm from the edge of Pattern to the edge of every
region from Regions is determined (see DistanceRrMinDil).

HALCON/COM Reference Manual, 2008-5-13


12.3. FEATURES 871

’distance_contour’ The minimum Euclidean distance from the edge of Pattern to the edge of every region
from Regions is determined. (see DistanceRrMin).
’distance_center’ The Euclidean distance from the center of Pattern to the center of every region from
Regions is determined.
’covers’ It is examined how well the region Pattern fits into the regions from Regions. If there is no shift
so that Pattern is a subset of Regions the overlap is 0. If Pattern corresponds to the region after a
corresponding shift the overlap is 100. Otherwise the area of the opening of Regions with Pattern is put
into relation with the area of Regions (in percent).
’fits’ It is examined whether Pattern can be shifted in such a way that it fits in Regions. If this is possible the
corresponding region is copied from Regions. The parameters Min and Max are ignored.
’overlaps_abs’ The area of the intersection of Pattern and every region in Regions is computed.
’overlaps_rel’ The area of the intersection of Pattern and every region in Regions is computed. The relative
overlap is the ratio of the area of the intersection and the are of the respective region in Regions (in percent).

Attention

Parameter
. Regions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Regions to be examined.
. Pattern (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Region compared to Regions.
. SelectedRegions (output iconic) . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Regions fulfilling the condition.
. Feature (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Shape features to be checked.
Default Value : ’covers’
List of values : Feature ∈ {’distance_center’, ’distance_dilate’, ’distance_contour’, ’covers’, ’fits’,
’overlaps_abs’, ’overlaps_rel’}
. Min (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Lower border of feature.
Default Value : 50.0
Suggested values : Min ∈ {0.0, 1.0, 5.0, 10.0, 20.0, 30.0, 50.0, 60.0, 70.0, 80.0, 90.0, 95.0, 99.0, 100.0,
200.0, 400.0}
Minimum Increment : 0.001
Recommended Increment : 5.0
. Max (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Upper border of the feature.
Default Value : 100.0
Suggested values : Max ∈ {0.0, 10.0, 20.0, 30.0, 50.0, 60.0, 70.0, 80.0, 90.0, 95.0, 99.0, 100.0, 200.0, 300.0,
400.0}
Minimum Increment : 0.001
Recommended Increment : 5.0
Result
The operator SelectShapeProto returns the value TRUE if the input is not empty. The be-
havior in case of empty input (no input regions available) is set via the operator SetSystem
(’noObjectResult’,<Result>). The behavior in case of empty region (the region is the empty set) is
set via SetSystem(’emptyRegionResult’,<Result>). If necessary an exception handling is raised.
Parallelization Information
SelectShapeProto is reentrant and processed without parallelization.
Possible Predecessors
Connection, DrawRegion, GenCircle, GenRectangle1, GenRectangle2, GenEllipse
Possible Successors
SelectGray, ShapeTrans, ReduceDomain, CountObj
See also
Opening, Erosion1, DistanceRrMinDil, DistanceRrMin

HALCON 8.0.2
872 CHAPTER 12. REGIONS

Alternatives
SelectShape
Module
Foundation

[out] HRegionX SelectedRegions HRegionX.SelectShapeStd


([in] String Shape, [in] double Percent )
void HOperatorSetX.SelectShapeStd ([in] IHObjectX Regions,
[out] HUntypedObjectX SelectedRegions, [in] VARIANT Shape,
[in] VARIANT Percent )

Select regions of a given shape.


The operator SelectShapeStd compares the shape of the given regions with default shapes. If the region has
a similar shape it is adopted into the output. Possible values for Shape are:

’max_area’ The largest region is selected.


’rectangle1’ The surrounding rectangle parallel to the coordinate axes is determined via the operator
SmallestRectangle1. If the area difference in percent is larger than Percent the region is adopted.
’rectangle2’ The smallest surrounding rectangle with any orientation is determined via the operator
SmallestRectangle2. If the area difference in percent is larger than Percent the region is adopted.
Note that as a more robust alternative the operator SelectShape with Feature set to ’rectangularity’
can be used instead.

Parameter

. Regions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Input regions to be selected.
. SelectedRegions (output iconic) . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Regions with desired shape.
. Shape (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Shape features to be checked.
Default Value : ’max_area’
List of values : Shape ∈ {’max_area’, ’rectangle1’, ’rectangle2’}
. Percent (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Similarity measure.
Default Value : 70.0
Suggested values : Percent ∈ {10.0, 30.0, 50.0, 60.0, 70.0, 80.0, 90.0, 95.0, 100.0}
Typical range of values : 0.0 ≤ Percent ≤ 0.0(lin)
Minimum Increment : 0.1
Recommended Increment : 10.0
Parallelization Information
SelectShapeStd is reentrant and processed without parallelization.
Possible Predecessors
Threshold, Regiongrowing, Connection, SmallestRectangle1, SmallestRectangle2
See also
SmallestRectangle1, SmallestRectangle2, Rectangularity
Alternatives
Intersection, Complement, AreaCenter, SelectShape
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


12.3. FEATURES 873

[out] VARIANT Row HRegionX.SmallestCircle ([out] VARIANT Column,


[out] VARIANT Radius )
void HOperatorSetX.SmallestCircle ([in] IHObjectX Regions,
[out] VARIANT Row, [out] VARIANT Column, [out] VARIANT Radius )

Smallest surrounding circle of a region.


The operator SmallestCircle determines the smallest surrounding circle of a region, i.e., the circle with the
smallest area of all circles containing the region. For this circle the center (Row,Column) and the radius (Radius)
are calculated. The procedure is applied when, for example, the location and size of circular objects (e.g., coins)
which, however, are not homogeneous inside or have broken edges due to bad segmentation, has to be determined.
The output of the procedure is selected in such a way that it can be used as input for the HALCONprocedures
DispCircle and GenCircle.
If several regions are passed in Regions corresponding tuples are returned as output parameter. In case of empty
region all parameters have the value 0.0 if no other behavior was set (see SetSystem).
Attention
Internally, the calculation is based on the center coordinates of the region pixels. To take into account that pixels
are not just infinitely small points but have a certain area, the calculated radius is enlarged by 0.5 before it is
returned in Radius. This, in most cases, gives acceptable results. However, in the worst case (pixel diagonal) this
enlargement is not sufficient. If one wants √to ensure that the border of the input region completely lies within the
circle, one had to enlarge
√ the radius by 1/ 2 instead of 0.5. Consequently, the value returned in Radius must
be corrected by 1/ 2 − 0.5. However, this would also be only an upper bound, i.e., the circle with the corrected
radius would be slightly too big in most cases.
Parameter
. Regions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Regions to be examined.
. Row (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . circle.center.y(-array) ; VARIANT ( real )
Line index of the center.
. Column (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . circle.center.x(-array) ; VARIANT ( real )
Column index of the center.
. Radius (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . circle.radius(-array) ; VARIANT ( real )
Radius of the surrounding circle.
Restriction : (Radius ≥ 0)
Example

read_image(Image,’fabrik’)
open_window(0,0,-1,-1,’root’,’visible’,’’,WindowHandle)
regiongrowing(Image,Seg,5,5,6,100:)
select_shape(Seg,H,’area’,’and’,100,2000)
smallest_circle(H,Row,Column,Radius)
gen_circle(Circles,Row,Column,Radius)
set_draw(WindowHandle,’margin’)
disp_region(Circles,WindowHandle)

Complexity √
If F is the area of the region, then the mean runtime complexity is O( F .
Result
The operator SmallestCircle returns the value TRUE if the input is not empty. The be-
havior in case of empty input (no input regions available) is set via the operator SetSystem
(’noObjectResult’,<Result>). The behavior in case of empty region (the region is the empty set) is
set via SetSystem(’emptyRegionResult’,<Result>). If necessary an exception handling is raised.
Parallelization Information
SmallestCircle is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection, RunlengthFeatures

HALCON 8.0.2
874 CHAPTER 12. REGIONS

Possible Successors
GenCircle, DispCircle
See also
SetShape, SelectShape, InnerCircle
Alternatives
EllipticAxis, SmallestRectangle1, SmallestRectangle2
Module
Foundation

[out] VARIANT Row1 HRegionX.SmallestRectangle1 ([out] VARIANT Column1,


[out] VARIANT Row2, [out] VARIANT Column2 )
void HOperatorSetX.SmallestRectangle1 ([in] IHObjectX Regions,
[out] VARIANT Row1, [out] VARIANT Column1, [out] VARIANT Row2,
[out] VARIANT Column2 )

Surrounding rectangle parallel to the coordinate axes.


The operator SmallestRectangle1 calculates the surrounding rectangle of all input regions (parallel
to the coordinate axes). The surrounding rectangle is described by the coordinates of the corner pixels
(Row1,Column1,Row2,Column2)
If more than one region is passed in Regions, the results are stored in tuples, the index of a value in the tuple
corresponding to the index of a region in the input. In case of empty region all parameters have the value 0 if no
other behavior was set (see SetSystem).
Attention
In case of empty region the result of Row1,Column1, Row2 and Column2 (all are 0) can lead to confusion.
Parameter
. Regions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Regions to be examined.
. Row1 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.origin.y(-array) ; VARIANT ( integer )
Line index of upper left corner point.
. Column1 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . .rectangle.origin.x(-array) ; VARIANT ( integer )
Column index of upper left corner point.
. Row2 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.corner.y(-array) ; VARIANT ( integer )
Line index of lower right corner point.
. Column2 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.corner.x(-array) ; VARIANT ( integer )
Column index of lower right corner point.
Complexity
If F is the area of the region the mean runtime complexity is O(sqrt(F )).
Result
The operator SmallestRectangle1 returns the value TRUE if the input is not empty. The be-
havior in case of empty input (no input regions available) is set via the operator SetSystem
(’noObjectResult’,<Result>). The behavior in case of empty region (the region is the empty set) is
set via SetSystem(’emptyRegionResult’,<Result>). If necessary an exception handling is raised.
Parallelization Information
SmallestRectangle1 is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection, RunlengthFeatures
Possible Successors
DispRectangle1, GenRectangle1
See also
SelectShape
Alternatives
SmallestRectangle2, AreaCenter

HALCON/COM Reference Manual, 2008-5-13


12.3. FEATURES 875

Module
Foundation

[out] VARIANT Row HRegionX.SmallestRectangle2 ([out] VARIANT Column,


[out] VARIANT Phi, [out] VARIANT Length1, [out] VARIANT Length2 )
void HOperatorSetX.SmallestRectangle2 ([in] IHObjectX Regions,
[out] VARIANT Row, [out] VARIANT Column, [out] VARIANT Phi,
[out] VARIANT Length1, [out] VARIANT Length2 )

Smallest surrounding rectangle with any orientation.


The operator SmallestRectangle2 determines the smallest surrounding rectangle of a region, i.e., the rect-
angle with the smallest area of all rectangles containing the region. For this rectangle the center, the inclination
and the two radii are calculated.
The procedure is applied when, for example, the location of a scenery of several regions (e.g., printed text on a rect-
angular paper or in rectangular print (justified lines)) must be found. The parameters of SmallestRectangle2
are chosen in such a way that they can be used directly as input for the HALCON-procedures DispRectangle2
and GenRectangle2.
If more than one region is passed in Regions the results are stored in tuples, the index of a value in the tuple
corresponding to the index of a region in the input. In case of empty region all parameters have the value 0.0 if no
other behavior was set (see SetSystem).
Attention

Parameter

. Regions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Regions to be examined.
. Row (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle2.center.y(-array) ; VARIANT ( real )
Line index of the center.
. Column (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle2.center.x(-array) ; VARIANT ( real )
Column index of the center.
. Phi (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle2.angle.rad(-array) ; VARIANT ( real )
Orientation of the surrounding rectangle (arc measure)
Restriction : (((−(pi)/2) < P hi) ∧ (P hi ≤ (pi/2)))
. Length1 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle2.hwidth(-array) ; VARIANT ( real )
First radius (half length) of the surrounding rectangle.
Restriction : (Length1 ≥ 0.0)
. Length2 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle2.hheight(-array) ; VARIANT ( real )
Second radius (half width) of the surrounding rectangle.
Restriction : ((Length2 ≥ 0.0) ∧ (Length2 ≤ Length1))
Example

read_image(Image,’fabrik’)
open_window(0,0,-1,-1,’root’,’visible’,’’,WindowHandle)
regiongrowing(Image,Seg,5,5,6,100)
smallest_rectangle2(Seg,Row,Column,Phi,Length1,Length2)
gen_rectangle2(Rectangle,Row,Column,Phi,Length1,Length2)
set_draw(WindowHandle,’margin’)
disp_region(Rectangle,WindowHandle)

Complexity
If F is
√ the area of the region and N is the number of supporting points of the convex hull, the runtime complexity
is O( F + N 2 ).

HALCON 8.0.2
876 CHAPTER 12. REGIONS

Result
The operator SmallestRectangle2 returns the value TRUE if the input is not empty. The be-
havior in case of empty input (no input regions available) is set via the operator SetSystem
(’noObjectResult’,<Result>). The behavior in case of empty region (the region is the empty set) is
set via SetSystem(’emptyRegionResult’,<Result>). If necessary an exception handling is raised.
Parallelization Information
SmallestRectangle2 is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection, RunlengthFeatures
Possible Successors
DispRectangle2, GenRectangle2
See also
SmallestCircle, SetShape
Alternatives
EllipticAxis, SmallestRectangle1
Module
Foundation

[out] VARIANT RegionIndex1 HRegionX.SpatialRelation


([in] HRegionX Regions2, [in] long Percent, [out] VARIANT RegionIndex2,
[out] VARIANT Relation1, [out] VARIANT Relation2 )
void HOperatorSetX.SpatialRelation ([in] IHObjectX Regions1,
[in] IHObjectX Regions2, [in] VARIANT Percent, [out] VARIANT RegionIndex1,
[out] VARIANT RegionIndex2, [out] VARIANT Relation1,
[out] VARIANT Relation2 )

Pose relation of regions with regard to the coordinate axes.


The operator SpatialRelation selects regions located by Percent percent “left”, “right”, “above” or “be-
low” other regions. Regions1 and Regions2 contain the regions to be compared. Regions1 can have three
states:

• Regions1 is empty:
In this case all regions in Regions2 are permutatively checked for neighborhood.
• Regions1 consists of one region:
The regions of Regions1 are compared to all regions in Regions2.
• Regions1 consists of the same number of regions as Regions2:
Regions1 and Regions2 are checked for a neighboring relation.

The percentage Percent is interpreted in such a way that the area of the second region has to be located really
left/right or above/below the region margins of the first region by at least Percent percent. The indices of
the regions that fulfill at least one of these conditions are then located at the n-th position in the output parame-
ters RegionIndex1 and RegionIndex2. Additionally the output parameters Relation1 and Relation2
contain at the n-th position the type of relation of the region pair (RegionIndex1[n], RegionIndex2[n]),
i.e., region with index RegionIndex2[n] has the relation Relation1[n] and Relation2[n] with region with
index RegionIndex1[n].
Possible values for Relation1 and Relation2 are:

Relation1: ’left’, ’right’ or ”


Relation2: ’above’, ’below’ or ”

In RegionIndex1 and RegionIndex2 the indices of the regions in the tuples of the input regions (Regions1
or Regions2), respectively, are entered as image identifiers. Access to chosen regions via the index can be
obtained by the operator CopyObj.

HALCON/COM Reference Manual, 2008-5-13


12.4. GEOMETRIC-TRANSFORMATIONS 877

Attention

Parameter

. Regions1 (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Starting regions.
. Regions2 (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Comparative regions.
. Percent (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Percentage of the area of the comparative region which must be located left/right or above/below the region
margins of the starting region.
Default Value : 50
Suggested values : Percent ∈ {0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100}
Typical range of values : 0 ≤ Percent ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 10
Restriction : ((0 ≤ P ercent) ∧ (P ercent ≤ 100))
. RegionIndex1 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Indices of the regions in the tuple of the input regions which fulfill the pose relation.
. RegionIndex2 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Indices of the regions in the tuple of the input regions which fulfill the pose relation.
. Relation1 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( string )
Horizontal pose relation in which RegionIndex2[n] stands with RegionIndex1[n].
. Relation2 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( string )
Vertical pose relation in which RegionIndex2[n] stands with RegionIndex1[n].
Result
The operator SpatialRelation returns the value TRUE if Regions2 is not empty and Percent is cor-
rectly choosen. The behavior in case of empty parameter Regions2 (no input regions available) is set via the
operator SetSystem(’noObjectResult’,<Result>). The behavior in case of empty region (the region
is the empty set) is set via SetSystem(’emptyRegionResult’,<Result>). If necessary an exception
handling is raised.
Parallelization Information
SpatialRelation is reentrant and processed without parallelization.
Possible Predecessors
Threshold, Regiongrowing, Connection
See also
SelectRegionSpatial, FindNeighbors, CopyObj, ObjToInteger
Alternatives
AreaCenter, Intersection
Module
Foundation

12.4 Geometric-Transformations
[out] HRegionX RegionAffineTrans HRegionX.AffineTransRegion
([in] HHomMat2dX HomMat2D, [in] String Interpolate )
[out] HRegionX RegionAffineTrans HHomMat2dX.AffineTransRegion
([in] HRegionX Region, [in] String Interpolate )
void HOperatorSetX.AffineTransRegion ([in] IHObjectX Region,
[out] HUntypedObjectX RegionAffineTrans, [in] VARIANT HomMat2D,
[in] VARIANT Interpolate )

Apply an arbitrary affine 2D transformation to regions.

HALCON 8.0.2
878 CHAPTER 12. REGIONS

AffineTransRegion applies an arbitrary affine 2D transformation, i.e., scaling, rotation, translation, and slant
(skewing), to the regions given in Region and returns the transformed regions in RegionAffineTrans.
The affine transformation is described by the homogeneous transformation matrix given in HomMat2D, which
can be created using the operators HomMat2dIdentity, HomMat2dScale, HomMat2dRotate,
HomMat2dTranslate, etc., or be the result of operators like VectorAngleToRigid.
The components of the homogeneous transformation matrix are interpreted as follows: The row coordinate of the
image corresponds to x and the col coordinate corresponds to y of the coordinate system in which the transforma-
tion matrix was defined. This is necessary to obtain a right-handed coordinate system for the image. In particular,
this assures that rotations are performed in the correct direction. Note that the (x,y) order of the matrices quite
naturally corresponds to the usual (row,column) order for coordinates in the image.
The parameter Interpolate determines whether the transformation is to be done by using interpolation in-
ternally. This can lead to smoother region boundaries, especially if regions are enlarged. However, the runtime
increases drastically.
Attention
AffineTransRegion in general is not reversible (clipping and discretization during rotation and scaling).
The used coordinate system is the same as in AffineTransPixel. This means that in fact not HomMat2D
is applied but a modified version. Therefore, applying AffineTransRegion corresponds to the following
chain of transformations, which is applied to each point (Row_i, Col_i) of the region (input and output pixels as
homogeneous vectors):
       
RowT rans_i 1 0 −0.5 1 0 +0.5 Row_i
 ColT rans_i  =  0 1 −0.5  · HomMat2D ·  0 1 +0.5  ·  Col_i 
1 0 0 1 0 0 1 1

As an effect, you might get unexpected results when creating affine transformations based on coordinates that
are derived from the region, e.g., by operators like AreaCenter. For example, if you use this operator to
calculate the center of gravity of a rotationally symmetric region and then rotate the region around this point using
HomMat2dRotate, the resulting region will not lie on the original one. In such a case, you can compensate this
effect by applying the following translations to HomMat2D before using it in AffineTransRegion:
hom_mat2d_translate(HomMat2D, 0.5, 0.5, HomMat2DTmp)
hom_mat2d_translate_local(HomMat2DTmp, -0.5, -0.5, HomMat2DAdapted)
affine_trans_region(Region, RegionAffinTrans, HomMat2DAdapted, ’false’)

Parameter
. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Region(s) to be rotated and scaled.
. RegionAffineTrans (output iconic) . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Transformed output region(s).
Number of elements : (RegionAf f ineT rans = Region)
. HomMat2D (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )
Input transformation matrix.
. Interpolate (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Should the transformation be done using interpolation?
Default Value : ’false’
List of values : Interpolate ∈ {’true’, ’false’}
Result
If the matrix HomMat2D represents an affine transformation (i.e., not a projective transformation),
AffineTransRegion returns TRUE. The behavior in case of empty input (no regions given) can be set
via SetSystem(’noObjectResult’,<Result>), the behavior in case of an empty input region via
SetSystem(’emptyRegionResult’,<Result>), and the behavior in case of an empty result region via
SetSystem(’storeEmptyRegion’,<true/false>). If necessary, an exception handling is raised.
Parallelization Information
AffineTransRegion is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
HomMat2dIdentity, HomMat2dScale, HomMat2dTranslate, HomMat2dInvert,
HomMat2dRotate

HALCON/COM Reference Manual, 2008-5-13


12.4. GEOMETRIC-TRANSFORMATIONS 879

Possible Successors
SelectShape
See also
AffineTransImage
Alternatives
MoveRegion, MirrorRegion, ZoomRegion
Module
Foundation

[out] HRegionX RegionMirror HRegionX.MirrorRegion


([in] String RowColumn, [in] long WidthHeight )
void HOperatorSetX.MirrorRegion ([in] IHObjectX Region,
[out] HUntypedObjectX RegionMirror, [in] VARIANT RowColumn,
[in] VARIANT WidthHeight )

Reflect a region about an axis parallel to the x- or y-axis.


MirrorRegion reflects a region about an axis parallel to the x- respectively y-axis (parameter RowColumn).
The parameter WidthHeight specifies two times the coordinate of the axis of symmetry. Hence, if Region
has been extracted from an image and should be mirrored in a way such as if it had been extracted from a mir-
rored version of this image, WidthHeight corresponds to to one of the dimensions of this image (according to
RowColumn).
Parameter

. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Region(s) to be reflected.
. RegionMirror (output iconic) . . . . . . . . . . . . . . . . . . . . . . . .region(-array) ; HRegionX / HUntypedObjectX
Reflected region(s).
Number of elements : (RegionM irror = Region)
. RowColumn (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Axis of symmetry.
Default Value : ’row’
List of values : RowColumn ∈ {’column’, ’row’}
. WidthHeight (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Twice the coordinate of the axis of symmetry.
Default Value : 512
Suggested values : WidthHeight ∈ {128, 256, 512, 525, 768, 1024}
Typical range of values : 1 ≤ WidthHeight ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 1
Restriction : (W idthHeight > 0)
Parallelization Information
MirrorRegion is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Connection, Regiongrowing, Pouring
Possible Successors
SelectShape, DispRegion
See also
ZoomRegion
Alternatives
AffineTransRegion
Module
Foundation

HALCON 8.0.2
880 CHAPTER 12. REGIONS

[out] HRegionX RegionMoved HRegionX.MoveRegion ([in] long Row,


[in] long Column )
void HOperatorSetX.MoveRegion ([in] IHObjectX Region,
[out] HUntypedObjectX RegionMoved, [in] VARIANT Row, [in] VARIANT Column )

Translate a region.
MoveRegion translates the input regions by the vector given by (Row, Column). If necessary, the resulting
regions are clipped with the current image format.
Parameter

. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Region(s) to be moved.
. RegionMoved (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Translated region(s).
Number of elements : (RegionM oved = Region)
. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; long / VARIANT
Row coordinate of the vector by which the region is to be moved.
Default Value : 30
Suggested values : Row ∈ {-128, -64, -32, -16, -10, -8, -4, -2, -1, 0, 1, 2, 4, 5, 8, 10, 16, 32, 64, 128}
Typical range of values : -512 ≤ Row ≤ -512(lin)
Minimum Increment : 1
Recommended Increment : 10
. Column (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; long / VARIANT
Row coordinate of the vector by which the region is to be moved.
Default Value : 30
Suggested values : Column ∈ {-128, -64, -32, -16, -10, -8, -4, -2, -1, 0, 1, 2, 4, 5, 8, 10, 16, 32, 64, 128}
Typical range of values : -512 ≤ Column ≤ -512(lin)
Minimum Increment : 1
Recommended Increment : 10
Complexity
Let F be the area of the input region. Then the runtime complexity is O(F ).
Result
MoveRegion always returns the value TRUE. The behavior in case of empty input (no regions given) can be
set via SetSystem(’noObjectResult’,<Result>), the behavior in case of an empty input region via
SetSystem(’emptyRegionResult’,<Result>), and the behavior in case of an empty result region via
SetSystem(’storeEmptyRegion’,<true/false>). If necessary, an exception handling is raised.
Parallelization Information
MoveRegion is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Connection, Regiongrowing, Pouring
Possible Successors
SelectShape, DispRegion
See also
AffineTransImage, MirrorRegion, ZoomRegion
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


12.4. GEOMETRIC-TRANSFORMATIONS 881

[out] HRegionX PolarTransRegion HRegionX.PolarTransRegion


([in] VARIANT Row, [in] VARIANT Column, [in] double AngleStart,
[in] double AngleEnd, [in] VARIANT RadiusStart, [in] VARIANT RadiusEnd,
[in] long Width, [in] long Height, [in] String Interpolation )
void HOperatorSetX.PolarTransRegion ([in] IHObjectX Region,
[out] HUntypedObjectX PolarTransRegion, [in] VARIANT Row,
[in] VARIANT Column, [in] VARIANT AngleStart, [in] VARIANT AngleEnd,
[in] VARIANT RadiusStart, [in] VARIANT RadiusEnd, [in] VARIANT Width,
[in] VARIANT Height, [in] VARIANT Interpolation )

Transform a region within an annular arc to polar coordinates.


PolarTransRegion transforms a Region within the annular arc specified by the center point (Row, Column),
the radii RadiusStart and RadiusEnd and the angles AngleStart and AngleEnd to its polar coordinate
version in a virtual image of the dimensions Width × Height.
The polar transformation is a change of the coordinate system. Instead of a row and a column coordinate, each
point’s position is expressed by its radius r (i.e. the distance to the center point Row, Column) and the angle φ
between the column axis (through the center point) and the line from the center point towards the point. Note that
this transformation is not affine.
The coordinate (0, 0) in the output region always corresponds to the point in the input region that is specified by
RadiusStart and AngleStart. Analogously, the coordinate (Height − 1, Width − 1) corresponds to the
point in the input region that is specified by RadiusEnd and AngleEnd. In the usual mode (AngleStart
< AngleEnd and RadiusStart < RadiusEnd), the polar transformation is performed in the mathemati-
cally positive orientation (counterclockwise). Furthermore, points with smaller radii lie in the upper part of the
output region. By suitably exchanging the values of these parameters (e.g., AngleStart > AngleEnd or
RadiusStart > RadiusEnd), any desired orientation of the output region can be achieved.
The angles can be chosen from all real numbers. Center point and radii can be real as well. However, if they are
both integers and the difference of RadiusEnd and RadiusStart equals Height−1, calculation will be sped
up through an optimized routine.
The radii and angles are inclusive, which means that the first row of the virtual target image contains the circle
with radius RadiusStart and the last row contains the circle with radius RadiusEnd. For complete circles,
where the difference between AngleStart and AngleEnd equals 2π (360 degrees), this also means that the
first column of the target image will be the same as the last.
1
To avoid this, do not make this difference 2π, but 2π(1 − Width ) degrees instead.
The parameter Interpolation is used to select the interpolation method ’bilinear’ or ’nearest_neighbor’.
Setting Interpolation to ’bilinear’ leads to smoother region boundaries, especially if regions are enlarged.
However, the runtime increases significantly.
If more than one region is passed in Region, their polar transformations are computed individually and stored
as a tuple in PolarTransRegion. Please note that the indices of an input region and its transformation only
correspond if the system variable ’store_empty_regions’ is set to ’true’ (see SetSystem). Otherwise empty
output regions are discarded and the length of the input tuple Region is most likely not equal to the length of the
output tuple PolarTransRegion.
Attention
If Width or Height are chosen greater than the dimensions of the current image, the system variable
’clip_region’ should be set to ’false’ (see SetSystem). Otherwise, an output region that does not lie within
the dimensions of the current image can produce an error message.
Parameter

. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Input region.
. PolarTransRegion (output iconic) . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Output region.

HALCON 8.0.2
882 CHAPTER 12. REGIONS

. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )


Row coordinate of the center of the arc.
Default Value : 256
Suggested values : Row ∈ {0, 16, 32, 64, 128, 240, 256, 480, 512}
Typical range of values : 0 ≤ Row ≤ 0
Restriction : ((Row ≥ −131068) ∧ (Row ≤ 131068))
. Column (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Column coordinate of the center of the arc.
Default Value : 256
Suggested values : Column ∈ {0, 16, 32, 64, 128, 256, 320, 512, 640}
Typical range of values : 0 ≤ Column ≤ 0
Restriction : ((Column ≥ −131068) ∧ (Column ≤ 131068))
. AngleStart (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Angle of the ray to be mapped to column coordinate 0 of PolarTransRegion.
Default Value : 0.0
Suggested values : AngleStart ∈ {0.0, 0.78539816, 1.57079632, 3.141592654, 6.2831853,
12.566370616}
Typical range of values : -6.2831853 ≤ AngleStart ≤ -6.2831853
. AngleEnd (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Angle of the ray to be mapped to column coordinate Width − 1 of PolarTransRegion.
Default Value : 6.2831853
Suggested values : AngleEnd ∈ {0.0, 0.78539816, 1.57079632, 3.141592654, 6.2831853, 12.566370616}
Typical range of values : -6.2831853 ≤ AngleEnd ≤ -6.2831853
. RadiusStart (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Radius of the circle to be mapped to row coordinate 0 of PolarTransRegion.
Default Value : 0
Suggested values : RadiusStart ∈ {0, 16, 32, 64, 100, 128, 256, 512}
Typical range of values : 0 ≤ RadiusStart ≤ 0
. RadiusEnd (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Radius of the circle to be mapped to row coordinate Height − 1 of PolarTransRegion.
Default Value : 100
Suggested values : RadiusEnd ∈ {0, 16, 32, 64, 100, 128, 256, 512}
Typical range of values : 0 ≤ RadiusEnd ≤ 0
. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; long / VARIANT
Width of the virtual output image.
Default Value : 512
Suggested values : Width ∈ {256, 320, 512, 640, 800, 1024}
Typical range of values : 0 ≤ Width ≤ 0
. Height (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; long / VARIANT
Height of the virtual output image.
Default Value : 512
Suggested values : Height ∈ {240, 256, 480, 512, 600, 1024}
Typical range of values : 0 ≤ Height ≤ 0
. Interpolation (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Interpolation method for the transformation.
Default Value : ’nearest_neighbor’
List of values : Interpolation ∈ {’nearest_neighbor’, ’bilinear’}
Parallelization Information
PolarTransRegion is reentrant and automatically parallelized (on tuple level).
See also
PolarTransImage, PolarTransImageExt, PolarTransImageInv, PolarTransRegionInv,
PolarTransContourXld, PolarTransContourXldInv
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


12.4. GEOMETRIC-TRANSFORMATIONS 883

[out] HRegionX XYTransRegion HRegionX.PolarTransRegionInv


([in] VARIANT Row, [in] VARIANT Column, [in] double AngleStart,
[in] double AngleEnd, [in] VARIANT RadiusStart, [in] VARIANT RadiusEnd,
[in] long WidthIn, [in] long HeightIn, [in] long Width, [in] long Height,
[in] String Interpolation )
void HOperatorSetX.PolarTransRegionInv ([in] IHObjectX PolarRegion,
[out] HUntypedObjectX XYTransRegion, [in] VARIANT Row, [in] VARIANT Column,
[in] VARIANT AngleStart, [in] VARIANT AngleEnd, [in] VARIANT RadiusStart,
[in] VARIANT RadiusEnd, [in] VARIANT WidthIn, [in] VARIANT HeightIn,
[in] VARIANT Width, [in] VARIANT Height, [in] VARIANT Interpolation )

Transform a region in polar coordinates back to cartesian coordinates.


PolarTransRegionInv transforms the polar coordinate representation of a region, stored in PolarRegion,
back onto an annular arc in cartesian coordinates, described by the radii RadiusStart and RadiusEnd and the
angles AngleStart and AngleEnd with the center point located at (Row, Column). All of these values can
be chosen as real numbers. In addition, the dimensions of the virtual image containing the region PolarRegion
must be given in WidthIn and HeightIn. WidthIn−1 is the column coordinate corresponding to AngleEnd
and HeightIn − 1 is the row coordinate corresponding to RadiusEnd. AngleStart and RadiusStart
correspond to column and row coordinate 0. Furthermore, the dimensions Width and Height of the virtual
output image containing the transformed region XYTransRegion are required.
The angles and radii are inclusive, which means that the row coordinate 0 in PolarRegion will be mapped
onto a a circle with a distance of RadiusStart pixels from the specified center and the row with the coordinate
HeightIn − 1 will be mapped onto a circle of radius RadiusEnd. This applies to AngleStart, AngleEnd,
and WidthIn in an analogous way. If the width of the input region PolarRegion corresponds to an angle
interval greater than 2π, the region is cropped such that length of this interval is 2π.
The parameter Interpolation is used to select the interpolation method ’bilinear’ or ’nearest_neighbor’.
Setting Interpolation to ’bilinear’ leads to smoother region boundaries, especially if regions are enlarged.
However, the runtime increases significantly.
PolarTransRegionInv is the inverse function of PolarTransRegion.
The call sequence:
polar_trans_region(Region, PolarRegion, Row, Column, rad(360), 0, 0,
Radius, Width, Height, ’nearest_neighbor’)
polar_trans_region_inv(PolarRegion, XYTransRegion, Row, Column, rad(360),
0, 0, Radius, Width, Height, Width, Height, ’nearest_neighbor’)
returns the region Region, restricted to the circle around (Row, Column) with radius Radius, as its output
region XYTransRegion.
If more than one region is passed in PolarRegion, their cartesian transformations are computed individually
and stored as a tuple in XYTransRegion. Please note that the indices of an input region and its transformation
only correspond if the system variable ’store_empty_regions’ is set to ’false’ (see SetSystem). Otherwise empty
output regions are discarded and the length of the input tuple PolarRegion is most likely not equal to the length
of the output tuple XYTransRegion.
Attention
If Width or Height are chosen greater than the dimensions of the current image, the system variable
’clip_region’ should be set to ’false’ (see SetSystem). Otherwise, an output region that does not lie within
the dimensions of the current image can produce an error message.
Parameter

. PolarRegion (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Input region.
. XYTransRegion (output iconic) . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Output region.

HALCON 8.0.2
884 CHAPTER 12. REGIONS

. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )


Row coordinate of the center of the arc.
Default Value : 256
Suggested values : Row ∈ {0, 16, 32, 64, 128, 240, 256, 480, 512}
Typical range of values : 0 ≤ Row ≤ 0
Restriction : ((Row ≥ −131068) ∧ (Row ≤ 131068))
. Column (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Column coordinate of the center of the arc.
Default Value : 256
Suggested values : Column ∈ {0, 16, 32, 64, 128, 256, 320, 512, 640}
Typical range of values : 0 ≤ Column ≤ 0
Restriction : ((Column ≥ −131068) ∧ (Column ≤ 131068))
. AngleStart (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Angle of the ray to map the column coordinate 0 of PolarRegion to.
Default Value : 0.0
Suggested values : AngleStart ∈ {0.0, 0.78539816, 1.57079632, 3.141592654, 6.2831853}
Typical range of values : -6.2831853 ≤ AngleStart ≤ -6.2831853
. AngleEnd (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Angle of the ray to map the column coordinate WidthIn − 1 of PolarRegion to.
Default Value : 6.2831853
Suggested values : AngleEnd ∈ {0.0, 0.78539816, 1.57079632, 3.141592654, 6.2831853}
Typical range of values : -6.2831853 ≤ AngleEnd ≤ -6.2831853
. RadiusStart (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Radius of the circle to map the row coordinate 0 of PolarRegion to.
Default Value : 0
Suggested values : RadiusStart ∈ {0, 16, 32, 64, 100, 128, 256, 512}
Typical range of values : 0 ≤ RadiusStart ≤ 0
. RadiusEnd (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Radius of the circle to map the row coordinate HeightIn − 1 of PolarRegion to.
Default Value : 100
Suggested values : RadiusEnd ∈ {0, 16, 32, 64, 100, 128, 256, 512}
Typical range of values : 0 ≤ RadiusEnd ≤ 0
. WidthIn (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; long / VARIANT
Width of the virtual input image.
Default Value : 512
Suggested values : WidthIn ∈ {256, 320, 512, 640, 800, 1024}
Typical range of values : 0 ≤ WidthIn ≤ 0
. HeightIn (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; long / VARIANT
Height of the virtual input image.
Default Value : 512
Suggested values : HeightIn ∈ {240, 256, 480, 512, 600, 1024}
Typical range of values : 0 ≤ HeightIn ≤ 0
. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; long / VARIANT
Width of the virtual output image.
Default Value : 512
Suggested values : Width ∈ {256, 320, 512, 640, 800, 1024}
Typical range of values : 0 ≤ Width ≤ 0
. Height (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; long / VARIANT
Height of the virtual output image.
Default Value : 512
Suggested values : Height ∈ {240, 256, 480, 512, 600, 1024}
Typical range of values : 0 ≤ Height ≤ 0
. Interpolation (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Interpolation method for the transformation.
Default Value : ’nearest_neighbor’
List of values : Interpolation ∈ {’nearest_neighbor’, ’bilinear’}
Parallelization Information
PolarTransRegionInv is reentrant and automatically parallelized (on tuple level).

HALCON/COM Reference Manual, 2008-5-13


12.4. GEOMETRIC-TRANSFORMATIONS 885

See also
PolarTransImage, PolarTransImageExt, PolarTransImageInv, PolarTransRegion,
PolarTransContourXld, PolarTransContourXldInv
Module
Foundation

[out] HRegionX TransRegions HRegionX.ProjectiveTransRegion


([in] HHomMat2dX HomMat2D, [in] String Interpolation )
[out] HRegionX TransRegions HHomMat2dX.ProjectiveTransRegion
([in] HRegionX Regions, [in] String Interpolation )
void HOperatorSetX.ProjectiveTransRegion ([in] IHObjectX Regions,
[out] HUntypedObjectX TransRegions, [in] VARIANT HomMat2D,
[in] VARIANT Interpolation )

Apply a projective transformation to a region.


ProjectiveTransRegion applies the projective transformation specified by the homogeneous matrix
HomMat2D on the regions in Regions and returns the transformed regions in TransRegions.
For creation and interpretation details of this matrix see also ProjectiveTransImage.
If ’clip_region’ is set to its default value ’true’ by SetSystem(’clipRegion’, ’true’) or if the transfor-
mation is degenerated and thus produces infinite regions, the output region is clipped by the rectangle with upper
left corner (0, 0) and lower right corner (’width’, ’height’), where ’width’ and ’height’ are system variables (see
also GetSystem). If ’clip_region’ is ’false’, the output region is not clipped except by the maximum supported
coordinate size MAX_FORMAT. This may result in extremely memory and time intensive computations, so use
with care.
Parameter
. Regions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Input regions.
. TransRegions (output iconic) . . . . . . . . . . . . . . . . . . . . . . . .region(-array) ; HRegionX / HUntypedObjectX
Output regions.
. HomMat2D (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )
Homogeneous projective transformation matrix.
. Interpolation (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Interpolation method for the transformation.
Default Value : ’bilinear’
List of values : Interpolation ∈ {’nearest_neighbor’, ’bilinear’}
Parallelization Information
ProjectiveTransRegion is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
VectorToProjHomMat2d, HomVectorToProjHomMat2d, ProjMatchPointsRansac,
HomMat3dProject
See also
ProjectiveTransImage, ProjectiveTransImageSize, ProjectiveTransContourXld,
ProjectiveTransPoint2D, ProjectiveTransPixel
Module
Foundation

[out] HRegionX Transposed HRegionX.TransposeRegion ([in] long Row,


[in] long Column )
void HOperatorSetX.TransposeRegion ([in] IHObjectX Region,
[out] HUntypedObjectX Transposed, [in] VARIANT Row, [in] VARIANT Column )

Reflect a region about a point.

HALCON 8.0.2
886 CHAPTER 12. REGIONS

TransposeRegion reflects a region about a point. The fixed point is given by Column and Row. The image
P 0 of a point P is determined by the following requirement:
If P = S, then P 0 = S, i.e., the point S is the fixed point of the mapping. If P 6= S, S is the center point of a line
segment connecting P and P 0 . Therefore, the following equations result:

x + x0
Column =
2
y + y0
Row = .
2

If Row and Column are set to the origin, the in morphology often used transposition results. Hence
TransposeRegion is often used to reflect (transpose) a structuring element.
Parameter

. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Region to be reflected.
. Transposed (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Transposed region.
. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; long / VARIANT
Row coordinate of the reference point.
Default Value : 0
Suggested values : Row ∈ {0, 64, 128, 256, 512}
Typical range of values : 0 ≤ Row ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 1
. Column (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; long / VARIANT
Column coordinate of the reference point.
Default Value : 0
Suggested values : Column ∈ {0, 64, 128, 256, 512}
Typical range of values : 0 ≤ Column ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 1
Complexity
Let F be the area of the input region. Then the runtime complexity for one region is

O( F ) .

Result
TransposeRegion returns TRUE if all parameters are correct. The behavior in case of empty or no input region
can be set via:

• no region: SetSystem(’noObjectResult’,<RegionResult>)
• empty region: SetSystem(’emptyRegionResult’,<RegionResult>)

Otherwise, an exception is raised.


Parallelization Information
TransposeRegion is reentrant and automatically parallelized (on tuple level).
Possible Successors
ReduceDomain, SelectShape, AreaCenter, Connection
See also
Dilation1, Opening, Closing
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


12.5. SETS 887

[out] HRegionX RegionZoom HRegionX.ZoomRegion ([in] double ScaleWidth,


[in] double ScaleHeight )
void HOperatorSetX.ZoomRegion ([in] IHObjectX Region,
[out] HUntypedObjectX RegionZoom, [in] VARIANT ScaleWidth,
[in] VARIANT ScaleHeight )

Zoom a region.
ZoomRegion enlarges or reduces the regions given in Region in the x- and y-direction by the given scale factors
ScaleWidth and ScaleHeight.
Parameter

. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Region(s) to be zoomed.
. RegionZoom (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Zoomed region(s).
Number of elements : (RegionZoom = Region)
. ScaleWidth (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; double / VARIANT
Scale factor in x-direction.
Default Value : 2.0
Suggested values : ScaleWidth ∈ {0.25, 0.5, 1.0, 2.0, 3.0}
Typical range of values : 0.0 ≤ ScaleWidth ≤ 0.0(lin)
Minimum Increment : 0.01
Recommended Increment : 0.5
. ScaleHeight (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; double / VARIANT
Scale factor in y-direction.
Default Value : 2.0
Suggested values : ScaleHeight ∈ {0.25, 0.5, 1.0, 2.0, 3.0}
Typical range of values : 0.0 ≤ ScaleHeight ≤ 0.0(lin)
Minimum Increment : 0.01
Recommended Increment : 0.5
Parallelization Information
ZoomRegion is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Connection, Regiongrowing, Pouring
Possible Successors
SelectShape, DispRegion
See also
ZoomImageSize, ZoomImageFactor
Module
Foundation

12.5 Sets
HRegionX.Complement ( )
[out] HRegionX RegionComplement
void HOperatorSetX.Complement ([in] IHObjectX Region,
[out] HUntypedObjectX RegionComplement )

Return the complement of a region.


Complement determines the complement of the input region(s).
If the system flag ’clip_region’ is ’true’, which is the default, the difference of the largest image processed so far
(see ResetObjDb) and the input region is returned.
If the system flag ’clip_region’ is ’false’ (see SetSystem), the resluting region would be infinitely large. To avoid
this, the complement is done only virtually by setting the complement flag of Region to TRUE. For succeeding

HALCON 8.0.2
888 CHAPTER 12. REGIONS

operations the de Morgan laws are applied while calculating results. Using Complement with ’clip_region’
set to ’false’ makes sense only to avoid fringe effects, e.g., if the area of interest is bigger or smaller than the
image. For the latter case, the clipping would be set explicitly. If there is no reason to use the operator with
’clip_region’=’false’ but you need the flag for other operations of your program, it is recommended to temporarilly
set the system flag to’true’ and change it back to ’false’ after applying Complement. Otherwise, negative regions
may result from succeeding operations.
Parameter
. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Input region(s).
. RegionComplement (output iconic) . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Complemented regions.
Number of elements : (RegionComplement = Region)
Result
Complement always returns the value TRUE. The behavior in case of empty input (no regions given) can be set
via SetSystem(’noObjectResult’,<Result>) and the behavior in case of an empty input region via
SetSystem(’emptyRegionResult’,<Result>). If necessary, an exception handling is raised.
Parallelization Information
Complement is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Connection, Regiongrowing, Pouring, ClassNdimNorm
Possible Successors
SelectShape
See also
Difference, Union1, Union2, Intersection, ResetObjDb, SetSystem
Module
Foundation

[out] HRegionX RegionDifference HRegionX.Difference ([in] HRegionX Sub )


void HOperatorSetX.Difference ([in] IHObjectX Region,
[in] IHObjectX Sub, [out] HUntypedObjectX RegionDifference )

Calculate the difference of two regions.


Difference calculates the set-theoretic difference of two regions:

(Regions in Region) − (Regions in Sub)

The resulting region is defined as the input region (Region) with all points from Sub removed.
Attention
Empty regions are valid for both parameters. On output, empty regions may result. The value of the system flag
’store_empty_region’ determines the behavior in this case.
Parameter
. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Regions to be processed.
. Sub (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
The union of these regions is subtracted from Region.
. RegionDifference (output iconic) . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Resulting region.
Example

/* provides the region X without the points in Y */


difference(X,Y,RegionDifference)

HALCON/COM Reference Manual, 2008-5-13


12.5. SETS 889

Complexity
Let N be the number of regions, F _1 be their average√ F _2 be the total area of all regions in Sub. Then
area, and√
the runtime complexity is O(F _1 ∗ log(F _1) + N ∗ ( F _1 + F _2)).
Result
Difference always returns the value TRUE. The behavior in case of empty input (no regions given) can be set
via SetSystem(’noObjectResult’,<Result>) and the behavior in case of an empty input region via
SetSystem(’emptyRegionResult’,<Result>). If necessary, an exception handling is raised.
Parallelization Information
Difference is reentrant and processed without parallelization.
Possible Predecessors
Threshold, Connection, Regiongrowing, Pouring, ClassNdimNorm
Possible Successors
SelectShape, DispRegion
See also
Intersection, Union1, Union2, Complement, SymmDifference
Module
Foundation

[out] HRegionX RegionIntersection HRegionX.Intersection


([in] HRegionX Region2 )
void HOperatorSetX.Intersection ([in] IHObjectX Region1,
[in] IHObjectX Region2, [out] HUntypedObjectX RegionIntersection )

Calculate the intersection of two regions.


Intersection calculates the intersection of the regions in Region1 with the regions in Region2. Each
region in Region1 is intersected with all regions in Region2. The order of regions in RegionIntersection
is identical to the order of regions in Region1.
Attention
Empty input regions are permitted. Because empty result regions are possible, the system flag ’store_empty_region’
should be set appropriately.
Parameter
. Region1 (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Regions to be intersected with all regions in Region2.
. Region2 (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Regions with which Region1 is intersected.
. RegionIntersection (output iconic) . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Result of the intersection.
Number of elements : (RegionIntersection ≤ Region1)
Complexity

Let N be the number of regions in Region1, F1 be their average√ √ F2 be the total area of all regions in
area, and
Region2. Then the runtime complexity is O(F1 log (F1 ) + N ∗ ( F1 + F2 )).
Result
Intersection always returns TRUE. The behavior in case of empty input (no regions given) can be set
via SetSystem(’noObjectResult’,<Result>) and the behavior in case of an empty input region via
SetSystem(’emptyRegionResult’,<Result>). If necessary, an exception handling is raised.
Parallelization Information
Intersection is reentrant and processed without parallelization.
Possible Predecessors
Threshold, Connection, Regiongrowing, Pouring
Possible Successors
SelectShape, DispRegion

HALCON 8.0.2
890 CHAPTER 12. REGIONS

See also
Union1, Union2, Complement
Module
Foundation

[out] HRegionX RegionDifference HRegionX.SymmDifference


([in] HRegionX Region2 )
void HOperatorSetX.SymmDifference ([in] IHObjectX Region1,
[in] IHObjectX Region2, [out] HUntypedObjectX RegionDifference )

Calculate the symmetric difference of two regions.


SymmDifference calculates the symmetric difference of two regions. Two possible definitions of the symmetric
difference can be seen in the example below. A third definition is to regard the exclusive or of the two regions.
Attention
Empty regions are valid for both parameters. On output, empty regions may result. The value of the system flag
’store_empty_region’ determines the behavior in this case.
Parameter

. Region1 (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Input region 1.
. Region2 (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Input region 2.
. RegionDifference (output iconic) . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Resulting region.
Example

/* Simulate the symmetric difference of Region1 and Region2 with */


/* difference and union: */
difference(Region1, Region2, Diff1)
difference(Region2, Region1, Diff2)
union(Diff1, Diff2, Difference)

/* Simulate the symmetric difference of Region1 and Region2 with */


/* union, intersection, and difference: */
union(Region1, Region2, Union)
intersection(Region1, Region2, Intersection)
difference(Union, Intersection, Difference)

Result
SymmDifference always returns the value TRUE. The behavior in case of empty input (no regions given) can
be set via SetSystem(’noObjectResult’,<Result>) and the behavior in case of an empty input region
via SetSystem(’emptyRegionResult’,<Result>). If necessary, an exception handling is raised.
Parallelization Information
SymmDifference is reentrant and processed without parallelization.
Possible Successors
SelectShape, DispRegion
See also
Intersection, Union1, Union2, Complement, Difference
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


12.5. SETS 891

HRegionX.Union1 ( )
[out] HRegionX RegionUnion
void HOperatorSetX.Union1 ([in] IHObjectX Region,
[out] HUntypedObjectX RegionUnion )

Return the union of all input regions.


Union1 computes the union of all input regions and returns the result in RegionUnion.
Parameter

. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX


Regions of which the union is to be computed.
. RegionUnion (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX
Union of all input regions.
Number of elements : (RegionU nion ≤ Region)
Example

/* Union of segmentation results: */


threshold(Image,Region1,128,255)
dyn_threshold(Image,Mean,Region2,5,’light’)
concat_obj(Region1,Region2,Regions)
union1(Regions,RegionUnion).

Complexity √ √
Let F be the sum of all areas of the input regions. Then the runtime complexity is O(log( F ) ∗ F ).
Result
Union1 always returns TRUE. The behavior in case of empty input (no regions given) can be set via SetSystem
(’noObjectResult’,<Result>) and the behavior in case of an empty input region via SetSystem
(’emptyRegionResult’,<Result>). If necessary, an exception handling is raised.
Parallelization Information
Union1 is reentrant and processed without parallelization.
Possible Predecessors
Threshold, Connection, Regiongrowing, Pouring
Possible Successors
SelectShape, DispRegion
See also
Intersection, Complement
Alternatives
Union2
Module
Foundation

HRegionX.Union2 ([in] HRegionX Region2 )


[out] HRegionX RegionUnion
void HOperatorSetX.Union2 ([in] IHObjectX Region1,
[in] IHObjectX Region2, [out] HUntypedObjectX RegionUnion )

Return the union of two regions.


Union2 computes the union of the region in Region1 with all regions in Region2. This means that Union2
is not commutative!

HALCON 8.0.2
892 CHAPTER 12. REGIONS

Parameter

. Region1 (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Region for which the union with all regions in Region2 is to be computed.
. Region2 (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Regions which should be added to Region1.
. RegionUnion (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Resulting regions.
Number of elements : (RegionU nion = Region1)
Complexity √ √
Let F be the sum of all areas of the input regions. Then the runtime complexity is O(log( F ) ∗ F ).
Result
Union2 always returns TRUE. The behavior in case of empty input (no regions given) can be set via SetSystem
(’noObjectResult’,<Result>) and the behavior in case of an empty input region via SetSystem
(’emptyRegionResult’,<Result>). If necessary, an exception handling is raised.
Parallelization Information
Union2 is reentrant and processed without parallelization.
Possible Predecessors
Threshold, Connection, Regiongrowing, Pouring
Possible Successors
SelectShape, DispRegion
See also
Intersection, Complement
Alternatives
Union1
Module
Foundation

12.6 Tests
[out] long IsEqual HRegionX.TestEqualRegion ([in] HRegionX Regions2 )
void HOperatorSetX.TestEqualRegion ([in] IHObjectX Regions1,
[in] IHObjectX Regions2, [out] VARIANT IsEqual )

Test whether the regions of two objects are identical.


The operator TestEqualRegion compares the regions of the two input parameters. The n-th element in
Regions1 is compared to the n-th object in Regions2 (for all n). If all regions are equal and the number of
regions is identical the operator IsEqual is set to TRUE, otherwise FALSE.
Attention

Parameter

. Regions1 (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Test regions.
. Regions2 (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Comparative regions.
Number of elements : (Regions1 = Regions2)
. IsEqual (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
boolean result value.
Complexity √ √
If F is the area of a region the runtime complexity is O(1) or O( F ) if the result is TRUE, O( F ) if the result is
FALSE.

HALCON/COM Reference Manual, 2008-5-13


12.6. TESTS 893

Result
The operator TestEqualRegion returns the value TRUE if the parameters are correct. The be-
havior in case of empty input (no input objects available) is set via the operator SetSystem(::
’noObjectResult’,<Result>:). If the number of objects differs an exception is raised. Else
TestEqualRegion returns the value TRUE
Parallelization Information
TestEqualRegion is reentrant and processed without parallelization.
See also
TestEqualObj
Alternatives
Intersection, Complement, AreaCenter
Module
Foundation

[out] long IsInside HRegionX.TestRegionPoint ([in] long Row,


[in] long Column )
void HOperatorSetX.TestRegionPoint ([in] IHObjectX Regions,
[in] VARIANT Row, [in] VARIANT Column, [out] VARIANT IsInside )

Test if the region consists of the given point.


TestRegionPoint tests if at least one input region of Regions consists of the test point (Row,Column). Is
this the case, IsInside is set to TRUE, else to FALSE
Attention
In case of empty input (= no region) and SetSystem(’noObjectResult’,’true’) IsInside is set to
FALSE (no region contains the pixel).
The test pixel is not contained in an empty region (no pixel of the region corresponds to the pixel). If all regions
are empty IsInside is set to FALSE , i.e., an empty region behaves as if it did not exist.
Parameter

. Regions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Region(s) to be examined.
. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; long / VARIANT
Line index of the test pixel.
Default Value : 100
Typical range of values : 0 ≤ Row ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 1
. Column (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; long / VARIANT
Column index of the test pixel.
Default Value : 100
Typical range of values : 0 ≤ Column ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 1
. IsInside (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
boolean result value.
Complexity √
If F is the area of one region and N is the number of regions, the runtime complexity is O(ln( F ) ∗ N ).
Result
The operator TestRegionPoint returns the value TRUE if the parameters are correct. The be-
havior in case of empty input (no input regions available) is set via the operator SetSystem
(’noObjectResult’,<Result>). If necessary an exception handling is raised.
Parallelization Information
TestRegionPoint is reentrant and processed without parallelization.

HALCON 8.0.2
894 CHAPTER 12. REGIONS

Possible Predecessors
Threshold, Regiongrowing, Connection
See also
SelectRegionPoint
Alternatives
Union1, Intersection, AreaCenter
Module
Foundation

[out] VARIANT IsSubset HRegionX.TestSubsetRegion


([in] HRegionX Region2 )
void HOperatorSetX.TestSubsetRegion ([in] IHObjectX Region1,
[in] IHObjectX Region2, [out] VARIANT IsSubset )

Test whether a region is contained in another region.


TestSubsetRegion tests whether Region1 is a subset of Region2 and returns the result in IsSubset. If
more than one region should be tested, Region1 and Region2 must have the same number of elements. In this
case, a tuple that contains as many elements as Region1 and Region2 is returned in IsSubset.
Parameter
. Region1 (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Test region.
. Region2 (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Region for comparison.
Number of elements : (Region1 = Region2)
. IsSubset (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT
Is Region1 contained in Region2?
Result
TestSubsetRegion returns the value TRUE if the parameters are correct. The behavior in case of empty input
(no input objects available) is set via the operator SetSystem(::’noObjectResult’,<Result>:). If
the number of objects differs an exception is raised.
Parallelization Information
TestSubsetRegion is reentrant and automatically parallelized (on tuple level).
See also
TestEqualRegion
Alternatives
Difference, AreaCenter
Module
Foundation

12.7 Transformation
HRegionX.BackgroundSeg ( )
[out] HRegionX BackgroundRegions
void HOperatorSetX.BackgroundSeg ([in] IHObjectX Foreground,
[out] HUntypedObjectX BackgroundRegions )

Determine the connected components of the background of given regions.


BackgroundSeg determines connected components of the background of the foreground regions given in
Foreground. This operator is normally used after an edge operator in order to determine the regions enclosed
by the extracted edges. The connected components are determined using 4-neighborhood.

HALCON/COM Reference Manual, 2008-5-13


12.7. TRANSFORMATION 895

Parameter
. Foreground (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Input regions.
. BackgroundRegions (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX
Connected components of the background.
Example

/* Simulation of background_seg: */
background_seg(Foreground,BackgroundRegions):
complement(Foreground,Background)
get_system(’neighborhood’,Save)
set_system(’neighborhood’,4)
connection(Background,BackgroundRegions)
clear_obj(Background)
set_system(’neighborhood’,Save).

/* Segmentation with edge filter: */


read_image(Image,’fabrik’)
sobel_dir(Image,Sobel,Dir,’sum_sqrt’,3)
threshold(Sobel,Edges,20,255)
skeleton(Edges,Margins)
background_seg(Margins,Regions).

Complexity
Let F be the area of the background, H and W be the height
√ and√ width of the image, and N be the number of
resulting regions. Then the runtime complexity is O(H + F ∗ N ).
Result
BackgroundSeg always returns the value TRUE. The behavior in case of empty input (no regions given) can be
set via SetSystem(’noObjectResult’,<Result>) and the behavior in case of an empty input region
via SetSystem(’emptyRegionResult’,<Result>). If necessary, an exception handling is raised.
Parallelization Information
BackgroundSeg is reentrant and processed without parallelization.
Possible Predecessors
Threshold, Connection, Regiongrowing, Pouring, ClassNdimNorm
Possible Successors
SelectShape
See also
Threshold, HysteresisThreshold, Skeleton, ExpandRegion, SetSystem, SobelAmp,
EdgesImage, Roberts, BandpassImage
Alternatives
Complement, Connection
Module
Foundation

[out] HRegionX RegionClipped HRegionX.ClipRegion ([in] long Row1,


[in] long Column1, [in] long Row2, [in] long Column2 )
void HOperatorSetX.ClipRegion ([in] IHObjectX Region,
[out] HUntypedObjectX RegionClipped, [in] VARIANT Row1, [in] VARIANT Column1,
[in] VARIANT Row2, [in] VARIANT Column2 )

Clip a region to a rectangle.


ClipRegion clips the input regions to the rectangle given by the four control parameters. ClipRegion is
more efficient than calling Intersection with a rectangle generated by GenRectangle1.

HALCON 8.0.2
896 CHAPTER 12. REGIONS

Parameter
. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Region to be clipped.
. RegionClipped (output iconic) . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Clipped regions.
. Row1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.origin.y ; long / VARIANT
Row coordinate of the upper left corner of the rectangle.
Default Value : 0
Suggested values : Row1 ∈ {0, 128, 200, 256}
(lin)
. Column1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.origin.x ; long / VARIANT
Column coordinate of the upper left corner of the rectangle.
Default Value : 0
Suggested values : Column1 ∈ {0, 128, 200, 256}
(lin)
. Row2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.corner.y ; long / VARIANT
Row coordinate of the lower right corner of the rectangle.
Default Value : 256
Suggested values : Row2 ∈ {128, 200, 256, 512}
Typical range of values : 0 ≤ Row2 ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 10
. Column2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle.corner.x ; long / VARIANT
Column coordinate of the lower right corner of the rectangle.
Default Value : 256
Suggested values : Column2 ∈ {128, 200, 256, 512}
Typical range of values : 0 ≤ Column2 ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 10
Result
ClipRegion returns TRUE if all parameters are correct. The behavior in case of empty input (no regions
given) can be set via SetSystem(’noObjectResult’,<Result>) and the behavior in case of an empty
input region via SetSystem(’emptyRegionResult’,<Result>). If necessary, an exception handling is
raised.
Parallelization Information
ClipRegion is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Connection, Regiongrowing, Pouring
Possible Successors
SelectShape, DispRegion
Alternatives
Intersection, GenRectangle1, ClipRegionRel
Module
Foundation

[out] HRegionX RegionClipped HRegionX.ClipRegionRel ([in] long Top,


[in] long Bottom, [in] long Left, [in] long Right )
void HOperatorSetX.ClipRegionRel ([in] IHObjectX Region,
[out] HUntypedObjectX RegionClipped, [in] VARIANT Top, [in] VARIANT Bottom,
[in] VARIANT Left, [in] VARIANT Right )

Clip a region relative to its size.


ClipRegionRel clips a region to a rectangle lying within the region. The size of the rectangle is determined by
the enclosing rectangle of the region, which is reduced by the values given in the four control parameters. All four

HALCON/COM Reference Manual, 2008-5-13


12.7. TRANSFORMATION 897

parameters must contain numbers larger or equal to zero, and determine by which amount the rectangle is reduced
at the top (Top), at the bottom (Bottom), at the left (Left), and at the right (Right). If all parameters are set to
zero, the region remains unchanged.
Parameter

. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Regions to be clipped.
. RegionClipped (output iconic) . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Clipped regions.
. Top (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of rows clipped at the top.
Default Value : 1
Suggested values : Top ∈ {0, 1, 2, 3, 4, 5, 7, 10, 20, 30, 50}
(lin)Minimum Increment : 1
Recommended Increment : 1
. Bottom (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of rows clipped at the bottom.
Default Value : 1
Suggested values : Bottom ∈ {0, 1, 2, 3, 4, 5, 7, 10, 20, 30, 50}
(lin)Minimum Increment : 1
Recommended Increment : 1
. Left (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of columns clipped at the left.
Default Value : 1
Suggested values : Left ∈ {0, 1, 2, 3, 4, 5, 7, 10, 20, 30, 50}
(lin)Minimum Increment : 1
Recommended Increment : 1
. Right (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of columns clipped at the right.
Default Value : 1
Suggested values : Right ∈ {0, 1, 2, 3, 4, 5, 7, 10, 20, 30, 50}
(lin)Minimum Increment : 1
Recommended Increment : 1
Result
ClipRegionRel returns TRUE if all parameters are correct. The behavior in case of empty input (no regions
given) can be set via SetSystem(’noObjectResult’,<Result>) and the behavior in case of an empty
input region via SetSystem(’emptyRegionResult’,<Result>). If necessary, an exception handling is
raised.
Parallelization Information
ClipRegionRel is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Connection, Regiongrowing, Pouring
Possible Successors
SelectShape, DispRegion
Alternatives
SmallestRectangle1, Intersection, GenRectangle1, ClipRegion
Module
Foundation

HRegionX.Connection ( )
[out] HRegionX ConnectedRegions
void HOperatorSetX.Connection ([in] IHObjectX Region,
[out] HUntypedObjectX ConnectedRegions )

Compute connected components of a region.

HALCON 8.0.2
898 CHAPTER 12. REGIONS

Connection determines the connected components of the input regions given in Region. The neighborhood
used for this can be set via SetSystem(’neighborhood’,<4/8>). The default is 8-neighborhood, which
is useful for determining the connected components of the foreground. The maximum number of connected com-
ponents that is returned by Connection can be set via SetSystem(’maxConnection’,<Num>). The
default value of 0 causes all connected components to be returned. The inverse operator of Connection is
Union1.
Parameter

. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Input region.
. ConnectedRegions (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX
Connected components.
Example

read_image(Image,’affe’)
set_colored(WindowHandle,12)
threshold(Image,Light,150.0,255.0)
count_obj(Light,Number1)
fwrite_string(’Nummber of regions after threshold = ’+Number1)
fnew_line()
disp_region(Light,WindowHandle)
connection(Light,Many)
count_obj(Many,Number2)
fwrite_string(’Nummber of regions after threshold = ’+Number2)
fnew_line()
disp_region(Many,WindowHandle).

Complexity
Let F be the area√of the√input region and N be the number of generated connected components. Then the runtime
complexity is O( F ∗ N ).
Result
Connection always returns the value TRUE. The behavior in case of empty input (no regions given) can be set
via SetSystem(’noObjectResult’,<Result>) and the behavior in case of an empty input region via
SetSystem(’emptyRegionResult’,<Result>). If necessary, an exception handling is raised.
Parallelization Information
Connection is reentrant and processed without parallelization.
Possible Predecessors
AutoThreshold, Threshold, DynThreshold, Erosion1
Possible Successors
SelectShape, SelectGray, ShapeTrans, SetColored, Dilation1, CountObj, ReduceDomain,
AddChannels
See also
SetSystem, Union1
Alternatives
BackgroundSeg
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


12.7. TRANSFORMATION 899

[out] HImageX DistanceImage HRegionX.DistanceTransform


([in] String Metric, [in] String Foreground, [in] long Width,
[in] long Height )
void HOperatorSetX.DistanceTransform ([in] IHObjectX Region,
[out] HUntypedObjectX DistanceImage, [in] VARIANT Metric,
[in] VARIANT Foreground, [in] VARIANT Width, [in] VARIANT Height )

Compute the distance transformation of a region.


DistanceTransform computes for every point of the input region Region (or its complement, respectively)
the distance of the point to the border of the region. The parameter Foreground determines whether the dis-
tances are calculated for all points within the region (Foreground = ’true’) or for all points outside the region
(Foreground = ’false’). The distance is computed for every point of the output image DistanceImage, which
has the specified dimensions Width and Height. The input region is always clipped to the extent of the output
image. If it is important that the distances within the entire region should be computed, the region should be moved
(see MoveRegion) so that it has only positive coordinates and the width and height of the output image should be
large enough to contain the region. The extent of the input region can be obtained with SmallestRectangle1.
The parameter Metric determines which metric is used for the calculation of the distances. If Metric = ’city-
block’, the distance is calculated from the shortest path from the point to the border of the region, where only
horizontal and vertical “movements” are allowed. They are weighted with a distance of 1. If Metric = ’chess-
board’, the distance is calculated from the shortest path to the border, where horizontal, vertical, and diagonal
“movements” are allowed. They are weighted with a distance of 1. If Metric = ’octagonal’, a combination
of these approaches is used, which leads to diagonal paths getting a higher weight. If Metric = ’chamfer-3-4’,
horizontal and vertical movements are weighted with a weight of 3, while diagonal movements are weighted with a
weight of 4. To normalize the distances, the resulting distance image is divided by 3. Since this normalization step
takes some time, and one usually is interested in the relative distances of the points, the normalization can be sup-
pressed with Metric = ’chamfer-3-4-unnormalized’. Finally, if Metric = ’euclidean’, the computed distance is
approximately Euclidean.
Parameter
. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Region for which the distance to the border is computed.
. DistanceImage (output iconic) . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / HUntypedObjectX ( int4 )
Image containing the distance information.
. Metric (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Type of metric to be used for the distance transformation.
Default Value : ’city-block’
List of values : Metric ∈ {’city-block’, ’chessboard’, ’octagonal’, ’chamfer-3-4’,
’chamfer-3-4-unnormalized’, ’euclidean’}
. Foreground (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Compute the distance for pixels inside (true) or outside (false) the input region.
Default Value : ’true’
List of values : Foreground ∈ {’true’, ’false’}
. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; long / VARIANT
Width of the output image.
Default Value : 640
Suggested values : Width ∈ {160, 192, 320, 384, 640, 768}
. Height (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; long / VARIANT
Height of the output image.
Default Value : 480
Suggested values : Height ∈ {120, 144, 240, 288, 480, 576}
Example

/* Step towards extracting the medial axis of a shape: */


gen_rectangle1 (Rectangle1, 0, 0, 200, 400)
gen_rectangle1 (Rectangle2, 200, 0, 400, 200)
union2 (Rectangle1, Rectangle2, Shape)
distance_transform (Shape, DistanceImage, ’chessboard’, ’true’, 640, 480)

HALCON 8.0.2
900 CHAPTER 12. REGIONS

Complexity
The runtime complexity is O(Width ∗ Height).
Result
DistanceTransform returns H_MSG_TRUE if all parameters are correct.
Parallelization Information
DistanceTransform is reentrant and processed without parallelization.
Possible Predecessors
Threshold, DynThreshold, Regiongrowing
Possible Successors
Threshold
See also
Skeleton
References
P. Soille: “Morphological Image Analysis, Principles and Applications”; Springer Verlag Berlin Heidelberg New
York, 1999.
G. Borgefors: “Distance Transformations in Arbitrary Dimensions”; Computer Vision, Graphics, and Image Pro-
cessing, Vol. 27, pages 321–345, 1984.
P.E. Danielsson: “Euclidean Distance Mapping”; Computer Graphics and Image Processing, Vol. 14, pages 227–
248, 1980.
Module
Foundation

[out] HRegionX RegionClipped HRegionX.EliminateRuns


([in] long ElimShorter, [in] long ElimLonger )
void HOperatorSetX.EliminateRuns ([in] IHObjectX Region,
[out] HUntypedObjectX RegionClipped, [in] VARIANT ElimShorter,
[in] VARIANT ElimLonger )

Eliminate runs of a given length.


EliminateRuns eliminates all runs of the run length encoding of the input regions which are shorter than
ElimShorter or longer as ElimLonger.
Parameter

. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Region to be clipped.
. RegionClipped (output iconic) . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Clipped regions.
. ElimShorter (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
All runs which are shorter are eliminated.
Default Value : 3
Suggested values : ElimShorter ∈ {2, 3, 4, 5, 6, 8, 10, 12, 15}
Typical range of values : 1 ≤ ElimShorter ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 1
. ElimLonger (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
All runs which are longer are eliminated.
Default Value : 1000
Suggested values : ElimLonger ∈ {50, 100, 200, 500, 1000, 2000}
Typical range of values : 1 ≤ ElimLonger ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 10
Result
EliminateRuns returns TRUE if all parameters are correct. The behavior in case of empty input (no regions

HALCON/COM Reference Manual, 2008-5-13


12.7. TRANSFORMATION 901

given) can be set via SetSystem(’noObjectResult’,<Result>) and the behavior in case of an empty
input region via SetSystem(’emptyRegionResult’,<Result>). If necessary, an exception handling is
raised.
Parallelization Information
EliminateRuns is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Connection, Regiongrowing, Pouring
Possible Successors
Erosion1, Dilation1, DispRegion
Alternatives
ShapeTrans
Module
Foundation

[out] HRegionX RegionExpanded HRegionX.ExpandRegion


([in] HRegionX ForbiddenArea, [in] VARIANT Iterations, [in] String Mode )
void HOperatorSetX.ExpandRegion ([in] IHObjectX Regions,
[in] IHObjectX ForbiddenArea, [out] HUntypedObjectX RegionExpanded,
[in] VARIANT Iterations, [in] VARIANT Mode )

Fill gaps between regions or split overlapping regions.


ExpandRegion closes gaps between the input regions, which resulted from the suppression of small regions in
a segmentation operator, for example, (mode ’image’), or to separate overlapping regions (mode ’region’). Both
uses result from the expansion of regions. The operator works by adding or removing a one pixel wide “strip” to a
region.
The expansion takes place only in regions that are designated as not “forbidden” (parameter ForbiddenArea).
The number of iterations is determined by the parameter Iterations. By passing ’maximal’, ExpandRegion
iterates until convergence, i.e., until no more changes occur. By passing 0 for this parameter, all non-overlapping
regions are returned. The two modes of operation (’image’ and ’region’) are different in the following ways:

’image’ The input regions are expanded iteratively until they touch another region or the image border. In this
case, the image border is defined to be the rectangle ranging from (0,0) to (row_max,col_max). Here,
(row_max,col_max) corresponds to the lower right corner of the smallest surrounding rectangle of all input
regions (i.e., of all regions that are passed in Regions and ForbiddenArea). Because ExpandRegion
processes all regions simultaneously, gaps between regions are distributed evenly to all regions. Overlapping
regions are split by distributing the area of overlap evenly to both regions.
’region’ No expansion of the input regions is performed. Instead, only overlapping regions are split by distributing
the area of overlap evenly to the respective regions. Because the intersection with the original region is
computed after the shrinking operation gaps in the output regions may result, i.e., the segmentation is not
complete. This can be prevented by calling ExpandRegion a second time with the complement of the
original regions as “forbidden area.”

Parameter

. Regions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Regions for which the gaps are to be closed, or which are to be separated.
. ForbiddenArea (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
Regions in which no expansion takes place.
. RegionExpanded (output iconic) . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Expanded or separated regions.

HALCON 8.0.2
902 CHAPTER 12. REGIONS

. Iterations (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer, string )


Number of iterations.
Default Value : ’maximal’
Suggested values : Iterations ∈ {’maximal’, 0, 1, 2, 3, 5, 7, 10, 15, 20, 30, 50, 70, 100, 200}
Typical range of values : 0 ≤ Iterations ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 1
. Mode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Expansion mode.
Default Value : ’image’
List of values : Mode ∈ {’image’, ’region’}
Example

read_image(Image,’fabrik’)
threshold(Image,Light,100,255)
disp_region(Light,WindowHandle)
connection(Light,Seg)
expand_region(Seg,[],Exp1,’maximal’,’image’)
set_colored(WindowHandle,12)
set_draw(WindowHandle,’margin’)
disp_region(Exp1,WindowHandle)

Result
ExpandRegion always returns the value TRUE. The behavior in case of empty input (no regions given) can be
set via SetSystem(’noObjectResult’,<Result>), the behavior in case of an empty input region via
SetSystem(’emptyRegionResult’,<Result>), and the behavior in case of an empty result region via
SetSystem(’storeEmptyRegion’,<true/false>). If necessary, an exception handling is raised.
Parallelization Information
ExpandRegion is reentrant and processed without parallelization.
Possible Predecessors
Pouring, Threshold, DynThreshold, Regiongrowing
See also
ExpandGray, Interjacent, Skeleton
Alternatives
Dilation1
Module
Foundation

HRegionX.FillUp ( )
[out] HRegionX RegionFillUp
void HOperatorSetX.FillUp ([in] IHObjectX Region,
[out] HUntypedObjectX RegionFillUp )

Fill up holes in regions.


FillUp fills up holes in regions. The number of regions remains unchanged. The neighborhood type is set via
SetSystem(’neighborhood’,<4/8>) (default: 8-neighborhood).
Parameter
. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Input regions containing holes.
. RegionFillUp (output iconic) . . . . . . . . . . . . . . . . . . . . . . . .region(-array) ; HRegionX / HUntypedObjectX
Regions without holes.
Result
FillUp returns TRUE if all parameters are correct. The behavior in case of empty input (no regions given) can

HALCON/COM Reference Manual, 2008-5-13


12.7. TRANSFORMATION 903

be set via SetSystem(’noObjectResult’,<Result>) and the behavior in case of an empty input region
via SetSystem(’emptyRegionResult’,<Result>). If necessary, an exception handling is raised.
Parallelization Information
FillUp is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Connection, Regiongrowing, Pouring
Possible Successors
SelectShape, DispRegion
See also
Boundary
Alternatives
FillUpShape
Module
Foundation

[out] HRegionX RegionFillUp HRegionX.FillUpShape ([in] String Feature,


[in] VARIANT Min, [in] VARIANT Max )
void HOperatorSetX.FillUpShape ([in] IHObjectX Region,
[out] HUntypedObjectX RegionFillUp, [in] VARIANT Feature, [in] VARIANT Min,
[in] VARIANT Max )

Fill up holes in regions having given shape features.


FillUpShape fills up those holes in the input region Region having given shape features. The parameter
Feature determines the shape feature to be used, while Min and Max determine the range the shape feature has
to lie in in order for the hole to be filled up.
Parameter

. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Input region(s).
. RegionFillUp (output iconic) . . . . . . . . . . . . . . . . . . . . . . . .region(-array) ; HRegionX / HUntypedObjectX
Output region(s) with filled holes.
. Feature (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Shape feature used.
Default Value : ’area’
List of values : Feature ∈ {’area’, ’compactness’, ’convexity’, ’anisometry’, ’phi’, ’ra’, ’rb’, ’inner_circle’,
’outer_circle’}
. Min (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Minimum value for Feature.
Default Value : 1.0
Suggested values : Min ∈ {0.0, 1.0, 10.0, 50.0, 100.0, 500.0, 1000.0, 10000.0}
. Max (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Maximum value for Feature.
Default Value : 100.0
Suggested values : Max ∈ {10.0, 50.0, 100.0, 500.0, 1000.0, 10000.0, 100000.0}
Result
FillUpShape returns TRUE if all parameters are correct. The behavior in case of empty input (no regions
given) can be set via SetSystem(’noObjectResult’,<Result>) and the behavior in case of an empty
input region via SetSystem(’emptyRegionResult’,<Result>). If necessary, an exception handling is
raised.
Parallelization Information
FillUpShape is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Connection, Regiongrowing, Pouring

HALCON 8.0.2
904 CHAPTER 12. REGIONS

Possible Successors
SelectShape, DispRegion
See also
SelectShape, Connection, AreaCenter
Alternatives
FillUp
Module
Foundation

[out] HRegionX OutputRegion HRegionX.HammingChangeRegion


([in] long Width, [in] long Height, [in] long Distance )
void HOperatorSetX.HammingChangeRegion ([in] IHObjectX InputRegion,
[out] HUntypedObjectX OutputRegion, [in] VARIANT Width, [in] VARIANT Height,
[in] VARIANT Distance )

Generate a region having a given Hamming distance.


HammingChangeRegion changes the region in the left upper part of the image given by Width and Height
such that the resulting regions have a Hamming distance of Distance to the input regions. This is done by
adding or removing Distance points from the input region.
Attention
If Width and Height are chosen too large the resulting region requires a lot of memory.
Parameter
. InputRegion (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Region to be modified.
. OutputRegion (output iconic) . . . . . . . . . . . . . . . . . . . . . . . .region(-array) ; HRegionX / HUntypedObjectX
Regions having the required Hamming distance.
. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; long / VARIANT
Width of the region to be changed.
Default Value : 100
Suggested values : Width ∈ {64, 128, 256, 512}
Typical range of values : 1 ≤ Width ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 10
Restriction : (W idth > 0)
. Height (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; long / VARIANT
Height of the region to be changed.
Default Value : 100
Suggested values : Height ∈ {64, 128, 256, 512}
Typical range of values : 1 ≤ Height ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 10
Restriction : (Height > 0)
. Distance (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Hamming distance between the old and new regions.
Default Value : 1000
Suggested values : Distance ∈ {100, 500, 1000, 5000, 10000}
Typical range of values : 0 ≤ Distance ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 10
Restriction : ((Distance ≥ 0) ∧ (Distance < (W idth · Height)))
Complexity
Memory requirement of the generated region (worst case): O(2 ∗ Width ∗ Height).
Result
HammingChangeRegion returns TRUE if all parameters are correct. The behavior in case of empty input (no

HALCON/COM Reference Manual, 2008-5-13


12.7. TRANSFORMATION 905

regions given) can be set via SetSystem(’noObjectResult’,<Result>). If necessary, an exception


handling is raised.
Parallelization Information
HammingChangeRegion is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Connection, Regiongrowing, Pouring, ClassNdimNorm
Possible Successors
SelectShape
See also
HammingDistance
Module
Foundation

[out] HRegionX RegionInterjacent HRegionX.Interjacent


([in] String Mode )
void HOperatorSetX.Interjacent ([in] IHObjectX Region,
[out] HUntypedObjectX RegionInterjacent, [in] VARIANT Mode )

Partition the image plane using given regions.


Interjacent partitions the image plane using the regions given in Region. The result is a region containing
the extracted separating lines. The following modes of operation can be used:

’medial_axis’ This mode is used for regions that do not touch or overlap. The operator will find separating lines
between the regions which partition the background evenly between the input regions. This corresponds to
the following calls:
complement(’full’,Region,Tmp) skeleton(Tmp,Result)
’border’ If the input regions do not touch or overlap this mode is equivalent to Boundary(Region,Result),
i.e., it replaces each region by its boundary. If regions are touching they are aggregated into one region. The
corresponding output region then contains the boundary of the aggregated region, as well as the one pixel
wide separating line between the original regions. This corresponds to the following calls:
boundary(Region,Tmp1,’inner’) union1(Tmp1,Tmp2)
skeleton(Tmp2,Result)
’mixed’ In this mode the operator behaves like the mode ’medial_axis’ for non-overlapping regions. If regions
touch or overlap, again separating lines between the input regions are generated on output, but this time
including the “touching line” between regions, i.e., touching regions are separated by a line in the output
region. This corresponds to the following calls:
erosion1(Region,Mask,Tmp1,1) union1(Tmp1,Tmp2)
complement(full,Tmp2,Tmp3) skeleton(Tmp3,Result)
where Mask denotes the following “cross mask”:

×
× × ×
×

Parameter
. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Regions for which the separating lines are to be determined.
. RegionInterjacent (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX
Output region containing the separating lines.
. Mode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Mode of operation.
Default Value : ’mixed’
List of values : Mode ∈ {’medial_axis’, ’border’, ’mixed’}

HALCON 8.0.2
906 CHAPTER 12. REGIONS

Example

read_image(Image,’wald1_rot’)
mean(Image,Mean,31,31)
dyn_threshold(Mean,Seg,20)
interjacent(Seg,Graph,’medial_axis’)
disp_region(Graph,WindowHandle)

Result
Interjacent always returns the value TRUE. The behavior in case of empty input (no regions given) can be
set via SetSystem(’noObjectResult’,<Result>), the behavior in case of an empty input region via
SetSystem(’emptyRegionResult’,<Result>), and the behavior in case of an empty result region via
SetSystem(’storeEmptyRegion’,<true/false>). If necessary, an exception handling is raised.
Parallelization Information
Interjacent is reentrant and processed without parallelization.
Possible Predecessors
Threshold, Connection, Regiongrowing, Pouring
Possible Successors
SelectShape, DispRegion
See also
ExpandRegion, JunctionsSkeleton, Boundary
Module
Foundation

[out] HRegionX EndPoints HRegionX.JunctionsSkeleton


([out] HRegionX JuncPoints )
void HOperatorSetX.JunctionsSkeleton ([in] IHObjectX Region,
[out] HUntypedObjectX EndPoints, [out] HUntypedObjectX JuncPoints )

Find junctions and end points in a skeleton.


JunctionsSkeleton detects junctions and end points in a skeleton (see Skeleton). The junctions in the
input region Region are output as a region in JuncPoints, while the end points are output as a region in
EndPoints.
To obtain reasonable results with JunctionsSkeleton the input region Region must not contain lines which
are more than one pixel wide. Regions obtained by Skeleton meet this condition, while regions obtained by
MorphSkeleton do not meet this condition in general.
Parameter

. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Input skeletons.
. EndPoints (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Extracted end points.
Number of elements : (EndP oints = Region)
. JuncPoints (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Extracted junctions.
Number of elements : (JuncP oints = Region)
Example

/* non-connected branches of a skeleton */


skeleton(Region,Skeleton)
junctions_skeleton(Skeleton,EPoints,JPoints)
difference(S,JPoints,Rows)

HALCON/COM Reference Manual, 2008-5-13


12.7. TRANSFORMATION 907

set_system(’heighbourhood’,4)
connection(Rows,Parts).

Complexity
Let F be the area of the input region. Then the runtime complexity is O(F ).
Result
JunctionsSkeleton always returns the value TRUE. The behavior in case of empty input (no regions given)
can be set via SetSystem(’noObjectResult’,<Result>), the behavior in case of an empty input region
via SetSystem(’emptyRegionResult’,<Result>), and the behavior in case of an empty result region
via SetSystem(’storeEmptyRegion’,<true/false>). If necessary, an exception handling is raised.
Parallelization Information
JunctionsSkeleton is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Skeleton
Possible Successors
AreaCenter, Connection, GetRegionPoints, Difference
See also
Pruning, SplitSkeletonRegion
Module
Foundation

[out] HRegionX CurrMergedRegions HRegionX.MergeRegionsLineScan


([in] HRegionX PrevRegions, [out] HRegionX PrevMergedRegions,
[in] long ImageHeight, [in] String MergeBorder, [in] long MaxImagesRegion )
void HOperatorSetX.MergeRegionsLineScan ([in] IHObjectX CurrRegions,
[in] IHObjectX PrevRegions, [out] HUntypedObjectX CurrMergedRegions,
[out] HUntypedObjectX PrevMergedRegions, [in] VARIANT ImageHeight,
[in] VARIANT MergeBorder, [in] VARIANT MaxImagesRegion )

Merge regions from line scan images.


The operator MergeRegionsLineScan connects adjacent regions, which were segmentated from adjacent im-
ages with the height ImageHeight. This operator was especially designed to process regions that were extracted
from images grabbed by a line scan camera. CurrRegions contains the regions from the current image and
PrevRegions the regions from the previous one.
With the help of the parameter MergeBorder two cases can be distinguished: If the top (first) line of the current
image touches the bottom (last) line of the previous image, MergeBorder must be set to ’top’, otherwise set
MergeBorder to ’bottom’.
If the operator MergeRegionsLineScan is used recursivly, the parameter MaxImagesRegion determines
the maximum number of images which are covered by a merged region. All older region parts are removed.
The operator MergeRegionsLineScan returns two region arrays. PrevMergedRegions contains all
those regions from the previous input regions PrevRegions, which could not be merged with a current
region. CurrMergedRegions collects all current regions together with the merged parts from the previ-
ous images. Merged regions will exceed the original image, because the previous regions are moved upward
(MergeBorder=’top’) or downward (MergeBorder=’bottom’) according to the image height. For this the
system parameter ’clip_region’ (see also SetSystem) will internaly be set to ’false’.
Parameter
. CurrRegions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Current input regions.
. PrevRegions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Merged regions from the previous iteration.
. CurrMergedRegions (output iconic) . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Current regions, merged with old ones where applicable.

HALCON 8.0.2
908 CHAPTER 12. REGIONS

. PrevMergedRegions (output iconic) . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX


Regions from the previous iteration which could not be merged with the current ones.
. ImageHeight (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Height of the line scan images.
Default Value : 512
List of values : ImageHeight ∈ {240, 480, 512}
. MergeBorder (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Image line of the current image, which touches the previous image.
Default Value : ’top’
List of values : MergeBorder ∈ {’top’, ’bottom’}
. MaxImagesRegion (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Maximum number of images for a single region.
Default Value : 3
Suggested values : MaxImagesRegion ∈ {1, 2, 3, 4, 5}
Result
The operator MergeRegionsLineScan returns the value TRUE if the given parameters are correct. Otherwise,
an exception will be raised.
Parallelization Information
MergeRegionsLineScan is reentrant and processed without parallelization.
Module
Foundation

[out] HRegionX Partitioned HRegionX.PartitionDynamic


([in] double Distance, [in] double Percent )
void HOperatorSetX.PartitionDynamic ([in] IHObjectX Region,
[out] HUntypedObjectX Partitioned, [in] VARIANT Distance,
[in] VARIANT Percent )

Partition a region horizontally at positions of small vertical extent.


PartitionDynamic partitions the input Region horizontally into regions that have an approximate width of
Distance. The input region is split at positions where it has a relativly small vertical extent.
The positions where the input region is split are determined by the following approach: First, initial split positions
are determined such that they are equally distributed over the horizontal extent of the input region, i.e., such that all
the resulting parts would have the same width. For this, the number n of resulting parts is determined by dividing
the width of the input region by Distance and rounding the result to the closest integer value. The distance
between the initial split positions is now calculated by dividing the width of the input region by n. Note that the
distance between these initial split positions is typically not identical to Distance. Then, the final split positions
are determined in the neighborhood of the initial split positions such that the input region is split at positions where
it has the least vertical extent within this neighborhood. The maximum deviation of the final split position from
the initial split position is Distance*Percent*0.01.
The resulting regions are returned in Partitioned. Note that the input region is only partitioned if its width is
larger than 1.5 times Distance.
Parameter
. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Region to be partitioned.
. Partitioned (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX
Partitioned region.
. Distance (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Approximate width of the resulting region parts.
. Percent (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Maximum percental shift of the split position.
Default Value : 20
Suggested values : Percent ∈ {0, 10, 20, 30, 40, 50, 70, 90, 100}
Typical range of values : 0 ≤ Percent ≤ 0

HALCON/COM Reference Manual, 2008-5-13


12.7. TRANSFORMATION 909

Result
PartitionDynamic returns TRUE if all parameters are correct. The behavior in case of empty input (no
regions given) can be set via SetSystem(’noObjectResult’,<Result>), the behavior in case of an
empty input region via SetSystem(’emptyRegionResult’,<Result>), and the behavior in case of an
empty result region via SetSystem(’storeEmptyRegion’,<true/false>). If necessary, an exception
handling is raised.
Parallelization Information
PartitionDynamic is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Connection
See also
Intersection, SmallestRectangle1, ShapeTrans, ClipRegion
Alternatives
PartitionRectangle
Module
Foundation

[out] HRegionX Partitioned HRegionX.PartitionRectangle


([in] double Width, [in] double Height )
void HOperatorSetX.PartitionRectangle ([in] IHObjectX Region,
[out] HUntypedObjectX Partitioned, [in] VARIANT Width, [in] VARIANT Height )

Partition a region into rectangles of equal size.


PartitionRectangle partitions the input region into rectangles having an extent of Width times Height.
The region is always split into rectangles of equal size. Therefore, Width and Height are adapted to the actual
size of the region. If the region is smaller than the given size its output remains unchanged. A partition is only
done if the size of the region is at least 1.5 times the size of the rectangle given by the paramters.
Parameter
. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Region to be partitioned.
. Partitioned (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Partitioned region.
. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Width of the individual rectangles.
. Height (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Height of the individual rectangles.
Result
PartitionRectangle returns TRUE if all parameters are correct. The behavior in case of empty input (no
regions given) can be set via SetSystem(’noObjectResult’,<Result>), the behavior in case of an
empty input region via SetSystem(’emptyRegionResult’,<Result>), and the behavior in case of an
empty result region via SetSystem(’storeEmptyRegion’,<true/false>). If necessary, an exception
handling is raised.
Parallelization Information
PartitionRectangle is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Connection
See also
Intersection, SmallestRectangle1, ShapeTrans, ClipRegion
Alternatives
PartitionDynamic
Module
Foundation

HALCON 8.0.2
910 CHAPTER 12. REGIONS

[out] HRegionX RegionCount HRegionX.RankRegion ([in] long Width,


[in] long Height, [in] long Number )
void HOperatorSetX.RankRegion ([in] IHObjectX Region,
[out] HUntypedObjectX RegionCount, [in] VARIANT Width, [in] VARIANT Height,
[in] VARIANT Number )

Rank operator for regions.


RankRegion calculates the binary rank operator. A filter mask of size Height x Width) is used. In the process,
for each point in the region the number of points of Region lying within the filter mask are counted. If this number
is greater or equal to Number, the current point is added to the output region. If

Height ∗ Width
Number = ,
2

is chosen, the median operator is obtained.


Attention
For Height and Width only odd values > 3 are valid. If invalid parameters are chosen they are converted
automatically (without raising an exception handling) to the next larger odd values.
Parameter

. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Region(s) to be transformed.
. RegionCount (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Resulting region(s).
. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; long / VARIANT
Width of the filter mask.
Default Value : 15
Suggested values : Width ∈ {3, 5, 7, 9, 11, 13, 15, 17, 19, 21}
Typical range of values : 3 ≤ Width ≤ 3(lin)
Minimum Increment : 2
Recommended Increment : 2
Restriction : (W idth ∧ odd)
. Height (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; long / VARIANT
Height of the filter mask.
Default Value : 15
Suggested values : Height ∈ {3, 5, 7, 9, 11, 13, 15, 17, 19, 21}
Typical range of values : 3 ≤ Height ≤ 3(lin)
Minimum Increment : 2
Recommended Increment : 2
Restriction : (Height ∧ odd)
. Number (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Minimum number of points lying within the filter mask.
Default Value : 70
Suggested values : Number ∈ {5, 10, 20, 40, 60, 80, 90, 120, 150, 200}
Typical range of values : 1 ≤ Number ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 10
Restriction : (N umber > 0)
Example

read_image(Image,’affe’)
mean_image(Image,Mean,5,5)
dyn_threshold(Mean,Points,25)
rank_region(Points,Textur,15,15,30)
gen_circle(Mask,10,10,3)
opening1(Textur,Mask,Seg).

HALCON/COM Reference Manual, 2008-5-13


12.7. TRANSFORMATION 911

Complexity
Let F be the area of the input region. Then the runtime complexity is O(F ∗ 8).
Result
RankRegion returns TRUE if all parameters are correct. The behavior in case of empty input (no regions
given) can be set via SetSystem(’noObjectResult’,<Result>) and the behavior in case of an empty
input region via SetSystem(’emptyRegionResult’,<Result>). If necessary, an exception handling is
raised.
Parallelization Information
RankRegion is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Connection, Regiongrowing, Pouring, ClassNdimNorm
Possible Successors
SelectShape, DispRegion
See also
RankImage, MeanImage
Alternatives
ClosingRectangle1, ExpandRegion
Module
Foundation

[out] HRegionX OutputRegion HRegionX.RemoveNoiseRegion


([in] String Type )
void HOperatorSetX.RemoveNoiseRegion ([in] IHObjectX InputRegion,
[out] HUntypedObjectX OutputRegion, [in] VARIANT Type )

Remove noise from a region.


RemoveNoiseRegion removes noise from a region. In mode ’n_4’, a structuring element consisting of the four
neighbors of a point is generated. A dilation with this structuring element is performed, and the intersection of the
result and the input region is calculated. Thus all pixels having no 4-connected neighbor are removed.
Parameter
. InputRegion (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Regions to be modified.
. OutputRegion (output iconic) . . . . . . . . . . . . . . . . . . . . . . . .region(-array) ; HRegionX / HUntypedObjectX
Less noisy regions.
. Type (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Mode of noise removal.
Default Value : ’n_4’
List of values : Type ∈ {’n_4’, ’n_8’, ’n_48’}
Complexity √
Let F be the area of the input region. Then the runtime complexity is O( F ∗ 4).
Result
RemoveNoiseRegion returns TRUE if all parameters are correct. The behavior in case of empty input (no
regions given) can be set via SetSystem(’noObjectResult’,<Result>). If necessary, an exception
handling is raised.
Parallelization Information
RemoveNoiseRegion is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Connection, Regiongrowing, Pouring, ClassNdimNorm
Possible Successors
SelectShape
See also
Dilation1, Intersection, GenRegionPoints

HALCON 8.0.2
912 CHAPTER 12. REGIONS

Module
Foundation

HRegionX.ShapeTrans ([in] String Type )


[out] HRegionX RegionTrans
void HOperatorSetX.ShapeTrans ([in] IHObjectX Region,
[out] HUntypedObjectX RegionTrans, [in] VARIANT Type )

Transform the shape of a region.


ShapeTrans transforms the shape of the input regions depending on the parameter Type:

’convex’ Convex hull.


’ellipse’ Ellipse with the same moments and area as the input region.
’outer_circle’ Smallest enclosing circle.
’inner_circle’ Largest circle fitting into the region.
’rectangle1’ Smallest enclosing rectangle parallel to the coordinate axes.
’rectangle2’ Smallest enclosing rectangle.
’inner_rectangle1’ Largest axis-parallel rectangle fitting into the region.
’inner_center’ The point on the skeleton of the input region having the smallest distance to the center of gravity
of the input region.

Attention
If Type = ’outer_circle’ is selected it might happen that the resulting circular region does not completely cover the
input region. This is because internally the operators SmallestCircle and GenCircle are used to compute
the outer circle.
√ As described in the documentation of SmallestCircle, the calculated radius can be too small
by up to 1/ 2 − 0.5 pixels. Additionally, √ the circle that is generated by GenCircle is translated by up to 0.5
pixels in both directions, i.e., by up to 1/ 2 pixels. Consequently, when adding up both effects, the original region
might protrude beyond the returned circular region by at most 1 pixel.
Parameter
. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Regions to be transformed.
. RegionTrans (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Transformed regions.
. Type (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Type of transformation.
Default Value : ’convex’
List of values : Type ∈ {’convex’, ’ellipse’, ’outer_circle’, ’inner_circle’, ’rectangle1’, ’rectangle2’,
’inner_rectangle1’, ’inner_center’}
Complexity
Let F be the area of the input region. Then the runtime complexity is O(F ).
Result
ShapeTrans returns TRUE if all parameters are correct. The behavior in case of empty input (no regions given)
can be set via SetSystem(’noObjectResult’,<Result>). If necessary, an exception handling is raised.
Parallelization Information
ShapeTrans is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Connection, Regiongrowing
Possible Successors
DispRegion, RegiongrowingMean, AreaCenter
See also
Convexity, EllipticAxis, AreaCenter, SmallestRectangle1, SmallestRectangle2,
InnerRectangle1, SetShape, SelectShape, InnerCircle
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


12.7. TRANSFORMATION 913

HRegionX.Skeleton ( )
[out] HRegionX Skeleton
void HOperatorSetX.Skeleton ([in] IHObjectX Region,
[out] HUntypedObjectX Skeleton )

Compute the skeleton of a region.


Skeleton computes the skeleton, i.e., the medial axis of the input regions. The skeleton is constructed in a way
that each point on it can be seen as the center point of a circle with the largest radius possible while still being
completely contained in the region.
Parameter
. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Region to be thinned.
. Skeleton (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Resulting skeleton.
Number of elements : (Skeleton = Region)
Complexity
Let F be the area of the enclosing rectangle of the input region. Then the runtime complexity is O(F ) (per region).
Result
Skeleton returns TRUE if all parameters are correct. The behavior in case of empty input (no regions given) can
be set via SetSystem(’noObjectResult’,<Result>) and the behavior in case of an empty input region
via SetSystem(’emptyRegionResult’,<Result>). If necessary, an exception handling is raised.
Parallelization Information
Skeleton is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
SobelAmp, EdgesImage, BandpassImage, Threshold, HysteresisThreshold
Possible Successors
JunctionsSkeleton, Pruning
See also
GraySkeleton, SobelAmp, EdgesImage, Roberts, BandpassImage, Threshold
Alternatives
MorphSkeleton, Thinning
References
Eckardt, U. “Verdünnung mit Perfekten Punkten”, Proceedings 10. DAGM-Symposium, IFB 180, Zurich, 1988
Module
Foundation

[out] HRegionX SortedRegions HRegionX.SortRegion ([in] String SortMode,


[in] String Order, [in] String RowOrCol )
void HOperatorSetX.SortRegion ([in] IHObjectX Regions,
[out] HUntypedObjectX SortedRegions, [in] VARIANT SortMode,
[in] VARIANT Order, [in] VARIANT RowOrCol )

Sorting of regions with respect to their relative position.


The operator SortRegion sorts the regions with respect to their relative position. All sorting methods with the
exception of ’character’ use one point of the region. With the help of the parameter RowOrCol = ’row’ these
points will be sorted according to their row and then according to their column. By using ’column’, the column
value will be used first. The following values are available for the parameter SortMode:

’character’ The regions will be treated like characters in a row and will be sorted according to their order in the
line: If two regions overlap horizontally, they will be sorted with respect to their column values, otherwise
they will be sorted with regard to their row values. To be able to sort a line correctly, all regions in the line
must overlap each other vertically. Furthermore, the regions in adjacent rows must not overlap.
’first_point’ The point with the lowest column value in the first row of the region.

HALCON 8.0.2
914 CHAPTER 12. REGIONS

’last_point’ The point with the highest column value in the last row of the region.
’upper_left’ Upper left corner of the surrounding rectangle.
’upper_right’ Upper right corner of the surrounding rectangle.
’lower_left’ Lower left corner of the surrounding rectangle.
’lower_right’ Lower right corner of the surrounding rectangle.

The parameter Order determines whether the sorting order is increasing or decreasing: using ’true’ the order will
be increasing, using ’false’ the order will be decreasing.
Attention

Parameter
. Regions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
Regions to be sorted.
. SortedRegions (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX
Sorted regions.
. SortMode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Kind of sorting.
Default Value : ’first_point’
List of values : SortMode ∈ {’character’, ’first_point’, ’last_point’, ’upper_left’, ’lower_left’, ’upper_right’,
’lower_right’}
. Order (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Increasing or decreasing sorting order.
Default Value : ’true’
List of values : Order ∈ {’true’, ’false’}
. RowOrCol (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Sorting first with respect to row, then to column.
Default Value : ’row’
List of values : RowOrCol ∈ {’row’, ’column’}
Example

Result
If the parameters are correct, the operator SortRegion returns the value TRUE. Otherwise an exception will be
raised.
Parallelization Information
SortRegion is reentrant and processed without parallelization.
Possible Successors
DoOcrMulti, DoOcrSingle
Module
Foundation

[out] VARIANT BeginRow HRegionX.SplitSkeletonLines


([in] long MaxDistance, [out] VARIANT BeginCol, [out] VARIANT EndRow,
[out] VARIANT EndCol )
void HOperatorSetX.SplitSkeletonLines ([in] IHObjectX SkeletonRegion,
[in] VARIANT MaxDistance, [out] VARIANT BeginRow, [out] VARIANT BeginCol,
[out] VARIANT EndRow, [out] VARIANT EndCol )

Split lines represented by one pixel wide, non-branching lines.


SplitSkeletonLines splits lines represented by one pixel wide, non-branching regions into shorter lines
based on their curvature. A line is split if the maximum distance of a point on the line to the line segment

HALCON/COM Reference Manual, 2008-5-13


12.7. TRANSFORMATION 915

connecting its end points is larger than MaxDistance (split & merge algorithm). The start and end points of
the approximating line segments are returned in BeginRow, BeginCol, EndRow, and EndCol.
Attention
The input regions must represent non-branching lines, that is single branches of the skeleton.
Parameter

. SkeletonRegion (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX


Input lines (represented by 1 pixel wide, non-branching regions).
. MaxDistance (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Maximum distance of the line points to the line segment connecting both end points.
Default Value : 3
Suggested values : MaxDistance ∈ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Typical range of values : 1 ≤ MaxDistance ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 1
. BeginRow (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.begin.y ; VARIANT ( integer )
Row coordinates of the start points of the output lines.
. BeginCol (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.begin.x ; VARIANT ( integer )
Column coordinates of the start points of the output lines.
. EndRow (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.end.y ; VARIANT ( integer )
Row coordinates of the end points of the output lines.
. EndCol (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.end.x ; VARIANT ( integer )
Column coordinates of the end points of the output lines.
Example

read_image(Image,’fabrik’)
edges_image (Image, ImaAmp, ImaDir, ’lanser2’, 0.5, ’nms’, 8, 16)
threshold (ImaAmp, RawEdges, 8, 255)
skeleton (RawEdges, Skeleton)
junctions_skeleton (Skeleton, EndPoints, JuncPoints)
difference (Skeleton, JuncPoints, SkelWithoutJunc)
connection (SkelWithoutJunc, SingleBranches)
select_shape (SingleBranches, SelectedBranches, ’area’, ’and’, 16, 99999)
split_skeleton_lines (SelectedBranches, 3, BeginRow, BeginCol, EndRow,
EndCol).

Result
SplitSkeletonLines always returns the value TRUE. The behavior in case of empty input (no regions given)
can be set via SetSystem(’noObjectResult’,<Result>), the behavior in case of an empty input region
via SetSystem(’emptyRegionResult’,<Result>), and the behavior in case of an empty result region
via SetSystem(’storeEmptyRegion’,<true/false>). If necessary, an exception handling is raised.
Parallelization Information
SplitSkeletonLines is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Connection, SelectShape, Skeleton, JunctionsSkeleton, Difference
Possible Successors
SelectLines, PartitionLines, DispLine
See also
SplitSkeletonRegion, DetectEdgeSegments
Module
Foundation

HALCON 8.0.2
916 CHAPTER 12. REGIONS

[out] HRegionX RegionLines HRegionX.SplitSkeletonRegion


([in] long MaxDistance )
void HOperatorSetX.SplitSkeletonRegion
([in] IHObjectX SkeletonRegion, [out] HUntypedObjectX RegionLines,
[in] VARIANT MaxDistance )

Split lines represented by one pixel wide, non-branching regions.


SplitSkeletonRegion splits lines represented by one pixel wide, non-branching regions into shorter lines
based on their curvature. A line is split if the maximum distance of a point on the line to the line segment connecting
its end points is larger than MaxDistance (split & merge algorithm). However, not the approximating lines are
returned, but rather the original lines split into several output regions.
Attention
The input regions must represent non-branching lines, that is single branches of the skeleton.
Parameter
. SkeletonRegion (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Input lines (represented by 1 pixel wide, non-branching regions).
. RegionLines (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX
Split lines.
. MaxDistance (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Maximum distance of the line points to the line segment connecting both end points.
Default Value : 3
Suggested values : MaxDistance ∈ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Typical range of values : 1 ≤ MaxDistance ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 1
Example

read_image(Image,’fabrik’)
edges_image (Image, ImaAmp, ImaDir, ’lanser2’, 0.5, ’nms’, 8, 16)
threshold (ImaAmp, RawEdges, 8, 255)
skeleton (RawEdges, Skeleton)
junctions_skeleton (Skeleton, EndPoints, JuncPoints)
difference (Skeleton, JuncPoints, SkelWithoutJunc)
connection (SkelWithoutJunc, SingleBranches)
select_shape (SingleBranches, SelectedBranches, ’area’, ’and’, 16, 99999)
split_skeleton_region (SelectedBranches, Lines, 3)

Result
SplitSkeletonRegion always returns the value TRUE. The behavior in case of empty input (no regions
given) can be set via SetSystem(’noObjectResult’,<Result>), the behavior in case of an empty input
region via SetSystem(’emptyRegionResult’,<Result>), and the behavior in case of an empty result
region via SetSystem(’storeEmptyRegion’,<true/false>). If necessary, an exception handling is
raised.
Parallelization Information
SplitSkeletonRegion is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Connection, SelectShape, Skeleton, JunctionsSkeleton, Difference
Possible Successors
CountObj, SelectShape, SelectObj, AreaCenter, EllipticAxis, SmallestRectangle2,
GetRegionPolygon, GetRegionContour
See also
SplitSkeletonLines, GetRegionPolygon, GenPolygonsXld
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


Chapter 13

Segmentation

13.1 Classification
void HClassGmmX.AddSamplesImageClassGmm ([in] HImageX Image,
[in] HRegionX ClassRegions, [in] double Randomize )
void HImageX.AddSamplesImageClassGmm ([in] HRegionX ClassRegions,
[in] HClassGmmX GMMHandle, [in] double Randomize )
void HOperatorSetX.AddSamplesImageClassGmm ([in] IHObjectX Image,
[in] IHObjectX ClassRegions, [in] VARIANT GMMHandle, [in] VARIANT Randomize )

Add training samples from an image to the training data of a Gaussian Mixture Model.
AddSamplesImageClassGmm adds training samples from the Image to the Gaussian Mixture Model (GMM)
given by GMMHandle. AddSamplesImageClassGmm is used to store the training samples before a classifier
to be used for the pixel classification of multichannel images with ClassifyImageClassGmm is trained.
AddSamplesImageClassGmm works analogously to AddSampleClassGmm. The Image must have a
number of channels equal to NumDim, as specified with CreateClassGmm. The training regions for the
NumClasses pixel classes are passed in ClassRegions. Hence, ClassRegions must be a tuple containing
NumClasses regions. The order of the regions in ClassRegions determines the class of the pixels. If there
are no samples for a particular class in Image an empty region must be passed at the position of the class in
ClassRegions. With this mechanism it is possible to use multiple images to add training samples for all rel-
evant classes to the GMM by calling AddSamplesImageClassGmm multiple times with the different images
and suitably chosen regions. The regions in ClassRegions should contain representative training samples for
the respective classes. Hence, they need not cover the entire image. The regions in ClassRegions should not
overlap each other, because this would lead to the fact that in the training data the samples from the overlapping
areas would be assigned to multiple classes, which may lead to a lower classification performance. Image data of
integer type can be particularly badly suited for modelling with a GMM. Randomize can be used to overcome
this problem, as explained in AddSampleClassGmm.
Parameter

. Image (input iconic) . . . . . . (multichannel-)image ; HImageX / IHObjectX ( byte, cyclic, direction, int1,
int2, uint2, int4, real )
Training image.
. ClassRegions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
Regions of the classes to be trained.
. GMMHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_gmm ; HClassGmmX / VARIANT
GMM handle.
. Randomize (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Standard deviation of the Gaussian noise added to the training data.
Default Value : 0.0
Suggested values : Randomize ∈ {0.0, 1.5, 2.0}
Restriction : (Randomize ≥ 0.0)

917
918 CHAPTER 13. SEGMENTATION

Result
If the parameters are valid, the operator AddSamplesImageClassGmm returns the value TRUE. If necessary
an exception handling is raised.
Parallelization Information
AddSamplesImageClassGmm is processed completely exclusively without parallelization.
Possible Predecessors
CreateClassGmm
Possible Successors
TrainClassGmm, WriteSamplesClassGmm
See also
ClassifyImageClassGmm, AddSampleClassGmm, ClearSamplesClassGmm,
GetSampleNumClassGmm, GetSampleClassGmm
Alternatives
ReadSamplesClassGmm
Module
Foundation

void HClassMlpX.AddSamplesImageClassMlp ([in] HImageX Image,


[in] HRegionX ClassRegions )
void HImageX.AddSamplesImageClassMlp ([in] HRegionX ClassRegions,
[in] HClassMlpX MLPHandle )
void HOperatorSetX.AddSamplesImageClassMlp ([in] IHObjectX Image,
[in] IHObjectX ClassRegions, [in] VARIANT MLPHandle )

Add training samples from an image to the training data of a multilayer perceptron.
AddSamplesImageClassMlp adds training samples from the image Image to the multilayer perceptron
(MLP) given by MLPHandle. AddSamplesImageClassMlp is used to store the training samples before
a classifier to be used for the pixel classification of multichannel images with ClassifyImageClassMlp
is trained. AddSamplesImageClassMlp works analogously to AddSampleClassMlp. Because here
the MLP is always used for classification, OutputFunction = ’softmax’ must be specified when the MLP is
created with CreateClassMlp. The image Image must have a number of channels equal to NumInput,
as specified with CreateClassMlp. The training regions for the NumOutput pixel classes are passed in
ClassRegions. Hence, ClassRegions must be a tuple containing NumOutput regions. The order of the
regions in ClassRegions determines the class of the pixels. If there are no samples for a particular class
in Image an empty region must be passed at the position of the class in ClassRegions. With this mecha-
nism it is possible to use multiple images to add training samples for all relevant classes to the MLP by calling
AddSamplesImageClassMlp multiple times with the different images and suitably chosen regions. The re-
gions in ClassRegions should contain representative training samples for the respective classes. Hence, they
need not cover the entire image. The regions in ClassRegions should not overlap each other, because this
would lead to the fact that in the training data the samples from the overlapping areas would be assigned to multi-
ple classes, which may lead to slower convergence of the training and a lower classification performance.
Parameter

. Image (input iconic) . . . . . . (multichannel-)image ; HImageX / IHObjectX ( byte, cyclic, direction, int1,
int2, uint2, int4, real )
Training image.
. ClassRegions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
Regions of the classes to be trained.
. MLPHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_mlp ; HClassMlpX / VARIANT
MLP handle.
Result
If the parameters are valid, the operator AddSamplesImageClassMlp returns the value TRUE. If necessary
an exception handling is raised.

HALCON/COM Reference Manual, 2008-5-13


13.1. CLASSIFICATION 919

Parallelization Information
AddSamplesImageClassMlp is processed completely exclusively without parallelization.
Possible Predecessors
CreateClassMlp
Possible Successors
TrainClassMlp, WriteSamplesClassMlp
See also
ClassifyImageClassMlp, AddSampleClassMlp, ClearSamplesClassMlp,
GetSampleNumClassMlp, GetSampleClassMlp, AddSamplesImageClassSvm
Alternatives
ReadSamplesClassMlp
Module
Foundation

void HClassSvmX.AddSamplesImageClassSvm ([in] HImageX Image,


[in] HRegionX ClassRegions )
void HImageX.AddSamplesImageClassSvm ([in] HRegionX ClassRegions,
[in] HClassSvmX SVMHandle )
void HOperatorSetX.AddSamplesImageClassSvm ([in] IHObjectX Image,
[in] IHObjectX ClassRegions, [in] VARIANT SVMHandle )

Add training samples from an image to the training data of a support vector machine.
AddSamplesImageClassSvm adds training samples from the image Image to the support vector machine
(SVM) given by SVMHandle. AddSamplesImageClassSvm is used to store the training samples be-
fore training a classifier for the pixel classification of multichannel images with ClassifyImageClassSvm.
AddSamplesImageClassSvm works analogously to AddSampleClassSvm.
The image Image must have a number of channels equal to NumFeatures, as specified with
CreateClassSvm. The training regions for the NumClasses pixel classes are passed in ClassRegions.
Hence, ClassRegions must be a tuple containing NumClasses regions. The order of the regions in
ClassRegions determines the class of the pixels. If there are no samples for a particular class in Image,
an empty region must be passed at the position of the class in ClassRegions. With this mechanism it
is possible to use multiple images to add training samples for all relevant classes to the SVM by calling
AddSamplesImageClassSvm multiple times with the different images and suitably chosen regions.
The regions in ClassRegions should contain representative training samples for the respective classes. Hence,
they need not cover the entire image. The regions in ClassRegions should not overlap each other, because
this would lead to the fact that in the training data the samples from the overlapping areas would be assigned to
multiple classes, which may lead to slower convergence of the training and a lower classification performance.
A further application of this operator is the automatic novelty detection, where, e.g., anomalies in color or texture
can be detected. For this mode a training set that defines a sample region (e.g., skin regions for skin detection or
samples of the correct texture) is passed to the SVMHandle, which is created in the Mode ’novelty-detection’.
After training, regions that differ from the trained sample regions are detected (e.g., the rejection class for skin or
errors in texture).
Parameter
. Image (input iconic) . . . . . . (multichannel-)image ; HImageX / IHObjectX ( byte, cyclic, direction, int1,
int2, uint2, int4, real )
Training image.
. ClassRegions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
Regions of the classes to be trained.
. SVMHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_svm ; HClassSvmX / VARIANT
SVM handle.
Result
If the parameters are valid AddSamplesImageClassSvm returns the value TRUE. If necessary, an exception
handling is raised.

HALCON 8.0.2
920 CHAPTER 13. SEGMENTATION

Parallelization Information
AddSamplesImageClassSvm is processed completely exclusively without parallelization.
Possible Predecessors
CreateClassSvm
Possible Successors
TrainClassSvm, WriteSamplesClassSvm
See also
ClassifyImageClassSvm, AddSampleClassSvm, ClearSamplesClassSvm,
GetSampleNumClassSvm, GetSampleClassSvm, AddSamplesImageClassMlp
Alternatives
ReadSamplesClassSvm
Module
Foundation

[out] HRegionX RegionClass2Dim HImageX.Class2DimSup


([in] HImageX ImageRow, [in] HRegionX FeatureSpace )
void HOperatorSetX.Class2DimSup ([in] IHObjectX ImageCol,
[in] IHObjectX ImageRow, [in] IHObjectX FeatureSpace,
[out] HUntypedObjectX RegionClass2Dim )

Segment an image using two-dimensional pixel classification.


Class2DimSup classifies the points in two-channel images using a two-dimensional feature space. For each
point, two gray values (one from each image) are used as features. The feature space is represented by the input
region. The classification is done as follows:
A point from the input region of an image is accepted if the point (gr , gc ), which is determined by the respective
gray values, is contained in the region FeatureSpace. gr is here a gray value from the image ImageRow,
while gc is the corresponding gray value from ImageCol.
Let P be a point with the coordinates P = (R, C), gr be the gray value at position (R, C) in the image ImageRow,
and gc be the gray value at position (R, C) in the image ImageCol. Then the point P is aggregated into the output
region if

(gr , gc ) ∈ FeatureSpace

gr is interpreted as row coordinate and gc as column coordinate.


For the generation of FeatureSpace, see Histo2Dim. The feature space can be modified by applying region
transformation operators, such as RankRegion, Dilation1, ShapeTrans, EllipticAxis, etc., before
calling Class2DimSup.
The parameters ImageCol and ImageRow must contain an equal number of images with the same size. The
image points are taken from the intersection of the domains of both images (see ReduceDomain).
Parameter
. ImageCol (input iconic) . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic, int1 )
Input image (first channel).
. ImageRow (input iconic) . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic, int1 )
Input image (second channel).
. FeatureSpace (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Region defining the feature space.
. RegionClass2Dim (output iconic) . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Classified regions.
Complexity
Let A be the area of the input region. Then the runtime complexity is O(2562 + A).
Result
Class2DimSup returns TRUE. If all parameters are correct, the behavior with respect to the input images and

HALCON/COM Reference Manual, 2008-5-13


13.1. CLASSIFICATION 921

output regions can be determined by setting the values of the flags ’no_object_result’, ’empty_region_result’, and
’store_empty_region’ with SetSystem. If necessary, an exception is raised.
Parallelization Information
Class2DimSup is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Histo2Dim, Threshold, DrawRegion, Dilation1, Opening, ShapeTrans
Possible Successors
Connection, SelectShape, SelectGray
See also
Histo2Dim
Alternatives
ClassNdimNorm, ClassNdimBox, Threshold
Module
Foundation

[out] HRegionX Classes HImageX.Class2DimUnsup ([in] HImageX Image2,


[in] long Threshold, [in] long NumClasses )
void HOperatorSetX.Class2DimUnsup ([in] IHObjectX Image1,
[in] IHObjectX Image2, [out] HUntypedObjectX Classes, [in] VARIANT Threshold,
[in] VARIANT NumClasses )

Segment two images by clustering.


Class2DimUnsup performs a classification with two single-channel images. First, a two-dimensional histogram
of the two images is computed ( Histo2Dim). In this histogram, the first maximum is extracted; it serves
as the first cluster center. The histogram is computed with the intersection of the domains of both images (see
ReduceDomain). After this, all pixels in the images that are at most Threshold pixels from the cluster center
in the maximum norm, are determined. These pixels form one output region. Next, the pixels thus classified are
deleted from the histogram so that they are not taken into account for the next class. In this modified histogram,
again the maximum is extracted; it again serves as a cluster center. The above steps are repeated NumClasses
times; thus, NumClasses output regions result. Only pixels defined in both images are returned.
Attention
Both input images must have the same size.
Parameter
. Image1 (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte )
First input image.
. Image2 (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte )
Second input image.
. Classes (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX
Classification result.
. Threshold (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Threshold (maximum distance to the cluster’s center).
Default Value : 15
Suggested values : Threshold ∈ {0, 2, 5, 8, 12, 17, 20, 30, 50, 70}
. NumClasses (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of classes (cluster centers).
Default Value : 5
Suggested values : NumClasses ∈ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 15, 20, 30, 40, 50}
Result
Class2DimUnsup returns TRUE if all parameters are correct. The behavior with respect to the input images
and output regions can be determined by setting the values of the flags ’no_object_result’, ’empty_region_result’,
and ’store_empty_region’ with SetSystem. If necessary, an exception is raised.
Parallelization Information
Class2DimUnsup is reentrant and processed without parallelization.

HALCON 8.0.2
922 CHAPTER 13. SEGMENTATION

Possible Predecessors
Decompose2, Decompose3, MedianImage, AnisotropicDiffusion, ReduceDomain
Possible Successors
SelectShape, SelectGray, Connection
Alternatives
Threshold, Histo2Dim, Class2DimSup, ClassNdimNorm, ClassNdimBox
Module
Foundation

[out] HRegionX Regions HImageX.ClassNdimBox


([in] HClassBoxX ClassifHandle )
[out] HRegionX Regions HClassBoxX.ClassNdimBox
([in] HImageX MultiChannelImage )
void HOperatorSetX.ClassNdimBox ([in] IHObjectX MultiChannelImage,
[out] HUntypedObjectX Regions, [in] VARIANT ClassifHandle )

Classify pixels using hyper-cuboids.


ClassNdimBox classifies the pixels of the multi-channel image given in MultiChannelImage. To do so,
the classificator ClassifHandle created with CreateClassBox is used. The classificator can be trained
using LearnNdimBox or as described with CreateClassBox. More information on the structure of the
classificator can be found also under that operator.
MultiChannelImage is a multi channel image. Its pixel values are used for the classification.
Parameter
. MultiChannelImage (input iconic) . . . . . . multichannel-image-array ; HImageX / IHObjectX ( byte,
direction, cyclic, int1, int2, int4,
real )
Multi channel input image.
. Regions (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX
Classification result.
. ClassifHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_box ; HClassBoxX / VARIANT
Classificator handle.
Example

read_image(Bild,’meer’)
disp_image(Image,WindowHandle)
set_color(WindowHandle,’green’)
fwrite_string(’Draw the learning region’)
fnew_line()
draw_region(Reg1,WindowHandle)
reduce_domain(Image,Reg1,Foreground)
set_color(WindowHandle,’red’)
fwrite_string(’Draw Background’)
fnew_line()
draw_region(Reg2,WindowHandle)
reduce_domain(Image,Reg2,Background)
fwrite_string(’Training’)
fnew_line()
create_class_box(ClassifHandle)
learn_ndim_box(Foreground,Background,Image,ClassifHandle)
fwrite_string(’Classification’)
fnew_line()
class_ndim_box(Image,Res,ClassifHandle)
set_draw(WindowHandle,’fill’)

HALCON/COM Reference Manual, 2008-5-13


13.1. CLASSIFICATION 923

disp_region(Res,WindowHandle)
close_class_box(ClassifHandle).

Complexity
Let N be the number of hyper-cuboids and A be the area of the input region. Then the runtime complexity is
O(N, A).
Result
ClassNdimBox returns TRUE if all parameters are correct. The behavior with respect to the input images and
output regions can be determined by setting the values of the flags ’no_object_result’, ’empty_region_result’, and
’store_empty_region’ with SetSystem. If necessary, an exception is raised.
Parallelization Information
ClassNdimBox is local and processed completely exclusively without parallelization.
Possible Predecessors
CreateClassBox, LearnClassBox, MedianImage, Compose2, Compose3, Compose4, Compose5,
Compose6, Compose7
See also
DescriptClassBox
Alternatives
ClassNdimNorm, Class2DimSup, Class2DimUnsup
Module
Foundation

[out] HRegionX Regions HImageX.ClassNdimNorm ([in] String Metric,


[in] String SingleMultiple, [in] VARIANT Radius, [in] VARIANT Center )
void HOperatorSetX.ClassNdimNorm ([in] IHObjectX MultiChannelImage,
[out] HUntypedObjectX Regions, [in] VARIANT Metric,
[in] VARIANT SingleMultiple, [in] VARIANT Radius, [in] VARIANT Center )

Classify pixels using hyper-spheres or hyper-cubes.


ClassNdimNorm classifies the pixels of the multi-channel image given in MultiChannelImage. The result
is returned in Regions as one region per classification object. The metric used (’euclid’ or ’maximum’) is
determined by Metric. This parameter must be set to the same value used in LearnNdimNorm. The parameter
SingleMultiple determines whether one region (’single’) or multiples regions (’multiple’) are generated for
each cluster. Radius determines the radii or half edge length of the clusters, respectively. Center determines
their centers.
Parameter
. MultiChannelImage (input iconic) . . . . . . . . multichannel-image-array ; HImageX / IHObjectX ( byte )
Multi channel input image.
. Regions (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX
Classification result.
. Metric (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Metric to be used.
Default Value : ’euclid’
List of values : Metric ∈ {’euclid’, ’maximum’}
. SingleMultiple (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Return one region or one region for each cluster.
Default Value : ’single’
List of values : SingleMultiple ∈ {’single’, ’multiple’}
. Radius (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( integer, real )
Cluster radii or half edge lengths (returned by LearnNdimNorm).
. Center (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( integer, real )
Coordinates of the cluster centers (returned by LearnNdimNorm).

HALCON 8.0.2
924 CHAPTER 13. SEGMENTATION

Complexity
Let N be the number of clusters and A be the area of the input region. Then the runtime complexity is O(N, A).
Result
ClassNdimNorm returns TRUE if all parameters are correct. The behavior with respect to the input images and
output regions can be determined by setting the values of the flags ’no_object_result’, ’empty_region_result’, and
’store_empty_region’ with SetSystem. If necessary, an exception is raised.
Parallelization Information
ClassNdimNorm is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
LearnNdimNorm, Compose2, Compose3, Compose4, Compose5, Compose6, Compose7
Possible Successors
Connection, SelectShape, ReduceDomain, SelectGray
Alternatives
ClassNdimBox, Class2DimSup, Class2DimUnsup
Module
Foundation

[out] HRegionX ClassRegions HImageX.ClassifyImageClassGmm


([in] HClassGmmX GMMHandle, [in] double RejectionThreshold )
[out] HRegionX ClassRegions HClassGmmX.ClassifyImageClassGmm
([in] HImageX Image, [in] double RejectionThreshold )
void HOperatorSetX.ClassifyImageClassGmm ([in] IHObjectX Image,
[out] HUntypedObjectX ClassRegions, [in] VARIANT GMMHandle,
[in] VARIANT RejectionThreshold )

Classify an image with a Gaussian Mixture Model.


ClassifyImageClassGmm performs a pixel classification with the Gaussian Mixture Model (GMM)
GMMHandle on the multichannel image Image. Before calling ClassifyImageClassGmm the GMM
must be trained with TrainClassGmm. Image must have NumDim channels, as specified with
CreateClassGmm. On output, ClassRegions contains NumClasses regions as the result of the classi-
fication. The parameter RejectionThreshold can be used to reject pixels that have an uncertain classifi-
cation. RejectionThreshold represents a threshold on the K-sigma probability measure returned by the
classification (see ClassifyClassGmm and EvaluateClassGmm). All pixels having a probability below
RejectionThreshold are not assigned to any class.
Parameter

. Image (input iconic) . . . . . . (multichannel-)image ; HImageX / IHObjectX ( byte, cyclic, direction, int1,
int2, uint2, int4, real )
Input image.
. ClassRegions (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX
Segmented classes.
. GMMHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_gmm ; HClassGmmX / VARIANT
GMM handle.
. RejectionThreshold (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Threshold for the rejection of the classification.
Default Value : 0.5
Suggested values : RejectionThreshold ∈ {0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}
Restriction : ((RejectionT hreshold ≥ 0.0) ∧ (RejectionT hreshold ≤ 1.0))
Example

read_image (Image, ’ic’)


gen_rectangle1 (Board, 80, 320, 110, 350)
gen_rectangle1 (Cap, 359, 263, 371, 302)

HALCON/COM Reference Manual, 2008-5-13


13.1. CLASSIFICATION 925

gen_rectangle1 (Resistor, 200, 252, 290, 256)


gen_rectangle1 (IC, 180, 135, 216, 165)
Classes := [Board,Cap]
Classes := [Classes,Resistor]
Classes := [Classes,IC]
create_class_gmm (3, 4, [1,30], ’full’, ’none’,0, 42, GMMHandle)
add_samples_image_class_gmm (Image, Classes, GMMHandle, 1.5)
get_sample_num_class_gmm (GMMHandle, NumSamples)
train_class_gmm (GMMHandle, 150, 1e-4, ’training’, 1e-4, Centers, Iter)
classify_image_class_gmm (Image, ClassRegions, GMMHandle, 0.0001)
clear_class_gmm (GMMHandle)

Result
If the parameters are valid, the operator ClassifyImageClassGmm returns the value TRUE. If necessary an
exception handling is raised.
Parallelization Information
ClassifyImageClassGmm is reentrant and processed without parallelization.
Possible Predecessors
TrainClassGmm, ReadClassGmm
See also
AddSamplesImageClassGmm, CreateClassGmm
Module
Foundation

[out] HRegionX ClassRegions HImageX.ClassifyImageClassMlp


([in] HClassMlpX MLPHandle, [in] double RejectionThreshold )
[out] HRegionX ClassRegions HClassMlpX.ClassifyImageClassMlp
([in] HImageX Image, [in] double RejectionThreshold )
void HOperatorSetX.ClassifyImageClassMlp ([in] IHObjectX Image,
[out] HUntypedObjectX ClassRegions, [in] VARIANT MLPHandle,
[in] VARIANT RejectionThreshold )

Classify an image with a multilayer perceptron.


ClassifyImageClassMlp performs a pixel classification with the multilayer perceptron (MLP) MLPHandle
on the multichannel image Image. Before calling ClassifyImageClassMlp the MLP must be trained
with TrainClassMlp. Image must have NumInput channels, as specified with CreateClassMlp.
On output, ClassRegions contains NumOutput regions as the result of the classification. The
parameter RejectionThreshold can be used to reject pixels that have an uncertain classification.
RejectionThreshold represents a threshold on the probability measure returned by the classifica-
tion (see ClassifyClassMlp and EvaluateClassMlp). All pixels having a probability below
RejectionThreshold are not assigned to any class. Because an MLP typically assigns pixels that lie out-
side the convex hull of the training data in the feature space to one of the classes with high probability (confi-
dence), it is useful in many cases to explicitly train a rejection class, even if RejectionThreshold is used, by
adding samples for the rejection class with AddSamplesImageClassMlp and by re-training the MLP with
TrainClassMlp.
Parameter
. Image (input iconic) . . . . . . (multichannel-)image ; HImageX / IHObjectX ( byte, cyclic, direction, int1,
int2, uint2, int4, real )
Input image.
. ClassRegions (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX
Segmented classes.
. MLPHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_mlp ; HClassMlpX / VARIANT
MLP handle.

HALCON 8.0.2
926 CHAPTER 13. SEGMENTATION

. RejectionThreshold (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT


Threshold for the rejection of the classification.
Default Value : 0.5
Suggested values : RejectionThreshold ∈ {0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0}
Restriction : ((RejectionT hreshold ≥ 0.0) ∧ (RejectionT hreshold ≤ 1.0))
Example

read_image (Image, ’ic’)


gen_rectangle1 (Board, 80, 320, 110, 350)
gen_rectangle1 (Capacitor, 359, 263, 371, 302)
gen_rectangle1 (Resistor, 200, 252, 290, 256)
gen_rectangle1 (IC, 180, 135, 216, 165)
Classes := [Board,Capacitor]
Classes := [Classes,Resistor]
Classes := [Classes,IC]
create_class_mlp (3, 3, 4, ’softmax’, ’principal_components’, 3, 42,
MLPHandle)
add_samples_image_class_mlp (Image, Classes, MLPHandle)
get_sample_num_class_mlp (MLPHandle, NumSamples)
train_class_mlp (MLPHandle, 200, 1, 0.01, Error, ErrorLog)
classify_image_class_mlp (Image, ClassRegions, MLPHandle, 0.5)
dev_display (ClassRegions)
clear_class_mlp (MLPHandle)

Result
If the parameters are valid, the operator ClassifyImageClassMlp returns the value TRUE. If necessary an
exception handling is raised.
Parallelization Information
ClassifyImageClassMlp is reentrant and processed without parallelization.
Possible Predecessors
TrainClassMlp, ReadClassMlp
See also
AddSamplesImageClassMlp, CreateClassMlp
Alternatives
ClassifyImageClassSvm, ClassNdimBox, ClassNdimNorm, Class2DimSup
Module
Foundation

[out] HRegionX ClassRegions HImageX.ClassifyImageClassSvm


([in] HClassSvmX SVMHandle )
[out] HRegionX ClassRegions HClassSvmX.ClassifyImageClassSvm
([in] HImageX Image )
void HOperatorSetX.ClassifyImageClassSvm ([in] IHObjectX Image,
[out] HUntypedObjectX ClassRegions, [in] VARIANT SVMHandle )

Classify an image with a support vector machine.


ClassifyImageClassSvm performs a pixel classification with the support vector machine (SVM)
SVMHandle on the multichannel image Image. Before calling ClassifyImageClassSvm the SVM
must be trained with TrainClassSvm. Image must have NumFeatures channels, as specified with
CreateClassSvm. On output, ClassRegions contains NumClasses regions as the result of the classi-
fication.
To prevent that the SVM assigns pixels that lie outside the convex hull of the training data in the feature space to
one of the classes, it is useful in many cases to explicitly train a rejection class by adding samples for the rejection
class with AddSamplesImageClassSvm and by re-training the SVM with TrainClassSvm.

HALCON/COM Reference Manual, 2008-5-13


13.1. CLASSIFICATION 927

An alternative for explicitly defining a rejection class is to use an SVM in the mode ’novelty-detection’. Please
refer to the description in CreateClassSvm and AddSamplesImageClassSvm.
Parameter

. Image (input iconic) . . . . . . (multichannel-)image ; HImageX / IHObjectX ( byte, cyclic, direction, int1,
int2, uint2, int4, real )
Input image.
. ClassRegions (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX
Segmented classes.
. SVMHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_svm ; HClassSvmX / VARIANT
SVM handle.
Example

read_image (Image, ’ic’)


gen_rectangle1 (Board, 20, 270, 160, 420)
gen_rectangle1 (Capacitor, 359, 263, 371, 302)
gen_rectangle1 (Resistor, 200, 252, 290, 256)
gen_rectangle1 (IC, 180, 135, 216, 165)
Classes := [Board,Capacitor]
Classes := [Classes,Resistor]
Classes := [Classes,IC]
create_class_svm (3, ’rbf’, 0.01, 0.01, 4, ’one-versus-all’,
’normalization’, 3, SVMHandle)
add_samples_image_class_svm (Image, Classes, SVMHandle)
train_class_svm (SVMHandle, 0.001, ’default’)
reduce_class_svm (SVMHandle, ’bottom_up’, 2, 0.01, SVMHandleReduced)
classify_image_class_svm (Image, ClassRegions, SVMHandleReduced)
dev_display (ClassRegions)
clear_class_svm (SVMHandleReduced)
clear_class_svm (SVMHandle)

Result
If the parameters are valid the operator ClassifyImageClassSvm returns the value TRUE. If necessary, an
exception handling is raised.
Parallelization Information
ClassifyImageClassSvm is reentrant and processed without parallelization.
Possible Predecessors
TrainClassSvm, ReadClassSvm, ReduceClassSvm
See also
AddSamplesImageClassSvm, CreateClassSvm
Alternatives
ClassifyImageClassMlp, ClassNdimBox, ClassNdimNorm, Class2DimSup
Module
Foundation

HALCON 8.0.2
928 CHAPTER 13. SEGMENTATION

void HRegionX.LearnNdimBox ([in] HRegionX Background,


[in] HImageX MultiChannelImage, [in] HClassBoxX ClassifHandle )
void HImageX.LearnNdimBox ([in] HRegionX Foreground,
[in] HRegionX Background, [in] HClassBoxX ClassifHandle )
void HClassBoxX.LearnNdimBox ([in] HRegionX Foreground,
[in] HRegionX Background, [in] HImageX MultiChannelImage )
void HOperatorSetX.LearnNdimBox ([in] IHObjectX Foreground,
[in] IHObjectX Background, [in] IHObjectX MultiChannelImage,
[in] VARIANT ClassifHandle )

Train a classificator using a multi-channel image.


LearnNdimBox trains the classificator ClassifHandle with the gray values of MultiChannelImage
using the points in Foreground as training sample. The points in Background are to be rejected by the
classificator. The classificator trained thus can be used in ClassNdimBox to segment multi-channel images.
Foreground are the points that should be found, Background contains the points that should not be found.
Each pixel is trained once during the training process. For points in Foreground the class “0” is used, while
for Background “1” is used. Pixels are trained by alternating points from Foreground with points from
Background. If one region is smaller than the other, pixels are taken cyclically from the smaller region until the
larger region is exhausted. LearnNdimBox later accepts only points that can be classified into class “0”.
From a user’s point of view the key difference between LearnNdimNorm and LearnNdimBox is that in the
latter case the rejection class affects the classification process itself. Here, a hyper plane is generated that separates
Foreground and Background classes, so that no points in feature space are classified incorrectly. As for
LearnNdimNorm, however, an overlap between Foreground and Background class is allowed. This has its
effect on the return value Quality. The larger the overlap, the smaller this value.
Attention
All channels must be of the same type.
Parameter

. Foreground (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Foreground pixels to be trained.
. Background (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Background pixels to be trained (rejection class).
. MultiChannelImage (input iconic) . . . . . . multichannel-image-array ; HImageX / IHObjectX ( byte,
direction, cyclic, int1, int2, int4,
real )
Multi-channel training image.
. ClassifHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . class_box ; HClassBoxX / VARIANT
Classificator handle.
Complexity
Let N be the number of generated hyper-cuboids and A be the area of the larger input region. Then the runtime
complexity is O(N ∗ A).
Result
LearnNdimBox returns TRUE if all parameters are correct and there is an active classificator. The behav-
ior with respect to the input images can be determined by setting the values of the flags ’no_object_result’ and
’empty_region_result’ with SetSystem. If necessary, an exception is raised.
Parallelization Information
LearnNdimBox is local and processed completely exclusively without parallelization.
Possible Predecessors
CreateClassBox, DrawRegion
Possible Successors
ClassNdimBox, DescriptClassBox
Alternatives
LearnClassBox, LearnNdimNorm

HALCON/COM Reference Manual, 2008-5-13


13.1. CLASSIFICATION 929

Module
Foundation

[out] VARIANT Radius HRegionX.LearnNdimNorm ([in] HRegionX Background,


[in] HImageX Image, [in] String Metric, [in] VARIANT Distance,
[in] VARIANT MinNumberPercent, [out] VARIANT Center, [out] double Quality )
[out] VARIANT Radius HImageX.LearnNdimNorm ([in] HRegionX Foreground,
[in] HRegionX Background, [in] String Metric, [in] VARIANT Distance,
[in] VARIANT MinNumberPercent, [out] VARIANT Center, [out] double Quality )
void HOperatorSetX.LearnNdimNorm ([in] IHObjectX Foreground,
[in] IHObjectX Background, [in] IHObjectX Image, [in] VARIANT Metric,
[in] VARIANT Distance, [in] VARIANT MinNumberPercent, [out] VARIANT Radius,
[out] VARIANT Center, [out] VARIANT Quality )

Construct classes for ClassNdimNorm.


LearnNdimNorm generates classification clusters from the region Foreground and the corresponding gray
values in the multi-channel image Image, which can be used in ClassNdimNorm. Background determines
a class of pixels not to be found in ClassNdimNorm. This parameter may be empty (empty object).
The parameter Distance determines the maximum distance Radius of the clusters. It describes the minimum
distance between two cluster centers. If the parameter Distance is small the (small) hyper-cubes or hyper-
spheres can approximate the feature space well. Simultaneously the runtime during classification increases.
The ratio of the number of pixels in a cluster to the total number of pixels (in percent) must be larger than the
value of MinNumberPercent, otherwise the cluster is not returned. MinNumberPercent serves to eliminate
outliers in the training set. If it is chosen too large many clusters are suppressed.
Two different clustering procedures can be selected: The minimum distance algorithm (n-dimensional hyper-
spheres) and the maximum algorithm (n-dimensional hyper-cubes) for describing the pixels of the image to classify
in the n-dimensional histogram (parameter Metric). The Euclidian metric usually yields the better results, but
takes longer to compute. The parameter Quality returns the quality of the clustering. It is a measure of overlap
between the rejection class and the classificator classes. Values larger than 0 denote the corresponding ratio of
overlap. If no rejection region is given, its value is set to 1. The regions in Background do not influence on the
clustering. They are merely used to check the results that can be expected.
From a user’s point of view the key difference between LearnNdimNorm and LearnNdimBox is that in the
latter case the rejection class affects the classification process itself. Here, a hyper plane is generated that separates
Foreground and Background classes, so that no points in feature space are classified incorrectly. As for
LearnNdimNorm, however, an overlap between Foreground and Background class is allowed. This has its
effect on the return value Quality. The larger the overlap, the smaller this value.
Parameter

. Foreground (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Foreground pixels to be trained.
. Background (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Background pixels to be trained (rejection class).
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte )
Multi-channel training image.
. Metric (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Metric to be used.
Default Value : ’euclid’
List of values : Metric ∈ {’euclid’, ’maximum’}

HALCON 8.0.2
930 CHAPTER 13. SEGMENTATION

. Distance (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )


Maximum cluster radius.
Default Value : 10.0
Suggested values : Distance ∈ {1.0, 2.0, 3.0, 4.0, 6.0, 8.0, 10.0, 13.0, 17.0, 24.0, 30.0, 40.0}
Typical range of values : 0.0 ≤ Distance ≤ 0.0(lin)
Minimum Increment : 0.01
Recommended Increment : 1.0
Restriction : (Distance > 0.0)
. MinNumberPercent (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
The ratio of the number of pixels in a cluster to the total number of pixels (in percent) must be larger than
MinNumberPercent (otherwise the cluster is not output).
Default Value : 0.01
Suggested values : MinNumberPercent ∈ {0.001, 0.05, 0.1, 0.2, 0.5, 1.0, 2.0, 5.0, 10.0}
Typical range of values : 0.0 ≤ MinNumberPercent ≤ 0.0(lin)
Minimum Increment : 0.01
Recommended Increment : 0.1
Restriction : ((0 ≤ M inN umberP ercent) ∧ (M inN umberP ercent ≤ 100))
. Radius (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Cluster radii or half edge lengths.
. Center (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Coordinates of all cluster centers.
. Quality (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Overlap of the rejection class with the classified objects (1: no overlap).
Restriction : ((0 ≤ Quality) ∧ (Quality ≤ 1))
Result
LearnNdimNorm returns TRUE if all parameters are correct. The behavior with respect to the input images can
be determined by setting the values of the flags ’no_object_result’ and ’empty_region_result’ with SetSystem.
If necessary, an exception is raised.
Parallelization Information
LearnNdimNorm is local and processed completely exclusively without parallelization.
Possible Predecessors
MinMaxGray, SobelAmp, BinomialFilter, GaussImage, ReduceDomain, DiffOfGauss
Possible Successors
ClassNdimNorm, Connection, Dilation1, Erosion1, Opening, Closing, RankRegion,
ShapeTrans, Skeleton
See also
ClassNdimNorm, ClassNdimBox, Histo2Dim
Alternatives
LearnNdimBox, LearnClassBox
References
P. Haberäcker, "‘Digitale Bildverarbeitung"’; Hanser-Studienbücher, München, Wien, 1987
Module
Foundation

13.2 Edges

[out] VARIANT BeginRow HImageX.DetectEdgeSegments ([in] long SobelSize,


[in] long MinAmplitude, [in] long MaxDistance, [in] long MinLength,
[out] VARIANT BeginCol, [out] VARIANT EndRow, [out] VARIANT EndCol )
void HOperatorSetX.DetectEdgeSegments ([in] IHObjectX Image,
[in] VARIANT SobelSize, [in] VARIANT MinAmplitude, [in] VARIANT MaxDistance,
[in] VARIANT MinLength, [out] VARIANT BeginRow, [out] VARIANT BeginCol,
[out] VARIANT EndRow, [out] VARIANT EndCol )

Detect straight edge segments.

HALCON/COM Reference Manual, 2008-5-13


13.2. EDGES 931

DetectEdgeSegments detects straight edge segments in the gray image Image. The extracted edge segments
are returned as line segments with start point (BeginRow,BeginCol) and end point (EndRow,EndCol). Edge
detection is based on the Sobel filter, using ’sum_abs’ as parameter and SobelSize as the filter mask size (see
SobelAmp). Only pixels with a filter response larger than MinAmplitude are used as candidates for edge
points. These thresholded edge points are thinned and split into straight segments. Due to technical reasons, edge
points in which several edges meet are lost. Therefore, DetectEdgeSegments usually does not return closed
object contours. The parameter MaxDistance controls the maximum allowed distance of an edge point to its
approximating line. For efficiency reasons, the sum of the absolute values of the coordinate differences is used
instead of the Euclidean distance. MinLength controls the minimum length of the line segments. Lines shorter
than MinLength are not returned.
Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte )


Input image.
. SobelSize (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Mask size of the Sobel operator.
Default Value : 5
List of values : SobelSize ∈ {3, 5, 7, 9, 11, 13}
. MinAmplitude (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Minimum edge strength.
Default Value : 32
Suggested values : MinAmplitude ∈ {10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60, 65, 70, 80, 90, 100, 110}
Typical range of values : 1 ≤ MinAmplitude ≤ 1
Minimum Increment : 1
Recommended Increment : 1
Restriction : (M inAmplitude ≥ 0)
. MaxDistance (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Maximum distance of the approximating line to its original edge.
Default Value : 3
Suggested values : MaxDistance ∈ {2, 3, 4, 5, 6, 7, 8}
Typical range of values : 1 ≤ MaxDistance ≤ 1
Minimum Increment : 1
Recommended Increment : 1
Restriction : (M axDistance ≥ 0)
. MinLength (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Minimum length of to resulting line segments.
Default Value : 10
Suggested values : MinLength ∈ {3, 5, 7, 9, 11, 13, 16, 20}
Typical range of values : 1 ≤ MinLength ≤ 1
Minimum Increment : 1
Recommended Increment : 1
Restriction : (M inLength ≥ 0)
. BeginRow (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.begin.y ; VARIANT ( integer )
Row coordinate of the line segments’ start points.
. BeginCol (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.begin.x ; VARIANT ( integer )
Column coordinate of the line segments’ start points.
. EndRow (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.end.y ; VARIANT ( integer )
Row coordinate of the line segments’ end points.
. EndCol (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . line.end.x ; VARIANT ( integer )
Column coordinate of the line segments’ end points.
Result
DetectEdgeSegments returns TRUE if all parameters are correct. If the input is empty the behaviour can be
set via SetSystem(’noObjectResult’,<Result>). If necessary, an exception handling is raised.
Parallelization Information
DetectEdgeSegments is reentrant and automatically parallelized (on tuple level, channel level).
Possible Predecessors
SigmaImage, MedianImage

HALCON 8.0.2
932 CHAPTER 13. SEGMENTATION

Possible Successors
SelectLines, PartitionLines, SelectLinesLongest, LinePosition, LineOrientation
Alternatives
SobelAmp, Threshold, Skeleton
Module
Foundation

[out] HRegionX RegionHysteresis HImageX.HysteresisThreshold


([in] long Low, [in] long High, [in] long MaxLength )
void HOperatorSetX.HysteresisThreshold ([in] IHObjectX Image,
[out] HUntypedObjectX RegionHysteresis, [in] VARIANT Low, [in] VARIANT High,
[in] VARIANT MaxLength )

Perform a hysteresis threshold operation on an image.


HysteresisThreshold performs a hysteresis threshold operation (introduced by Canny) on an image. All
points in the input image Image having a gray value larger than or equal to High are immediately accepted
(“secure” points). Conversely, all points with gray values less than Low are immediately rejected. “Potential”
points with gray values between both thresholds are accepted if they are connected to “secure” points by a path of
“potential” points having a length of at most MaxLength points. This means that “secure” points influence their
surroundings (hysteresis).
Parameter
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte, uint2 )
Input image.
. RegionHysteresis (output iconic) . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Segmented region.
. Low (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Lower threshold for the gray values.
Default Value : 30
Suggested values : Low ∈ {5, 10, 15, 20, 30, 40, 50, 60, 70, 80, 90, 100}
Typical range of values : 0 ≤ Low ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 5
Restriction : ((0 < Low) ∧ (Low < 255))
. High (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Upper threshold for the gray values.
Default Value : 60
Suggested values : High ∈ {5, 10, 15, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130}
Typical range of values : 0 ≤ High ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 5
Restriction : (((0 < High) ∧ (High < 255)) ∧ (High > Low))
. MaxLength (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Maximum length of a path of “potential” points to reach a “secure” point.
Default Value : 10
Suggested values : MaxLength ∈ {1, 2, 3, 5, 7, 10, 12, 14, 17, 20, 25, 30, 35, 40, 50}
Minimum Increment : 1
Recommended Increment : 5
Restriction : (M axLength > 1)
Result
HysteresisThreshold returns TRUE if all parameters are correct. The behavior with respect to the
input images and output regions can be determined by setting the values of the flags ’no_object_result’,
’empty_region_result’, and ’store_empty_region’ with SetSystem. If necessary, an exception is raised.
Parallelization Information
HysteresisThreshold is reentrant and automatically parallelized (on tuple level).

HALCON/COM Reference Manual, 2008-5-13


13.2. EDGES 933

See also
EdgesImage, SobelDir, BackgroundSeg
Alternatives
DynThreshold, Threshold, Class2DimSup, FastThreshold
References
J. Canny, "‘Finding Edges and Lines in Images"’; Report, AI-TR-720, M.I.T. Artificial Intelligence Lab., Cam-
bridge, MA, 1983.
Module
Foundation

[out] HImageX ImageResult HImageX.NonmaxSuppressionAmp


([in] String Mode )
void HOperatorSetX.NonmaxSuppressionAmp ([in] IHObjectX ImgAmp,
[out] HUntypedObjectX ImageResult, [in] VARIANT Mode )

Suppress non-maximum points on an edge.


NonmaxSuppressionAmp suppresses all points in the regions of the image ImgAmp whose gray values are
not local (directed) maxima. In contrast to NonmaxSuppressionDir, a direction image is not needed. Two
modes of operation can be selected:

’hvnms’ A point is labeled as a local maximum if its gray value is larger than or equal to the gray values within
a seach space of ± 5 pixels, either horizontally or vertically. Non-maximum points are removed from the
region, gray values remain unchanged.
’loc_max’ A point is labeled as a local maximum if its gray value is larger than or equal to the gray values of its
eight neighbors.

Parameter

. ImgAmp (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte, uint2 )


Amplitude (gradient magnitude) image.
. ImageResult (output iconic) . . . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, uint2 )
Image with thinned edge regions.
. Mode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Select horizontal/vertical or undirected NMS.
Default Value : ’hvnms’
List of values : Mode ∈ {’hvnms’, ’loc_max’}
Result
NonmaxSuppressionAmp returns TRUE if all parameters are correct. The behavior with respect to the
input images and output regions can be determined by setting the values of the flags ’no_object_result’,
’empty_region_result’, and ’store_empty_region’ with SetSystem. If necessary, an exception is raised.
Parallelization Information
NonmaxSuppressionAmp is reentrant and automatically parallelized (on tuple level, channel level).
Possible Predecessors
SobelAmp
Possible Successors
Threshold, HysteresisThreshold
See also
Skeleton
Alternatives
LocalMax, NonmaxSuppressionDir
References
S.Lanser: "‘Detektion von Stufenkanten mittels rekursiver Filter nach Deriche"’; Diplomarbeit; Technische Uni-
versität München, Institut für Informatik, Lehrstuhl Prof. Radig; 1991.

HALCON 8.0.2
934 CHAPTER 13. SEGMENTATION

J.Canny: "‘Finding Edges and Lines in Images"’; Report, AI-TR-720; M.I.T. Artificial Intelligence Lab., Cam-
bridge, MA; 1983.
Module
Foundation

[out] HImageX ImageResult HImageX.NonmaxSuppressionDir


([in] HImageX ImgDir, [in] String Mode )
void HOperatorSetX.NonmaxSuppressionDir ([in] IHObjectX ImgAmp,
[in] IHObjectX ImgDir, [out] HUntypedObjectX ImageResult, [in] VARIANT Mode )

Suppress non-maximum points on an edge using a direction image.


NonmaxSuppressionDir suppresses all points in the regions of the image ImgAmp whose gray values are not
local (directed) maxima. ImgDir is a direction image giving the direction perpendicular to the local maximum
(Unit: 2 degrees, i.e., 50 degrees are coded as 25 in the image). Such images are returned, for example, by
EdgesImage. Two modes of operation can be selected:

’nms’ Each point in the image is tested whether its gray value is a local maximum perpendicular to its direction.
In this mode only the two neighbors closest to the given direction are examined. If one of the two gray values
is greater than the gray value of the point to be tested, it is suppressed (i.e., removed from the input region.
The corresponding gray value remains unchanged).
’inms’ Like ’nms’. However, the two gray values for the test are obtained by interpolation from four adjacent
points.

Parameter
. ImgAmp (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte, uint2 )
Amplitude (gradient magnitude) image.
. ImgDir (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( direction )
Direction image.
. ImageResult (output iconic) . . . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, uint2 )
Image with thinned edge regions.
. Mode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Select non-maximum-suppression or interpolating NMS.
Default Value : ’nms’
List of values : Mode ∈ {’nms’, ’inms’}
Result
NonmaxSuppressionDir returns TRUE if all parameters are correct. The behavior with respect to the
input images and output regions can be determined by setting the values of the flags ’no_object_result’,
’empty_region_result’, and ’store_empty_region’ with SetSystem. If necessary, an exception is raised.
Parallelization Information
NonmaxSuppressionDir is reentrant and automatically parallelized (on tuple level, channel level).
Possible Predecessors
EdgesImage, SobelDir, FreiDir
Possible Successors
Threshold, HysteresisThreshold
See also
Skeleton
Alternatives
NonmaxSuppressionAmp
References
S.Lanser: "‘Detektion von Stufenkanten mittels rekursiver Filter nach Deriche"’; Diplomarbeit; Technische Uni-
versität München, Institut für Informatik, Lehrstuhl Prof. Radig; 1991.
J.Canny: "‘Finding Edges and Lines in Images"’; Report, AI-TR-720; M.I.T. Artificial Intelligence Lab., Cam-
bridge; 1983.

HALCON/COM Reference Manual, 2008-5-13


13.3. REGIONGROWING 935

Module
Foundation

13.3 Regiongrowing

[out] HRegionX RegionExpand HRegionX.ExpandGray ([in] HImageX Image,


[in] HRegionX ForbiddenArea, [in] VARIANT Iterations, [in] String Mode,
[in] VARIANT Threshold )
[out] HRegionX RegionExpand HImageX.ExpandGray ([in] HRegionX Regions,
[in] HRegionX ForbiddenArea, [in] VARIANT Iterations, [in] String Mode,
[in] VARIANT Threshold )
void HOperatorSetX.ExpandGray ([in] IHObjectX Regions,
[in] IHObjectX Image, [in] IHObjectX ForbiddenArea,
[out] HUntypedObjectX RegionExpand, [in] VARIANT Iterations,
[in] VARIANT Mode, [in] VARIANT Threshold )

Fill gaps between regions (depending on gray value or color) or split overlapping regions.
ExpandGray closes gaps between the input regions, which resulted from the suppression of small regions in a
segmentation operator, (mode ’image’), for example, or separates overlapping regions ’region’). Both uses result
from the expansion of regions. The operator works by adding a one pixel wide “strip” to a region, in which the
gray values or color are different from the gray values or color of neighboring pixles on the region’s border by at
most Threshold (in each channel). For images of type ’cyclic’ (e.g., direction images), also points with a gray
value difference of at least 255 − Threshold are added to the output region.
The expansion takes place only in regions, which are designated as not “forbidden” (parameter
ForbiddenArea). The number of iterations is determined by the parameter Iterations. By passing ’maxi-
mal’, ExpandGray iterates until convergence, i.e., until no more changes occur. By passing 0 for this parameter,
all non-overlapping regions are returned. The two modes of operation (’image’ and ’region’) are different in the
following ways:

’image’ The input regions are expanded iteratively until they touch another region or the image border, or the
expansion stops because of too high gray value differences. Because ExpandGray processes all regions
simultaneously, gaps between regions are distributed evenly to all regions with a similar gray value. Over-
lapping regions are split by distributing the area of overlap evenly to both regions.
’region’ No expansion of the input regions is performed. Instead, only overlapping regions are split by distributing
the area of overlap evenly to regions having a matching gray value or color.

Attention
Because regions are only expanded into areas having a matching gray value or color, usually gaps will remain
between the output regions, i.e., the segmentation is not complete.
Parameter
. Regions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Regions for which the gaps are to be closed, or which are to be separated.
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, cyclic )
Image (possibly multi-channel) for gray value or color comparison.
. ForbiddenArea (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
Regions in which no expansion takes place.
. RegionExpand (output iconic) . . . . . . . . . . . . . . . . . . . . . . . .region(-array) ; HRegionX / HUntypedObjectX
Expanded or separated regions.
. Iterations (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( integer, string )
Number of iterations.
Default Value : ’maximal’
Suggested values : Iterations ∈ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ’maximal’}
Typical range of values : 1 ≤ Iterations ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 1

HALCON 8.0.2
936 CHAPTER 13. SEGMENTATION

. Mode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT


Expansion mode.
Default Value : ’image’
List of values : Mode ∈ {’image’, ’region’}
. Threshold (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Maximum difference between the gray value or color at the region’s border and a candidate for expansion.
Default Value : 32
Suggested values : Threshold ∈ {5, 10, 15, 20, 25, 30, 40, 50}
Typical range of values : 1 ≤ Threshold ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 5
Result
ExpandGray always returns the value TRUE. The behavior in case of empty input (no regions given) can be
set via SetSystem(’noObjectResult’,<Result>), the behavior in case of an empty input region via
SetSystem(’emptyRegionResult’,<Result>), and the behavior in case of an empty result region via
SetSystem(’storeEmptyRegion’,<true/false>). If necessary, an exception handling is raised.
Parallelization Information
ExpandGray is reentrant and processed without parallelization.
Possible Predecessors
Connection, Regiongrowing, Pouring, ClassNdimNorm
Possible Successors
SelectShape
See also
ExpandGrayRef, ExpandRegion
Module
Foundation

[out] HRegionX RegionExpand HRegionX.ExpandGrayRef ([in] HImageX Image,


[in] HRegionX ForbiddenArea, [in] VARIANT Iterations, [in] String Mode,
[in] VARIANT RefGray, [in] VARIANT Threshold )
[out] HRegionX RegionExpand HImageX.ExpandGrayRef
([in] HRegionX Regions, [in] HRegionX ForbiddenArea, [in] VARIANT Iterations,
[in] String Mode, [in] VARIANT RefGray, [in] VARIANT Threshold )
void HOperatorSetX.ExpandGrayRef ([in] IHObjectX Regions,
[in] IHObjectX Image, [in] IHObjectX ForbiddenArea,
[out] HUntypedObjectX RegionExpand, [in] VARIANT Iterations,
[in] VARIANT Mode, [in] VARIANT RefGray, [in] VARIANT Threshold )

Fill gaps between regions (depending on gray value or color) or split overlapping regions.
ExpandGrayRef closes gaps between the input regions, which resulted from the suppression of small regions
in a segmentation operator, (mode ’image’), for example, or separates overlapping regions ’region’). Both uses
result from the expansion of regions. The operator works by adding a one pixel wide “strip” to a region, in
which the gray values or color are different from a reference gray value or color by at most Threshold (in each
channel). For images of type ’cyclic’ (e.g., direction images), also points with a gray value difference of at least
255 − Threshold are added to the output region.
The expansion takes place only in regions, which are designated as not “forbidden” (parameter
ForbiddenArea). The number of iterations is determined by the parameter Iterations. By passing ’max-
imal’, ExpandGrayRef iterates until convergence, i.e., until no more changes occur. By passing 0 for this
parameter, all non-overlapping regions are returned. The two modes of operation (’image’ and ’region’) are differ-
ent in the following ways:

’image’ The input regions are expanded iteratively until they touch another region or the image border, or the
expansion stops because of too high gray value differences. Because ExpandGrayRef processes all re-
gions simultaneously, gaps between regions are distributed evenly to all regions with a similar gray value.
Overlapping regions are split by distributing the area of overlap evenly to both regions.

HALCON/COM Reference Manual, 2008-5-13


13.3. REGIONGROWING 937

’region’ No expansion of the input regions is performed. Instead, only overlapping regions are split by distributing
the area of overlap evenly to regions having a matching gray value or color.

Attention
Because regions are only expanded into areas having a matching gray value or color, usually gaps will remain
between the output regions, i.e., the segmentation is not complete.
Parameter
. Regions (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Regions for which the gaps are to be closed, or which are to be separated.
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, cyclic )
Image (possibly multi-channel) for gray value or color comparison.
. ForbiddenArea (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
Regions in which no expansion takes place.
. RegionExpand (output iconic) . . . . . . . . . . . . . . . . . . . . . . . .region(-array) ; HRegionX / HUntypedObjectX
Expanded or separated regions.
. Iterations (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( integer, string )
Number of iterations.
Default Value : ’maximal’
Suggested values : Iterations ∈ {’maximal’, 1, 2, 3, 4, 5, 7, 10, 15, 20, 30, 50, 70, 100, 150, 200, 300,
500}
Typical range of values : 1 ≤ Iterations ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 1
. Mode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Expansion mode.
Default Value : ’image’
List of values : Mode ∈ {’image’, ’region’}
. RefGray (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Reference gray value or color for comparison.
Default Value : 128
Suggested values : RefGray ∈ {1, 10, 20, 50, 100, 128, 200, 255}
Typical range of values : 1 ≤ RefGray ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 10
. Threshold (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Maximum difference between the reference gray value or color and a candidate for expansion.
Default Value : 32
Suggested values : Threshold ∈ {4, 10, 15, 20, 25, 30, 40}
Typical range of values : 1 ≤ Threshold ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 5
Result
ExpandGrayRef always returns the value TRUE. The behavior in case of empty input (no regions given) can be
set via SetSystem(’noObjectResult’,<Result>), the behavior in case of an empty input region via
SetSystem(’emptyRegionResult’,<Result>), and the behavior in case of an empty result region via
SetSystem(’storeEmptyRegion’,<true/false>). If necessary, an exception handling is raised.
Parallelization Information
ExpandGrayRef is reentrant and processed without parallelization.
Possible Predecessors
Connection, Regiongrowing, Pouring, ClassNdimNorm
Possible Successors
SelectShape
See also
ExpandGray, ExpandRegion
Module
Foundation

HALCON 8.0.2
938 CHAPTER 13. SEGMENTATION

[out] HRegionX RegionExpand HImageX.ExpandLine ([in] long Coordinate,


[in] String ExpandType, [in] String RowColumn, [in] VARIANT Threshold )
void HOperatorSetX.ExpandLine ([in] IHObjectX Image,
[out] HUntypedObjectX RegionExpand, [in] VARIANT Coordinate,
[in] VARIANT ExpandType, [in] VARIANT RowColumn, [in] VARIANT Threshold )

Expand a region starting at a given line.


ExpandLine generates a region by expansion, starting at a given line (row or column). The expansion is ter-
minated when the current gray value differs by more than Threshold from the mean gray value along the line
(ExpandType = ’mean’) or from the previously added gray value (ExpandType = ’gradient’).
Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte )


Input image.
. RegionExpand (output iconic) . . . . . . . . . . . . . . . . . . . . . . . .region(-array) ; HRegionX / HUntypedObjectX
Extracted segments.
. Coordinate (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Row or column coordinate.
Default Value : 256
Suggested values : Coordinate ∈ {16, 64, 128, 200, 256, 300, 400, 511}
Restriction : (Coordinate ≥ 0)
. ExpandType (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Stopping criterion.
Default Value : ’gradient’
List of values : ExpandType ∈ {’gradient’, ’mean’}
. RowColumn (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Segmentation mode (row or column).
Default Value : ’row’
List of values : RowColumn ∈ {’row’, ’column’}
. Threshold (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Threshold for the expansion.
Default Value : 3.0
Suggested values : Threshold ∈ {0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 13.0, 17.0, 20.0, 30.0}
Typical range of values : 1.0 ≤ Threshold ≤ 1.0(lin)
Minimum Increment : 1.0
Recommended Increment : 1.0
Restriction : ((T hreshold ≥ 0.0) ∧ (T hreshold ≤ 255.0))
Parallelization Information
ExpandLine is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
BinomialFilter, GaussImage, SmoothImage, AnisotropicDiffusion, MedianImage,
AffineTransImage, RotateImage
Possible Successors
Intersection, Opening, Closing
Alternatives
RegiongrowingMean, ExpandGray, ExpandGrayRef
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


13.3. REGIONGROWING 939

[out] HRegionX Regions HImageX.Regiongrowing ([in] long Row,


[in] long Column, [in] VARIANT Tolerance, [in] long MinSize )
void HOperatorSetX.Regiongrowing ([in] IHObjectX Image,
[out] HUntypedObjectX Regions, [in] VARIANT Row, [in] VARIANT Column,
[in] VARIANT Tolerance, [in] VARIANT MinSize )

Segment an image using regiongrowing.


Regiongrowing segments images into regions of the same intensity — rastered into rectangles of size Row ×
Column. In order to decide whether two adjacent rectangles belong to the same region only the gray value of their
center points is used. If the gray value difference is less then or equal to Tolerance the rectangles are merged
into one region.
If g1 und g2 are two gray values to be examined, they are merged into the same region if:

|g1 − g2 | < Tolerance

For images of type ’cyclic’, the following formulas are used:

(|g1 − g2 | < Tolerance) ∧ (|g1 − g2 | ≤ 127)

(256 − |g1 − g2 | < Tolerance) ∧ (|g1 − g2 | > 127)

For rectangles larger than one pixel, ususally the images should be smoothed with a lowpass filter with a size of at
least Row × Column before calling Regiongrowing (so that the gray values at the centers of the regtangles
are “representative” for the whole rectangle). If the image contains little noise and the rectangles are small, the
smoothing can be omitted in many cases.
The resulting regions are collections of rectangles of the chosen size Row × Column . Only regions containing at
least MinSize points are returned.
Regiongrowing is a very fast operation, and thus suited for time-critical applications.
Attention
Column and Row are automatically converted to odd values if necessary.
Parameter

. Image (input iconic) . . . . . . image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2, int4,
real )
Input image.
. Regions (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX
Segmented regions.
. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; long / VARIANT
Vertical distance between tested pixels (height of the raster).
Default Value : 3
Suggested values : Row ∈ {1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21}
Typical range of values : 1 ≤ Row ≤ 1(lin)
Minimum Increment : 2
Recommended Increment : 2
Restriction : (Row ∧ odd)
. Column (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; long / VARIANT
Horizontal distance between tested pixels (height of the raster).
Default Value : 3
Suggested values : Column ∈ {1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21}
Typical range of values : 1 ≤ Column ≤ 1(lin)
Minimum Increment : 2
Recommended Increment : 2
Restriction : (Column ∧ odd)

HALCON 8.0.2
940 CHAPTER 13. SEGMENTATION

. Tolerance (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )


Points with a gray value difference less then or equal to tolerance are accumulated into the same object.
Default Value : 6.0
Suggested values : Tolerance ∈ {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 12.0, 14.0, 18.0, 25.0}
Typical range of values : 1.0 ≤ Tolerance ≤ 1.0(lin)
Minimum Increment : 0.01
Recommended Increment : 1.0
Restriction : ((0 ≤ T olerance) ∧ (T olerance < 127))
. MinSize (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Minimum size of the output regions.
Default Value : 100
Suggested values : MinSize ∈ {1, 5, 10, 20, 50, 100, 200, 500, 1000}
Minimum Increment : 1
Recommended Increment : 5
Restriction : (M inSize ≥ 1)
Example

read_image(Image,’fabrik’)
mean_image(Image,Mean,Row,Column)
regiongrowing(Mean,Result,Row,Column,6.0,100).

Complexity
Let N be the number of found regions and M the number of points in one of these regions. Then the runtime
complexity is O(N ∗ log(M ) ∗ M ).
Result
Regiongrowing returns TRUE if all parameters are correct. The behavior with respect to the input images and
output regions can be determined by setting the values of the flags ’no_object_result’, ’empty_region_result’, and
’store_empty_region’ with SetSystem. If necessary, an exception is raised.
Parallelization Information
Regiongrowing is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
BinomialFilter, MeanImage, GaussImage, SmoothImage, MedianImage,
AnisotropicDiffusion
Possible Successors
SelectShape, ReduceDomain, SelectGray
Alternatives
RegiongrowingN, RegiongrowingMean, LabelToRegion
Module
Foundation

[out] HRegionX Regions HImageX.RegiongrowingMean


([in] VARIANT StartRows, [in] VARIANT StartColumns, [in] double Tolerance,
[in] long MinSize )
void HOperatorSetX.RegiongrowingMean ([in] IHObjectX Image,
[out] HUntypedObjectX Regions, [in] VARIANT StartRows,
[in] VARIANT StartColumns, [in] VARIANT Tolerance, [in] VARIANT MinSize )

Perform a regiongrowing using mean gray values.


RegiongrowingMean performs a regiongrowing using the mean gray values of a region, starting from points
given by StartRows and StartColumns. At any point in the process the mean gray value of the current region
is calculated. Gray values at the boundary of the region are added to the region if they differ from the current mean
by less than Tolerance. Regions smaller than MinSize are suppressed.

HALCON/COM Reference Manual, 2008-5-13


13.3. REGIONGROWING 941

If no starting points are given (empty tuples), the expansion process starts at the upper leftmost point, and is
continued with the first unprocessed point after a region has been created.
Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte, uint2, int4 )


Input image.
. Regions (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX
Segmented regions.
. StartRows (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( integer )
Row coordinates of the starting points.
Default Value : []
Minimum Increment : 1
Recommended Increment : 1
. StartColumns (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( integer )
Column coordinates of the starting points.
Default Value : []
Minimum Increment : 1
Recommended Increment : 1
. Tolerance (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Maximum deviation from the mean.
Default Value : 5.0
Suggested values : Tolerance ∈ {0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 12.0, 15.0, 17.0,
20.0, 25.0, 30.0, 40.0}
Restriction : (T olerance > 0.0)
. MinSize (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Minimum size of a region.
Default Value : 100
Suggested values : MinSize ∈ {0, 10, 30, 50, 100, 500, 1000, 2000}
Minimum Increment : 1
Recommended Increment : 100
Restriction : (M inSize ≥ 0)
Result
RegiongrowingMean returns TRUE if all parameters are correct. The behavior with respect to the input images
and output regions can be determined by setting the values of the flags ’no_object_result’, ’empty_region_result’,
and ’store_empty_region’ with SetSystem. If necessary, an exception is raised.
Parallelization Information
RegiongrowingMean is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
BinomialFilter, GaussImage, SigmaImage, AnisotropicDiffusion, MedianImage,
MeanImage
Possible Successors
SelectShape, ReduceDomain, Opening, ExpandRegion
Alternatives
Regiongrowing, RegiongrowingN
Module
Foundation

[out] HRegionX Regions HImageX.RegiongrowingN ([in] String Metric,


[in] VARIANT MinTolerance, [in] VARIANT MaxTolerance, [in] long MinSize )
void HOperatorSetX.RegiongrowingN ([in] IHObjectX MultiChannelImage,
[out] HUntypedObjectX Regions, [in] VARIANT Metric,
[in] VARIANT MinTolerance, [in] VARIANT MaxTolerance, [in] VARIANT MinSize )

Segment an image using regiongrowing for multi-channel images.

HALCON 8.0.2
942 CHAPTER 13. SEGMENTATION

RegiongrowingN performs a multi-channel regiongrowing. The n channels give rise to an n-dimensional fea-
ture vector. Neighboring points are aggregated into the same region if the difference of their feature vectors with
respect to the given metric lies in the interval [MinTolerance, MaxTolerance]. Only neighbors of the 4-
neighborhood are examined. The following metrics can be used:
Let gA denote the gray value in the feature vector A at point a of the image, and likewise be gB the gray value
in the feature vector B at point a neighboring point b. Let g(d) be the gray value with index d. Furthermore, let
M inT denote MinTolerance and M axT denote MaxTolerance.

’1-norm’: Sum of absolute values


1X
M inT ≤ |gA − gB | ≤ M axT
n
’2-norm’: Euclidian distance rP
(gA − gB )2
M inT ≤ ≤ M axT
n
’3-norm’: p - Norm with p = 3 rP
3 (gA − gB )3
M inT ≤ ≤ M axT
n
’4-norm’: p - Norm with p = 4 rP
4 (gA − gB )4
M inT ≤ ≤ M axT
n
’n-norm’: Minkowski distance rP
n (gA − gB )n
M inT ≤ ≤ M axT
n
’max-diff’: Supremum distance
M inT ≤ max {|gA − gB |} ≤ M axT

’min-diff’: Infimum distance


M inT ≤ min {|gA − gB |} ≤ M axT

’variance’: Variance of gray value differences

M inT ≤ V ar(gA − gB ) ≤ M axT

’dot-product’: Dot product


1
qX
M inT ≤ (gA gB ) ≤ M axT
n
’correlation’: Correlation
1X
mA = gA
n
1 X
q
V arA = (gA − mA )2
n
1X
mB = gB
n
1
qX
V arB = (gB − mB )2
n
1 X (gA − mA )(gB − mB )
M inT ≤ 2 ≤ M axT
n (V arA V arB )
’mean-diff’: Difference of arithmetic means
1X
a= gA
n
1X
b= gB
n
M inT ≤ |a − b| ≤ M axT

HALCON/COM Reference Manual, 2008-5-13


13.3. REGIONGROWING 943

’mean-ratio’: Ratio of arithmetic means


1X
a= gA
n
1X
b= gB
n
 
a b
M inT ≤ min , ≤ M axT
b a
’length-diff’: Difference of the vector lengths rP
2
gA
a=
n
rP
gB2
b=
n
M inT ≤ |a − b| ≤ M axT

’length-ratio’: Ratio of the vector lengths rP


2
gA
a=
n
rP
2
gB
b=
n
 
a b
M inT ≤ min , ≤ M axT
b a
’n-norm-ratio’: Ratio of the vector lengths w.r.t the p-norm with p = n
rP
n
gA
n
a=
n
rP
n
gB
n
b=
n
 
a b
M inT ≤ min , ≤ M axT
b a
’gray-max-diff’: Difference of the maximum gray values

a = max {|gA |}

b = max {|gB |}
M inT ≤ |a − b| ≤ M axT
’gray-max-ratio’: Ratio of the maximum gray values

a = max {|gA |}

b = max {|gB |}
 
a b
M inT ≤ min , ≤ M axT
b a
’gray-min-diff’: Difference of the minimum gray values

a = min {|gA |}

b = min {|gB |}
M inT ≤ |a − b| ≤ M axT

HALCON 8.0.2
944 CHAPTER 13. SEGMENTATION

’gray-min-ratio’: Ratio of the minimum gray values

a = min {|gA |}

b = min {|gB |}
 
a b
M inT ≤ min , ≤ M axT
b a
’variance-diff’: Difference of the variances over all gray values (channels)

M inT ≤ |V ar(gA ) − V ar(gB )| ≤ M axT

’variance-ratio’: Ratio of the variances over all gray values (channels)

V ar(gB )
M inT ≤ ≤ M axT
V ar(gA )

’mean-abs-diff’: Difference of the sum of absolute values over all gray values (channels)
X
a= |gA (d) − gA (k)|
d,k,k<d

X
b= |gB (d) − gB (k)|
d,k,k<d

|a − b|
M inT ≤ ≤ M axT
Anzahl der Summen
’mean-abs-ratio’: Ratio of the sum of absolute values over all gray values (channels)
X
a= |gA (d) − gA (k)|
d,k,k<d

X
b= |gB (d) − gB (k)|
d,k,k<d
 
a b
M inT ≤ min , ≤ M axT
b a
’max-abs-diff’: Difference of the maximum distance of the components

a = max {gA (d), gA (k)}

b = max {gB (d), gB (k)}


M inT ≤ |a − b| ≤ M axT

’max-abs-ratio’: Ratio of the maximum distance of the components

a = max {gA (d), gA (k)}

b = max {gB (d), gB (k)}


 
a b
M inT ≤ min , ≤ M axT
b a
’min-abs-diff’: Difference of the minimum distance of the components

a = min {gA (d), gA (k)}, k < d

b = min {gB (d), gB (k)}, k < d


M inT ≤ |a − b| ≤ M axT

HALCON/COM Reference Manual, 2008-5-13


13.3. REGIONGROWING 945

’min-abs-ratio’: Ratio of the minimum distance of the components

a = min {gA (d), gA (k)}, k < d

b = min {gB (d), gB (k)}, k < d


 
a b
M inT ≤ min , ≤ M axT
b a
’plane’: The following has to hold for all d1 ,d2 ∈ [1, n]:

gA (d1 ) > gA (d2 ) ⇒ gB (d1 ) > gB (d2 )

gA (d1 ) < gA (d2 ) ⇒ gB (d1 ) < gB (d2 )

Regions with an area less than MinSize are suppressed.


Parameter
. MultiChannelImage (input iconic) . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte )
Input image.
. Regions (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX
Segmented regions.
. Metric (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Metric for the distance of the feature vectors.
Default Value : 2-norm
List of values : Metric ∈ {1-norm, 2-norm, 3-norm, 4-norm, ’n-norm’, ’max-diff’, ’min-diff’, ’variance’,
’dot-product’, ’correlation’, ’mean-diff’, ’mean-ratio’, ’length-diff’, ’length-ratio’, ’n-norm-ratio’,
’gray-max-diff’, ’gray-max-ratio’, ’gray-min-diff’, ’gray-min-ratio’, ’variance-diff’, ’variance-ratio’,
’mean-abs-diff’, ’mean-abs-ratio’, ’max-abs-diff’, ’max-abs-ratio’, ’min-abs-diff’, ’min-abs-ratio’, ’plane’}
. MinTolerance (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Lower threshold for the features’ distance.
Default Value : 0.0
Suggested values : MinTolerance ∈ {0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 12.0, 14.0, 16.0,
18.0, 20.0, 25.0, 30.0}
. MaxTolerance (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Upper threshold for the features’ distance.
Default Value : 20.0
Suggested values : MaxTolerance ∈ {0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 12.0, 14.0, 16.0,
18.0, 20.0, 25.0, 30.0}
. MinSize (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Minimum size of the output regions.
Default Value : 30
Suggested values : MinSize ∈ {1, 10, 25, 50, 100, 200, 500, 1000}
Minimum Increment : 1
Recommended Increment : 5
Result
RegiongrowingN returns TRUE if all parameters are correct. The behavior with respect to the input images
and output regions can be determined by setting the values of the flags ’no_object_result’, ’empty_region_result’,
and ’store_empty_region’ with SetSystem. If necessary, an exception is raised.
Parallelization Information
RegiongrowingN is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Compose2, Compose3
See also
RegiongrowingMean
Alternatives
Class2DimSup, ClassNdimNorm, ClassNdimBox
Module
Foundation

HALCON 8.0.2
946 CHAPTER 13. SEGMENTATION

13.4 Threshold
[out] HRegionX Regions HImageX.AutoThreshold ([in] VARIANT Sigma )
void HOperatorSetX.AutoThreshold ([in] IHObjectX Image,
[out] HUntypedObjectX Regions, [in] VARIANT Sigma )

Segment an image using thresholds determined from its histogram.


AutoThreshold segments a single-channel image using multiple thresholding. First, the absolute histogram of
the gray values is determined. Then, relevant minima are extracted from the histogram, which are used successively
as parameters for a thresholding operation. The thresholds used for byte images are 0, 255, and all minima extracted
from the histogram (after the histogram has been smoothed with a Gaussian filter with standard deviation Sigma).
For each gray value interval one region is generated. Thus, the number of regions is the number of minima +
1. For uint2 images, the above procedure is used analogously. However, here the highest threshold is 65535.
Furthermore, the value of Sigma (virtually) refers to a histogram with 256 values, although internally histograms
with a higher resolution are used. This is done to facilitate switching between image types without having to
change the parameter Sigma. The larger the value of Sigma is chosen, the fewer regions will be extracted. This
operator is useful if the regions to be extracted exhibit similar gray values (homogeneous regions).
Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte, uint2 )


Input image.
. Regions (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX
Regions with gray values within the automatically determined intervals.
. Sigma (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Sigma for the Gaussian smoothing of the histogram.
Default Value : 2.0
Suggested values : Sigma ∈ {0.0, 0.5, 1.0, 2.0, 3.0, 4.0, 5.0}
Typical range of values : 0.0 ≤ Sigma ≤ 0.0(lin)
Minimum Increment : 0.01
Recommended Increment : 0.3
Restriction : (Sigma ≥ 0.0)
Example

read_image (Image, ’fabrik’)


median_image (Image, Median, ’circle’, 3, ’mirrored’)
auto_threshold (Median, Seg, 2.0)
connection (Seg, Connected)

Parallelization Information
AutoThreshold is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
AnisotropicDiffusion, MedianImage, Illuminate
Possible Successors
Connection, SelectShape, SelectGray
See also
GrayHisto, GrayHistoAbs, HistoToThresh, SmoothFunct1DGauss, Threshold
Alternatives
BinThreshold, CharThreshold
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


13.4. THRESHOLD 947

HImageX.BinThreshold ( )
[out] HRegionX Region
void HOperatorSetX.BinThreshold ([in] IHObjectX Image,
[out] HUntypedObjectX Region )

Segment an image using an automatically determined threshold.


BinThreshold segments a single-channel gray value image using an automatically determined threshold. First,
the relative histogram of the gray values is determined. Then, relevant minima are extracted from the histogram,
which are used as parameters for a thresholding operation. In order to reduce the number of minima, the histogram
is smoothed with a Gaussian, as in AutoThreshold. The mask size is enlarged until there is only one minimum
in the smoothed histogram. The selected region contains the pixels with gray values from 0 to the minimum. This
operator is, for example useful for the segmentation of dark characters on a light paper.
Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte, uint2 )


Input image.
. Region (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Dark regions of the image.
Example

read_image (Image, ’letters’)


bin_threshold (Image, Seg)
connection (Seg, Connected)

Parallelization Information
BinThreshold is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
AnisotropicDiffusion, MedianImage, Illuminate
Possible Successors
Connection, SelectShape, SelectGray
See also
GrayHisto, SmoothFunct1DGauss, Threshold
Alternatives
AutoThreshold, CharThreshold
Module
Foundation

[out] HRegionX Characters HImageX.CharThreshold


([in] HRegionX HistoRegion, [in] double Sigma, [in] VARIANT Percent,
[out] VARIANT Threshold )
void HOperatorSetX.CharThreshold ([in] IHObjectX Image,
[in] IHObjectX HistoRegion, [out] HUntypedObjectX Characters,
[in] VARIANT Sigma, [in] VARIANT Percent, [out] VARIANT Threshold )

Perform a threshold segmentation for extracting characters.


The main application of CharThreshold is to segment single-channel images of dark characters on bright
paper. The operator works as follows: First, a histogram of the gray values in the image Image is computed for
the points in the region HistoRegion. To eliminate noise, the histogram is smoothed with the given Sigma
(Gaussian smoothing). In the histogram, the background (white paper) corresponds to a large peak at high gray
values, while the characters form a small peak at low gray values. In contrast to the operator BinThreshold,
which locates the minimum between the two peaks, here the threshold for the segmentation is determined in
relation to the maximum of the histogram, i.e., the background, with the following condition:

HALCON 8.0.2
948 CHAPTER 13. SEGMENTATION

histogram[threshold] ∗ 100.0 < histogram[maximum] ∗ (100.0 − Percent)

For example, if you choose Percent = 95 the operator locates the gray value whose frequency is at most 5
percent of the maximum frequency. Because CharThreshold assumes that the characters are darker than the
background, the threshold is searched for “to the left” of the maximum.
In comparison to BinThreshold, this operator should be used if there is no clear minimum between the his-
togram peaks corresponding to the characters and the background, respectively, or if there is no peak corresponding
to the characters at all. This may happen, e.g., if the image contains only few characters or in the case of a non-
uniform illumination.
Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte )


Input image.
. HistoRegion (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
Region in which the histogram is computed.
. Characters (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Dark regions (characters).
. Sigma (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Sigma for the Gaussian smoothing of the histogram.
Default Value : 2.0
Suggested values : Sigma ∈ {0.0, 0.5, 1.0, 2.0, 3.0, 4.0, 5.0}
Typical range of values : 0.0 ≤ Sigma ≤ 0.0(lin)
Minimum Increment : 0.01
Recommended Increment : 0.2
. Percent (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Percentage for the gray value difference.
Default Value : 95
Suggested values : Percent ∈ {90, 92, 95, 96, 97, 98, 99, 99.5, 100}
Typical range of values : 0.0 ≤ Percent ≤ 0.0(lin)
Minimum Increment : 0.1
Recommended Increment : 0.5
. Threshold (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Calculated threshold.
Example

read_image (Image, ’letters’)


char_threshold (Image, Image, Seg, 0.0, 5.0, Threshold)
connection (Seg, Connected)

Parallelization Information
CharThreshold is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
AnisotropicDiffusion, MedianImage, Illuminate
Possible Successors
Connection, SelectShape, SelectGray
Alternatives
BinThreshold, AutoThreshold, GrayHisto, SmoothFunct1DGauss, Threshold
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


13.4. THRESHOLD 949

[out] HRegionX Selected HImageX.CheckDifference ([in] HImageX Pattern,


[in] String Mode, [in] long DiffLowerBound, [in] long DiffUpperBound,
[in] long GrayOffset, [in] long AddRow, [in] long AddCol )
void HOperatorSetX.CheckDifference ([in] IHObjectX Image,
[in] IHObjectX Pattern, [out] HUntypedObjectX Selected, [in] VARIANT Mode,
[in] VARIANT DiffLowerBound, [in] VARIANT DiffUpperBound,
[in] VARIANT GrayOffset, [in] VARIANT AddRow, [in] VARIANT AddCol )

Compare two images pixel by pixel.


CheckDifference selects from the input image Image those pixels (go = gImage ), whose
gray value difference to the corresponding pixels in Pattern is inside (outside) of the interval
[DiffLowerBound, DiffUpperBound]. The pixels of Pattern are translated by (AddRow, AddCol) with
respect to Image. Let gp be the gray value from Pattern translated by (AddRow, AddCol) with respect to go .
If the selected mode Mode is ’diff_inside’, a pixel go is selected if

g_o − g_p − GrayOffset > DiffLowerBound and


g_o − g_p − GrayOffset < DiffUpperBound.

If the mode is set to ’diff_outside’, a pixel go is selected if

g_o − g_p − GrayOffset ≤ DiffLowerBound or


g_o − g_p − GrayOffset ≥ DiffUpperBound.

This test is performed for all points of the domain (region) of Image, intersected with the domain of the translated
Pattern. All points fulfilling the above condition are aggregated in the output region. The two images may be
of different size. Typically, Pattern is smaller than Image.
Parameter
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte )
Input image.
. Pattern (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte )
Comparison image.
. Selected (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Points in which the two images are similar/different.
. Mode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Mode: return similar or different pixels.
Default Value : ’diff_outside’
Suggested values : Mode ∈ {’diff_inside’, ’diff_outside’}
. DiffLowerBound (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; long / VARIANT
Lower bound of the tolerated gray value difference.
Default Value : -5
Suggested values : DiffLowerBound ∈ {0, -1, -2, -3, -5, -7, -10, -12, -15, -17, -20, -25, -30}
Typical range of values : -255 ≤ DiffLowerBound ≤ -255(lin)
Minimum Increment : 1
Recommended Increment : 2
Restriction : ((−255 ≤ Dif f LowerBound) ∧ (Dif f LowerBound ≤ 255))
. DiffUpperBound (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; long / VARIANT
Upper bound of the tolerated gray value difference.
Default Value : 5
Suggested values : DiffUpperBound ∈ {0, 1, 2, 3, 5, 7, 10, 12, 15, 17, 20, 25, 30}
Typical range of values : -255 ≤ DiffUpperBound ≤ -255(lin)
Minimum Increment : 1
Recommended Increment : 2
Restriction : ((−255 ≤ Dif f U pperBound) ∧ (Dif f U pperBound ≤ 255))

HALCON 8.0.2
950 CHAPTER 13. SEGMENTATION

. GrayOffset (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; long / VARIANT


Offset gray value subtracted from the input image.
Default Value : 0
Suggested values : GrayOffset ∈ {-30, -25, -20, -17, -15, -12, -10, -7, -5, -3, -2, -1, 0, 1, 2, 3, 5, 7, 10, 12,
15, 17, 20, 25, 30}
Typical range of values : -255 ≤ GrayOffset ≤ -255(lin)
Minimum Increment : 1
Recommended Increment : 2
Restriction : ((−255 ≤ GrayOf f set) ∧ (GrayOf f set ≤ 255))
. AddRow (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; long / VARIANT
Row coordinate by which the comparison image is translated.
Default Value : 0
Suggested values : AddRow ∈ {-200, -100, -20, -10, 0, 10, 20, 100, 200}
Typical range of values : -32000 ≤ AddRow ≤ -32000(lin)
Minimum Increment : 1
Recommended Increment : 1
. AddCol (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; long / VARIANT
Column coordinate by which the comparison image is translated.
Default Value : 0
Suggested values : AddCol ∈ {-200, -100, -20, -10, 0, 10, 20, 100, 200}
Typical range of values : -32000 ≤ AddCol ≤ -32000(lin)
Minimum Increment : 1
Recommended Increment : 1
Complexity
Let A be the number of valid pixels. Then the runtime complexity is O(A).
Result
CheckDifference returns TRUE if all parameters are correct. The behavior with respect to the input images
and output regions can be determined by setting the values of the flags ’no_object_result’, ’empty_region_result’,
and ’store_empty_region’ with SetSystem. If necessary, an exception is raised.
Parallelization Information
CheckDifference is reentrant and automatically parallelized (on tuple level).
Possible Successors
Connection, SelectShape, ReduceDomain, SelectGray, RankRegion, Dilation1, Opening
Alternatives
SubImage, DynThreshold
Module
Foundation

[out] HRegionX RegionCrossings HImageX.DualThreshold ([in] long MinSize,


[in] double MinGray, [in] double Threshold )
void HOperatorSetX.DualThreshold ([in] IHObjectX Image,
[out] HUntypedObjectX RegionCrossings, [in] VARIANT MinSize,
[in] VARIANT MinGray, [in] VARIANT Threshold )

Threshold operator for signed images.


DualThreshold segments the input image into a region with gray values ≥ Threshold (“positive” regions)
and a region with gray values ≤ -Threshold (“negative” regions). “Positive” or “negative” regions having a size
of less than MinSize are suppressed, as well as regions whose maximum gray value is less than MinGray in
absolute value.
The segmentation performed is not complete, i.e., the “positive” and “negative” regions together do not necessarily
cover the entire image: Areas with a gray value between −Threshold and Threshold, −MinGray and
MinGray, respectively, are not taken into account.
DualThreshold is usually called after applying a Laplace operator ( Laplace, LaplaceOfGauss,
DerivateGauss or DiffOfGauss) to an image or with the difference of two images ( SubImage).

HALCON/COM Reference Manual, 2008-5-13


13.4. THRESHOLD 951

The zero crossings of a Laplace image correspond to edges in an image, and are the separating regions of the
“positive” and “negative” regions in the Laplace image. They can be determined by calling DualThreshold
with Threshold = 1 and then creating the complement regions with Complement. The parameter MinGray
determines the noise invariance, while MinSize determines the resolution of the edge detection.
Using byte images, only the positive part of the operator is applied. Therefore DualThreshold behaves like a
standard threshold operator ( Threshold) with successive Connection and SelectGray.
Parameter
. Image (input iconic) . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte, int1, int2, int4, real )
Input image.
. RegionCrossings (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX
Positive and negative regions.
. MinSize (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Regions smaller than MinSize are suppressed.
Default Value : 20
Suggested values : MinSize ∈ {0, 10, 20, 50, 100, 200, 500, 1000}
Typical range of values : 0 ≤ MinSize ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 10
. MinGray (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Regions whose maximum absolute gray value is smaller than MinGray are suppressed.
Default Value : 5.0
Suggested values : MinGray ∈ {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 9.0, 11.0, 15.0, 20.0}
Typical range of values : 0.001 ≤ MinGray ≤ 0.001(lin)
Minimum Increment : 1.0
Recommended Increment : 10.0
Restriction : (M inGray > 0)
. Threshold (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Regions that have a gray value smaller than Threshold (or larger than -Threshold) are suppressed.
Default Value : 2.0
Suggested values : Threshold ∈ {1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 9.0, 11.0, 15.0, 20.0}
Typical range of values : 0.001 ≤ Threshold ≤ 0.001(lin)
Minimum Increment : 1.0
Recommended Increment : 10.0
Restriction : ((T hreshold ≥ 1) ∧ (T hreshold ≤ M inGray))
Example

/* Edge detection with the Laplace operator (and edge thinning) */


diff_of_gauss(Image,Laplace,2.0,1.6)
/* find "‘positive"’ and "‘negative"’ regions: */
dual_threshold(Laplace,Region,20,2,1)
/* The zero runnings are the complement to these image section: */
complement(’full’,Region,ZeroCrossings)

/* Simulation of dual_threshold */
dual_threshold(Laplace,Result,MinS,MinG,Threshold):
threshold(Laplace,Tmp1,Threshold,999999)
connection(Tmp1,Tmp2)
select_shape(Tmp2,Tmp3,’area’,’and’,MinS,999999)
select_gray(Laplace,Tmp3,Tmp4,’max’,’and’,MinG,999999)
threshold(Laplace,Tmp5,-999999,-Threshold)
connection(Tmp5,Tmp6)
select_shape(Tmp6,Tmp7,’area’,’and’,MinS,999999)
select_gray(Laplace,Tmp7,Tmp8,’min’,’and’,-999999,-MinG)
concat_obj(Tmp4,Tmp8,Result)

Result
DualThreshold returns TRUE if all parameters are correct. The behavior with respect to the input images and

HALCON 8.0.2
952 CHAPTER 13. SEGMENTATION

output regions can be determined by setting the values of the flags ’no_object_result’, ’empty_region_result’, and
’store_empty_region’ with SetSystem. If necessary, an exception is raised.
Parallelization Information
DualThreshold is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
MinMaxGray, SobelAmp, BinomialFilter, GaussImage, ReduceDomain, DiffOfGauss,
SubImage, DerivateGauss, LaplaceOfGauss, Laplace, ExpandRegion
Possible Successors
Connection, Dilation1, Erosion1, Opening, Closing, RankRegion, ShapeTrans, Skeleton
See also
Connection, SelectShape, SelectGray
Alternatives
Threshold, DynThreshold, CheckDifference
Module
Foundation

[out] HRegionX RegionDynThresh HImageX.DynThreshold


([in] HImageX ThresholdImage, [in] VARIANT Offset, [in] String LightDark )
void HOperatorSetX.DynThreshold ([in] IHObjectX OrigImage,
[in] IHObjectX ThresholdImage, [out] HUntypedObjectX RegionDynThresh,
[in] VARIANT Offset, [in] VARIANT LightDark )

Segment an image using a local threshold.


DynThreshold selects from the input image those regions in which the pixels fulfill a threshold condition. Let
go = gOrigImage , and gt = gThresholdImage . Then the condition for LightDark = ’light’ is:
go ≥ gt + Offset

For LightDark = ’dark’ the condition is:


go ≤ gt − Offset

For LightDark = ’equal’ it is:


gt − Offset ≤ go ≤ gt + Offset
Finally, for LightDark = ’not_equal’ it is:
gt − Offset > go ∨ go > gt + Offset

Typically, the threshold images are smoothed versions of the original image (e.g., by applying MeanImage,
BinomialFilter, GaussImage, etc.). Then the effect of DynThreshold is similar to applying
Threshold to a highpass-filtered version of the original image (see HighpassImage).
With DynThreshold, contours of an object can be extracted, where the objects’ size (diameter) is determined
by the mask size of the lowpass filter and the amplitude of the objects’ edges:
The larger the mask size is chosen, the larger the found regions become. As a rule of thumb, the mask size should
be about twice the diameter of the objects to be extracted. It is important not to set the parameter Offset to zero
because in this case too many small regions will be found (noise). Values between 5 and 40 are a useful choice.
The larger Offset is chosen, the smaller the extracted regions become.
All points of the input image fulfilling the above condition are stored jointly in one region. If necessary, the
connected components can be obtained by calling Connection.
Attention
If Offset is chosen from −1 to 1 usually a very noisy region is generated, requiring large storage. If Offset
is chosen too large (> 60, say) it may happen that no points fulfill the threshold condition (i.e., an empty region is
returned). If Offset is chosen too small (< -60, say) it may happen that all points fulfill the threshold condition
(i.e., a full region is returned).

HALCON/COM Reference Manual, 2008-5-13


13.4. THRESHOLD 953

Parameter
. OrigImage (input iconic) . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte, int2, uint2, int4, real )
Input image.
. ThresholdImage (input iconic) . . . image(-array) ; HImageX / IHObjectX ( byte, int2, uint2, int4, real )
Image containing the local thresholds.
. RegionDynThresh (output iconic) . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Segmented regions.
. Offset (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Offset applied to ThresholdImage.
Default Value : 5.0
Suggested values : Offset ∈ {1.0, 3.0, 5.0, 7.0, 10.0, 20.0, 30.0}
Typical range of values : -255.0 ≤ Offset ≤ -255.0(lin)
Minimum Increment : 0.01
Recommended Increment : 5
Restriction : ((−255 < Of f set) ∧ (Of f set < 255))
. LightDark (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Extract light, dark or similar areas?
Default Value : ’light’
List of values : LightDark ∈ {’dark’, ’light’, ’equal’, ’not_equal’}
Example

/* Looking for regions with the diameter D */


mean_image(Image,Mean,D*2+1,D*2+1)
dyn_threshold(Image,Mean,Seg:5,’light’)
connection(Seg,Regions).

Complexity
Let A be the area of the input region. Then the runtime complexity is O(A).
Result
DynThreshold returns TRUE if all parameters are correct. The behavior with respect to the input images and
output regions can be determined by setting the values of the flags ’no_object_result’, ’empty_region_result’, and
’store_empty_region’ with SetSystem. If necessary, an exception is raised.
Parallelization Information
DynThreshold is reentrant and automatically parallelized (on tuple level, domain level).
Possible Predecessors
MeanImage, SmoothImage, BinomialFilter, GaussImage
Possible Successors
Connection, SelectShape, ReduceDomain, SelectGray, RankRegion, Dilation1, Opening,
Erosion1
See also
HighpassImage, SubImage
Alternatives
CheckDifference, Threshold
Module
Foundation

[out] HRegionX Region HImageX.FastThreshold ([in] VARIANT MinGray,


[in] VARIANT MaxGray, [in] long MinSize )
void HOperatorSetX.FastThreshold ([in] IHObjectX Image,
[out] HUntypedObjectX Region, [in] VARIANT MinGray, [in] VARIANT MaxGray,
[in] VARIANT MinSize )

Fast thresholding of images using global thresholds.

HALCON 8.0.2
954 CHAPTER 13. SEGMENTATION

FastThreshold selects the pixels from the input image whose gray values g fulfill the following condition:

MinGray ≤ g ≤ MaxGray .

To reduce procesing time, the selection is done in two steps: At first all pixels along rows and columns with dis-
tances MinSize are processed. In the next step the neighborhood (size MinSize × MinSize) of all previously
selected points are processed.
Parameter

. Image (input iconic) . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte, uint2, direction, cyclic )
Input image.
. Region (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Segmented regions.
. MinGray (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Lower threshold for the gray values.
Default Value : 128
Suggested values : MinGray ∈ {0.0, 10.0, 30.0, 64.0, 128.0, 200.0, 220.0, 255.0}
Typical range of values : 0.0 ≤ MinGray ≤ 0.0(lin)
Minimum Increment : 1
Recommended Increment : 5.0
. MaxGray (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Upper threshold for the gray values.
Default Value : 255.0
Suggested values : MaxGray ∈ {0.0, 10.0, 30.0, 64.0, 128.0, 200.0, 220.0, 255.0}
Typical range of values : 0.0 ≤ MaxGray ≤ 0.0(lin)
Minimum Increment : 1
Recommended Increment : 5.0
. MinSize (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; long / VARIANT
Minimum size of objects to be extracted.
Default Value : 20
Suggested values : MinSize ∈ {5, 10, 15, 20, 25, 30, 40, 50, 60, 70, 100}
Typical range of values : 2 ≤ MinSize ≤ 2(lin)
Minimum Increment : 1
Recommended Increment : 2
Complexity
Let A be the area of the ouput region and height the height of Image. Then the runtime complexity is O(A +
height/MinSize).
Result
FastThreshold returns TRUE if all parameters are correct. The behavior with respect to the input images and
output regions can be determined by setting the values of the flags ’no_object_result’, ’empty_region_result’, and
’store_empty_region’ with SetSystem. If necessary, an exception is raised.
Parallelization Information
FastThreshold is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
HistoToThresh, MinMaxGray, SobelAmp, BinomialFilter, GaussImage, ReduceDomain,
FillInterlace
Possible Successors
Connection, Dilation1, Erosion1, Opening, Closing, RankRegion, ShapeTrans, Skeleton
See also
Class2DimSup, HysteresisThreshold
Alternatives
Threshold, GenGridRegion, DilationRectangle1, DynThreshold
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


13.4. THRESHOLD 955

[out] VARIANT MinThresh HHistogramX.HistoToThresh


([in] VARIANT Histogramm, [in] double Sigma, [out] VARIANT MaxThresh )
void HOperatorSetX.HistoToThresh ([in] VARIANT Histogramm,
[in] VARIANT Sigma, [out] VARIANT MinThresh, [out] VARIANT MaxThresh )

Determine gray value thresholds from a histogram.


HistoToThresh determines gray value thresholds from a histogram for a segmentation of an image using
Threshold. The thresholds returned are 0, the maximum gray value in the histogram, and all minima extracted
from the histogram. Before the thresholds are determined, the histogram is smoothed with a Gaussian smoothing
function.
HistoToThresh can process the absolute and relative histograms that are returned by GrayHisto. Note,
however, that here only byte images should be used, because otherwise the returned thresholds cannot easily be
transformed to the thresholds for the actual image. For images of type uint2, the histograms should be computed
with GrayHistoAbs since this facilitates a simple transformation of the thresholds by simply multiplying the
thresholds with the quantization selected in GrayHistoAbs. For uint2 images, it is important to ensure that the
quantization must be chosen in such a manner that the histogram still contains salient information. For example, a
640×480 image with 16 bits per pixel gray value resolution contains on average only 307200/65536 = 4.7 entries
per histogram bin, i.e., the histogram is too sparsely populated to derive any useful statistics from it. To be able to
extract useful thresholds from such a histogram, Sigma would have to be set to an extremely large value, which
would lead to very high run times and numerical problems. The quantization in GrayHistoAbs should therefore
normally be chosen such that the histogram contains a maximum of 1024 entries. Hence, for images with more than
10 bits per pixel, the quantization must be chosen greater than 1. The histogram returned by GrayHistoAbs
should furthermore be restricted to the parts that contain salient information. For example, for an image with 12
bits per pixel, the quantization should be set to 4. Only the first 1024 entries of the computed histogram (which
contains 16384 entries in this example) should be passed to HistoToThresh. Finally, MinThresh must be
multiplied by 4 (i.e., the quantization), while MaxThresh must be multiplied by 4 and increased by 3 (i.e., the
quantization minus 1).
Parameter
. Histogramm (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . histogram ; VARIANT ( integer, real )
Gray value histogram.
. Sigma (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Sigma for the Gaussian smoothing of the histogram.
Default Value : 2.0
Suggested values : Sigma ∈ {0.5, 1.0, 2.0, 3.0, 4.0, 5.0}
Typical range of values : 0.5 ≤ Sigma ≤ 0.5(lin)
Minimum Increment : 0.01
Recommended Increment : 0.2
. MinThresh (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Minimum thresholds.
. MaxThresh (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Maximum thresholds.
Example

/* Calculate thresholds from a byte image and threshold the image. */


gray_histo (Image, Image, AbsoluteHisto, RelativeHisto)
histo_to_thresh (AbsoluteHisto, 4, MinThresh, MaxThresh)
threshold (Image, Region, MinThresh, MaxThresh)

/* Calculate thresholds from a 12 bit uint2 image and threshold the image. */
gray_histo_abs (Image, Image, 4, AbsoluteHisto)
AbsoluteHisto := AbsoluteHisto[0:1023]
histo_to_thresh (AbsoluteHisto, 16, MinThresh, MaxThresh)
MinThresh := MinThresh*4
MaxThresh := MaxThresh*4+3
threshold (Image, Region, MinThresh, MaxThresh)

HALCON 8.0.2
956 CHAPTER 13. SEGMENTATION

Parallelization Information
HistoToThresh is reentrant and processed without parallelization.
Possible Predecessors
GrayHisto
Possible Successors
Threshold
See also
AutoThreshold, BinThreshold, CharThreshold
Module
Foundation

[out] HRegionX Region HImageX.Threshold ([in] VARIANT MinGray,


[in] VARIANT MaxGray )
void HOperatorSetX.Threshold ([in] IHObjectX Image,
[out] HUntypedObjectX Region, [in] VARIANT MinGray, [in] VARIANT MaxGray )

Segment an image using global threshold.


Threshold selects the pixels from the input image whose gray values g fulfill the following condition:

MinGray ≤ g ≤ MaxGray .

All points of an image fulfilling the condition are returned as one region. If more than one gray value interval is
passed (tuples for MinGray and MaxGray), one separate region is returned for each interval.
Parameter
. Image (input iconic) . . . . . . image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2,
uint2, int4, real, vector_field )
Input image.
. Region (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Segmented region.
. MinGray (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( integer, real )
Lower threshold for the gray values.
Default Value : 128.0
Suggested values : MinGray ∈ {0.0, 10.0, 30.0, 64.0, 128.0, 200.0, 220.0, 255.0}
. MaxGray (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( integer, real )
Upper threshold for the gray values.
Default Value : 255.0
Suggested values : MaxGray ∈ {0.0, 10.0, 30.0, 64.0, 128.0, 200.0, 220.0, 255.0}
Restriction : (M axGray ≥ M inGray)
Example

read_image(Image,’fabrik’)
sobel_dir(Image,EdgeAmp,EdgeDir,’sum_abs’,3)
threshold(EdgeAmp,Seg,50,255,2)
skeleton(Seg,Rand)
connection(Rand,Lines)
select_shape(Lines,Edges,’area’,’and’,10,1000000).

Complexity
Let A be the area of the input region. Then the runtime complexity is O(A).
Result
Threshold returns TRUE if all parameters are correct. The behavior with respect to the input images and
output regions can be determined by setting the values of the flags ’no_object_result’, ’empty_region_result’, and
’store_empty_region’ with SetSystem. If necessary, an exception is raised.

HALCON/COM Reference Manual, 2008-5-13


13.4. THRESHOLD 957

Parallelization Information
Threshold is reentrant and automatically parallelized (on tuple level, domain level).
Possible Predecessors
HistoToThresh, MinMaxGray, SobelAmp, BinomialFilter, GaussImage, ReduceDomain,
FillInterlace
Possible Successors
Connection, Dilation1, Erosion1, Opening, Closing, RankRegion, ShapeTrans, Skeleton
See also
ZeroCrossing, BackgroundSeg, Regiongrowing
Alternatives
Class2DimSup, HysteresisThreshold, DynThreshold, BinThreshold, CharThreshold,
AutoThreshold, DualThreshold
Module
Foundation

[out] HXLDContX Border HImageX.ThresholdSubPix


([in] VARIANT Threshold )
void HOperatorSetX.ThresholdSubPix ([in] IHObjectX Image,
[out] HUntypedObjectX Border, [in] VARIANT Threshold )

Extract level crossings from an image with subpixel accuracy.


ThresholdSubPix extracts the level crossings at the level Threshold of the input image Image with sub-
pixel accuracy. The extracted level crossings are returned as XLD-contours in Border. In contrast to the operator
Threshold, ThresholdSubPix does not return regions, but the lines that separate regions with a gray value
less than Threshold from regions with a gray value greater than Threshold.
For the extraction, the input image is regarded as a surface, in which the gray values are interpolated bilinearly
between the centers of the individual pixels. Consistent with the surface thus defined, level crossing lines are
extracted for each pixel and linked into topologically sound contours. This means that the level crossing contours
are correctly split at junction points. If the image contains extended areas of constant gray value Threshold,
only the border of such areas is returned as level crossings.
Parameter
. Image (input iconic) . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, int1, int2, uint2, int4, real )
Input image.
. Border (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xld_cont ; HXLDContX / HUntypedObjectX
Extracted level crossings.
. Threshold (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Threshold for the level crossings.
Default Value : 128
Suggested values : Threshold ∈ {0.0, 10.0, 30.0, 64.0, 128.0, 200.0, 220.0, 255.0}
Example

read_image(Image,’fabrik’)
threshold_sub_pix(Image,Border,35)
disp_xld(Border,WindowHandle)

Result
ThresholdSubPix usually returns the value TRUE. If necessary, an exception is raised.
Parallelization Information
ThresholdSubPix is reentrant and processed without parallelization.
See also
ZeroCrossingSubPix

HALCON 8.0.2
958 CHAPTER 13. SEGMENTATION

Alternatives
Threshold
Module
2D Metrology

[out] HRegionX Region HImageX.VarThreshold ([in] long MaskWidth,


[in] long MaskHeight, [in] double StdDevScale, [in] double AbsThreshold,
[in] String LightDark )
void HOperatorSetX.VarThreshold ([in] IHObjectX Image,
[out] HUntypedObjectX Region, [in] VARIANT MaskWidth,
[in] VARIANT MaskHeight, [in] VARIANT StdDevScale, [in] VARIANT AbsThreshold,
[in] VARIANT LightDark )

Threshold an image by local mean and standard deviation analysis.


The operator VarThreshold selects from the input image Image those regions Region in which the pixels
fulfill a threshold condition. The threshold is calculated from the mean gray value and the standard deviation in a
local window of size MaskWidth x MaskHeight around each pixel (x, y). If MaskWidth or MaskHeight
is even, the next larger odd value is used. The mask window should be greater than the image features to be
segmented and it should comprise at least three pixels.
Let g(x, y) be the gray value at position (x, y) in the input image Image and m(x, y) and d(x, y) the corresponding
mean and standard deviation of the gray values in the window around that pixel and
v(x, y) = max(StdDevScale ∗ d(x, y), AbsThreshold) for StdDevScale ≥ 0
or
v(x, y) = min(StdDevScale ∗ d(x, y), AbsThreshold) for StdDevScale < 0.
The standard deviation is used as a measure of noise in the image and scaled by StdDevScale to reflect the
desired sensitivity. The threshold condition is determined by the parameter LightDark:
LightDark = ’light’:
g(x, y) ≥ m(x, y) + v(x, y).
LightDark = ’dark’:
g(x, y) ≤ m(x, y) − v(x, y).
LightDark = ’equal’:
m(x, y) − v(x, y) ≤ g(x, y) ≤ m(x, y) + v(x, y).
LightDark = ’not_equal’:
m(x, y) − v(x, y) > g(x, y) ∨ g(x, y) < m(x, y) + v(x, y).
All pixels fulfilling the above condition are aggregated into the resulting region Region.
For the parameter StdDevScale values between −1.0 and 1.0 are sensible choices, with 0.2 as a suggested
value. If the parameter is too high or too low, an empty or full region may be returned. The parameter
AbsThreshold places an additional threshold on StdDevScale ∗ dev(x, y). If StdDevScale ∗ dev(x, y)
is below AbsThreshold for positive values of StdDevScale or above for negative values StdDevScale,
AbsThreshold is taken instead.
Parameter

. Image (input iconic) . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte, int2, int4, uint2, real )
Input image.
. Region (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Segmented regions.
. MaskWidth (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; long / VARIANT
Mask width for mean and deviation calculation.
Default Value : 15
Suggested values : MaskWidth ∈ {9, 11, 13, 15}
Restriction : (M askW idth ≥ 1)

HALCON/COM Reference Manual, 2008-5-13


13.4. THRESHOLD 959

. MaskHeight (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; long / VARIANT


Mask height for mean and deviation calculation.
Default Value : 15
Suggested values : MaskHeight ∈ {9, 11, 13, 15}
Restriction : (M askHeight ≥ 1)
. StdDevScale (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Factor for the standard deviation of the gray values.
Default Value : 0.2
Suggested values : StdDevScale ∈ {-0.2, -0.1, 0.1, 0.2}
. AbsThreshold (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Minimum gray value difference from the mean.
Default Value : 2
Suggested values : AbsThreshold ∈ {-2, -1, 0, 1, 2}
. LightDark (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Threshold type.
Default Value : ’dark’
List of values : LightDark ∈ {’dark’, ’light’, ’equal’, ’not_equal’}
Complexity
Let A be the area of the input region, then the runtime is O(A).
Result
VarThreshold returns TRUE if all parameters are correct. The behavior with respect to the input images and
output regions can be determined by setting the values of the flags ’no_object_result’, ’empty_region_result’, and
’store_empty_region’ with set_system. If necessary, an exception is raised.
Parallelization Information
VarThreshold is reentrant and automatically parallelized (on tuple level, domain level).
Alternatives
DynThreshold, Threshold
References
W.Niblack, ”An Introduction to Digital Image Processing”, Page 115-116, Englewood Cliffs, N.J., Prentice Hall,
1986
Module
Foundation

HImageX.ZeroCrossing ( )
[out] HRegionX RegionCrossing
void HOperatorSetX.ZeroCrossing ([in] IHObjectX Image,
[out] HUntypedObjectX RegionCrossing )

Extrakt zero crossings from an image.


ZeroCrossing returns the zero crossings of the input image as a region. A pixel is accepted as a zero crossing
if its gray value (in Image) is zero, or if at least one of its neighbors of the 4-neighborhood has a different sign.
This operator is intended to be used after edge operators returning the second derivative of the image (e.g.,
LaplaceOfGauss), which were possibly followed by a smoothing operator. In this case, the zero crossings
are (candidates for) edges.
Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( int1, int2, int4, real )
Input image.
. RegionCrossing (output iconic) . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Zero crossings.
Result
ZeroCrossing usually returns the value TRUE. If necessary, an exception is raised.
Parallelization Information
ZeroCrossing is reentrant and automatically parallelized (on tuple level).

HALCON 8.0.2
960 CHAPTER 13. SEGMENTATION

Possible Predecessors
Laplace, LaplaceOfGauss, DerivateGauss
Possible Successors
Connection, Skeleton, Boundary, SelectShape, FillUp
Alternatives
Threshold, DualThreshold, ZeroCrossingSubPix
Module
Foundation

HImageX.ZeroCrossingSubPix ( )
[out] HXLDContX ZeroCrossings
void HOperatorSetX.ZeroCrossingSubPix ([in] IHObjectX Image,
[out] HUntypedObjectX ZeroCrossings )

Extract zero crossings from an image with subpixel accuracy.


ZeroCrossingSubPix extracts the zero crossings of the input image Image with subpixel accuracy. The
extracted zero crossings are returned as XLD-contours in ZeroCrossings. Thus, ZeroCrossingSubPix
can be used as a sub-pixel precise edge extractor if the input image is a Laplace-filtered image (see Laplace,
LaplaceOfGauss, DerivateGauss).
For the extraction, the input image is regarded as a surface, in which the gray values are interpolated bilinearly
between the centers of the individual pixels. Consistent with the surface thus defined, zero crossing lines are
extracted for each pixel and linked into topologically sound contours. This means that the zero crossing contours
are correctly split at junction points. If the image contains extended areas of constant gray value 0, only the border
of such areas is returned as zero crossings.
Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( int1, int2, int4, real )
Input image.
. ZeroCrossings (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . xld_cont ; HXLDContX / HUntypedObjectX
Extracted zero crossings.
Example

/* Detection zero crossings of the Laplacian-of-Gaussian


of an aerial image */
read_image(Image,’mreut’)
derivate_gauss(Image,Laplace,3,’laplace’)
zero_crossing_sub_pix(Laplace,ZeroCrossings)
disp_xld(ZeroCrossings,WindowHandle)

/* Detection of edges, i.e, zero crossings of the Laplacian-of-Gaussian


that have a large gradient magnitude, in an aerial image */
read_image(Image,’mreut’)
Sigma := 1.5
/* Compensate the threshold for the fact that derivate_gauss(...,’gradient’)
calculates a Gaussian-smoothed gradient, in which the edge amplitudes
are too small because of the Gaussian smoothing, to correspond to a true
edge amplitude of 20. */
Threshold := 20/(Sigma*sqrt(2*3.1415926))
derivate_gauss(Image,Gradient,Sigma,’gradient’)
threshold(Gradient,Region,Threshold,255)
reduce_domain(Image,Region,ImageReduced)
derivate_gauss(ImageReduced,Laplace,Sigma,’laplace’)
zero_crossing_sub_pix(Laplace,Edges)
disp_xld(Edges,WindowHandle)

HALCON/COM Reference Manual, 2008-5-13


13.5. TOPOGRAPHY 961

Result
ZeroCrossingSubPix usually returns the value TRUE. If necessary, an exception is raised.
Parallelization Information
ZeroCrossingSubPix is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Laplace, LaplaceOfGauss, DiffOfGauss, DerivateGauss
See also
ThresholdSubPix
Alternatives
ZeroCrossing
Module
2D Metrology

13.5 Topography

[out] VARIANT RowMin HImageX.CriticalPointsSubPix ([in] String Filter,


[in] double Sigma, [in] double Threshold, [out] VARIANT ColMin,
[out] VARIANT RowMax, [out] VARIANT ColMax, [out] VARIANT RowSaddle,
[out] VARIANT ColSaddle )
void HOperatorSetX.CriticalPointsSubPix ([in] IHObjectX Image,
[in] VARIANT Filter, [in] VARIANT Sigma, [in] VARIANT Threshold,
[out] VARIANT RowMin, [out] VARIANT ColMin, [out] VARIANT RowMax,
[out] VARIANT ColMax, [out] VARIANT RowSaddle, [out] VARIANT ColSaddle )

Subpixel precise detection of critical points in an image.


CriticalPointsSubPix extracts critical points, i.e., local maxima, local minima, and saddle points, from the
image Image with subpixel precision. To do so, in each point the input image is approximated by a quadratic
polynomial in x and y and subsequently the polynomial is examined for extremal values and saddle points. The
partial derivatives, which are necessary for setting up the polynomial, are calculated either with various Gaussian
derivatives or using the facet model, depending on Filter. In the first case, Sigma determines the size of the
Gaussian kernels, while in the second case, before being processed the input image is smoothed by a Gaussian
whose size is determined by Sigma. Therefore, ’facet’ results in a faster extraction at the expense of slightly less
accurate results. A point is accepted to be a critical point if the absolute values of both eigenvalues of the Hessian
matrix are greater than Threshold. The eigenvalues correspond to the curvature of the gray value surface. If
both eigenvalues are negative, the point is a local maximum, if both are positive, a local minimum, and if they have
different signs, a saddle point.
Parameter
. Image (input iconic) . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, int1, int2, uint2, int4, real )
Input image.
. Filter (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Method for the calculation of the partial derivatives.
Default Value : ’facet’
List of values : Filter ∈ {’facet’, ’gauss’}
. Sigma (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Sigma of the Gaussian. If Filter is ’facet’, Sigma may be 0.0 to avoid the smoothing of the input image.
Suggested values : Sigma ∈ {0.7, 0.8, 0.9, 1.0, 1.2, 1.5, 2.0, 3.0}
Restriction : (Sigma ≥ 0.0)
. Threshold (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Minimum absolute value of the eigenvalues of the Hessian matrix.
Default Value : 5.0
Suggested values : Threshold ∈ {2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0}
Restriction : (T hreshold ≥ 0.0)
. RowMin (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; VARIANT ( real )
Row coordinates of the detected minima.

HALCON 8.0.2
962 CHAPTER 13. SEGMENTATION

. ColMin (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; VARIANT ( real )


Column coordinates of the detected minima.
. RowMax (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; VARIANT ( real )
Row coordinates of the detected maxima.
. ColMax (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; VARIANT ( real )
Column coordinates of the detected maxima.
. RowSaddle (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; VARIANT ( real )
Row coordinates of the detected saddle points.
. ColSaddle (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; VARIANT ( real )
Column coordinates of the detected saddle points.
Result
CriticalPointsSubPix returns TRUE if all parameters are correct and no error occurs during the execu-
tion. If the input is empty the behavior can be set via SetSystem(’noObjectResult’,<Result>). If
necessary, an exception handling is raised.
Parallelization Information
CriticalPointsSubPix is reentrant and processed without parallelization.
Possible Successors
GenCrossContourXld, DispCross
See also
LocalMin, LocalMax, Plateaus, PlateausCenter, Lowlands, LowlandsCenter
Alternatives
LocalMinSubPix, LocalMaxSubPix, SaddlePointsSubPix
Module
Foundation

HImageX.LocalMax ( )
[out] HRegionX LocalMaxima
void HOperatorSetX.LocalMax ([in] IHObjectX Image,
[out] HUntypedObjectX LocalMaxima )

Detect all local maxima in an image.


LocalMax extracts all points from Image having a gray value larger than the gray value of all its
neighbors and returns them in LocalMaxima. The neighborhood used can be set by SetSystem(::
’neighborhood’,<4/8>).
Parameter
. Image (input iconic) . . . . . . image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2,
uint2, int4, real )
Input image.
. LocalMaxima (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Extracted local maxima as a region.
Number of elements : (LocalM axima = Image)
Parallelization Information
LocalMax is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
BinomialFilter, GaussImage, SmoothImage
Possible Successors
GetRegionPoints, Connection
See also
Monotony, TopographicSketch, CornerResponse, TextureLaws
Alternatives
NonmaxSuppressionAmp, Plateaus, PlateausCenter
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


13.5. TOPOGRAPHY 963

[out] VARIANT Row HImageX.LocalMaxSubPix ([in] String Filter,


[in] double Sigma, [in] double Threshold, [out] VARIANT Col )
void HOperatorSetX.LocalMaxSubPix ([in] IHObjectX Image,
[in] VARIANT Filter, [in] VARIANT Sigma, [in] VARIANT Threshold,
[out] VARIANT Row, [out] VARIANT Col )

Subpixel precise detection of local maxima in an image.


LocalMaxSubPix extracts local maxima from the image Image with subpixel precision. To do so, in each
point the input image is approximated by a quadratic polynomial in x and y and subsequently the polynomial
is examined for local maxima. The partial derivatives, which are necessary for setting up the polynomial, are
calculated either with various Gaussian derivatives or using the facet model, depending on Filter. In the first
case, Sigma determines the size of the Gaussian kernels, while in the second case, before being processed the
input image is smoothed by a Gaussian whose size is determined by Sigma. Therefore, ’facet’ results in a faster
extraction at the expense of slightly less accurate results. A point is accepted to be a local maximum if both
eigenvalues of the Hessian matrix are smaller than -Threshold. The eigenvalues correspond to the curvature of
the gray value surface.
Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, int1, int2, uint2, int4, real )
Input image.
. Filter (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Method for the calculation of the partial derivatives.
Default Value : ’facet’
List of values : Filter ∈ {’facet’, ’gauss’}
. Sigma (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Sigma of the Gaussian. If Filter is ’facet’, Sigma may be 0.0 to avoid the smoothing of the input image.
Suggested values : Sigma ∈ {0.7, 0.8, 0.9, 1.0, 1.2, 1.5, 2.0, 3.0}
Restriction : (Sigma ≥ 0.0)
. Threshold (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Minimum absolute value of the eigenvalues of the Hessian matrix.
Default Value : 5.0
Suggested values : Threshold ∈ {2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0}
Restriction : (T hreshold ≥ 0.0)
. Row (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; VARIANT ( real )
Row coordinates of the detected maxima.
. Col (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; VARIANT ( real )
Column coordinates of the detected maxima.
Result
LocalMaxSubPix returns TRUE if all parameters are correct and no error occurs during the execution. If the
input is empty the behavior can be set via SetSystem(’noObjectResult’,<Result>). If necessary, an
exception handling is raised.
Parallelization Information
LocalMaxSubPix is reentrant and processed without parallelization.
Possible Successors
GenCrossContourXld, DispCross
See also
LocalMax, Plateaus, PlateausCenter
Alternatives
CriticalPointsSubPix, LocalMinSubPix, SaddlePointsSubPix
Module
Foundation

HALCON 8.0.2
964 CHAPTER 13. SEGMENTATION

HImageX.LocalMin ( )
[out] HRegionX LocalMinima
void HOperatorSetX.LocalMin ([in] IHObjectX Image,
[out] HUntypedObjectX LocalMinima )

Detect all local minima in an image.


LocalMin extracts all points from Image having a gray value smaller than the gray value of all its
neighbors and returns them in LocalMinima. The neighborhood used can be set by SetSystem(::
’neighborhood’,<4/8>).
Parameter

. Image (input iconic) . . . . . . image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2,
uint2, int4, real )
Image to be processed.
. LocalMinima (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Extracted local minima as regions.
Number of elements : (LocalM inima = Image)
Parallelization Information
LocalMin is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
BinomialFilter, GaussImage, SmoothImage
Possible Successors
GetRegionPoints, Connection
See also
Monotony, TopographicSketch, CornerResponse, TextureLaws
Alternatives
GraySkeleton, Lowlands, LowlandsCenter
Module
Foundation

[out] VARIANT Row HImageX.LocalMinSubPix ([in] String Filter,


[in] double Sigma, [in] double Threshold, [out] VARIANT Col )
void HOperatorSetX.LocalMinSubPix ([in] IHObjectX Image,
[in] VARIANT Filter, [in] VARIANT Sigma, [in] VARIANT Threshold,
[out] VARIANT Row, [out] VARIANT Col )

Subpixel precise detection of local minima in an image.


LocalMinSubPix extracts local minima from the image Image with subpixel precision. To do so, in each point
the input image is approximated by a quadratic polynomial in x and y and subsequently the polynomial is examined
for local minima. The partial derivatives, which are necessary for setting up the polynomial, are calculated either
with various Gaussian derivatives or using the facet model, depending on Filter. In the first case, Sigma
determines the size of the Gaussian kernels, while in the second case, before being processed the input image is
smoothed by a Gaussian whose size is determined by Sigma. Therefore, ’facet’ results in a faster extraction at
the expense of slightly less accurate results. A point is accepted to be a local minimum if both eigenvalues of
the Hessian matrix are greater than Threshold. The eigenvalues correspond to the curvature of the gray value
surface.
Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, int1, int2, uint2, int4, real )
Input image.
. Filter (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Method for the calculation of the partial derivatives.
Default Value : ’facet’
List of values : Filter ∈ {’facet’, ’gauss’}

HALCON/COM Reference Manual, 2008-5-13


13.5. TOPOGRAPHY 965

. Sigma (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT


Sigma of the Gaussian. If Filter is ’facet’, Sigma may be 0.0 to avoid the smoothing of the input image.
Suggested values : Sigma ∈ {0.7, 0.8, 0.9, 1.0, 1.2, 1.5, 2.0, 3.0}
Restriction : (Sigma ≥ 0.0)
. Threshold (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Minimum absolute value of the eigenvalues of the Hessian matrix.
Default Value : 5.0
Suggested values : Threshold ∈ {2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0}
Restriction : (T hreshold ≥ 0.0)
. Row (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; VARIANT ( real )
Row coordinates of the detected minima.
. Col (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; VARIANT ( real )
Column coordinates of the detected minima.
Result
LocalMinSubPix returns TRUE if all parameters are correct and no error occurs during the execution. If the
input is empty the behavior can be set via SetSystem(’noObjectResult’,<Result>). If necessary, an
exception handling is raised.
Parallelization Information
LocalMinSubPix is reentrant and processed without parallelization.
Possible Successors
GenCrossContourXld, DispCross
See also
LocalMin, Lowlands, LowlandsCenter
Alternatives
CriticalPointsSubPix, LocalMaxSubPix, SaddlePointsSubPix
Module
Foundation

[out] HRegionX Lowlands HImageX.Lowlands ( )


void HOperatorSetX.Lowlands ([in] IHObjectX Image,
[out] HUntypedObjectX Lowlands )

Detect all gray value lowlands.


Lowlands extracts all points from Image with a gray value less or equal to the gray value of its neighbors
(8-neighborhood) and returns them in Lowlands. Each lowland is returned as a separate region.
Parameter
. Image (input iconic) . . . . . . image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2,
uint2, int4, real )
Image to be processed.
. Lowlands (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX
Extracted lowlands as regions (one region for each lowland).
Parallelization Information
Lowlands is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
BinomialFilter, GaussImage, SmoothImage
Possible Successors
AreaCenter, GetRegionPoints, SelectShape
See also
Monotony, TopographicSketch, CornerResponse, TextureLaws
Alternatives
LowlandsCenter, GraySkeleton, LocalMin
Module
Foundation

HALCON 8.0.2
966 CHAPTER 13. SEGMENTATION

HImageX.LowlandsCenter ( )
[out] HRegionX Lowlands
void HOperatorSetX.LowlandsCenter ([in] IHObjectX Image,
[out] HUntypedObjectX Lowlands )

Detect the centers of all gray value lowlands.


LowlandsCenter extracts all points from Image with a gray value less or equal to the gray value of its neigh-
bors (8-neighborhood) and returns them in Lowlands. If more than one of these points are connected (lowland),
their center of gravity is returned. Each lowland is returned as a separate region.
Parameter
. Image (input iconic) . . . . . . image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2,
uint2, int4, real )
Image to be processed.
. Lowlands (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX
Centers of gravity of the extracted lowlands as regions (one region for each lowland).
Parallelization Information
LowlandsCenter is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
BinomialFilter, GaussImage, SmoothImage
Possible Successors
AreaCenter, GetRegionPoints, SelectShape
See also
Monotony, TopographicSketch, CornerResponse, TextureLaws
Alternatives
Lowlands, GraySkeleton, LocalMin
Module
Foundation

HImageX.Plateaus ( )
[out] HRegionX Plateaus
void HOperatorSetX.Plateaus ([in] IHObjectX Image,
[out] HUntypedObjectX Plateaus )

Detect all gray value plateaus.


Plateaus extracts all points from Image with a gray value greater or equal to the gray value of its neighbors
(8-neighborhood) and returns them in Plateaus. Each maximum is returned as a separate region.
Parameter
. Image (input iconic) . . . . . . image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2,
uint2, int4, real )
Input image.
. Plateaus (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX
Extracted plateaus as regions (one region for each plateau).
Parallelization Information
Plateaus is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
BinomialFilter, GaussImage, SmoothImage
Possible Successors
AreaCenter, GetRegionPoints, SelectShape
See also
Monotony, TopographicSketch, CornerResponse, TextureLaws
Alternatives
PlateausCenter, NonmaxSuppressionAmp, LocalMax

HALCON/COM Reference Manual, 2008-5-13


13.5. TOPOGRAPHY 967

Module
Foundation

HImageX.PlateausCenter ( )
[out] HRegionX Plateaus
void HOperatorSetX.PlateausCenter ([in] IHObjectX Image,
[out] HUntypedObjectX Plateaus )

Detect the centers of all gray value plateaus.


PlateausCenter extracts all points from Image with a gray value greater or equal to the gray value of its
neighbors (8-neighborhood) and returns them in Plateaus. If more than one of these points are connected
(plateau), their center of gravity is returned. Each plateau center is returned as a separate region.
Parameter

. Image (input iconic) . . . . . . image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2,
uint2, int4, real )
Input image.
. Plateaus (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX
Centers of gravity of the extracted plateaus as regions (one region for each plateau).
Parallelization Information
PlateausCenter is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
BinomialFilter, GaussImage, SmoothImage
Possible Successors
AreaCenter, GetRegionPoints, SelectShape
See also
Monotony, TopographicSketch, CornerResponse, TextureLaws
Alternatives
Plateaus, NonmaxSuppressionAmp, LocalMax
Module
Foundation

[out] HRegionX Regions HImageX.Pouring ([in] String Mode,


[in] long MinGray, [in] long MaxGray )
void HOperatorSetX.Pouring ([in] IHObjectX Image,
[out] HUntypedObjectX Regions, [in] VARIANT Mode, [in] VARIANT MinGray,
[in] VARIANT MaxGray )

Segment an image by “pouring water” over it.


Pouring regards the input image as a “mountain range.” Larger gray values correspond to mountain peaks, while
smaller gray values correspond to valley bottoms. Pouring segments the input image in several steps. First,
the local maxima are extracted, i.e., pixels which either alone or in the form of an extended plateau have larger
gray values than their immediate neighbors (in 4-neighborhood). In the next step, the maxima thus found are the
starting points for an expansion until “valley bottoms” are reached. The expansion is done as long as there are
chains of pixels in which the gray value becomes smaller (like water running downhill from the maxima in all
directions). Again, the 4-neighborhood is used, but with a weaker condition (smaller or equal). This means that
points at valley bottoms may belong to more than one maximum. These areas are at first not assigned to a region,
but rather are split among all competing segments in the last step. The split is done by a uniform expansion of
all involved segments, until all ambiguous pixels were assigned. The parameter Mode determines which steps are
executed. The following values are possible:

’all’ This is the normal mode of operation. All steps of the segmentation are performed. The regions are assigned
to maxima, and overlapping regions are split.

HALCON 8.0.2
968 CHAPTER 13. SEGMENTATION

’maxima’ The segmentation only extracts the local maxima of the input image. No corresponding regions are
extracted.
’regions’ The segmentation extracts the local maxima of the input image and the corresponding regions, which
are uniquely determined. Areas that were assigned to more than one maximum are not split.

In order to prevent the algorithm from splitting a uniform background that is different from the rest of the image,
the parameters MinGray and MaxGray determine gray value thresholds for regions in the image that should
be regarded as background. All parts of the image having a gray value smaller than MinGray or larger than
MaxGray are disregarded for the extraction of the maxima as well as for the assignment of regions. For a complete
segmentation of the image, MinGray = 0 und MaxGray = 255 should be selected. MinGray < MaxGray must
be observed.
Parameter
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte )
Input image.
. Regions (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX
Segmented regions.
. Mode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Mode of operation.
Default Value : ’all’
List of values : Mode ∈ {’all’, ’maxima’, ’regions’}
. MinGray (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
All gray values smaller than this threshold are disregarded.
Default Value : 0
Suggested values : MinGray ∈ {0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110}
Typical range of values : 0 ≤ MinGray ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 10
Restriction : (M inGray ≥ 0)
. MaxGray (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
All gray values larger than this threshold are disregarded.
Default Value : 255
Suggested values : MaxGray ∈ {100, 110, 120, 130, 140, 150, 160, 170, 180, 190, 200, 210, 220, 230, 240,
250, 255}
Typical range of values : 0 ≤ MaxGray ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 10
Restriction : ((M axGray ≤ 255) ∧ (M axGray > M inGray))
Example

/* Segmentation of a filtering Image */


read_image(Image,’br2’)
mean_image(Image,Mean,11,11)
pouring(Mean,Seg,’all’,0,255)
disp_image(Mean,WindowHandle)
set_colored(WindowHandle,12)
disp_region(Seg,WindowHandle).

/* Segmentation of a Image with masking of a dark backround */


read_image(Image,’hand’)
mean_image(ImageMean,15,15)
pouring(Mean,Seg,’all’,40,255)
disp_image(Mean,WindowHandle)
set_colored(WindowHandle,12)
disp_region(Seg,WindowHandle).

/* Segmentation of a histogram */
read_image(Image,’monkey’)

HALCON/COM Reference Manual, 2008-5-13


13.5. TOPOGRAPHY 969

texture_laws(Image,Texture,’el’,2,5)
draw_region(Region,draw_region)
reduce_domain(Texture,Region,Testreg)
histo_2dim(Testreg,Texture,Region,Histo)
pouring(Histo,Seg,’all’,0,255).

Complexity
Let N be the number of pixels in the input image and M be the number of found segments, where the enclosing
rectangle of the segment i contains mi pixels. Furthermore, let Ki be the number of chords in segment i. Then the
runtime complexity is

O(3 ∗ N + sumM (3 ∗ mi ) + sumM (Ki )) .

Result
Pouring usually returns the value TRUE. If necessary, an exception is raised.
Parallelization Information
Pouring is processed under mutual exclusion against itself and without parallelization.
Possible Predecessors
BinomialFilter, GaussImage, SmoothImage, MeanImage
See also
Histo2Dim, ExpandRegion, ExpandGray, ExpandGrayRef
Alternatives
Watersheds, LocalMax
Module
Foundation

[out] VARIANT Row HImageX.SaddlePointsSubPix ([in] String Filter,


[in] double Sigma, [in] double Threshold, [out] VARIANT Col )
void HOperatorSetX.SaddlePointsSubPix ([in] IHObjectX Image,
[in] VARIANT Filter, [in] VARIANT Sigma, [in] VARIANT Threshold,
[out] VARIANT Row, [out] VARIANT Col )

Subpixel precise detection of saddle points in an image.


SaddlePointsSubPix extracts saddle points from the image Image with subpixel precision, i.e., points where
along one direction the image intensity is minimal while at the same time along a different direction the image
intensity is maximal. To do so, in each point the input image is approximated by a quadratic polynomial in x and
y and subsequently the polynomial is examined for saddle points. The partial derivatives, which are necessary
for setting up the polynomial, are calculated either with various Gaussian derivatives or using the facet model,
depending on Filter. In the first case, Sigma determines the size of the Gaussian kernels, while in the second
case, before being processed the input image is smoothed by a Gaussian whose size is determined by Sigma.
Therefore, ’facet’ results in a faster extraction at the expense of slightly less accurate results. A point is accepted
to be a saddle point if the absolute values of both eigenvalues of the Hessian matrix are greater than Threshold
but their signs differ. The eigenvalues correspond to the curvature of the gray value surface.
SaddlePointsSubPix is especially useful for the detection of corners, where fields of different intensity join
together like the black and white fields of a chess board. Their high contrast and shape facilitate the location and
the determination of the precise position of such corners.
Parameter
. Image (input iconic) . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, int1, int2, uint2, int4, real )
Input image.
. Filter (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Method for the calculation of the partial derivatives.
Default Value : ’facet’
List of values : Filter ∈ {’facet’, ’gauss’}

HALCON 8.0.2
970 CHAPTER 13. SEGMENTATION

. Sigma (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT


Sigma of the Gaussian. If Filter is ’facet’, Sigma may be 0.0 to avoid the smoothing of the input image.
Suggested values : Sigma ∈ {0.7, 0.8, 0.9, 1.0, 1.2, 1.5, 2.0, 3.0}
Restriction : (Sigma ≥ 0.0)
. Threshold (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Minimum absolute value of the eigenvalues of the Hessian matrix.
Default Value : 5.0
Suggested values : Threshold ∈ {2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0}
Restriction : (T hreshold ≥ 0.0)
. Row (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; VARIANT ( real )
Row coordinates of the detected saddle points.
. Col (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; VARIANT ( real )
Column coordinates of the detected saddle points.
Result
SaddlePointsSubPix returns TRUE if all parameters are correct and no error occurs during the execution. If
the input is empty the behavior can be set via SetSystem(’noObjectResult’,<Result>). If necessary,
an exception handling is raised.
Parallelization Information
SaddlePointsSubPix is reentrant and processed without parallelization.
Possible Successors
GenCrossContourXld, DispCross
Alternatives
CriticalPointsSubPix, LocalMinSubPix, LocalMaxSubPix
Module
Foundation

HImageX.Watersheds ([out] HRegionX Watersheds )


[out] HRegionX Basins
void HOperatorSetX.Watersheds ([in] IHObjectX Image,
[out] HUntypedObjectX Basins, [out] HUntypedObjectX Watersheds )

Extract watersheds and basins from an image.


Watersheds segments an image based on the topology of the gray values. The image is interpreted as a “moun-
tain range.” Higher gray values correspond to “mountains,” while lower gray values correspond to “valleys.” In the
resulting mountain range watersheds are extracted. These correspond to the bright ridges between dark basins. On
output, the parameter Basins contains these basins, while Watersheds contains the watersheds, which are at
most one pixel wide. Watersheds always is a single region per input image, while Basins contains a separate
region for each basin.
It is advisable to apply a smoothing operator (e.g., BinomialFilter or GaussImage) to the input
image before calling Watersheds in order to reduce the number of output regions. A more sophisti-
cated way to reduce the number of output regions is to merge neighboring basins based on a threshold cri-
terion by using WatershedsThreshold instead (for more details please refer to the documentation of
WatershedsThreshold).
Attention
If the image contains many fine structures or is noisy, many output regions result, and thus the runtime increases
considerably.
Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte, uint2, real )


Input image.
. Basins (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX
Segmented basins.
. Watersheds (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Watersheds between the basins.

HALCON/COM Reference Manual, 2008-5-13


13.5. TOPOGRAPHY 971

Result
Watersheds always returns TRUE. The behavior with respect to the input images and output regions can be
determined by setting the values of the flags ’no_object_result’, ’empty_region_result’, and ’store_empty_region’
with SetSystem. If necessary, an exception is raised.
Parallelization Information
Watersheds is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
BinomialFilter, GaussImage, SmoothImage, InvertImage
Possible Successors
ExpandRegion, SelectShape, ReduceDomain, Opening
Alternatives
WatershedsThreshold, Pouring
References
L. Vincent, P. Soille: “Watersheds in Digital Space: An Efficient Algorithm Based on Immersion Simulations”;
IEEE Transactions on Pattern Analysis and Machine Intelligence; vol. 13, no. 6; pp. 583-598; 1991.
Module
Foundation

[out] HRegionX Basins HImageX.WatershedsThreshold


([in] VARIANT Threshold )
void HOperatorSetX.WatershedsThreshold ([in] IHObjectX Image,
[out] HUntypedObjectX Basins, [in] VARIANT Threshold )

Extract watershed basins from an image using a threshold.


The operator WatershedsThreshold segments regions (basins) that are separated from each other by a wa-
tershed that has a height of at least Threshold.
In the first step, WatershedsThreshold computes the watersheds without applying a threshold, resulting in
the same basins that would be obtained when calling Watersheds (for more details please refer to the description
of Watersheds). In the second step, the basins are successively merged if they are separated by a watershed
that is smaller than Threshold. Let B1 and B2 be the minimum gray values of two neighboring basins and W
the minimum gray value of the watershed that separates the two basins. The watershed is eliminated and the two
basins are merged if
max{W − B1 , W − B2 } < Threshold.

The thus obtained basins are returned in Basins.


If Threshold is set to 0, WatershedsThreshold is comparable to Watersheds except that no watersheds
but only expanded basins are returned. If Threshold is set to the maximum gray value range of Image then
no two basins are separated by a watershed exceeding Threshold, and hence, Basins will contain only one
region.
Parameter
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, uint2, real )
Image to be segmented.
. Basins (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX
Segments found (dark basins).
. Threshold (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Threshold for the watersheds.
Default Value : 10
Suggested values : Threshold ∈ {0, 5, 10, 20, 30, 50}
Restriction : (T hreshold ≥ 0)
Result
Watersheds always returns TRUE. The behavior with respect to the input image and output regions can be
determined by setting the values of the flags ’no_object_result’, ’empty_region_result’, and ’store_empty_region’
with SetSystem. If necessary, an exception is raised.

HALCON 8.0.2
972 CHAPTER 13. SEGMENTATION

Parallelization Information
WatershedsThreshold is reentrant and processed without parallelization.
Possible Predecessors
BinomialFilter, GaussImage, SmoothImage, InvertImage
Possible Successors
ExpandRegion, SelectShape, ReduceDomain, Opening
Alternatives
Watersheds, Pouring
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


Chapter 14

System

14.1 Database
[out] long NumOfTuples HSystemX.CountRelation
([in] String RelationName )
void HOperatorSetX.CountRelation ([in] VARIANT RelationName,
[out] VARIANT NumOfTuples )

Number of entries in the HALCON database.


The operator CountRelation counts the number of entries in one of the four relations of the HALCON
database. The HALCON database is organized as follows:
There are two basic relations for region-data and image-matrices. The HALCON objects region and image are
constructed from elements from these two relations: a region consists of a pointer to a tuple in the region-data
relation. An image consists also of a pointer to a tuple in the region-data relation (like a region) and additionally of
one or more pointers to tuples in the matrix relation. If there is more than one matrix pointer, the image is called a
multi-channel image.
Both regions and images are called objects. A region can be considered as the special case of an iconic object
having no image matrixes. For reasons of an efficient memory managment, the tuples of the region-data relation
and the image-matrix relation will be used by different objects together. Therefore there may be for example more
images than image matrices. Only the two lowlevel relations are of relevance to the memory consumption. Image
objects (regions as well as images) consist only of references on region and matrix data and therefore only need a
couple of bytes of memory.
Possible values for RelationName:

’image’: Image matrices. One matrix may also be the component of more than one image (no redundant storage).
’region’: Regions (the full and the empty region are always available). One region may of course also be the
component of more than one image object (no redundant storage).
’XLD’: eXtended Line Description: Contours, Polygons, paralles, lines, etc. XLD data types don’t have gray
values and are stored with subpixel accuracy.
’object’: Iconic objects. Composed of a region (called region) and optionally image matrices (called image).
’tuple’: In the compact mode, tuples of iconic objects are stored as a surrogate in this relation. Instead of working
with the individual object keys, only this tuple key is used. It depends on the host language, whether the
objects are passed individually (Prolog and C++) or as tuples (C, Smalltalk, Lisp, OPS-5).

Certain database objects will be created already by the operator ResetObjDb and therefore have to be avail-
able all the time (the undefined gray value component, the objects ’full’ (FULL_REGION in HALCON/C) and
’empty’ (EMPTY_REGION in HALCON/C) as well as the herein included empty and full region). By calling
GetChannelInfo, the operator therefore appears correspondingly also as ’creator’ of the full and empty region.
The procedure can be used for example to check the completeness of the ClearObj operation.
Attention

973
974 CHAPTER 14. SYSTEM

Parameter
. RelationName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Relation of interest of the HALCON database.
Default Value : ’object’
List of values : RelationName ∈ {’image’, ’region’, ’XLD’, ’object’, ’tuple’}
. NumOfTuples (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of tuples in the relation.
Example

reset_obj_db(512,512,3)
count_relation(’image’,I1)
count_relation(’region’,R1)
count_relation(’XLD’,X1)
count_relation(’object’,O1)
count_relation(’tuple’,T1)
read_image(X,’monkey’)
count_relation(’image’,I2)
count_relation(’region’,R2)
count_relation(’XLD’,X2)
count_relation(’object’,O2)
count_relation(’tuple’,T2)

/*
Result: I1 = 1 (undefined image)
R1 = 2 (full and empty region)
X1 = 0 (no XLD data)
O1 = 2 (full and empty objects)
T1 = 0 (always 0 in the normal mode )

I2 = 2 (additionally the image ’monkey’)


R2 = 2 (read_image uses the full region)
X2 = 0 (no XLD data)
O2 = 3 (additionally the image object X)
T2 = 0.
*/

Result
If the parameter is correct, the operator CountRelation returns the value TRUE. Otherwise an exception is
raised.
Parallelization Information
CountRelation is reentrant and processed without parallelization.
Possible Predecessors
ResetObjDb
See also
ClearObj
Module
Foundation

HSystemX.GetModules ([out] long ModuleKey )


[out] VARIANT UsedModules
void HOperatorSetX.GetModules ([out] VARIANT UsedModules,
[out] VARIANT ModuleKey )

Query of used modules and the module key.


GetModules returns the module numbers of all operators used up to this point. Each operator belongs to one
module (maximum 32). Each module has a name, which is returned in UsedModules. Based on the used

HALCON/COM Reference Manual, 2008-5-13


14.1. DATABASE 975

modules, a key is generated that is needed for the licence manager. GetModules is normally called at the end
of a programm to check the used modules.
Parameter

. UsedModules (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( string )


Names of used modules.
. ModuleKey (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Key for licence manager.
Parallelization Information
GetModules is reentrant and processed without parallelization.
Module
Foundation

void HSystemX.ResetObjDb ([in] long DefaultImageWidth,


[in] long DefaultImageHeight, [in] long DefaultChannels )
void HOperatorSetX.ResetObjDb ([in] VARIANT DefaultImageWidth,
[in] VARIANT DefaultImageHeight, [in] VARIANT DefaultChannels )

Initialization of the HALCON system.


The operator ResetObjDb initializes the HALCON system. With this procedure the four relations (grayvalue
data, region data, iconic objects and object tuplets) which are necessary for image processing with HALCON will
be installed (see also CountRelation). In case the relations already exist, all tuplets in the relations will be
deallocated!
The parameters DefaultImageWidth and DefaultImageHeight provide the initial values for the global
maximum image size. If the first created object is an image, (e.g. ReadImage), the set values will be overruled
in Standard-HALCON by the size of this picture. Instead of this, in Parallel HALCON the set values will only be
changed, if they are smaller than the size of the created object. If on the other hand the first object to be created
is a region, both in Standard- and in Parallel HALCON the values will only be adjusted in case the new image is
larger than the set values. This is not only the case for the first image which is created or read: the global image
size will always be enlarged, if larger images are created.
The global image size is of consequence for the opening of windows ( OpenWindow) and the clipping of regions.
Whenever the clip mode is activated, regions will be clipped according to the global image size ( SetSystem
(’clipRegion’,’true’)). This can lead to problems if images of various sizes are used. In this case only
the fact that a region is smaller or of the same size as the largest image can be guaranteed.
The parameter DefaultChannels returns the most frequent number of channels of an image object. This value
can be set to 0 if for the most part regions are used. If more channels than those having been set at the initialization
are necessary for one image, the number will be enlarged dynamically for this image. If less channels than those
having been set at the initialization are necessary for the image, the superfluous channels will be set as undefined.
For the user this will seem as if they were non existent, however, memory is allocated unnecessarily.
The parameter values can be queried using the operator GetSystem.
Attention
If the operator ResetObjDb is not called at the beginning of a HALCON session, HALCON will be initialized
automatically by the operator ResetObjDb(128,128,0). In case the operator ResetObjDb is called again,
all image objects in the database will be deallocated.
Parameter

. DefaultImageWidth (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT


Default image width (in pixels).
Default Value : 128
Suggested values : DefaultImageWidth ∈ {64, 128, 256, 512, 525, 1024}
. DefaultImageHeight (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Default image height (in pixels).
Default Value : 128
Suggested values : DefaultImageHeight ∈ {64, 128, 256, 512, 768, 1024}

HALCON 8.0.2
976 CHAPTER 14. SYSTEM

. DefaultChannels (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT


Usual number of channels by which the system constant ’max_channels’ is limited.
Default Value : 0
Suggested values : DefaultChannels ∈ {0, 1, 2, 3, 4, 5, 6, 7}
Result
The operator ResetObjDb returns the value TRUE if the parameter values are correct. Otherwise an exception
will be raised.
Parallelization Information
ResetObjDb is reentrant and processed without parallelization.
See also
GetChannelInfo, CountRelation
Module
Foundation

14.2 Error-Handling

HSystemX.GetCheck ( )
[out] VARIANT Check
void HOperatorSetX.GetCheck ([out] VARIANT Check )

State of the HALCON control modes.


Executing the operator GetCheck the user can inquire what kind of control modes are currently activated and
which are not. Check gives the tuplet containing the names of the control modes (see also SetCheck) which
are preceded by a tilde (˜, e.g. ’˜data’), if the corresponding control is deactivated.
Attention

Parameter
. Check (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( string )
Tuplet of the currently activated control modes.
Result
GetCheck always returns the value TRUE.
Parallelization Information
GetCheck is reentrant and processed without parallelization.
Possible Predecessors
SetCheck
See also
SetCheck
Module
Foundation

HSystemX.GetErrorText ([in] long ErrorNumber )


[out] String ErrorText
void HOperatorSetX.GetErrorText ([in] VARIANT ErrorNumber,
[out] VARIANT ErrorText )

Inquiry after the error text of a HALCON error number.


The operator GetErrorText returns the error text for the corresponding HALCON error number. This is indeed
the same text which will be given during an exception. The operator GetErrorText is especially useful if the
error treatment is programmed by the users themselves (see also SetCheck(::’˜give_error’:)).
Attention
Unknown error numbers will trigger a standard message.

HALCON/COM Reference Manual, 2008-5-13


14.2. ERROR-HANDLING 977

Parameter

. ErrorNumber (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT


Number of the HALCON error.
Restriction : ((1 ≤ ErrorN umber) ∧ (ErrorN umber ≤ 36000))
. ErrorText (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Corresponding error text.
Result
The operator GetErrorText always returns the value TRUE.
Parallelization Information
GetErrorText is reentrant and processed without parallelization.
Possible Predecessors
SetCheck
See also
SetCheck
Module
Foundation

[out] VARIANT Value HSystemX.GetSpy ([in] String Class )


void HOperatorSetX.GetSpy ([in] VARIANT Class, [out] VARIANT Value )
Current configuration of the HALCON debugging-tool.
The operator GetSpy returns the current configuration of spy, the HALCON debugging tool. The available
control modes (possible choices for Class) as well as the corresponding tuning possibilities (possible values for
Value) can be called up by using the operator QuerySpy. You will find a more detailed description under
SetSpy.
Attention

Parameter

. Class (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT


Control mode
Default Value : ’mode’
List of values : Class ∈ {’mode’, ’procedure’, ’input_control’, ’output_control’, ’parameter_values’, ’db’,
’input_gray_window’, ’input_region_window’, ’input_region_window’, ’halt’, ’timeout’, ’button_window’,
’button_window’, ’button_click’, ’button_notify’, ’log_file’, ’error’, ’internal’}
. Value (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( string, integer, real )
State of the control mode.
Result
The operator GetSpy returns the value TRUE if the parameter Class is correct. Otherwise an exception is
raised.
Parallelization Information
GetSpy is reentrant and processed without parallelization.
Possible Predecessors
ResetObjDb
See also
SetSpy, QuerySpy
Module
Foundation

HALCON 8.0.2
978 CHAPTER 14. SYSTEM

[out] VARIANT Classes HSystemX.QuerySpy ([out] VARIANT Values )


void HOperatorSetX.QuerySpy ([out] VARIANT Classes,
[out] VARIANT Values )

Inquiring for possible settings of the HALCON debugging tool.


The operator QuerySpy returns all possible settings of spy, the HALCON debugging tool, i.e. all the available
control modes (Classes) as well as the corresponding possible ways of setting (Values). For a more detailed
description of spy see operator SetSpy.
Attention
The values of Values cannot be used as direct input for SetSpy, as they are transmitted as a symbolic constant.
Parameter
. Classes (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( string )
Available control modes (see also set_spy).
. Values (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( string )
Corresponding state of the control modes.
Result
query_spy always returns the value TRUE.
Parallelization Information
QuerySpy is reentrant and processed without parallelization.
Possible Predecessors
ResetObjDb
See also
SetSpy, GetSpy
Module
Foundation

void HSystemX.SetCheck ([in] VARIANT Check )


void HOperatorSetX.SetCheck ([in] VARIANT Check )

Activating and deactivating of HALCON control modes.


With the help of the operator SetCheck different control modes of the HALCONsystem can be activated or
deactivated. If a certain control mode is activated, parameters etc. will be checked at runtime. Whenever an
inconsistency is hereby detected, the program will be interrupted by an exception.
It is recommendable to activate the control modes during the development of a program and to deactivate them
only after a successfully concluded testrun. For if the control mode is deactivated and an error occurs, the system
may react in an unpredictable way.
The HALCONsystem provides various possible control modes which can be activated and deactivated indepen-
dently. By calling the operator SetCheck with the name (Check) of the desired control mode, this control
mode is activated; the control mode is deactivated by passing its name prefixed with a tilde (˜, z.B. ’˜data’).

Available control modes:

’color’: If this control mode is activated, only colors may be used which are supported by the display for the
currently active window. Otherwise an error message is displayed.
In case of deactivated control mode and non existent colors, the nearest color is used (see also SetColor,
SetGray, SetRgb).
’text’: If this control mode is activated, it will check the coordinates during the setting of the text cursor as well
as during the display of strings ( WriteString) to the effect whether a part of a sign would lie outside the
windowframe (a fact which is not forbidden in principle by the system).
If the control mode is deactivaed, the text will be clipped at the windowframe.
’data’: (For program development)
Checks the consistency of image objects (regions and grayvalue components.

HALCON/COM Reference Manual, 2008-5-13


14.2. ERROR-HANDLING 979

’interface’: If this control mode is activated, the interface between the host language and the HALCON proce-
dures will be checked in course (e.g. typifying and counting of the values).
’database’: This is a consistency check of the database (e.g. checks whether an object which shall be canceled
does indeed exist or not.)
’give_error’: Determines whether errors shall trigger exceptions or not. If this control modes is deactivated,
the application program must provide a suitable error treatment itself. Please note that errors which are
not reported usually lead to undefined output parameters which may cause an unpredictable reaction of the
program. Details about how to handle exceptions in the different HALCON language interfaces can be found
in the HALCON Programmer’s Guide and the HDevelop User’s Guide.
’father’: If this control mode is activated when calling the operators OpenWindow or OpenTextwindow,
HALCON allows only the usage of the number of another HALCON window as the father window of the
new window; otherwise it allows also the usage of IDs of operating system windows as the father window.
This control mode ist only relevant for windows of type ’X-Window’ and ’WIN32-Window’.
’region’: (For program development)
Checks the consistency of chords (this may lead to a notable speed reduction of routines).
’clear’: Normally, if a list of objects shall be canceled by using ClearObj, an exception will be raised, in case
individual objects do not or no longer exist. If the ’clear’ mode is activated, such objects will be ignored.
’memory’: (For program development)
Checks the memory blocks freed by the HALCON memory managemnet on consistency and overwriting of
memory borders.
’all’: Activates all control modes.
’none’: Deactivates all control modes.
’default’: Default settings: [’give_error’,’database’]

Attention

Parameter
. Check (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Desired control mode.
Default Value : ’default’
List of values : Check ∈ {’color’, ’text’, ’database’, ’data’, ’interface’, ’give_error’, ’father’, ’region’, ’clear’,
’memory’, ’all’, ’none’, ’default’}
Result
The operator SetCheck returns the value TRUE, if the parameters are correct. Otherwise an exception will be
raised.
Parallelization Information
SetCheck is reentrant and processed without parallelization.
See also
GetCheck, SetColor, SetRgb, SetHsi, WriteString
Module
Foundation

void HSystemX.SetSpy ([in] String Class, [in] VARIANT Value )


void HOperatorSetX.SetSpy ([in] VARIANT Class, [in] VARIANT Value )

Control of the HALCON Debugging Tools.


The operator SetSpy is the HALCON debugging tool. This tool allows the flexible control of the input and
output data of HALCON-operators - in graphical as well as in textual form. The datacontrol is activated by using

SetSpy(::’mode’,’on’:),
and deactivated by using

HALCON 8.0.2
980 CHAPTER 14. SYSTEM

SetSpy(::’mode’,’off’:).
The debugging tool can further be activated with the help of the environment variable HALCONSPY. The definition
of this variable corresponds to calling up ’mode’ and ’on’.
The following control modes can be tuned (in any desired combination of course) with the help of Class/Value:

Class Meaning / Value


’operator’ When a routine is called, its name and the names of its parameters will be given (in TRIAS notation).
Value: ’on’ or ’off’
default: ’off’
’input_control’ When a routine is called, the names and values of the input control parameters will be given.
Value: ’on’ or ’off’
default: ’off’
’output_control’ When a routine is called, the names and values of the output control parameters are given.
Value: ’on’ or ’off’
default: ’off’
’parameter_values’ Additional information on ’input_control’ and ’output_control’: indicates how many values
per parameter shall be displayed at most (maximum tuplet length of the output).
Value: tuplet length (integer)
default: 4
’db’ Information concerning the 4 relations in the HALCON-database. This is especially valuable in looking for
forgotten ClearObj.
Value: ’on’ or ’off’
default: ’off’
’input_gray_window’ Any reading access of the gray-value component of an (input) image object will cause the
gray-value component to be shown in the indicated window (Window-ID; ’none’ will deactivate this control
).
Value: Window-ID (integer) or ’none’
default: ’none’
’input_region_window’ Any reading access of the region of an (input) iconic object will cause this region to be
shown in the indicated (Window-ID; ’none’ will deactivate this control ).
Value: Window-ID (integer) or ’none’
default: ’none’
’input_xld_window’ Any reading access of the xld will cause this xld to be shown in the indicated (Window-ID;
’none’ will deactivate this control ).
Value: Window-ID (integer) or ’none’
default: ’none’
’time’ Processing time of the operator
Value: ’on’ or ’off’
default: ’off’
’halt’ Determines whether there is a halt after every individual action (’multiple’) or only at the end of each oper-
ator (’single’). The parameter is only effective if the halt has been activated by ’timeout’ or ’button_window’.
Value: ’single’ or ’multiple’
default: ’multiple’
’timeout’ After every output there will be a halt of the indicated number of seconds.
Value: seconds (real)
default 0.0
’button_window’ Alternative to ’timeout’: after every output spy waits until the cursor indicates (’button_click’
= ’false’) or clicks into (’button_click’ = ’true’) the indicated window. (Window-ID; ’none’ will deactivate
this control ).
Value: Window-ID (integer) or ’none’
default: ’none’
’button_click’ Additional option for ’button_window’: determines whether or not a mouse-click has to be waited
for after an output.
Value: ’on’ or ’off’
default: ’off’

HALCON/COM Reference Manual, 2008-5-13


14.3. INFORMATION 981

’button_notify’ If ’button_notify’ is activated, spy generates a beep after every output. This is useful in combi-
nation with ’button_window’.
Value: ’on’ or ’off’
default: ’off’
’log_file’ Spy can hereby divert the text output into a file having been opened with open_file.
Value: a file handle (see OpenFile)
’error’ If ’error’ is activated and an internal error occurs, spy will show the internal procedures (file/line) con-
cerned.
Value: ’on’ or ’off’
default: ’off’
’internal’ If ’internal’ is activated, spy will display the internal procedures and their parameters (file/line) while
an HALCON-operator is processed.
Value: ’on’ or ’off’
default: ’off’
Attention

Parameter
. Class (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Control mode
Default Value : ’mode’
List of values : Class ∈ {’mode’, ’operator’, ’input_control’, ’output_control’, ’parameter_values’,
’input_gray_window’, ’input_region_window’, ’input_xld_window’, ’db’, ’time’, ’halt’, ’timeout’,
’button_window’, ’button_click’, ’button_notify’, ’log_file’, ’error’, ’internal’}
. Value (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( string, integer, real )
State of the control mode to be set.
Default Value : ’on’
Suggested values : Value ∈ {’on’, ’off’, 1, 2, 3, 4, 5, 10, 50, 0.0, 1.0, 2.0, 5.0, 10.0}
Result
The operator SetSpy returns the value TRUE if the parameters are correct. Otherwise an exception is raised.
Parallelization Information
SetSpy is processed completely exclusively without parallelization.
Possible Predecessors
ResetObjDb
See also
GetSpy, QuerySpy
Module
Foundation

14.3 Information
HInfoX.GetChapterInfo ([in] VARIANT Chapter )
[out] VARIANT Info
void HOperatorSetX.GetChapterInfo ([in] VARIANT Chapter,
[out] VARIANT Info )

Get information concerning the chapters on procedures.


The operator GetChapterInfo gives information concerning the chapters on procedures. If instead of
Chapter the empty string is transmitted, the routine will provide in Info the names of all chapters. If on the
other hand a certain chapter or a chapter and its subchapter(s) are indicated (by a tuple of names), the corresponding
subchapters or - in case there are no further subchapters - the names of the corresponding procedures will be given.
The organization of the chapters on procedures is the same as the organization of chapters and subchapters in the
HALCON-manual. Please note: The chapters on procedures respectively the subchapters concerning an individual
procedure can be called by using the operator GetOperatorInfo(::<Name>,’chapter’,Info:). The
Online-texts will be taken from the files english.hlp, english.sta, english.num, english.key, and english.idx, which

HALCON 8.0.2
982 CHAPTER 14. SYSTEM

will be searched by HALCON in the currently used directory or the directory ’help_dir’ (see also GetSystem
and SetSystem).
Parameter
. Chapter (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Procedure class or subclass of interest.
Default Value : ”
. Info (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( string )
Procedure classes (Chapter = ”) or procedure subclasses respectively procedures.
Result
If the parameter values are correct and the helpfile is available, the operator GetChapterInfo returns the value
TRUE. Otherwise an exception handling is raised.
Parallelization Information
GetChapterInfo is processed completely exclusively without parallelization.
Possible Predecessors
GetSystem, SetSystem
See also
GetOperatorInfo, GetSystem, SetSystem
Module
Foundation

HInfoX.GetKeywords ([in] String ProcName )


[out] VARIANT Keywords
void HOperatorSetX.GetKeywords ([in] VARIANT ProcName,
[out] VARIANT Keywords )

Get keywords which are assigned to procedures.


The operator GetKeywords returns all the keywords in the online-texts corresponding to those procedures which
have the indicated substring ProcName in their name. If instead of ProcName the empty string is transmitted,
the operator GetKeywords returns all keywords. The keywords of an individual procedure can also be called
by using the operator GetOperatorInfo. The online-texts will be taken from the files english.hlp, english.sta,
english.num, english.key and english.idx, which are searched by HALCON in the currently used directory and in
the directory ’help_dir’ (see also GetSystem and SetSystem).
Attention

Parameter
. ProcName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . proc_name ; String / VARIANT
Substring in the names of those procedures for which keywords are needed.
Default Value : ’get_keywords’
. Keywords (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( string )
Keywords for the procedures.
Result
The operator GetKeywords returns the value TRUE if the parameters are correct and the helpfiles are available.
Otherwise an exception handling is raised.
Parallelization Information
GetKeywords is processed completely exclusively without parallelization.
Possible Predecessors
GetChapterInfo
See also
GetOperatorName, SearchOperator, GetParamInfo
Alternatives
GetOperatorInfo
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


14.3. INFORMATION 983

[out] VARIANT Information HInfoX.GetOperatorInfo ([in] String ProcName,


[in] String Slot )
void HOperatorSetX.GetOperatorInfo ([in] VARIANT ProcName,
[in] VARIANT Slot, [out] VARIANT Information )

Get information concerning a HALCON-procedure.


With the help of the operator GetOperatorInfo the online-texts concerning a certain procedure can be called
(see also GetOperatorName). The form of information available for all procedures (Slot) can be called using
the operator QueryOperatorInfo. For the time being the following slots are available:

’short’: Short description of the procedure.


’abstract’: Description of the procedure.
’procedure_class’: Name(s) of the chapter(s) in the procedure hierarchy (chapter, subchapter in the HALCON
manual).
’functionality’: Functionality is equivalent to the object class to which the procedure can be assigned.
’keywords’: Keywords of the procedure (optional).
’example’: Example for the use of the procedure (optional). The operator ’example.LANGUAGE’ (LANGUAGE
∈ {c,c++,smalltalk,trias}) calls up examples for a certain language if available. If the language is not indi-
cated or if no example is available in this language, the TRIAS-example will be returned.
’complexity’: Complexity of the procedure (optional).
’effect’: Not in use so far.
’alternatives’: Alternative procedures (optional).
’see_also’: Procedures containing further information (optional).
’predecessor’: Possible and sensible predecessor
’successor’: Possible and sensible successor
’result_state’: Return value of the procedure (TRUE, FALSE, FAIL, VOID or EXCEPTION).
’attention’: Restrictions and advice concering the correct use of the procedure (optional).
’parameter’: Names of the parameter of the procedure (see also GetParamInfo).
’references’: Literary references (optional).
’module’: The module to which the operator is assigned.
’html_path’: The directory where the HTML documentation of the operator resides.
’warning’: Possible warnings for using the operator.

The texts will be taken from the files english.hlp, english.sta, english.key, english.num und english.idx which
will be searched by HALCON in the currently used directory or in the directory ’help_dir’ (respectively
’user_help_dir’) (see also GetSystem and SetSystem). By adding ’.latex’ after the slotname, the text of
slots containing textual information can be made available in LATEX notation.
Parameter

. ProcName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . proc_name ; String / VARIANT


Name of the operator on which more information is needed.
Default Value : ’get_operator_info’
. Slot (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Desired information.
Default Value : ’abstract’
List of values : Slot ∈ {’short’, ’abstract’, ’procedure_class’, ’functionality’, ’effect’, ’complexity’,
’predecessor’, ’successor’, ’alternatives’, ’see_also’, ’keywords’, ’example’, ’attention’, ’result_state’,
’return_value’, ’references’, ’module’, ’html_path’, ’warning’}
. Information (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Information (empty if no information is available)

HALCON 8.0.2
984 CHAPTER 14. SYSTEM

Result
The operator GetOperatorInfo returns the value TRUE if the parameters are correct and the helpfiles are
availabe. Otherwise an exception handling is raised.
Parallelization Information
GetOperatorInfo is processed completely exclusively without parallelization.
Possible Predecessors
GetKeywords, SearchOperator, GetOperatorName, QueryOperatorInfo, QueryParamInfo,
GetParamInfo
Possible Successors
GetParamNames, GetParamNum, GetParamTypes
See also
QueryOperatorInfo, GetParamInfo, GetOperatorName, GetParamNum, GetParamTypes
Alternatives
GetParamNames
Module
Foundation

HInfoX.GetOperatorName ([in] String Pattern )


[out] VARIANT ProcNames
void HOperatorSetX.GetOperatorName ([in] VARIANT Pattern,
[out] VARIANT ProcNames )

Get procedures with the given string as a substring of their name.


The operator GetOperatorName takes a string (Pattern) as input and searches all HALCON-procedures
having this string as a substring in their name. If an empty string is entered, the names of all procedures available
will be returned.
Attention

Parameter

. Pattern (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT


Substring of the seeked names (empty <=> all names).
Default Value : ’info’
. ProcNames (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( string )
Detected procedure names.
Result
The operator GetOperatorName returns the value TRUE if the helpfiles are available. Otherwise an exception
handling is raised.
Parallelization Information
GetOperatorName is reentrant and processed without parallelization.
Possible Successors
GetOperatorInfo, GetParamNames, GetParamNum, GetParamTypes
See also
GetOperatorInfo, GetParamNames, GetParamNum, GetParamTypes
Alternatives
SearchOperator
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


14.3. INFORMATION 985

[out] VARIANT Information HInfoX.GetParamInfo ([in] String ProcName,


[in] String ParamName, [in] String Slot )
void HOperatorSetX.GetParamInfo ([in] VARIANT ProcName,
[in] VARIANT ParamName, [in] VARIANT Slot, [out] VARIANT Information )

Get information concerning the procedure parameters.


The operator GetParamInfo is used for calling up the online-texts assigned to a parameter of an indicated
procedure. The form of information available for each parameter (Slot), can be called up by using the operator
QueryParamInfo. At the moment the following slots are available:

’description’: Description of the parameter.


’description.latex’: Description of the parameter in LATEX notation.
’parameter_class’: Parameter classes: ’input_object’, ’output_object’, ’input_control’ oder ’output_control’.
’type_list’: Permitted type(s) of data for parameter values Values: ’real’, ’integer’ or ’string’ (for control parame-
ters), ’byte’, ’direction’, ’cyclic’, ’int1’, ’int2’, ’uint2’, ’int4’, ’real’, ’complex’, ’vector_field’ (for images).
’default_type’: Default-type for parameter values (for control parameters only). This type of parameter is the one
HALCON/C uses in the "‘simple mode"’. If ’none’ is indicated, the "‘tuple mode"’ must be used. Value:
’real’, ’integer’, ’string’ oder ’none’.
’sem_type’: Semantic type of the parameter. This is important to allow the assignment of the parameters to object
classes in object-oriented languages (C++, .NET, COM). If more than one parameter belongs semantically to
one type, this fact is indicated as well. So far the the following objects are supported:
object, image, region, xld,
xld_cont, xld_para, xld_poly, xld_ext_para, xld_mod_para,
integer, real, number, string,
channel, grayval, window,
histogram, distribution,
point(.x, .y), extent(.x, .y),
angle(.rad oder .deg),
circle(.center.x, .center.y, .radius),
arc(.center.x, .center.y, .angle.rad, .begin.x, .begin.y),
ellipse(.center.x, .center.y, .angle.rad, .radius1, .radius2),
line(.begin.x, .begin.y, .end.x, .end.y)
rectangle(.origin.x, .origin.y, .corner.x, .corner.y
or .extent.x, .extent.y),
polygon(.x, .y), contour(.x, .y),
coordinates(.x, .y), chord(.x1, .x2, .y),
chain(.begin.x, .begin.y, .code).
’default_value’: Default-value for the parameter (for input-control parameters only). It is the question of mere
information only (the parameter value must be transmitted explicitly, even if the default-value is used). This
entry serves only as a notice, a point of departure for own experiments. The values have been selected so that
they normally do not cause any errors but generate something that makes sense.
’multi_value’: ’true’, if more than one value is permitted in this parameter position, otherwise ’false’.
’multichannel’: ’true’, in case the input image object may be multichannel.
’mixed_type’: For control parameters exclusively and only if value tuples (’multivalue’-’true’) and various types
of data are permitted for the parameter values (’type_list’ having more than one value). In this case Slot
indicates, whether values of various types may be mixed in one tuple (’true’ or ’false’).
’values’: Selection of values (optional).
’value_list’: In case a parameter can take only a limited number of values, this fact will be indicated explicitly
(optional).
’valuemin’: Minimum value of a value interval.
’valuemax’: Maximum value of a value interval.
’valuefunction’: Function discribing the course of the values for a series of tests (lin, log, quadr, ...).
’steprec’: Recommended step width for the parameter values in a series of tests.

HALCON 8.0.2
986 CHAPTER 14. SYSTEM

’steprec’: Minimum step width of the parameter values in a series of tests.


’valuenumber’: Expression describing the number of parameters as such or in relation to other parameters.
’assertion’: Expression describing the parameter values as such or in relation to other parameters.

The online-texts will be taken from the files english.hlp, english.sta, english.key, english.num and english.idx
which will be searched by HALCON in the currently used directory or the directory ’help_dir’ (see also
GetSystem and SetSystem).
Attention

Parameter

. ProcName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . proc_name ; String / VARIANT


Name of the procedure on whose parameter more information is needed.
Default Value : ’get_param_info’
. ParamName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Name of the parameter on which more information is needed.
Default Value : ’Slot’
. Slot (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Desired information.
Default Value : ’description’
List of values : Slot ∈ {’description’, ’type_list’, ’default_type’, ’sem_type’, ’default_value’, ’values’,
’value_list’, ’valuemin’, ’valuemax’, ’valuefunction’, ’valuenumber’, ’assertion’, ’steprec’, ’stepmin’,
’mixed_type’, ’multivalue’, ’multichannel’}
. Information (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Information (empty in case there is no information available).
Parallelization Information
GetParamInfo is processed completely exclusively without parallelization.
Possible Predecessors
GetKeywords, SearchOperator
See also
QueryParamInfo, GetOperatorInfo, GetOperatorName
Alternatives
GetParamNames, GetParamNum, GetParamTypes
Module
Foundation

[out] VARIANT InpObjPar HInfoX.GetParamNames ([in] String ProcName,


[out] VARIANT OutpObjPar, [out] VARIANT InpCtrlPar,
[out] VARIANT OutpCtrlPar )
void HOperatorSetX.GetParamNames ([in] VARIANT ProcName,
[out] VARIANT InpObjPar, [out] VARIANT OutpObjPar, [out] VARIANT InpCtrlPar,
[out] VARIANT OutpCtrlPar )

Get the names of the parameters of a HALCON-procedure.


For the HALCON-procedure indicated in ProcName the operator GetParamNames returns the names of the
input objects, the output objects, of the input control parameters and the output control parameters.
Parameter

. ProcName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . proc_name ; String / VARIANT


Name of the procedure.
Default Value : ’get_param_names’
. InpObjPar (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( string )
Names of the input objects.

HALCON/COM Reference Manual, 2008-5-13


14.3. INFORMATION 987

. OutpObjPar (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( string )


Names of the output objects.
. InpCtrlPar (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( string )
Names of the input control parameters.
. OutpCtrlPar (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( string )
Names of the output control parameters.
Result
The operator GetParamNames returns the value TRUE if the name of the procedure exists and the helpfiles are
available. Otherwise an exception handling is raised.
Parallelization Information
GetParamNames is reentrant and processed without parallelization.
Possible Predecessors
GetKeywords, SearchOperator, GetOperatorName, GetOperatorInfo
Possible Successors
GetParamNum, GetParamTypes
See also
GetParamNum, GetParamTypes, GetOperatorName
Alternatives
GetOperatorInfo, GetParamInfo
Module
Foundation

[out] String CName HInfoX.GetParamNum ([in] String ProcName,


[out] long InpObjPar, [out] long OutpObjPar, [out] long InpCtrlPar,
[out] long OutpCtrlPar, [out] String Type )
void HOperatorSetX.GetParamNum ([in] VARIANT ProcName,
[out] VARIANT CName, [out] VARIANT InpObjPar, [out] VARIANT OutpObjPar,
[out] VARIANT InpCtrlPar, [out] VARIANT OutpCtrlPar, [out] VARIANT Type )

Get number of the different parameter classes of a HALCON-procedure.


The operator GetParamNum returns the number of the input and output object parameters, as well as the input
and output control parameters for the indicated HALCON-procedure. Further, you will receive the name of the
C-function (CName) called by the procedure. The output parameter Type indicates, whether the procedure is a
system procedure or an user procedure.
Parameter

. ProcName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . proc_name ; String / VARIANT


Name of the procedure.
Default Value : ’get_param_num’
. CName (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Name of the called C-function.
. InpObjPar (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of the input object parameters.
. OutpObjPar (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of the output object parameters.
. InpCtrlPar (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of the input control parameters.
. OutpCtrlPar (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of the output control parameters.
. Type (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
System procedure or user procedure.
Suggested values : Type ∈ {’system’, ’user’}

HALCON 8.0.2
988 CHAPTER 14. SYSTEM

Result
The operator GetParamNum returns the value TRUE if the name of the procedure exists. Otherwise an exception
handling is raised.
Parallelization Information
GetParamNum is reentrant and processed without parallelization.
Possible Predecessors
GetKeywords, SearchOperator, GetOperatorName, GetOperatorInfo
Possible Successors
GetParamTypes
See also
GetParamNames, GetParamTypes, GetOperatorName
Alternatives
GetOperatorInfo, GetParamInfo
Module
Foundation

[out] VARIANT InpCtrlParType HInfoX.GetParamTypes ([in] String ProcName,


[out] VARIANT OutpCtrlParType )
void HOperatorSetX.GetParamTypes ([in] VARIANT ProcName,
[out] VARIANT InpCtrlParType, [out] VARIANT OutpCtrlParType )

Get default data type for the control parameters of a HALCON-procedure.


The operator GetParamTypes returns the default data type for each input and output control parameter. The
default type of a parameter is the type used in "‘simple mode"’ in HALCON/C. This concerns parameters which
allow more than one type as for example WriteString. Hereby the types of input parameters are com-
bined in the variable InpCtrlParType, whereas the types of output parameters are combined in the variable
OutpCtrlParType. The following types are possible:

’integer’: an integer.
’integer tuple’: an integer or a tuple of integers.
’real’: a floating point number.
’real tuple’: a floating point number or a tuple of floating point numbers.
’string’: a string.
’string tuple’: a string or a tuple of strings.
’no_default’: individual value of which the type cannot be determined.
’no_default tuple’: individual value or tuple of values of which the type cannot be determined.
’default’: individual value of unknown type, whereby the systems assumes it to be an ’integer’.

Parameter

. ProcName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . proc_name ; String / VARIANT


Name of the procedure.
Default Value : ’get_param_types’
. InpCtrlParType (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( string )
Default type of the input control parameters.
. OutpCtrlParType (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( string )
Default type of the output control parameters.
Parallelization Information
GetParamTypes is reentrant and processed without parallelization.
Possible Predecessors
GetKeywords, SearchOperator, GetOperatorName, GetOperatorInfo

HALCON/COM Reference Manual, 2008-5-13


14.3. INFORMATION 989

See also
GetParamNames, GetParamNum, GetOperatorInfo, GetOperatorName
Alternatives
GetParamInfo
Module
Foundation

HInfoX.QueryOperatorInfo ( )
[out] VARIANT Slots
void HOperatorSetX.QueryOperatorInfo ([out] VARIANT Slots )

Query slots concerning information with relation to the operator GetOperatorInfo.


The operator QueryOperatorInfo returns the names of those online texts (Slots) which are available online
for each procedure. The information itself can be called up using
GetOperatorInfo(::<ProcName>,<Slot>:<Information>).
Attention

Parameter

. Slots (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( string )


Slotnames of the operator GetOperatorInfo.
Result
The operator QueryOperatorInfo always returns the value TRUE.
Parallelization Information
QueryOperatorInfo is local and processed completely exclusively without parallelization.
Possible Successors
GetOperatorInfo
See also
GetOperatorInfo
Module
Foundation

HInfoX.QueryParamInfo ( )
[out] VARIANT Slots
void HOperatorSetX.QueryParamInfo ([out] VARIANT Slots )

Query slots of the online-information concerning the operator GetParamInfo.


The operator QueryParamInfo returns the names of those pieces of information (Slots) which are available
online for each parameter (online texts). The online texts themselves can be called up using
GetParamInfo(::<Procedurname>,<Parametername>,<Slot>:<Information>).
Attention

Parameter

. Slots (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( string )


Slotnames for the operator GetParamInfo.
Result
QueryParamInfo always returns the value TRUE.
Parallelization Information
QueryParamInfo is reentrant and processed without parallelization.
Possible Successors
GetParamInfo

HALCON 8.0.2
990 CHAPTER 14. SYSTEM

See also
GetParamInfo
Module
Foundation

HInfoX.SearchOperator ([in] String Keyword )


[out] VARIANT ProcNames
void HOperatorSetX.SearchOperator ([in] VARIANT Keyword,
[out] VARIANT ProcNames )

Search names of all procedures assigned to one keyword.


The operator SearchOperator returns the names of all procedures whose online-texts include the key-
word Keyword (see also GetOperatorInfo). All available keywords are called by using the operator
GetKeywords(::”: <keywords>). The online-texts are taken from the files english.hlp, english.sta, en-
glish.key, english.num and Halcon.idx, which are searched by HALCON in the currently used directory or the
directory ’help_dir’ (see also GetSystem and GetSystem).
Attention

Parameter

. Keyword (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT


Keyword for which corresponding procedures are searched.
Default Value : ’Information’
. ProcNames (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( string )
Procedures whose slot ’keyword’ contains the keyword.
Result
The operator SearchOperator returns the value TRUE if the parameters are correct and the helpfiles are
available. Otherwise an exception handling is raised.
Parallelization Information
SearchOperator is processed completely exclusively without parallelization.
Possible Predecessors
GetKeywords
See also
GetKeywords, GetOperatorInfo, GetParamInfo
Module
Foundation

14.4 Operating-System

HSystemX.CountSeconds ( )
[out] double Seconds
void HOperatorSetX.CountSeconds ([out] VARIANT Seconds )

Elapsed processing time since the last call of CountSeconds.


The operator CountSeconds helps to measure time. Each operator call returns a time value. The difference of
the values of two successive calls provides the time interval in seconds. The mode of measuring time can be set
with SetSystem(’clockMode’,...).
Attention
The time measurement is not exact and depends on the load of the computer.
Parameter

. Seconds (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT


Processtime since the program start.

HALCON/COM Reference Manual, 2008-5-13


14.4. OPERATING-SYSTEM 991

Example

count_seconds(Start)
/* program segment to be measured */
count_seconds(End)
Seconds := End - Start

Result
The operator CountSeconds always returns the value TRUE.
Parallelization Information
CountSeconds is reentrant and processed without parallelization.
See also
SetSystem
Module
Foundation

void HSystemX.SystemCall ([in] String Command )


void HOperatorSetX.SystemCall ([in] VARIANT Command )

Executes a system command.


The operator SystemCall executes the system command specified by the string pointed to by Command (C-
procedure "‘system"’). If the string is empty, an interactive shell will be started (’csh -i’).
Attention

Parameter

. Command (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT


Command to be called by the system.
Default Value : ’ls’
Result
If the entered operator can be executed by the system, the operator SystemCall returns the value TRUE.
Otherwise an exception will be raised.
Parallelization Information
SystemCall is reentrant and processed without parallelization.
Possible Predecessors
CountSeconds
See also
WaitSeconds, CountSeconds
Module
Foundation

void HSystemX.WaitSeconds ([in] double Seconds )


void HOperatorSetX.WaitSeconds ([in] VARIANT Seconds )

Delaying the execution of the program.


The operator WaitSeconds delays the execution by the number of seconds indicated in Seconds.
Attention

HALCON 8.0.2
992 CHAPTER 14. SYSTEM

Parameter
. Seconds (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Number of seconds by which the execution of the program will be delayed.
Default Value : 10
Restriction : (Seconds ≥ 0)
Result
The operator WaitSeconds always returns the value TRUE.
Parallelization Information
WaitSeconds is reentrant and processed without parallelization.
Possible Successors
SystemCall
See also
SystemCall, CountSeconds
Module
Foundation

14.5 Parallelization
void HSystemX.CheckParHwPotential ([in] long AllInpPars )
void HOperatorSetX.CheckParHwPotential ([in] VARIANT AllInpPars )

Check hardware regarding its potential for parallel processing.


CheckParHwPotential is necessary for an efficient automatic parallelization, which is used by HALCON
to better utilize multiprocessor hardware in order to speed up the processing of operators. As the parallelization
of operators is done automatically, there is no need for the user to explicitely prepare or change programs for
their parallelization. Thus, all HALCON-based programs can be used unchanged on multiprocessor hardware
and nevertheless utilize the potential of parallel hardware. CheckParHwPotential checks a given hardware
with respect to a parallel processing of HALCON operators. At this, it examines every operator, which can be
sped up in principle by an automatic parallelization. Each examined operator is processed several times - both
sequentially and in parallel - with a changing set of input parameter values/images. The latter helps to evaluate
dependencies between an operator’s input parameter characteristics (e.g. the size of an input image) and the
efficiency of its parallel processing. At this, AllInpPars is used in the following way: In the normal case,
i.e. if AllInpPars contains the default value 0 (“false”), only those input parameters are examined which are
supposed to show influence on the processing time. Other parameters are not examined so that the whole process is
sped up. However, in some rare cases, the internal implementation of a HALCON operator might change from one
HALCON release to another. Then, a parameter which did not show any direct influence on the processing time in
former releases, may now show such an influence. In this case it is necessary to set AllInpPars to 1 (“true”) in
order to force the examination of all input parameters. If this happens, the HALCON release notes will most likely
contain an appropriate note about this fact. Overall, CheckParHwPotential performs several test loops and
collects a lot of hardware-specific informations, which enable HALCON to optimize the automatic parallelization
for a given hardware. The hardware information is stored so that it can be used again in future HALCON sessions.
Thus, it is sufficient, to start CheckParHwPotential once on each multiprocessor machine that is used for
parallel processing. Of course, it should be started again, if the hardware of the machine changes, for example,
by installing a new cpu, or if the operating system of the machine changes, or if the machine gets a new host
name. The latter is necessary, because HALCON identifies the machine-specific parallelization information by
the machine’s host name. If the same multiprocessor machine is used with different operating systems, such as
Windows and Linux, it is necessary to start CheckParHwPotential once for each operating system in order to
correctly measure the rather strong influence of the operating system on the potential of exploiting multiprocessor
hardware. Under Windows, HALCON stores the parallelization knowledge, which belongs to a specific machine,
in the machine’s registry. At this, it uses a machine-specific registry key, which can be used by different users
simultaneously. In the normal case, this key can be written or changed by any user under Windows NT. However,
under Windows 2000 the key may only be changed by users with administrator privileges or by users which at least
belong to the “power user” group. For all other users CheckParHwPotential shows no effect (but does not
return an error). Under Linux/UNIX the parallelization information is stored in a file in the HALCON installation
directory ($HALCONROOT). Again this means that CheckParHwPotential must be called by users with

HALCON/COM Reference Manual, 2008-5-13


14.5. PARALLELIZATION 993

the appropriate privileges, here by users which have write access to the HALCON directory. If HALCON is used
within a network under Linux/UNIX, the denoted file contains the information about every computer in the network
for which the hardware check has been successfully completed.
Attention
During its test loops CheckParHwPotential has to start every examined operator several times. Thus,
the processing of CheckParHwPotential can take rather a long time. CheckParHwPotential
bases on the automatic parallelization of operators which is exclusively supported by Parallel HALCON. Thus,
CheckParHwPotential always returns an appropriate error, if it used with a non-parallel HALCON version.
CheckParHwPotential must be called by users with the appropriate privileges for storing the parallelization
information permanently (see the operator’s description above for more details about this subject).
Parameter
. AllInpPars (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Check every input parameter?
Default Value : 0
List of values : AllInpPars ∈ {0, 1}
Result
CheckParHwPotential returns TRUE if all parameters are correct.
Parallelization Information
CheckParHwPotential is local and processed completely exclusively without parallelization.
Possible Successors
StoreParKnowledge
See also
StoreParKnowledge, LoadParKnowledge
Module
Foundation

void HSystemX.LoadParKnowledge ([in] String FileName )


void HOperatorSetX.LoadParKnowledge ([in] VARIANT FileName )

Load knowledge about automatic parallelization from file.


LoadParKnowledge supports the automatic parallelization of HALCON operators, which is used to better uti-
lize multiprocessor hardware in order to speed up the processing of operators. To parallelize the processing of op-
erators automatically HALCON needs some specific knowledge about the used hardware. This hardware-specific
knowledge can be obtained by using the operator CheckParHwPotential. In the normal case, HALCON
stores this knowledge in a specific file in the HALCON installation directory (Linux/UNIX) or within the “reg-
istry” (Windows). This enables HALCON to use the knowledge again later on. With LoadParKnowledge
it is possible to load this knowledge explicitely from an ASCII file. At this, FileName denotes the name of
this file (incl. path and file extension). The file must conform to a specific syntax and must have been stored
beforehand by using StoreParKnowledge. While reading the file LoadParKnowledge checks whether
its content was written for the currently used computer and whether the contained parallelization information re-
gards the currently used HALCON version (and revision). If this is the case, LoadParKnowledge adopts the
information so that it will also be used with further HALCON sessions. Otherwise, the information is ignored and
LoadParKnowledge returns an appropriate error message.
Parameter
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.read ; String / VARIANT
Name of parallelization knowledge file.
Default Value : ”
Result
LoadParKnowledge returns TRUE if all parameters are correct.
Parallelization Information
LoadParKnowledge is local and processed completely exclusively without parallelization.
Possible Predecessors
StoreParKnowledge

HALCON 8.0.2
994 CHAPTER 14. SYSTEM

See also
StoreParKnowledge, CheckParHwPotential
Module
Foundation

void HSystemX.StoreParKnowledge ([in] String FileName )


void HOperatorSetX.StoreParKnowledge ([in] VARIANT FileName )

Store knowledge about automatic parallelization in file.


StoreParKnowledge supports the automatic parallelization of HALCON operators, which is used to better
utilize multiprocessor hardware in order to speed up the processing of operators. To parallelize the processing
of operators automatically HALCON needs some specific knowledge about the used hardware. This hardware-
specific knowledge can be obtained by calling the operator CheckParHwPotential. There, HALCON stores
the knowledge in a specific file in the HALCON installation directory (Linux/UNIX) or within the “registry”
(Windows). This enables HALCON to use the knowledge again later on. With StoreParKnowledge it is
possible to store this knowledge explicitely as an ASCII file. At this, FileName denotes the name of this file
(incl. path and file extension). The stored knowledge can be read again later on by using LoadParKnowledge.
Parameter
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.write ; String / VARIANT
Name of parallelization knowledge file.
Default Value : ”
Result
StoreParKnowledge returns TRUE if all parameters are correct.
Parallelization Information
StoreParKnowledge is local and processed completely exclusively without parallelization.
Possible Predecessors
CheckParHwPotential
Possible Successors
LoadParKnowledge
See also
LoadParKnowledge, CheckParHwPotential
Module
Foundation

14.6 Parameters
HSystemX.GetSystem ([in] VARIANT Query )
[out] VARIANT Information
void HOperatorSetX.GetSystem ([in] VARIANT Query,
[out] VARIANT Information )

Information concerning the currently used HALCON system parameter.


The operator GetSystem returns information concerning the currently activated HALCON system parameters.
Some of these parameters can be changed dynamically by using the operator SetSystem. They are marked by
a + in the list below. By passing the string ’?’ as the parameter Query, the names of all system parameters are
provided with Information.
The following system parameters can be queried:

Versions
’parallel_halcon’: The currently used variant of HALCON: Parallel HALCON (’true’) or Standard HAL-
CON (’false’)
’version’: HALCON version number, e.g.: 6.0

HALCON/COM Reference Manual, 2008-5-13


14.6. PARAMETERS 995

’last_update’: Date of creation of the HALCON library


’revision’: Revision number of the HALCON library, e.g.: 1
Upper Limits
’max_contour_length’: Maximum number of contour respectively polygone control points of a region.
’max_images’: Maximum total of images.
’max_channels’: Maximum number of channels of an image.
’max_obj_per_par’: Maximum number of image objects which may be used during one call up per param-
eter
’max_inp_obj_par’: Maximum number of input parameters.
’max_outp_obj_par’: Maximum number of output parameters.
’max_inp_ctrl_par’: Maximum number of input control parameters.
’max_outp_ctrl_par’: Maximum number of output control parameters.
’max_window’: Maximum number of windows.
’max_window_types’: Maximum number of window systems.
’max_proc’: Maximum number of HALCON procedures (system defined + user defined).
Graphic
+’flush_graphic’: Determines, whether the flush operation is called or not after each visualization operation
in HALCON. Unix operating systems flash the display buffer auto- matically and make this parameter
effectless on respective operating systems, therefore.
+’int2_bits’: Number of significant bits of int2 images. This number is used when scaling the gray values.
If the values is -1 the gray values will be automatically scaled (default).
+’backing_store’: Storage of the window contents in case of overlaps.
+’icon_name’: Name of iconified graphics windows under X-Window. By default the number of the graph-
ics window is displayed.
+’window_name’: (no description available)
+’default_font’: Name of the font to set at opening the window.
+’update_lut’: (no description available)
+’x_package’: Number of bytes which are sent to the X server during each transfer of data.
+’num_gray_4’: Number of colors reserved under X Xindows concerning the output of graylevels (
DispChannel) on a machine with 4 bitplanes (16 colors).
+’num_gray_6’: Number of colors reserved under X Windows concerning the output of graylevels (
DispChannel) on a machine with 6 bitplanes (64 colors).
+’num_gray_8’: Number of colors reserved under X Windows concerning the output of graylevels (
DispChannel) on a machine with 8 bitplanes (256 colors).
+’num_gray_percentage’: HALCON reserves a certain amount of the available colors under X Windows
for the representation of graylevels ( DispImage). This shall interfere with other X applications as
little as possible. However, if HALCON does not succeed in reserving a minimum percentage of
’num_gray_percentage’ of the necessary colors on the X server, a certain amount of the lookup-table
will be claimed for the HALCON graylevels regardless of the consequences for other applications.
This may result in undesired shifts of color when switching between HALCON windows and windows
of other applications, or if (outside HALCON) a window-dump is generated. The number of the real
graylevels to be reserved depends on the number of available bitplanes on the outputmachine (see also
’num_gray_*’. Naturally no colors will be reserved on monochrome machines - the graylevels will
instead be dithered when displayed. If graylevel displays are used, only different shades of gray will
be applied (’black’, ’white’, ’gray’, etc.). ’num_gray_percentage’ is only used on machines with 8 bit
pseudo-color displays. For machines with displays with 16 bits or more (true color machines), no colors
are reserved for the display of gray levels in this case.
Note: Before the first window on a machine with x bitplanes is opened, num_gray_x indicates the
number of colors which have to be reserved for the display of graylevels, afterwards, however, it will
indicate the number of colors which actually have been reserved.
+’num_graphic_percentage’: Similar to ’num_gray_percentage’, ’num_graphic_percentage’ determines
how many graphics colors (for use with set_color) should be reserved in the LUT on an 8 bit pseudo-
color display under X windows.
+’num_graphic_2’: Number of the HALCON graphic colors reserved under X Windows (for
DispRegion etc.) on a machine with 2 bitplanes (4 colors).

HALCON 8.0.2
996 CHAPTER 14. SYSTEM

+’num_graphic_4’: Number of the HALCON graphic colors reserved under X Windows (for
DispRegion etc.) on a machine with 4 bitplanes (16 colors).
+’num_graphic_6’: Number of the HALCON graphic colors reserved under X Windows (for
DispRegion etc.) on a machine with 6 bitplanes (64 colors).
+’num_graphic_8’: Number of the HALCON graphic colors reserved under X Windows (for
DispRegion etc.) on a machine with 8 bitplanes (256 colors).
Image Processing
+’neighborhood’: Using the 4 or 8 neighborhood.
+’init_new_image’: Initialization of images before applying grayvalue transformations.
+’no_object_result’: Behavior for an empty object lists.
+’empty_region_result’: Reaction of procedures concerning input objects with empty regions which
actually are not useful for such objects (e.g. certain region features, segmentation, etc.). Possible return
values:
’true’: the error will be ignored if possible
’false’: the procedure returns FALSE
’fail’: the procedure returns FAIL
’void’: the procedure returns VOID
’exception’: an exception is raised

+’store_empty_region’: Storing of objects with empty regions.


+’clip_region’: Clipping of output regions so that they fit the global image size.
+’int_zooming’: Determines if the zooming of images is done with integer arithmetic or with floating point
arithmetic.
+’pregenerate_shape_models’: This parameter determines whether the shape models created with
CreateShapeModel or CreateScaledShapeModel are pregenerated completely or not, if this
is not explicitly specified in CreateShapeModel or CreateScaledShapeModel.
+’border_shape_models’: This parameter determines whether the shape models to be found
with FindShapeModel, FindShapeModels, FindScaledShapeModel, or
FindScaledShapeModels may lie partially outside the image (i.e., whether they may cross
the image border).
+’image_dpi’: This parameter determines the DPI resolution that is stored in image files written with
WriteImage in formats that support the storing of the DPI resolution.
’width’: Global maximum image width - in Standard-HALCON this value contains the maximum image
width of all HALCON image objects which are currently stored in memory. In Parallel HALCON
this value contains the maximum image width of all HALCON image objects which are or were in
memory since the start of the current HALCON session (this also includes objects which may be deleted
meanwhile).
’height’: Global maximum image height - in Standard-HALCON this value contains the maximum image
height of all HALCON image objects which are currently stored in memory. In Parallel HALCON
this value contains the maximum image height of all HALCON image objects which are or were in
memory since the start of the current HALCON session (this also includes objects which may be deleted
meanwhile).
’obj_images’: Current number of grayvalue components per image object.
+’current_runlength_number’: Currently used number of chords which can be used for the encoding of
regions.
Parallelization
+’parallelize_operators’: Determines whether Parallel HALCON uses an automatic parallelization to speed
up the processing of operators on multiprocessor machines.
+’reentrant’: Denotes whether Parallel HALCON currently supports reentrancy (default case), or whether
this feature has been switched off. Reentrancy is necessary for the automatic parallelization of Parallel
HALCON and for calling and processing multiple HALCON operators in parallel within multithreaded
applications.
’processor_num’: Returns the number of processors which Parallel HALCON has found on the hardware it
is running on. This also indicates the number of processors which is used by Parallel HALCON for the
automatic parallelization of operators.

HALCON/COM Reference Manual, 2008-5-13


14.6. PARAMETERS 997

+’thread_num’: Denotes the number of threads that Parallel HALCON uses for automatic parallelization.
The number contains the main thread and cannot exeed the number of processors for efficiency reasons.
+’thread_pool’: Denotes whether Parallel HALCON always creates new threads for automatic paralleliza-
tion (’false’) or uses an existing pool of threads (’true’). Using a pool is more efficient for automatic
parallelization.
File
+’flush_file’: Buffering of file output.
+’ocr_trainf_version’: This parameter returns the file format used for writing an OCR training file. The
operators WriteOcrTrainf, WriteOcrTrainfImage and ConcatOcrTrainf write training
data in ASCII format for version number 1 or in binary format for version number 2 and 3. Version
number 3 stores images of type byte and uint2. Depending on the file version, the OCR training files can
be read by the following HALCON releases:
File Version HALCON Release
1 All
2 7.0.2 and higher
3 7.1 and higher
+’filename_encoding’: This parameter returns how file and directory names are interpreted that are passed
as string parameters to and from HALCON. With the value ’locale’ these names are used unaltered,
while with the value ’utf8’ these names are interpreted as being UTF-8 encoded. In the latter case,
HALCON tries to translate input parameters from UTF-8 to the locale encoding according to the current
system settings, and output parameters from locale to UTF-8 encoding.
Directories
+’image_dir’: Path which will searched for the image file after the default directory (see also:
ReadImage).
+’lut_dir’: Path for the default directory for color tables (see also: SetLut).
+’help_dir’: Path for the default help directory for the online help files:
{german,english}.{hlp,sta,idx,num,key}.
Other
+’do_low_error’: Flag, if low level error should be printed.
’hostids’: The hostids of the computer that can be used for licensing HALCON.
’num_proc’: Total number of the available HALCON procedures (’num_sys_proc’ + ’num_user_proc’).
’num_sys_proc’: Number of the system procedures (supported procedures).
’num_user_proc’: Number of the user defined procedures (see also ’Extension Packages’ manual).
’byte_order’: Byte order of the processor (’msb_first’ or ’lsb_first’).
’operating_system’: Name of the operating system of the computer on which the HALCONprocess is being
executed.
’operating_system_version’: Version number of the operating system of the computer on which the HAL-
CON process is being executed.
’halcon_arch’: Name of the HALCON architecture of the running HALCON process.
+’clock_mode’ Method used for measuring the time in CountSeconds (’processor_time’,
’elapsed_time’, or ’performance_counter’).
+’max_connection’ Maximum number of regions returned by Connection.
+’extern_alloc_funct’: Pointer to external function for memory allocation of result images.
’extern_free_funct’: Pointer to external function for memory deallocation of result images.
+’image_cache_capacity’: Upper limit in bytes of the image memory cache.
This parameter is only available in Standard HALCON but ignored in Parallel HALCON.
+’global_mem_cache’: Cache mode of global memory, i.e., memory that is visible beyond an operator. It
specifies whether unused global memory should be cached (’shared’) or freed (’idle’). Additionally,
Parallel HALCON offers the option to cache global memory for each thread separately (’exclusive’).
This mde can accelerate processing at the cost of memory consumption. However, Standard HALCON
treats the value ’exclusive’ like the value ’shared’.
+’temporary_mem_cache’: Flag for unused temporary memory of an operator. It specifies whether mem-
ory that is only used within an operator should be cached (’true’, default) or freed (’false’).

HALCON 8.0.2
998 CHAPTER 14. SYSTEM

+’alloctmp_max_blocksize’: Maximum size of memory blocks to be allocated within temporary memory


management. (No effect, if ’alloctmp_max_blocksize’ == -1 or ’temporary_mem_cache’ == ’false’)
’temp_mem’: Amount of temporary memory used by the last operator in byte. The return value is only
defined if SetCheck(’memory’) was called before the operator to be measured. Additionally, in
Parallel HALCON the memory value is not specified when calling operators not sequentially but parallel
in multiple threads.
’mmx_supported’: Flag, if the processor supports MMX operations (’true’) or not (’false’).
+’mmx_enable’: Flag, if MMX operations are used to accelerate selected image processing operators
(’true’) or not (’false’).
+’language’: Language used for error messages (’english’ or ’german’).

Attention

Parameter
. Query (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Desired system parameter.
Default Value : ’width’
List of values : Query ∈ {’?’, ’alloctmp_max_blocksize’, ’backing_store’, ’border_shape_models’,
’byte_order’, ’clip_region’, ’clock_mode’, ’current_runlength_number’, ’default_font’, ’do_low_error’,
’empty_region_result’, ’extern_alloc_funct’, ’extern_free_funct’, ’filename_encoding’, ’flush_file’,
’flush_graphic’, ’global_mem_cache’, ’halcon_arch’, ’height’, ’help_dir’, ’hostids’, ’icon_name’,
’image_cache_capacity’, ’image_dir’, ’image_dpi’, ’init_new_image’, ’int2_bits’, ’int_zooming’, ’language’,
’last_update’, ’lut_dir’, ’max_channels’, ’max_connection’, ’max_images’, ’max_inp_ctrl_par’,
’max_inp_obj_par’, ’max_obj_per_par’, ’max_outp_ctrl_par’, ’max_outp_obj_par’, ’max_proc’,
’max_window’, ’max_window_types’, ’mmx_enable’, ’mmx_supported’, ’neighborhood’, ’no_object_result’,
’num_graphic_2’, ’num_graphic_4’, ’num_graphic_6’, ’num_graphic_8’, ’num_graphic_percentage’,
’num_gray_4’, ’num_gray_6’, ’num_gray_8’, ’num_gray_percentage’, ’num_proc’, ’num_sys_proc’,
’num_user_proc’, ’obj_images’, ’ocr_trainf_version’, ’operating_system’, ’operating_system_version’,
’parallel_halcon’, ’parallelize_operators’, ’pregenerate_shape_models’, ’processor_num’, ’reentrant’,
’revision’, ’store_empty_region’, ’temp_mem’, ’temporary_mem_cache’, ’thread_num’, ’thread_pool’,
’update_lut’, ’version’, ’width’, ’window_name’, ’x_package’}
. Information (output control) . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer, real, string )
Current value of the system parameter.
Result
The operator GetSystem returns the value TRUE if the parameters are correct. Otherwise an exception is raised.
Parallelization Information
GetSystem is local and processed completely exclusively without parallelization.
Possible Predecessors
ResetObjDb
Possible Successors
SetSystem
See also
SetSystem
Module
Foundation

void HSystemX.SetSystem ([in] VARIANT SystemParameter,


[in] VARIANT Value )
void HOperatorSetX.SetSystem ([in] VARIANT SystemParameter,
[in] VARIANT Value )

Setting of HALCON system parameters.


The operator SetSystem allows to change different system parameters with relation to the runlength.
Available system parameters:

HALCON/COM Reference Manual, 2008-5-13


14.6. PARAMETERS 999

’neighborhood’: This parameter is used with all procedures which examine neighborhood rela-
tions: Connection, GetRegionContour, GetRegionChain, GetRegionPolygon,
GetRegionThickness, Boundary, PaintRegion, DispRegion, FillUp, Contlength,
ShapeHistoAll.
Value: 4 or 8
default: 8
’default_font’: Whenever a window is opened, a font will be set for the text output, whereby the ’default_font’
will be used. If the preset font cannot be found, another fontname can be set before opening the window.
Value: Filename of the fonts
default: fixed
’update_lut’ Determines whether the HALCON color tables are adapted according to their environment or not.
Value: ’true’ or ’false’
default: ’false’
’image_dir’: Image files (e.g. ReadImage and ReadSequence) will be looked for in the currently used
directory and in ’image_dir’ (if no absolute paths are indicated). More than one directory name can be indi-
cated (searchpaths), seperated by semicolons (Windows) or colons (Unix). The path can also be determined
using the environment variable HALCONIMAGES.
Value: Name of the filepath
default: ’$HALCONROOT/images’ bzw. ’%HALCONROOT%/images’
’lut_dir’: Color tables ( SetLut) which are realized as an ASCII-file will be looked for in the currently used
directory and in ’lut_dir’ (if no absolute paths are indicated). If HALCONROOT is set, HALCON will
search the color tables in the sub-directory "‘lut"’.
Value: Name of the filepath
default: ’$HALCONROOT/lut’ bzw. ’%HALCONROOT%/lut’
’help_dir’: The online text files german or english.hlp, .sta, .key .num and .idx will be looked for in the cur-
rently used directory or in ’help_dir’. This system parameter is necessary for instance using the operators
GetOperatorInfo and GetParamInfo. This parameter can also be set by the environment variable
HALCONROOT before initializing HALCON. In this case the variable must indicate the directory above the
helpdirectories (that is the HALCON-Homedirectory): e.g.: ’/usr/local/halcon’
Value: Name of the filepath
default: ’$HALCONROOT/help’ bzw. ’%HALCONROOT%/help’
’init_new_image’: Determines whether new images shall be set to 0 before using filters. This is not necessary if
always the whole image is filtered of if the data of not filtered image areas are unimportant.
Value: ’true’ or ’false’
default: ’true’
’no_object_result’: Determines how operations processing iconic objects shall react if the object tuplet is empty
(= no objects). Available values for Value:
’true’: the error will be ignored
’false’: the procedure returns FALSE
’fail’: the procedure returns FAIL
’void’: the procedure returns VOID
’exception’: an exception is raised
default: ’true’
’empty_region_result’: Controls the reaction of procedures concerning input objects with empty regions which
actually are not useful for such objects (e.g. certain region features, segmentation, etc.). Available values for
Value:
’true’: the error will be ignored if possible
’false’: the procedure returns FALSE
’fail’: the procedure returns FAIL
’void’: the procedure returns VOID
’exception’: an exception is raised
default: ’true’
’store_empty_region’: Quite a number of operations will lead to the creation of objects with an empty region (=
no image points) (e.g. Intersection, Threshold, etc.). This parameter determines whether the object
with an empty region will be returned as a result (’true’) or whether it will be ignored (’false’) that is no result
will be returned.

HALCON 8.0.2
1000 CHAPTER 14. SYSTEM

Value: ’true’ or ’false’


default: ’true’
’pregenerate_shape_models’: This parameter determines whether the shape models created with
CreateShapeModel or CreateScaledShapeModel are pregenerated completely or not, if
this is not explicitly specified in CreateShapeModel or CreateScaledShapeModel. This
parameter mainly serves to achieve a switch between the two modes with minimal code changes. Normally,
only one line needs to be inserted or changed.
Value: ’true’ or ’false’
default: ’false’
’border_shape_models’: This parameter determines whether the shape models to be found
with FindShapeModel, FindShapeModels, FindScaledShapeModel, or
FindScaledShapeModels may lie partially outside the image (i.e., whether they may cross the
image border).
Value: ’true’ or ’false’
default: ’false’
’image_dpi’: This parameter determines the DPI resolution that is stored in image files written with
WriteImage in formats that support the storing of the DPI resolution.
default: 300
’backing_store’: Determines whether the window content will be refreshed in case of overlapping of the win-
dows. Some implementations of X Windows are faulty; in order to avoid these errors, the storing of contents
can be deactivated. It may be recommendable in some cases to deactivate the security mechanism, if e.g.
performance / memory is what matters.
Value: true or false
default: true
’flush_graphic’: After each HALCON operation which creates a graphic output, a flush operation will be ex-
ecuted in order to display the data immediately on screen. This is not necessary with all programs (e.g. if
everything is done with the help of the mouse). In this case ’flush_graphic’ can be set to ’false’ to improve the
runlength. Unix window manager flash the display buffer automatically and make this parameter effectless
on respective operating systems, therefore.
Value: ’true’ or ’false’
default: ’true’
’flush_file’: This parameter determines whether the output into a file (also to the terminal) shall be buffered or
not. If the output is to be buffered, in general the data will be displayed on the terminal only after entering
the operator FnewLine.
Value: ’true’ or ’false’
default: ’true’
’ocr_trainf_version’ This parameter determines the format that is used for writing an OCR training file. The
operators WriteOcrTrainf, WriteOcrTrainfImage and ConcatOcrTrainf write training data
in ASCII format for version number 1 or in binary format for version number 2 and 3. Version number 3
stores images of type byte and uint2. The binary version is faster in reading and writing data and stores
training files more packed. The ASCII format is compabtible to older HALCON releases. Depending on the
file version, the OCR training files can be read by the following HALCON releases:
File Version HALCON Release
1 All
2 7.0.2 and higher
3 7.1 and higher
Value: 1, 2, 3
default: 3
’filename_encoding’: This parameter determines how file and directory names are interpreted that are passed as
string parameters to and from HALCON. With the value ’locale’ these names are used unaltered, while with
the value ’utf8’ these names are interpreted as being UTF-8 encoded. In the latter case, HALCON tries to
translate input parameters from UTF-8 to the locale encoding according to the current system settings, and
output parameters from locale to UTF-8 encoding.
Value: ’locale’ or ’utf8’
default: ’locale’

HALCON/COM Reference Manual, 2008-5-13


14.6. PARAMETERS 1001

’x_package’: The output of image data via the network may cause errors owing to the heavy load on the computer
or on the network. In order to avoid this, the data are transmitted in small packages. If the computer is used
locally, these units can be enlarged at will. This can lead to a notably improved output performance.
Value: package size (in bytes)
default: 20480
’int2_bits’: Number of significant bits of int2 images. This number is used when scaling the gray values. If the
values is -1 the gray values will be automatically scaled (default).
Value: -1 or 9..16
default: -1
’num_gray_4’: Number of colors to be reserved under X Windows to allow the output of graylevels disp_channel
on a machine with 4 bitplanes (16 colors).
Attention! This value may only be changed before the first window has been opened on the machine.
Value: 2 - 12
default: 8
’num_gray_6’: Number of colors to be reserved under X Windows to allow the output of graylevels disp_channel
on a machine with 6 bitplanes (64 colors).
Attention! This value may only be changed before the first window has been opened on the machine.
Value: 2 - 62
default: 50
’num_gray_8’: Number of colors to be reserved under X Windows to allow the output of graylevels disp_channel
on a machine with 8 bitplanes (256 colors).
Attention! This value may only be changed before the first window has been opened on the machine.
Value: 2 - 254
default: 140
’num_gray_percentage’: Under X Windows HALCON reserves a part of the available colors for the represen-
tation of gray values ( DispChannel). This shall interfere with other X applications as little as possible.
However, if HALCON does not succeed in reserving a minimum percentage of ’num_gray_percentage’ of
the necessary colors on the X server, a certain amount of the lookup table will be claimed for the HALCON
graylevels regardless of the consequences. This may result in undesired shifts of color when switching be-
tween HALCON windows and windows of other applications, or (outside HALCON) if a window-dump is
generated. The number of the real graylevels to be reserved depends on the number of available bitplanes on
the outputmachine (see also ’num_gray_*’. Naturally no colors will be reserved on monochrome machines -
the graylevels will instead be dithered when displayed. If graylevel-displays are used, only different shades
of gray will be applied (’black’, ’white’, ’gray’, etc.). ’num_gray_percentage’ is only used on machines with
8 bit pseudo-color displays. For machines with displays with 16 bits or more (true color machines), no colors
are reserved for the display of gray levels in this case.
Note: This value may only be changed before the first window has been opened on the machine. For before
opening the first window on a machine with x bitplanes, num_gray_x indicates the number of colors which
have to be reserved for the display of graylevels, afterwards, however, it will indicate the number of colors
which actually have been reserved.
Value: 0 - 100
default: 30
’num_graphic_percentage’: Similar to ’num_gray_percentage’, ’num_graphic_percentage’ determines how
many graphics colors (for use with set_color) should be reserved in the LUT on an 8 bit pseudo-color display
under X windows.
default: 60
’int_zooming’: Determines if the zooming of images is done with integer arithmetic or with floating point arith-
metic. default: ’true’
’icon_name’: Name of iconified graphics windows under X-Window. By default the number of the graphics
window is displayed. default: ’default’
’num_graphic_2’: Number of the graphic colors to be reserved by HALCON under X Windows (concerning the
operators DispRegion etc.) on a machine with 2 bitplanes (4 colors).
Attention: This value may only be changed before the first window has been opened on the machine.
Value: 0 - 2
default: 2
’num_graphic_4’: Number of the graphic colors to be reserved by HALCON under X Windows (concerning the
operators DispRegion etc.) on a machine with 4 bitplanes (16 colors).

HALCON 8.0.2
1002 CHAPTER 14. SYSTEM

Attention: This value may only be changed before the first window has been opened on the machine.
Value: 0 - 14
default: 5
’num_graphic_6’: Number of the graphic colors to be reserved by HALCON under X Windows (concerning the
operators DispRegion etc.) on a machine with 6 bitplanes (64 colors).
Attention: This value may only be changed before the first window has been opened on the machine.
Value: 0 - 62
default: 10
’num_graphic_8’: Number of the graphic colors to be reserved by HALCON under X Windows (concerning the
operators DispRegion etc.) on a machine with 8 bitplanes (256 colors).
Attention: This value may only be changed before the first window has been opened on the machine.
Value: 0 - 64
default: 20
’graphic_colors’ HALCON reserves the first num_graphic_x colors form this list of color names as graphic col-
ors. As a default HALCON uses this same list which is also returned by using QueryAllColors. How-
ever, the list can be changed individually: hereby a tuplet of color names will be returned as value. It is
recommendable that such a tuplet always includes the colors ’black’ and ’white’, and optionally also ’red’,
’green’ and ’blue’. If ’default’ is set as Value, HALCON returns to the initial setting. Note: On graylevel
machines not the first x colors will be reserved, but the first x shades of gray from the list.
Attention: This value may only be changed before the first window has been opened on the machine.
Value: Tuplets of X Windows color names
default: see also query_all_colors
’current_runlength_number’: Regions will be stored internally in a certain runlengthcode. This parameter can
determine the maximum number of chords which may be used for representing a region. Please note that
some procedures raise the number on their own if necessary.
The value can be enlarged as well as reduced.
Value: maximum number of chords
default: 50000
’clip_region’: Determines whether the regions of iconic objects of the HALCON database will be clipped to
the currently used image size or not. This is the case for example in procedures like GenCircle,
GenRectangle1 or Dilation1.
See also: ResetObjDb
Value: ’true’ or ’false’
default: ’true’
’do_low_error’ Determines whether the HALCON should print low level error or not.
Value: ’true’ or ’false’
default: ’false’
’reentrant’ Determines whether HALCON must be reentrant for being used within a parallel programming en-
vironment (e.g. a multithreaded application). This parameter is only of importance for Parallel HALCON,
which can process several operators concurrently. Thus, the parameter is ignored by the sequentially working
HALCON-Version. If it is set to ’true’, Parallel HALCON internally uses synchronization mechanisms to
protect shared data objects from concurrent accesses. Though this is inevitable with any effectively paral-
lel working application, it may cause undesired overhead, if used within an application which works purely
sequentially. The latter case can be signalled by setting ’reentrant’ to ’false’. This switches off all internal
synchronization mechanisms and thus reduces overhead. Of course, Parallel HALCON then is no longer
thread-safe, which causes another side-effect: Parallel HALCON will then no longer use the internal paral-
lelization of operators, because this needs reentrancy. Setting ’reentrant’ to ’true’ resets Parallel HALCON
to its default state, i.e. it is reentrant (and thread-safe) and it uses the automatic parallelization to speed up
the processing of operators on multiprocessor machines.
Value: ’true’ or ’false’
default: Parallel HALCON: ’true’, otherwise: ’false’
’parallelize_operators’ Determines whether Parallel HALCON uses an automatic parallelization to speed up the
processing of operators on multiprocessor machines. This feature can be switched off by setting ’paral-
lelize_operators’ to ’false’. Even then, Parallel HALCON will remain reentrant (and thread-safe), unless
the parameter ’reentrant’ is changed via SetSystem accordingly. Changing ’parallelize_operators’ can
be helpful, for example, if HALCON operators are called by a multithreaded application that also does the
scheduling and load-balancing of operators and data by itself. Then, it may be undesired that HALCON

HALCON/COM Reference Manual, 2008-5-13


14.6. PARAMETERS 1003

performs additional parallelization steps, which may disturb the application’s scheduling and load-balancing
concepts. For a more detailed control of automatic parallelization single methods of data parallelization
can be switched. ’split_tuple’ enables the tuple parallelization method, ’split_channel’ the parallelization on
image channels, and ’split_domain’ the parallelization on the image domain. A preceding ’˜’ disables the
respective method. The method strings can also be passed within a control tuple to switch on or off methods
of automatic data parallelization at once. E.g., [’split_tuple’,’split_channel’,’split_domain’] is equivalent to
’true’.
The parameter ’parallelize_operators’ is only supported by Parallel HALCON and thus ignored by the se-
quentially working HALCON-Version.
Value:’true’, ’false’, ’split_tuple’, ’split_channel’, ’split_domain’, ’s̃plit_tuple’, ’s̃plit_channel’,
’s̃plit_domain’ default: Parallel HALCON: ’true’, else: ’false’
’thread_num’ Sets the number of threads used by the automatic parallelization of Parallel HALCON. The number
includes the main thread and is restricted to the number of processors for efficiency reasons. Decreasing the
number of threads is helpful if processors are occupied by user worker threads besides the threads of the
automatic parallelization. With this, the number of processing threads can be adapted to the number of
processors for best efficiency. Standard HALCON ignores this parameter value. Value: 1 <= Value <=
processor_num default: Parallel HALCON: processor_num, else: 1
’thread_pool’ Denotes whether Parallel HALCON always creates new threads for automatic parallelization
(’false’) or uses an existing pool of threads (’true’). Using a pool is more efficient for automatic paral-
lelization. When switching off atomatic parallelization permanently, deactivating the pool can save resources
of the operating system. Standard HALCON ignores this parameter value. Value: ’true’, ’false’ default:
Parallel HALCON: ’true’, else: ’false’
’clock_mode’ Determines the mode of the measurement of time intervals with CountSeconds. For
Value=’processor_time’, the time the running HALCON process occupies the cpu is measured. This kind
of measuring time is independend from the cpu load caused by other processes, but it features a lower reso-
lution on most systems and is more inaccurate for smaller time intervals, therefore.
For Value=’elapsed_time’, the actual elapsed system time is measured. It includes the waiting time of the
current process as well as the cpu time of other processes. Therefore, to get a reliable measurement make
sure that no other process causes any cpu load.
Value=’performance_counter’ measures the actual system time by using a performance counter,
which results in a higher resolution. If the system does not support any performance counter,
Value=’processor_time’ is used.
Value: ’processor_time’, ’elapsed_time’, ’performance_counter’
default: ’performance_counter’
’max_connection’ Determines the maximum number of regions returned by Connection. For Value=0, all
regions are returned.
’extern_alloc_funct’ Pointer to external function for memory allocation of result images. default: 0
’extern_free_funct’ Pointer to external function for memory deallocation of result images. default: 0
’image_cache_capacity’ Upper limit in bytes of the internal image memory cache. To speed up allocation of
new images HALCON does not free image memory but caches it to reuse it. Caching of freed images
is done as long as the upper limit is not reached. This functionality can be switched off by setting ’im-
age_cache_capacity’ to 0.
This parameter is only available in Standard HALCON and ignored in Parallel HALCON.
default: Standard HALCON: 4194304 (4MByte), else: 0
’global_mem_cache’ Cache mode of global memory,i.e., memory that is visible beyond an operator. It specifies
whether unused global memory should be cached (’shared’) or freed (’idle’). Generally, caching speeds up
memory allocation and processing at the cost of memory consumption. Additionally, Parallel HALCON of-
fers the option to cache global memory for each thread separately (’exclusive’). This mode can also accelerate
processing at the cost of higher memory consumption. Standard HALCON treats the value ’exclusive’ like
the value ’shared’.
Value: ’idle’,’exclusive’,’shared’
default: ’false’
’temporary_mem_cache’ Flag if unused temporary memory of an operator should be cached (’true’, default) or
freed (’false’). A single-threaded application can be speeded up by caching global memory, whereas freeing
reduces the memory consumption of a multithreaded application at the expense of speed.
Value: ’true’ or ’false’
default: ’true’

HALCON 8.0.2
1004 CHAPTER 14. SYSTEM

’alloctmp_max_blocksize’ Maximum size of memory blocks to be allocated within temporary memory manage-
ment. (No effect, if ’temporary_mem_cache’ == ’false’ ) Value: -1 or >= 0
default: -1
’mmx_enable’ Flag, if MMX operations were used to accelerate selected image processing operators (’true’) or
not (’false’). (No effect, if ’mmx_supported’ == ’false’, see also operator get_system) default: ’true’ if cpu
supports MMX, else ’false’
’language’ Language used for error messages. Value: ’english’ or ’german’. default: ’ english’

Attention

Parameter

. SystemParameter (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )


Name of the system parameter to be changed.
Default Value : ’image_dir’
List of values : SystemParameter ∈ {’alloctmp_max_blocksize’, ’backing_store’,
’border_shape_models’, ’clip_region’, ’clock_mode’, ’current_runlength_number’, ’default_font’,
’do_low_error’, ’empty_region_result’, ’extern_alloc_funct’, ’extern_free_funct’, ’filename_encoding’,
’flush_file’, ’flush_graphic’, ’global_mem_cache’, ’graphic_colors’, ’help_dir’, ’icon_name’,
’image_cache_capacity’, ’image_dir’, ’image_dpi’, ’init_new_image’, ’int2_bits’, ’int_zooming’, ’language’,
’lut_dir’, ’max_connection’, ’mmx_enable’, ’neighborhood’, ’no_object_result’, ’num_graphic_2’,
’num_graphic_4’, ’num_graphic_6’, ’num_graphic_8’, ’num_graphic_percentage’, ’num_gray_4’,
’num_gray_6’, ’num_gray_8’, ’num_gray_percentage’, ’ocr_trainf_version’, ’parallelize_operators’,
’pregenerate_shape_models’, ’reentrant’, ’store_empty_region’, ’temporary_mem_cache’, ’thread_num’,
’thread_pool’, ’update_lut’, ’x_package’}
. Value (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( integer, real, string )
New value of the system parameter.
Default Value : ’true’
Suggested values : Value ∈ {’true’, ’false’, 0, 4, 8, 100, 140, 255}
Result
The operator SetSystem returns the value TRUE if the parameters are correct. Otherwise an exception will be
raised.
Parallelization Information
SetSystem is local and processed completely exclusively without parallelization.
Possible Predecessors
ResetObjDb, GetSystem, SetCheck
See also
GetSystem, SetCheck, CountSeconds
Module
Foundation

14.7 Serial
void HSerialX.ClearSerial ([in] String Channel )
void HOperatorSetX.ClearSerial ([in] VARIANT SerialHandle,
[in] VARIANT Channel )

Clear the buffer of a serial connection.


ClearSerial discards data written to the serial device referred to by SerialHandle, but not transmitted
(Channel = ’output’), or data received, but not read (Channel = ’input’), or performs both these operations at
once (Channel = ’in_out’).

HALCON/COM Reference Manual, 2008-5-13


14.7. SERIAL 1005

Parameter
. SerialHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . serial_id ; HSerialX / VARIANT
Serial interface handle.
. Channel (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Buffer to be cleared.
Default Value : ’input’
List of values : Channel ∈ {’input’, ’output’, ’in_out’}
Result
If the parameters are correct and the buffers of the serial device could be cleared, the operator ClearSerial
returns the value TRUE. Otherwise an exception is raised.
Parallelization Information
ClearSerial is reentrant and processed without parallelization.
Possible Predecessors
OpenSerial
Possible Successors
ReadSerial, WriteSerial
See also
ReadSerial
Module
Foundation

void HMiscX.CloseAllSerials ( )
void HOperatorSetX.CloseAllSerials ( )
Close all serial devices.
CloseAllSerials closes all serial devices that have been opened with OpenSerial.
Result
CloseAllSerials returns always TRUE.
Parallelization Information
CloseAllSerials is reentrant and processed without parallelization.
Possible Predecessors
OpenSerial
See also
OpenSerial, CloseFile
Alternatives
CloseSerial
Module
Foundation

void HOperatorSetX.CloseSerial ([in] VARIANT SerialHandle )

Close a serial device.


CloseSerial closes a serial device that was opened with OpenSerial.
Parameter
. SerialHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . serial_id ; HSerialX / VARIANT
Serial interface handle.
Result
If the parameters are correct and the device could be closed, the operator CloseSerial returns the value TRUE.
Otherwise an exception is raised.

HALCON 8.0.2
1006 CHAPTER 14. SYSTEM

Parallelization Information
CloseSerial is reentrant and processed without parallelization.
Possible Predecessors
OpenSerial
See also
OpenSerial, CloseFile
Module
Foundation

[out] long BaudRate HSerialX.GetSerialParam ([out] long DataBits,


[out] String FlowControl, [out] String Parity, [out] long StopBits,
[out] long TotalTimeOut, [out] long InterCharTimeOut )
void HOperatorSetX.GetSerialParam ([in] VARIANT SerialHandle,
[out] VARIANT BaudRate, [out] VARIANT DataBits, [out] VARIANT FlowControl,
[out] VARIANT Parity, [out] VARIANT StopBits, [out] VARIANT TotalTimeOut,
[out] VARIANT InterCharTimeOut )

Get the parameters of a serial device.


GetSerialParam returns the current parameter settings of the serial device passed in SerialHandle. For a
description of the parameters of a serial device, see SetSerialParam.
Parameter

. SerialHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . serial_id ; HSerialX / VARIANT


Serial interface handle.
. BaudRate (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Speed of the serial interface.
. DataBits (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of data bits of the serial interface.
. FlowControl (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Type of flow control of the serial interface.
. Parity (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Parity of the serial interface.
. StopBits (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of stop bits of the serial interface.
. TotalTimeOut (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Total timeout of the serial interface in ms.
. InterCharTimeOut (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Inter-character timeout of the serial interface in ms.
Result
If the parameters are correct and the parameters of the device could be read, the operator GetSerialParam
returns the value TRUE. Otherwise an exception is raised.
Parallelization Information
GetSerialParam is reentrant and processed without parallelization.
Possible Predecessors
OpenSerial
Possible Successors
GetSerialParam, ReadSerial, WriteSerial
See also
SetSerialParam
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


14.7. SERIAL 1007

void HSerialX.OpenSerial ([in] String PortName )


void HOperatorSetX.OpenSerial ([in] VARIANT PortName,
[out] VARIANT SerialHandle )

Open a serial device.


OpenSerial opens a serial device. The name of the device is determined by the parameter PortName and is
operating system specific. On Windows machines, ’COM1’-’COM4’ is typically used, while on Unix systems the
serial devices usually are named ’/dev/tty*’. The parameters of the serial device, e.g., its speed or number of data
bits, are set to the system default values for the respective device after the device has been opened. They can be set
or changed by calling SetSerialParam.
Parameter

. PortName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename ; String / VARIANT


Name of the serial port.
Default Value : ’COM1’
Suggested values : PortName ∈ {’COM1’, ’COM2’, ’COM3’, ’COM4’, ’/dev/ttya’, ’/dev/ttyb’,
’/dev/tty00’, ’/dev/tty01’, ’/dev/ttyd1’, ’/dev/ttyd2’, ’/dev/cua0’, ’/dev/cua1’}
. SerialHandle (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . serial_id ; HSerialX / VARIANT
Serial interface handle.
Result
If the parameters are correct and the device could be opened, the operator OpenSerial returns the value TRUE.
Otherwise an exception is raised.
Parallelization Information
OpenSerial is reentrant and processed without parallelization.
Possible Successors
SetSerialParam, ReadSerial, WriteSerial, CloseSerial
See also
SetSerialParam, GetSerialParam, OpenFile
Module
Foundation

HSerialX.ReadSerial ([in] long NumCharacters )


[out] VARIANT Data
void HOperatorSetX.ReadSerial ([in] VARIANT SerialHandle,
[in] VARIANT NumCharacters, [out] VARIANT Data )

Read from a serial device.


ReadSerial tries to read NumCharacters from the serial device given in SerialHandle. The read char-
acters are returned in Data as a tuple of integers. This allows to read NUL characters, which would otherwise
be interpreted as the end of a string. If the timeout of the serial device has been set to a value greater than 0 with
SetSerialParam, ReadSerial waits at most as long for the arrival of the first character as indicated by the
timeout. Otherwise, the operator returns immediately. In any case, the number of characters available at the time
of return are passed back to the caller, i.e., fewer characters than requested can be returned. This can be checked
by the length of the tuple Data.
Parameter

. SerialHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . serial_id ; HSerialX / VARIANT


Serial interface handle.
. NumCharacters (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of characters to read.
Default Value : 1
Suggested values : NumCharacters ∈ {1, 2, 3, 4, 5, 10, 20, 40, 100}
. Data (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Read characters (as tuple of integers).

HALCON 8.0.2
1008 CHAPTER 14. SYSTEM

Result
If the parameters are correct and the read from the device was successful, the operator ReadSerial returns the
value TRUE. Otherwise an exception is raised.
Parallelization Information
ReadSerial is reentrant and processed without parallelization.
Possible Predecessors
OpenSerial
See also
WriteSerial
Module
Foundation

void HSerialX.SetSerialParam ([in] VARIANT BaudRate,


[in] VARIANT DataBits, [in] String FlowControl, [in] String Parity,
[in] VARIANT StopBits, [in] VARIANT TotalTimeOut,
[in] VARIANT InterCharTimeOut )
void HOperatorSetX.SetSerialParam ([in] VARIANT SerialHandle,
[in] VARIANT BaudRate, [in] VARIANT DataBits, [in] VARIANT FlowControl,
[in] VARIANT Parity, [in] VARIANT StopBits, [in] VARIANT TotalTimeOut,
[in] VARIANT InterCharTimeOut )

Set the parameters of a serial device.


SetSerialParam can be used to set the parameters of a serial device. The parameter BaudRate determines
the input and output speed of the device. It should be noted that not all devices support all possible speeds. The
number of sent and received data bits is set with DataBits. The parameter FlowControl determines if and
what kind of data flow control should be used. In the latter case, a choice between software control (’xon_xoff’) and
hardware control (’cts_rts’, ’dtr_dsr’) can be made. If and what kind of parity check of the transmitted data should
be performed can be determined by Parity. The number of stop bits sent is set with StopBits. Finally, two
timeout for reading from the serial device can be set. The parameter TotalTimeOut determines the maximum
time, which may pass in ReadSerial until the first character arrives, independent of the actual number of
characters requested. The parameter InterCharTimeOut determines the time which may pass between the
reading of individual characters, if multiple characters are requested with ReadSerial. If one of the timeouts
is set to -1, a read waits an arbitrary amount of time for the arrival of characters. If both timeouts are set to 0 the
a read doesn’t wait and returns the available or none characters. Thus, on Windows systems, a total timeout of
TotalTimeOut + nInterCharTimeOut results if n characters are to be read. On Unix systems, only one of
the two timeouts can be set. Thus, if both timeouts are passed larger than -1, only the total timeout is used. The
unit of both timeouts is milliseconds. It should be noted, however, that the timeout is specified in increments of one
tenths of a second on Unix systems, i.e., the the minimum timeout that has any effect is 100. For each parameter,
the current values can be left in effect by passing ’unchanged’.
Parameter
. SerialHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . serial_id ; HSerialX / VARIANT
Serial interface handle.
. BaudRate (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer, string )
Speed of the serial interface.
Default Value : ’unchanged’
List of values : BaudRate ∈ {50, 75, 110, 134, 150, 200, 300, 600, 1200, 1800, 2400, 4800, 9600, 19200,
38400, 57600, 76800, 115200, 153600, 230400, 307200, 460800, ’unchanged’}
. DataBits (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer, string )
Number of data bits of the serial interface.
Default Value : ’unchanged’
List of values : DataBits ∈ {5, 6, 7, 8, ’unchanged’}
. FlowControl (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Type of flow control of the serial interface.
Default Value : ’unchanged’
List of values : FlowControl ∈ {’none’, ’xon_xoff’, ’cts_rts’, ’dtr_dsr’, ’unchanged’}

HALCON/COM Reference Manual, 2008-5-13


14.7. SERIAL 1009

. Parity (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT


Parity of the serial interface.
Default Value : ’unchanged’
List of values : Parity ∈ {’none’, ’odd’, ’even’, ’unchanged’}
. StopBits (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer, string )
Number of stop bits of the serial interface.
Default Value : ’unchanged’
List of values : StopBits ∈ {1, 2, ’unchanged’}
. TotalTimeOut (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer, string )
Total timeout of the serial interface in ms.
Default Value : ’unchanged’
Suggested values : TotalTimeOut ∈ {-1, 0, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000,
’unchanged’}
. InterCharTimeOut (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer, string )
Inter-character timeout of the serial interface in ms.
Default Value : ’unchanged’
Suggested values : InterCharTimeOut ∈ {-1, 0, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000,
’unchanged’}
Result
If the parameters are correct and the parameters of the device could be set, the operator SetSerialParam
returns the value TRUE. Otherwise an exception is raised.
Parallelization Information
SetSerialParam is reentrant and processed without parallelization.
Possible Predecessors
OpenSerial, GetSerialParam
Possible Successors
ReadSerial, WriteSerial
See also
GetSerialParam
Module
Foundation

void HSerialX.WriteSerial ([in] VARIANT Data )


void HOperatorSetX.WriteSerial ([in] VARIANT SerialHandle,
[in] VARIANT Data )

Write to a serial connection.


WriteSerial writes the characters given in Data to the serial device given by SerialHandle. The data
to be written is passed as a tuple of integers. This allows to write NUL characters, which would otherwise be
interpreted as the end of a string. WriteSerial always waits until all data has been transmitted, i.e., a timout
for writing cannot be set.
Parameter
. SerialHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . serial_id ; HSerialX / VARIANT
Serial interface handle.
. Data (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Characters to write (as tuple of integers).
Result
If the parameters are correct and the write to the device was successful, the operator WriteSerial returns the
value TRUE. Otherwise an exception is raised.
Parallelization Information
WriteSerial is reentrant and processed without parallelization.
Possible Predecessors
OpenSerial

HALCON 8.0.2
1010 CHAPTER 14. SYSTEM

See also
ReadSerial
Module
Foundation

14.8 Sockets
void HOperatorSetX.CloseSocket ([in] VARIANT Socket )

Close a socket.
CloseSocket closes a socket that was previously opened with OpenSocketAccept,
OpenSocketConnect, or SocketAcceptConnect. For a detailed example, see OpenSocketAccept.
Parameter

. Socket (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . socket_id ; HSocketX / VARIANT


Socket number.
Parallelization Information
CloseSocket is reentrant and processed without parallelization.
See also
OpenSocketAccept, OpenSocketConnect, SocketAcceptConnect
Module
Foundation

HSocketX.GetNextSocketDataType ( )
[out] String DataType
void HOperatorSetX.GetNextSocketDataType ([in] VARIANT Socket,
[out] VARIANT DataType )

Determine the HALCON data type of the next socket data.


GetNextSocketDataType returns the data type of the next data that are present on the socket Socket and
returns it in DataType. The possible values for DataType are:

’no_data’: No data are present.


’no_halcon_data’: Some data are present, but they are not HALCON data.
’tuple’: The next data is a tuple.
’region’: The next data is a region object.
’image’: The next data is an image object.
’xld_cont’: The next data is an XLD contour.
’xld_poly’: The next data is an XLD polygon.
’xld_para’: The next data is an XLD parallel.
’xld_mod_para’: The next data is a modified XLD parallel.
’xld_ext_para’: The next data is an extended XLD parallel.

Parameter

. Socket (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . socket_id ; HSocketX / VARIANT


Socket number.
. DataType (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Data type of next HALCON data.

HALCON/COM Reference Manual, 2008-5-13


14.8. SOCKETS 1011

Parallelization Information
GetNextSocketDataType is reentrant and processed without parallelization.
See also
SendImage, ReceiveImage, SendRegion, ReceiveRegion, SendTuple, ReceiveTuple
Module
Foundation

HSocketX.GetSocketDescriptor ( )
[out] long SocketDescriptor
void HOperatorSetX.GetSocketDescriptor ([in] VARIANT Socket,
[out] VARIANT SocketDescriptor )

Get the socket descriptor of a socket used by the operating system.


GetSocketDescriptor returns the socket descriptor used by the operating system for the socket connection
that is passed in Socket. The socket descriptor can be used in operating system calls such as select, read,
write, recv, or send.
Parameter
. Socket (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . socket_id ; HSocketX / VARIANT
Socket number.
. SocketDescriptor (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Socket descriptor used by the operating system.
Parallelization Information
GetSocketDescriptor is reentrant and processed without parallelization.
Possible Predecessors
OpenSocketAccept, OpenSocketConnect, SocketAcceptConnect
See also
SetSocketTimeout
Module
Foundation

HSocketX.GetSocketTimeout ( )
[out] VARIANT Timeout
void HOperatorSetX.GetSocketTimeout ([in] VARIANT Socket,
[out] VARIANT Timeout )

Get the timout of a socket.


GetSocketTimeout returns the timout for the socket connection that is passed in Socket. For a description
of possible values of Timeout see SetSocketTimeout.
Parameter
. Socket (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . socket_id ; HSocketX / VARIANT
Socket number.
. Timeout (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, string )
Socket timeout.
Parallelization Information
GetSocketTimeout is reentrant and processed without parallelization.
Possible Predecessors
OpenSocketAccept, OpenSocketConnect, SocketAcceptConnect
See also
SetSocketTimeout
Module
Foundation

HALCON 8.0.2
1012 CHAPTER 14. SYSTEM

void HSocketX.OpenSocketAccept ([in] long Port )


void HOperatorSetX.OpenSocketAccept ([in] VARIANT Port,
[out] VARIANT AcceptingSocket )

Open a socket that accepts connection requests.


OpenSocketAccept opens a socket that accepts incoming connection requests by other HALCON processes.
This operator is the necessary first step in the establishment of a communication channel between two HALCON
processes. The socket listens for incoming connection requests on the port number given by Port. The accept-
ing socket is returned in AcceptingSocket. OpenSocketAccept returns immediately without waiting
for a request from another process, done by calling OpenSocketConnect in the other process. This allows
multiple other processes to connect to the particular HALCON process that calls OpenSocketAccept. To ac-
cept an incoming connection request, SocketAcceptConnect must be called after another process has called
OpenSocketConnect.
Parameter

. Port (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT


Port number.
Default Value : 3000
Typical range of values : 1024 ≤ Port ≤ 1024
Minimum Increment : 1
Recommended Increment : 1
. AcceptingSocket (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . socket_id ; HSocketX / VARIANT
Socket number.
Example

/* Process 1 */
dev_set_colored (12)
open_socket_accept (3000, AcceptingSocket)
/* Busy wait for an incoming connection */
dev_error_var (Error, 1)
dev_set_check (’~give_error’)
OpenStatus := 5
while (OpenStatus # 2)
socket_accept_connect (AcceptingSocket, ’false’, Socket)
OpenStatus := Error
wait_seconds (0.2)
endwhile
dev_set_check (’give_error’)
/* Connection established */
receive_image (Image, Socket)
threshold (Image, Region, 0, 63)
send_region (Region, Socket)
receive_region (ConnectedRegions, Socket)
area_center (ConnectedRegions, Area, Row, Column)
send_tuple (Socket, Area)
send_tuple (Socket, Row)
send_tuple (Socket, Column)
close_socket (Socket)
close_socket (AcceptingSocket)

/* Process 2 */
dev_set_colored (12)
open_socket_connect (’localhost’, 3000, Socket)
read_image (Image, ’fabrik’)
send_image (Image, Socket)
receive_region (Region, Socket)
connection (Region, ConnectedRegions)

HALCON/COM Reference Manual, 2008-5-13


14.8. SOCKETS 1013

send_region (ConnectedRegions, Socket)


receive_tuple (Socket, Area)
receive_tuple (Socket, Row)
receive_tuple (Socket, Column)
close_socket (Socket)

Parallelization Information
OpenSocketAccept is reentrant and processed without parallelization.
Possible Successors
SocketAcceptConnect
See also
OpenSocketConnect, CloseSocket, GetSocketTimeout, SetSocketTimeout, SendImage,
ReceiveImage, SendRegion, ReceiveRegion, SendTuple, ReceiveTuple
Module
Foundation

void HSocketX.OpenSocketConnect ([in] String HostName, [in] long Port )


void HOperatorSetX.OpenSocketConnect ([in] VARIANT HostName,
[in] VARIANT Port, [out] VARIANT Socket )

Open a socket to an existing socket.


OpenSocketConnect opens a connection to an accepting socket on the computer HostName, which listens
on port Port. The listening socket in the other HALCON process must have been created earlier with the oper-
ator OpenSocketAccept. The socket thus created is returned in Socket. To establish the connection, the
HALCON process, in which the accepting socket resides, must call SocketAcceptConnect. For a detailed
example, see OpenSocketAccept.
Parameter

. HostName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT


Hostname of the computer to connect to.
Default Value : ’localhost’
. Port (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Port number.
Default Value : 3000
Typical range of values : 1024 ≤ Port ≤ 1024
Minimum Increment : 1
Recommended Increment : 1
. Socket (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . socket_id ; HSocketX / VARIANT
Socket number.
Parallelization Information
OpenSocketConnect is reentrant and processed without parallelization.
Possible Successors
SendImage, ReceiveImage, SendRegion, ReceiveRegion, SendTuple, ReceiveTuple
See also
OpenSocketAccept, SocketAcceptConnect, GetSocketTimeout, SetSocketTimeout,
CloseSocket
Module
Foundation

HALCON 8.0.2
1014 CHAPTER 14. SYSTEM

void HImageX.ReceiveImage ([in] long Socket )


[out] HImageX Image HSocketX.ReceiveImage ( )
void HOperatorSetX.ReceiveImage ([out] HUntypedObjectX Image,
[in] VARIANT Socket )

Receive an image over a socket connection.


ReceiveImage reads an image object that was sent over the socket connection determined by Socket by
another HALCONprocess using the operator SendImage. If no image has been sent, the HALCON process
calling ReceiveImage blocks until enough data arrives. For a detailed example, see OpenSocketAccept.
Parameter

. Image (output iconic) . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte, direction, cyclic, int1,
int2, uint2, int4, real, complex, vector_field )
Received image.
. Socket (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . socket_id ; long / HSocketX / VARIANT
Socket number.
Parallelization Information
ReceiveImage is reentrant and processed without parallelization.
Possible Predecessors
OpenSocketConnect, SocketAcceptConnect, GetSocketTimeout, SetSocketTimeout
See also
SendImage, SendRegion, ReceiveRegion, SendTuple, ReceiveTuple,
GetNextSocketDataType
Module
Foundation

void HRegionX.ReceiveRegion ([in] long Socket )


HSocketX.ReceiveRegion ( )
[out] HRegionX Region
void HOperatorSetX.ReceiveRegion ([out] HUntypedObjectX Region,
[in] VARIANT Socket )

Receive regions over a socket connection.


ReceiveRegion reads a region object that was sent over the socket connection determined by Socket by
another HALCONprocess using the operator SendRegion. If no regions have been sent, the HALCON process
calling ReceiveRegion blocks until enough data arrives. For a detailed example, see OpenSocketAccept.
Parameter

. Region (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX


Received regions.
. Socket (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . socket_id ; long / HSocketX / VARIANT
Socket number.
Parallelization Information
ReceiveRegion is reentrant and processed without parallelization.
Possible Predecessors
OpenSocketConnect, SocketAcceptConnect, GetSocketTimeout, SetSocketTimeout
See also
SendRegion, SendImage, ReceiveImage, SendTuple, ReceiveTuple,
GetNextSocketDataType
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


14.8. SOCKETS 1015

HSocketX.ReceiveTuple ( )
[out] VARIANT Tuple
void HOperatorSetX.ReceiveTuple ([in] VARIANT Socket,
[out] VARIANT Tuple )

Receive a tuple over a socket connection.


ReceiveTuple reads a tuple that was sent over the socket connection determined by Socket by another
HALCON process using the operator SendTuple. If no tuple has been sent, the HALCON process calling
ReceiveTuple blocks until enough data arrives. For a detailed example, see OpenSocketAccept.
Parameter

. Socket (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . socket_id ; HSocketX / VARIANT


Socket number.
. Tuple (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( real, integer, string )
Received tuple.
Parallelization Information
ReceiveTuple is reentrant and processed without parallelization.
Possible Predecessors
OpenSocketConnect, SocketAcceptConnect, GetSocketTimeout, SetSocketTimeout
See also
SendTuple, SendImage, ReceiveImage, SendRegion, ReceiveRegion,
GetNextSocketDataType
Module
Foundation

void HXLDX.ReceiveXld ([in] long Socket )


[out] HUntypedObjectX XLD HSocketX.ReceiveXld ( )
void HOperatorSetX.ReceiveXld ([out] HUntypedObjectX XLD,
[in] VARIANT Socket )

Receive an XLD object over a socket connection.


ReceiveXld reads an XLD object that was sent over the socket connection determined by Socket by another
HALCONprocess using the operator SendXld. If no XLD object has been sent, the HALCON process calling
ReceiveXld blocks until enough data arrives. For a detailed example, see SendXld.
Parameter

. XLD (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xld(-array) ; HUntypedObjectX


Received XLD object.
. Socket (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . socket_id ; long / HSocketX / VARIANT
Socket number.
Parallelization Information
ReceiveXld is reentrant and processed without parallelization.
Possible Predecessors
OpenSocketConnect, SocketAcceptConnect, GetSocketTimeout, SetSocketTimeout
See also
SendXld, SendImage, ReceiveImage, SendRegion, ReceiveRegion, SendTuple,
ReceiveTuple, GetNextSocketDataType
Module
Foundation

HALCON 8.0.2
1016 CHAPTER 14. SYSTEM

void HImageX.SendImage ([in] long Socket )


void HSocketX.SendImage ([in] HImageX Image )
void HOperatorSetX.SendImage ([in] IHObjectX Image,
[in] VARIANT Socket )

Send an image over a socket connection.


SendImage sends an image object over the socket connection determined by Socket. The receiving HAL-
CON process must call ReceiveImage to read the image from the socket. For a detailed example, see
OpenSocketAccept.
Parameter

. Image (input iconic) . . . . . . image(-array) ; HImageX / IHObjectX ( byte, direction, cyclic, int1, int2,
uint2, int4, real, complex, vector_field )
Image to be sent.
. Socket (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . socket_id ; long / HSocketX / VARIANT
Socket number.
Parallelization Information
SendImage is reentrant and processed without parallelization.
Possible Predecessors
OpenSocketConnect, SocketAcceptConnect
See also
ReceiveImage, SendRegion, ReceiveRegion, SendTuple, ReceiveTuple,
GetNextSocketDataType
Module
Foundation

void HRegionX.SendRegion ([in] long Socket )


void HSocketX.SendRegion ([in] HRegionX Region )
void HOperatorSetX.SendRegion ([in] IHObjectX Region,
[in] VARIANT Socket )

Send regions over a socket connection.


SendRegion sends a region object over the socket connection determined by Socket. The receiving HAL-
CON process must call ReceiveRegion to read the regions from the socket. For a detailed example, see
OpenSocketAccept.
Parameter

. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Regions to be sent.
. Socket (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . socket_id ; long / HSocketX / VARIANT
Socket number.
Parallelization Information
SendRegion is reentrant and processed without parallelization.
Possible Predecessors
OpenSocketConnect, SocketAcceptConnect
See also
ReceiveRegion, SendImage, ReceiveImage, SendTuple, ReceiveTuple,
GetNextSocketDataType
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


14.8. SOCKETS 1017

void HSocketX.SendTuple ([in] VARIANT Tuple )


void HOperatorSetX.SendTuple ([in] VARIANT Socket, [in] VARIANT Tuple )

Send a tuple over a socket connection.


SendTuple sends a tuple over the socket connection determined by Socket. The receiving HALCON process
must call ReceiveTuple to read the tuple from the socket. For a detailed example, see OpenSocketAccept.
Parameter
. Socket (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . socket_id ; HSocketX / VARIANT
Socket number.
. Tuple (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( real, integer, string )
Tuple to be sent.
Parallelization Information
SendTuple is reentrant and processed without parallelization.
Possible Predecessors
OpenSocketConnect, SocketAcceptConnect
See also
ReceiveTuple, SendImage, ReceiveImage, SendRegion, ReceiveRegion,
GetNextSocketDataType
Module
Foundation

void HXLDX.SendXld ([in] long Socket )


void HSocketX.SendXld ([in] IHXLDX XLD )
void HOperatorSetX.SendXld ([in] IHObjectX XLD, [in] VARIANT Socket )
Send an XLD object over a socket connection.
SendXld sends an XLD object over the socket connection determined by Socket. The receiving HALCON
process must call ReceiveXld to read the XLD object from the socket.
Parameter
. XLD (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xld(-array) ; IHXLDX / IHObjectX
XLD object to be sent.
. Socket (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . socket_id ; long / HSocketX / VARIANT
Socket number.
Example

/* Process 1 */
dev_set_colored (12)
open_socket_accept (3000, AcceptingSocket)
socket_accept_connect (AcceptingSocket, ’true’, Socket)
receive_image (Image, Socket)
edges_sub_pix (Image, Edges, ’canny’, 1.5, 20, 40)
send_xld (Edges, Socket)
receive_xld (Polygons, Socket)
split_contours_xld (Polygons, Contours, ’polygon’, 1, 5)
gen_parallels_xld (Polygons, Parallels, 10, 30, 0.15, ’true’)
send_xld (Parallels, Socket)
receive_xld (ModParallels, Socket)
receive_xld (ExtParallels, Socket)
stop ()
close_socket (Socket)
close_socket (AcceptingSocket)

HALCON 8.0.2
1018 CHAPTER 14. SYSTEM

/* Process 2 */
dev_set_colored (12)
open_socket_connect (’localhost’, 3000, Socket)
read_image (Image, ’mreut’)
send_image (Image, Socket)
receive_xld (Edges, Socket)
gen_polygons_xld (Edges, Polygons, ’ramer’, 2)
send_xld (Polygons, Socket)
split_contours_xld (Polygons, Contours, ’polygon’, 1, 5)
receive_xld (Parallels, Socket)
mod_parallels_xld (Parallels, Image, ModParallels, ExtParallels,
0.4, 160, 220, 10)
send_xld (ModParallels, Socket)
send_xld (ExtParallels, Socket)
stop ()
close_socket (Socket)

Parallelization Information
SendXld is reentrant and processed without parallelization.
Possible Predecessors
OpenSocketConnect, SocketAcceptConnect
See also
ReceiveXld, SendImage, ReceiveImage, SendRegion, ReceiveRegion, SendTuple,
ReceiveTuple, GetNextSocketDataType
Module
Foundation

void HSocketX.SetSocketTimeout ([in] VARIANT Timeout )


void HOperatorSetX.SetSocketTimeout ([in] VARIANT Socket,
[in] VARIANT Timeout )

Set the timout of a socket.


SetSocketTimeout sets the timout for the socket connection that is passed in Socket. The Timeout is
used for reading and writing of data via the socket as well as for calls to SocketAcceptConnect. If problems
during the transmission of the data cause a timeout, the underlying protocol cannot synchonize itself with the data
any longer. Therefore, in these cases, the only possibility to put the system into a consistent state is to close both
sockets and to open them anew. It should be noted that sometimes while reading data no error message will be
returned if the sending socket is closed while the receiving socket is waiting for data. In these cases, empty data
are returned (either objects or tuples).
The timeout is given in seconds as a floating point number. It can also be set to ’infinite’, causing the read calls to
wait indefinitely.
Parameter
. Socket (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . socket_id ; HSocketX / VARIANT
Socket number.
. Timeout (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real, string )
Socket timeout.
Default Value : ’infinite’
Suggested values : Timeout ∈ {’infinite’, 0, 1, 2, 3, 4, 5, 10, 30, 60}
Parallelization Information
SetSocketTimeout is reentrant and processed without parallelization.
Possible Predecessors
OpenSocketAccept, OpenSocketConnect, SocketAcceptConnect

HALCON/COM Reference Manual, 2008-5-13


14.8. SOCKETS 1019

Possible Successors
SocketAcceptConnect, ReceiveImage, ReceiveRegion, ReceiveXld
See also
GetSocketTimeout
Module
Foundation

HSocketX.SocketAcceptConnect ([in] String Wait )


[out] long Socket
void HOperatorSetX.SocketAcceptConnect
([in] VARIANT AcceptingSocket, [in] VARIANT Wait, [out] VARIANT Socket )

Accept a connection request on a listening socket.


SocketAcceptConnect accepts an incoming connection request, generated by OpenSocketConnect in
another HALCONprocess, on the listening socket AcceptingSocket. The listening socket must have been
created earlier with OpenSocketAccept. If Wait=’true’, SocketAcceptConnect waits until a con-
nection request from another HALCON process arrives. If Wait=’false’, SocketAcceptConnect returns
with the error FAIL, if currently there are no connection requests from other HALCONprocesses. The result of
SocketAcceptConnect is another socket Socket, which is used for a two-way communication with another
HALCON process. After this connection has been established, data can be exchanged between the two processes
by calling the appropriate send or receive operators. For a detailed example, see OpenSocketAccept.
Parameter

. AcceptingSocket (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . socket_id ; HSocketX / VARIANT


Socket number of the accepting socket.
. Wait (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Should the operator wait until a connection request arrives?
List of values : Wait ∈ {’true’, ’false’}
. Socket (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . socket_id ; long / VARIANT
Socket number.
Parallelization Information
SocketAcceptConnect is reentrant and processed without parallelization.
Possible Predecessors
OpenSocketAccept
Possible Successors
SendImage, ReceiveImage, SendRegion, ReceiveRegion, SendTuple, ReceiveTuple
See also
OpenSocketConnect, CloseSocket, GetSocketTimeout, SetSocketTimeout
Module
Foundation

HALCON 8.0.2
1020 CHAPTER 14. SYSTEM

HALCON/COM Reference Manual, 2008-5-13


Chapter 15

Tools

15.1 2D-Transformations
[out] VARIANT RowTrans HHomMat2dX.AffineTransPixel ([in] VARIANT Row,
[in] VARIANT Col, [out] VARIANT ColTrans )
void HOperatorSetX.AffineTransPixel ([in] VARIANT HomMat2D,
[in] VARIANT Row, [in] VARIANT Col, [out] VARIANT RowTrans,
[out] VARIANT ColTrans )

Apply an arbitrary affine 2D transformation to pixel coordinates.


AffineTransPixel applies an arbitrary affine 2D transformation, i.e., scaling, rotation, translation, and slant
(skewing), to the input pixels (Row,Col) and returns the resulting pixels in (RowTrans,ColTrans); the input
and output pixels are subpixel precise coordinates. The affine transformation is described by the homogeneous
transformation matrix given in HomMat2D.
The difference between AffineTransPixel and AffineTransPoint2D lies in the used coordinate sys-
tem: AffineTransPixel uses a coordinate system with origin in the upper left corner of the image, while
AffineTransPoint2D uses the standard image coordinate system, whose origin lies in the middle of the upper
left pixel and which is also used by operators like AreaCenter.
Applying AffineTransPixel corresponds to the following chain of tansformations (input and output pixels
as homogeneous vectors):
       
RowTrans 1 0 −0.5 1 0 +0.5 Row
 ColTrans  =  0 1 −0.5  · HomMat2D ·  0 1 +0.5  ·  Col 
1 0 0 1 0 0 1 1

Hence,
affine_trans_pixel (HomMat2D, Row, Col, RowTrans, ColTrans)
corresponds to the following operator sequence:
affine_trans_point_2d (HomMat2D, Row+0.5, Col+0.5, RowTmp, ColTmp)
RowTrans := RowTmp-0.5
ColTrans := ColTmp-0.5
Parameter

. HomMat2D (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )


Input transformation matrix.
. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( real, integer )
Input pixel(s) (row coordinate).
Default Value : 64
Suggested values : Row ∈ {0, 16, 32, 64, 128, 256, 512, 1024}

1021
1022 CHAPTER 15. TOOLS

. Col (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( real, integer )


Input pixel(s) (column coordinate).
Default Value : 64
Suggested values : Col ∈ {0, 16, 32, 64, 128, 256, 512, 1024}
. RowTrans (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( real )
Output pixel(s) (row coordinate).
. ColTrans (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( real )
Output pixel(s) (column coordinate).
Result
If the matrix HomMat2D represents an affine transformation (i.e., not a projective transformation),
AffineTransPixel returns TRUE. Otherwise, an exception is raised.
Parallelization Information
AffineTransPixel is reentrant and processed without parallelization.
Possible Predecessors
HomMat2dTranslate, HomMat2dTranslateLocal, HomMat2dScale, HomMat2dScaleLocal,
HomMat2dRotate, HomMat2dRotateLocal, HomMat2dSlant, HomMat2dSlantLocal
Alternatives
AffineTransPoint2D
Module
Foundation

[out] VARIANT Qx HHomMat2dX.AffineTransPoint2D ([in] VARIANT Px,


[in] VARIANT Py, [out] VARIANT Qy )
void HOperatorSetX.AffineTransPoint2D ([in] VARIANT HomMat2D,
[in] VARIANT Px, [in] VARIANT Py, [out] VARIANT Qx, [out] VARIANT Qy )

Apply an arbitrary affine 2D transformation to points.


AffineTransPoint2D applies an arbitrary affine 2D transformation, i.e., scaling, rotation, translation, and
slant (skewing), to the input points (Px,Py) and returns the resulting points in (Qx,Qy). The affine transformation
is described by the homogeneous transformation matrix given in HomMat2D. This corresponds to the following
equation (input and output points as homogeneous vectors):
   
Qx Px
 Qy  = HomMat2D ·  Py 
1 1

If the points to transform are specified in standard image coordinates, their row coordinates must be passed in Px
and their column coordinates in Py. This is necessary to obtain a right-handed coordinate system for the image. In
particular, this assures that rotations are performed in the correct direction. Note that the (x,y) order of the matrices
quite naturally corresponds to the usual (row,column) order for coordinates in the image.
The transformation matrix can be created using the operators HomMat2dIdentity, HomMat2dRotate,
HomMat2dTranslate, etc., or can be the result of operators like VectorAngleToRigid.
For example, if HomMat2D corresponds to a rigid transformation, i.e., if it consists of a rotation and a translation,
the points are transformed as follows:
       
Qx   Px Px
R t R· +t 
 Qy  = ·  Py  =  Py
00 1
1 1 1

HALCON/COM Reference Manual, 2008-5-13


15.1. 2D-TRANSFORMATIONS 1023

Parameter
. HomMat2D (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )
Input transformation matrix.
. Px (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( real, integer )
Input point(s) (x or row coordinate).
Default Value : 64
Suggested values : Px ∈ {0, 16, 32, 64, 128, 256, 512, 1024}
. Py (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( real, integer )
Input point(s) (y or column coordinate).
Default Value : 64
Suggested values : Py ∈ {0, 16, 32, 64, 128, 256, 512, 1024}
. Qx (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( real )
Output point(s) (x or row coordinate).
. Qy (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( real )
Output point(s) (y or column coordinate).
Result
If the matrix HomMat2D represents an affine transformation (i.e., not a projective transformation),
AffineTransPoint2D returns TRUE. Otherwise, an exception is raised.
Parallelization Information
AffineTransPoint2D is reentrant and processed without parallelization.
Possible Predecessors
HomMat2dTranslate, HomMat2dTranslateLocal, HomMat2dScale, HomMat2dScaleLocal,
HomMat2dRotate, HomMat2dRotateLocal, HomMat2dSlant, HomMat2dSlantLocal
Possible Successors
HomMat2dTranslate, HomMat2dTranslateLocal, HomMat2dScale, HomMat2dScaleLocal,
HomMat2dRotate, HomMat2dRotateLocal, HomMat2dSlant, HomMat2dSlantLocal
Module
Foundation

[out] HHomMat2dX MosaicMatrices2D HHomMat2dX.BundleAdjustMosaic


([in] long NumImages, [in] long ReferenceImage, [in] VARIANT MappingSource,
[in] VARIANT MappingDest, [in] VARIANT Rows1, [in] VARIANT Cols1,
[in] VARIANT Rows2, [in] VARIANT Cols2, [in] VARIANT NumCorrespondences,
[in] String Transformation, [out] VARIANT Rows, [out] VARIANT Cols,
[out] VARIANT Error )
void HOperatorSetX.BundleAdjustMosaic ([in] VARIANT NumImages,
[in] VARIANT ReferenceImage, [in] VARIANT MappingSource,
[in] VARIANT MappingDest, [in] VARIANT HomMatrices2D, [in] VARIANT Rows1,
[in] VARIANT Cols1, [in] VARIANT Rows2, [in] VARIANT Cols2,
[in] VARIANT NumCorrespondences, [in] VARIANT Transformation,
[out] VARIANT MosaicMatrices2D, [out] VARIANT Rows, [out] VARIANT Cols,
[out] VARIANT Error )

Perform a bundle adjustment of an image mosaic.


BundleAdjustMosaic performs a bundle adjustment of an image mosaic. This can be used to determine the
geometry of a mosaic as robustly as possible, and hence to determine the transformations of the images in the
mosaic more accurately than with single image pairs.
To achieve this, the projective transformation for each overlapping image pair in the mosaic should be determined
with ProjMatchPointsRansac. For example, for a 2×2 block of images in the following layout
1 2
3 4
the following projective transformations should be determined, assuming that all images overlap each other: 17→2,
17→3, 17→4, 27→3, 27→4 und 37→4. The indices of the images that determine the respective transformation are

HALCON 8.0.2
1024 CHAPTER 15. TOOLS

given by MappingSource and MappingDest. The indices are start at 1. Consequently, in the above example
MappingSource = [1,1,1,2,2,3] and MappingDest = [2,3,4,3,4,4] must be used. The number of images
in the mosaic is given by NumImages. It is used to check whether each image can be reached by a chain of
transformations. The index of the reference image is given by ReferenceImage. On output, this image has the
identity matrix as its transformation matrix.
The 3 × 3 projective transformation matrices that correspond to the image pairs are passed in HomMatrices2D.
Additionally, the coordinates of the matched point pairs in the image pairs must be passed in Rows1, Cols1,
Rows2, and Cols2. They can be determined from the output of ProjMatchPointsRansac with
TupleSelect or with the HDevelop function subset. To enable BundleAdjustMosaic to determine
which point pair belongs to which image pair, NumCorrespondences must contain the number of found point
matches for each image pair.
The parameter Transformation determines the class of transformations that is used in the bundle adjustment
to transform the image points. This can be used to restrict the allowable transformations. For Transformation
= ’projective’, projective transformations are used (see VectorToProjHomMat2d). For Transformation
= ’affine’, affine transformations are used (see VectorToHomMat2d), for Transformation = ’similarity’,
similarity transformations (see VectorToSimilarity), and for Transformation = ’rigid’ rigid transfor-
mations (see VectorToRigid).
The resulting bundle-adjusted transformations are retuned as an array of 3 × 3 projective transformation matrices
in MosaicMatrices2D. In addition, the points reconstructed by the bundle adjustment are returned in (Rows,
Cols). The average projection error of the reconstructed points is returned in Error. This can be used to check
whether the optimization has converged to useful values.
Parameter
. NumImages (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of different images that are used for the calibration.
Restriction : (N umImages ≥ 2)
. ReferenceImage (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Index of the reference image.
. MappingSource (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Indices of the source images of the transformations.
. MappingDest (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Indices of the target images of the transformations.
. HomMatrices2D (input control) . . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )
Array of 3 × 3 projective transformation matrices.
. Rows1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; VARIANT ( real, integer )
Row coordinates of corresponding points in the respective source images.
. Cols1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; VARIANT ( real, integer )
Column coordinates of corresponding points in the respective source images.
. Rows2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; VARIANT ( real, integer )
Row coordinates of corresponding points in the respective destination images.
. Cols2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; VARIANT ( real, integer )
Column coordinates of corresponding points in the respective destination images.
. NumCorrespondences (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Number of point correspondences in the respective image pair.
. Transformation (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Transformation class to be used.
Default Value : ’projective’
List of values : Transformation ∈ {’projective’, ’affine’, ’similarity’, ’rigid’}
. MosaicMatrices2D (output control) . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )
Array of 3 × 3 projective transformation matrices that determine the position of the images in the mosaic.
. Rows (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; VARIANT ( real )
Row coordinates of the points reconstructed by the bundle adjustment.
. Cols (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; VARIANT ( real )
Column coordinates of the points reconstructed by the bundle adjustment.
. Error (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Average error per reconstructed point.

HALCON/COM Reference Manual, 2008-5-13


15.1. 2D-TRANSFORMATIONS 1025

Example

* Assume that Images contains the four images of the mosaic in the
* layout given in the above description. Then the following example
* computes the bundle-adjusted transformation matrices.
From := [1,1,1,2,2,3]
To := [2,3,4,3,4,4]
HomMatrices2D := []
Rows1 := []
Cols1 := []
Rows2 := []
Cols2 := []
NumMatches := []
for J := 0 to |From|-1 by 1
select_obj (Images, From[J], ImageF)
select_obj (Images, To[J], ImageT)
points_foerstner (ImageF, 1, 2, 3, 100, 0.1, ’gauss’, ’true’,
RowsF, ColsF, _, _, _, _, _, _, _, _)
points_foerstner (ImageT, 1, 2, 3, 100, 0.1, ’gauss’, ’true’,
RowsT, ColsT, _, _, _, _, _, _, _, _)
proj_match_points_ransac (ImageF, ImageT, RowsF, ColsF, RowsT, ColsT,
’ncc’, 10, 0, 0, 480, 640, 0, 0.5,
’gold_standard’, 2, 42, HomMat2D,
Points1, Points2)
HomMatrices2D := [HomMatrices2D,HomMat2D]
Rows1 := [Rows1,subset(RowsF,Points1)]
Cols1 := [Cols1,subset(ColsF,Points1)]
Rows2 := [Rows2,subset(RowsT,Points2)]
Cols2 := [Cols2,subset(ColsT,Points2)]
NumMatches := [NumMatches,|Points1|]
endfor
bundle_adjust_mosaic (4, 1, From, To, HomMatrices2D, Rows1, Cols1,
Rows2, Cols2, NumMatches, ’rigid’, MosaicMatrices)
gen_bundle_adjusted_mosaic (Images, MosaicImage, HomMatrices2D,
’default’, ’false’, TransMat2D)

Result
If the parameters are valid, the operator BundleAdjustMosaic returns the value TRUE. If necessary an
exception handling is raised.
Parallelization Information
BundleAdjustMosaic is reentrant and processed without parallelization.
Possible Predecessors
ProjMatchPointsRansac
Possible Successors
GenBundleAdjustedMosaic
See also
GenProjectiveMosaic
Module
Matching

HALCON 8.0.2
1026 CHAPTER 15. TOOLS

[out] HHomMat2dX HomMat2DCompose HHomMat2dX.HomMat2dCompose


([in] HHomMat2dX HomMat2DRight )
void HOperatorSetX.HomMat2dCompose ([in] VARIANT HomMat2DLeft,
[in] VARIANT HomMat2DRight, [out] VARIANT HomMat2DCompose )

Multiply two homogeneous 2D transformation matrices.


HomMat2dCompose composes a new 2D transformation matrix by multiplying the two input matrices:

HomMat2DCompose = HomMat2DLeft · HomMat2DRight

For example, if the two input matrices correspond to rigid transformations, i.e., to transformations consisting of a
rotation and a translation, the resulting matrix is calculated as follows:
     
Rl tl Rr tr Rl · Rr Rl +tl · tr
HomMat2DCompose = · =
00 1 00 1 0 0 1

Parameter

. HomMat2DLeft (input control) . . . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )


Left input transformation matrix.
. HomMat2DRight (input control) . . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )
Right input transformation matrix.
. HomMat2DCompose (output control) . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )
Output transformation matrix.
Result
If the parameters are valid, the operator HomMat2dCompose returns TRUE. If necessary, an exception is raised.
Parallelization Information
HomMat2dCompose is reentrant and processed without parallelization.
Possible Predecessors
HomMat2dCompose, HomMat2dTranslate, HomMat2dTranslateLocal, HomMat2dScale,
HomMat2dScaleLocal, HomMat2dRotate, HomMat2dRotateLocal, HomMat2dSlant,
HomMat2dSlantLocal
Possible Successors
HomMat2dTranslate, HomMat2dTranslateLocal, HomMat2dScale, HomMat2dScaleLocal,
HomMat2dRotate, HomMat2dRotateLocal, HomMat2dSlant, HomMat2dSlantLocal
Module
Foundation

HHomMat2dX.HomMat2dDeterminant ( )
[out] double Determinant
void HOperatorSetX.HomMat2dDeterminant ([in] VARIANT HomMat2D,
[out] VARIANT Determinant )

Compute the determinant of a homogeneous 2D transformation matrix.


HomMat2dDeterminant computes the determinant of the homogeneous 2D transformation matrix given by
HomMat2D and returns it in Determinant.
Parameter

. HomMat2D (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )


Input transformation matrix.
. Determinant (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Determinant of the input matrix.

HALCON/COM Reference Manual, 2008-5-13


15.1. 2D-TRANSFORMATIONS 1027

Result
HomMat2dDeterminant always returns TRUE.
Parallelization Information
HomMat2dDeterminant is reentrant and processed without parallelization.
Possible Predecessors
HomMat2dTranslate, HomMat2dTranslateLocal, HomMat2dScale, HomMat2dScaleLocal,
HomMat2dRotate, HomMat2dRotateLocal, HomMat2dSlant, HomMat2dSlantLocal
Module
Foundation

void HHomMat2dX.HomMat2dIdentity ( )
void HOperatorSetX.HomMat2dIdentity ([out] VARIANT HomMat2DIdentity )

Generate the homogeneous transformation matrix of the identical 2D transformation.


HomMat2dIdentity generates the homogeneous transformation matrix HomMat2DIdentity describing the
identical 2D transformation:
 
1 0 0
HomMat2DIdentity =  0 1 0 
0 0 1

Attention
Note that homogeneous matrices are stored row-by-row as a tuple; the last row is not stored because it is identical
for all homogeneous matrices that describe an affine transformation. Thus, HomMat2DIdentity is stored as the
tuple [1,0,0,0,1,0].
Parameter
. HomMat2DIdentity (output control) . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )
Transformation matrix.
Result
HomMat2dIdentity always returns TRUE.
Parallelization Information
HomMat2dIdentity is reentrant and processed without parallelization.
Possible Successors
HomMat2dTranslate, HomMat2dTranslateLocal, HomMat2dScale, HomMat2dScaleLocal,
HomMat2dRotate, HomMat2dRotateLocal, HomMat2dSlant, HomMat2dSlantLocal
Module
Foundation

HHomMat2dX.HomMat2dInvert ( )
[out] HHomMat2dX HomMat2DInvert
void HOperatorSetX.HomMat2dInvert ([in] VARIANT HomMat2D,
[out] VARIANT HomMat2DInvert )

Invert a homogeneous 2D transformation matrix.


HomMat2dInvert inverts the homogeneous 2D transformation matrix given by HomMat2D. The resulting ma-
trix is returned in HomMat2DInvert.
Parameter
. HomMat2D (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )
Input transformation matrix.
. HomMat2DInvert (output control) . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )
Output transformation matrix.

HALCON 8.0.2
1028 CHAPTER 15. TOOLS

Result
HomMat2dInvert returns TRUE if the parameters are valid and the input matrix is invertible. Otherwise, an
exception is raised.
Parallelization Information
HomMat2dInvert is reentrant and processed without parallelization.
Possible Predecessors
HomMat2dTranslate, HomMat2dTranslateLocal, HomMat2dScale, HomMat2dScaleLocal,
HomMat2dRotate, HomMat2dRotateLocal, HomMat2dSlant, HomMat2dSlantLocal
Possible Successors
HomMat2dTranslate, HomMat2dTranslateLocal, HomMat2dScale, HomMat2dScaleLocal,
HomMat2dRotate, HomMat2dRotateLocal, HomMat2dSlant, HomMat2dSlantLocal
Module
Foundation

[out] HHomMat2dX HomMat2DRotate HHomMat2dX.HomMat2dRotate


([in] VARIANT Phi, [in] VARIANT Px, [in] VARIANT Py )
void HOperatorSetX.HomMat2dRotate ([in] VARIANT HomMat2D,
[in] VARIANT Phi, [in] VARIANT Px, [in] VARIANT Py,
[out] VARIANT HomMat2DRotate )

Add a rotation to a homogeneous 2D transformation matrix.


HomMat2dRotate adds a rotation by the angle Phi to the homogeneous 2D transformation matrix HomMat2D
and returns the resulting matrix in HomMat2DRotate. The rotation is described by a 2×2 rotation matrix R.
It is performed relative to the global (i.e., fixed) coordinate system; this corresponds to the following chain of
transformation matrices:
 
0  
R cos(Phi) − sin(Phi)
HomMat2DRotate =  0  · HomMat2D R =
sin(Phi) cos(Phi)
0 0 1

The point (Px,Py) is the fixed point of the transformation, i.e., this point remains unchanged when transformed
using HomMat2DRotate. To obtain this behavior, first a translation is added to the input transformation matrix
that moves the fixed point onto the origin of the global coordinate system. Then, the rotation is added, and finally
a translation that moves the fixed point back to its original position. This corresponds to the following chain of
transformations:
     
1 0 +Px 0 1 0 −Px
R
HomMat2DRotate =  0 1 +Py  ·  0  ·  0 1 −Py  · HomMat2D
0 0 1 0 0 1 0 0 1

To perform the transformation in the local coordinate system, i.e., the one described by HomMat2D, use
HomMat2dRotateLocal.
Attention
It should be noted that homogeneous transformation matrices refer to a general right-handed mathematical coor-
dinate system. If a homogeneous transformation matrix is used to transform images, regions, XLD contours, or
any other data that has been extracted from images, the row coordinates of the transformation must be passed in
the x coordinates, while the column coordinates must be passed in the y coordinates. Consequently, the order of
passing row and column coordinates follows the usual order (Row,Column). This convention is essential to obtain
a right-handed coordinate system for the transformation of iconic data, and consequently to ensure in particular
that rotations are performed in the correct mathematical direction.
Note that homogeneous matrices are stored row-by-row as a tuple; the last row is usually not stored because it
is identical for all homogeneous matrices that describe an affine transformation. For example, the homogeneous
matrix
 
ra rb tc
 rd re tf 
0 0 1

HALCON/COM Reference Manual, 2008-5-13


15.1. 2D-TRANSFORMATIONS 1029

is stored as the tuple [ra, rb, tc, rd, re, tf]. However, it is also possible to process full 3×3 matrices, which represent
a projective 2D transformation.
Parameter
. HomMat2D (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )
Input transformation matrix.
. Phi (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; VARIANT ( real, integer )
Rotation angle.
Default Value : 0.78
Suggested values : Phi ∈ {0.1, 0.2, 0.3, 0.4, 0.78, 1.57, 3.14}
Typical range of values : 0 ≤ Phi ≤ 0
. Px (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .point.x ; VARIANT ( real, integer )
Fixed point of the transformation (x coordinate).
Default Value : 0
Suggested values : Px ∈ {0, 16, 32, 64, 128, 256, 512, 1024}
. Py (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .point.y ; VARIANT ( real, integer )
Fixed point of the transformation (y coordinate).
Default Value : 0
Suggested values : Py ∈ {0, 16, 32, 64, 128, 256, 512, 1024}
. HomMat2DRotate (output control) . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )
Output transformation matrix.
Result
If the parameters are valid, the operator HomMat2dRotate returns TRUE. If necessary, an exception is raised.
Parallelization Information
HomMat2dRotate is reentrant and processed without parallelization.
Possible Predecessors
HomMat2dIdentity, HomMat2dTranslate, HomMat2dScale, HomMat2dRotate,
HomMat2dSlant
Possible Successors
HomMat2dTranslate, HomMat2dScale, HomMat2dRotate, HomMat2dSlant
See also
HomMat2dRotateLocal
Module
Foundation

[out] HHomMat2dX HomMat2DRotate HHomMat2dX.HomMat2dRotateLocal


([in] VARIANT Phi )
void HOperatorSetX.HomMat2dRotateLocal ([in] VARIANT HomMat2D,
[in] VARIANT Phi, [out] VARIANT HomMat2DRotate )

Add a rotation to a homogeneous 2D transformation matrix.


HomMat2dRotateLocal adds a rotation by the angle Phi to the homogeneous 2D transformation matrix
HomMat2D and returns the resulting matrix in HomMat2DRotate. The rotation is described by a 2×2 rota-
tion matrix R. In contrast to HomMat2dRotate, it is performed relative to the local coordinate system, i.e., the
coordinate system described by HomMat2D; this corresponds to the following chain of transformation matrices:
 
0  
R cos(Phi) − sin(Phi)
HomMat2DRotate = HomMat2D ·  0  R =
sin(Phi) cos(Phi)
0 0 1

The fixed point of the transformation is the origin of the local coordinate system, i.e., this point remains unchanged
when transformed using HomMat2DRotate.
Attention
It should be noted that homogeneous transformation matrices refer to a general right-handed mathematical coor-
dinate system. If a homogeneous transformation matrix is used to transform images, regions, XLD contours, or

HALCON 8.0.2
1030 CHAPTER 15. TOOLS

any other data that has been extracted from images, the row coordinates of the transformation must be passed in
the x coordinates, while the column coordinates must be passed in the y coordinates. Consequently, the order of
passing row and column coordinates follows the usual order (Row,Column). This convention is essential to obtain
a right-handed coordinate system for the transformation of iconic data, and consequently to ensure in particular
that rotations are performed in the correct mathematical direction.
Note that homogeneous matrices are stored row-by-row as a tuple; the last row is usually not stored because it
is identical for all homogeneous matrices that describe an affine transformation. For example, the homogeneous
matrix
 
ra rb tc
 rd re tf 
0 0 1
is stored as the tuple [ra, rb, tc, rd, re, tf]. However, it is also possible to process full 3×3 matrices, which represent
a projective 2D transformation.
Parameter
. HomMat2D (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )
Input transformation matrix.
. Phi (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; VARIANT ( real, integer )
Rotation angle.
Default Value : 0.78
Suggested values : Phi ∈ {0.1, 0.2, 0.3, 0.4, 0.78, 1.57, 3.14}
Typical range of values : 0 ≤ Phi ≤ 0
. HomMat2DRotate (output control) . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )
Output transformation matrix.
Result
If the parameters are valid, the operator HomMat2dRotateLocal returns TRUE. If necessary, an exception is
raised.
Parallelization Information
HomMat2dRotateLocal is reentrant and processed without parallelization.
Possible Predecessors
HomMat2dIdentity, HomMat2dTranslateLocal, HomMat2dScaleLocal,
HomMat2dRotateLocal, HomMat2dSlantLocal
Possible Successors
HomMat2dTranslateLocal, HomMat2dScaleLocal, HomMat2dRotateLocal,
HomMat2dSlantLocal
See also
HomMat2dRotate
Module
Foundation

[out] HHomMat2dX HomMat2DScale HHomMat2dX.HomMat2dScale


([in] VARIANT Sx, [in] VARIANT Sy, [in] VARIANT Px, [in] VARIANT Py )
void HOperatorSetX.HomMat2dScale ([in] VARIANT HomMat2D,
[in] VARIANT Sx, [in] VARIANT Sy, [in] VARIANT Px, [in] VARIANT Py,
[out] VARIANT HomMat2DScale )

Add a scaling to a homogeneous 2D transformation matrix.


HomMat2dScale adds a scaling by the scale factors Sx and Sy to the homogeneous 2D transformation matrix
HomMat2D and returns the resulting matrix in HomMat2DScale. The scaling is described by a 2×2 scaling
matrix S. It is performed relative to the global (i.e., fixed) coordinate system; this corresponds to the following
chain of transformation matrices:
 
0  
S Sx 0
HomMat2DScale =  0  · HomMat2D S =
0 Sy
0 0 1

HALCON/COM Reference Manual, 2008-5-13


15.1. 2D-TRANSFORMATIONS 1031

The point (Px,Py) is the fixed point of the transformation, i.e., this point remains unchanged when transformed
using HomMat2DScale. To obtain this behavior, first a translation is added to the input transformation matrix
that moves the fixed point onto the origin of the global coordinate system. Then, the scaling is added, and finally
a translation that moves the fixed point back to its original position. This corresponds to the following chain of
transformations:
     
1 0 +Px 0 1 0 −Px
S
HomMat2DScale =  0 1 +Py  ·  0 · 0 1 −Py  · HomMat2D
0 0 1 0 0 1 0 0 1

To perform the transformation in the local coordinate system, i.e., the one described by HomMat2D, use
HomMat2dScaleLocal.
Attention
It should be noted that homogeneous transformation matrices refer to a general right-handed mathematical coor-
dinate system. If a homogeneous transformation matrix is used to transform images, regions, XLD contours, or
any other data that has been extracted from images, the row coordinates of the transformation must be passed in
the x coordinates, while the column coordinates must be passed in the y coordinates. Consequently, the order of
passing row and column coordinates follows the usual order (Row,Column). This convention is essential to obtain
a right-handed coordinate system for the transformation of iconic data, and consequently to ensure in particular
that rotations are performed in the correct mathematical direction.
Note that homogeneous matrices are stored row-by-row as a tuple; the last row is usually not stored because it
is identical for all homogeneous matrices that describe an affine transformation. For example, the homogeneous
matrix
 
ra rb tc
 rd re tf 
0 0 1
is stored as the tuple [ra, rb, tc, rd, re, tf]. However, it is also possible to process full 3×3 matrices, which represent
a projective 2D transformation.
Parameter

. HomMat2D (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )


Input transformation matrix.
. Sx (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Scale factor along the x-axis.
Default Value : 2
Suggested values : Sx ∈ {0.125, 0.25, 0.5, 1, 2, 4, 8, 16}
Restriction : (Sx 6= 0)
. Sy (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Scale factor along the y-axis.
Default Value : 2
Suggested values : Sy ∈ {0.125, 0.25, 0.5, 1, 2, 4, 8, 16}
Restriction : (Sy 6= 0)
. Px (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .point.x ; VARIANT ( real, integer )
Fixed point of the transformation (x coordinate).
Default Value : 0
Suggested values : Px ∈ {0, 16, 32, 64, 128, 256, 512, 1024}
. Py (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .point.y ; VARIANT ( real, integer )
Fixed point of the transformation (y coordinate).
Default Value : 0
Suggested values : Py ∈ {0, 16, 32, 64, 128, 256, 512, 1024}
. HomMat2DScale (output control) . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )
Output transformation matrix.
Result
HomMat2dScale returns TRUE if both scale factors are not 0. If necessary, an exception is raised.
Parallelization Information
HomMat2dScale is reentrant and processed without parallelization.

HALCON 8.0.2
1032 CHAPTER 15. TOOLS

Possible Predecessors
HomMat2dIdentity, HomMat2dTranslate, HomMat2dScale, HomMat2dRotate,
HomMat2dSlant
Possible Successors
HomMat2dTranslate, HomMat2dScale, HomMat2dRotate, HomMat2dSlant
See also
HomMat2dScaleLocal
Module
Foundation

[out] HHomMat2dX HomMat2DScale HHomMat2dX.HomMat2dScaleLocal


([in] VARIANT Sx, [in] VARIANT Sy )
void HOperatorSetX.HomMat2dScaleLocal ([in] VARIANT HomMat2D,
[in] VARIANT Sx, [in] VARIANT Sy, [out] VARIANT HomMat2DScale )

Add a scaling to a homogeneous 2D transformation matrix.


HomMat2dScaleLocal adds a scaling by the scale factors Sx and Sy to the homogeneous 2D transformation
matrix HomMat2D and returns the resulting matrix in HomMat2DScale. The scaling is described by a 2×2
scaling matrix S. In contrast to HomMat2dScale, it is performed relative to the local coordinate system, i.e., the
coordinate system described by HomMat2D; this corresponds to the following chain of transformation matrices:
 
0  
S Sx 0
HomMat2DScale = HomMat2D ·  0  S =
0 Sy
0 0 1

The fixed point of the transformation is the origin of the local coordinate system, i.e., this point remains unchanged
when transformed using HomMat2DScale.
Attention
It should be noted that homogeneous transformation matrices refer to a general right-handed mathematical coor-
dinate system. If a homogeneous transformation matrix is used to transform images, regions, XLD contours, or
any other data that has been extracted from images, the row coordinates of the transformation must be passed in
the x coordinates, while the column coordinates must be passed in the y coordinates. Consequently, the order of
passing row and column coordinates follows the usual order (Row,Column). This convention is essential to obtain
a right-handed coordinate system for the transformation of iconic data, and consequently to ensure in particular
that rotations are performed in the correct mathematical direction.
Note that homogeneous matrices are stored row-by-row as a tuple; the last row is usually not stored because it
is identical for all homogeneous matrices that describe an affine transformation. For example, the homogeneous
matrix
 
ra rb tc
 rd re tf 
0 0 1
is stored as the tuple [ra, rb, tc, rd, re, tf]. However, it is also possible to process full 3×3 matrices, which represent
a projective 2D transformation.
Parameter

. HomMat2D (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )


Input transformation matrix.
. Sx (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Scale factor along the x-axis.
Default Value : 2
Suggested values : Sx ∈ {0.125, 0.25, 0.5, 1, 2, 4, 8, 16}
Restriction : (Sx 6= 0)

HALCON/COM Reference Manual, 2008-5-13


15.1. 2D-TRANSFORMATIONS 1033

. Sy (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )


Scale factor along the y-axis.
Default Value : 2
Suggested values : Sy ∈ {0.125, 0.25, 0.5, 1, 2, 4, 8, 16}
Restriction : (Sy 6= 0)
. HomMat2DScale (output control) . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )
Output transformation matrix.
Result
HomMat2dScaleLocal returns TRUE if both scale factors are not 0. If necessary, an exception is raised.
Parallelization Information
HomMat2dScaleLocal is reentrant and processed without parallelization.
Possible Predecessors
HomMat2dIdentity, HomMat2dTranslateLocal, HomMat2dScaleLocal,
HomMat2dRotateLocal, HomMat2dSlantLocal
Possible Successors
HomMat2dTranslateLocal, HomMat2dScaleLocal, HomMat2dRotateLocal,
HomMat2dSlantLocal
See also
HomMat2dScale
Module
Foundation

[out] HHomMat2dX HomMat2DSlant HHomMat2dX.HomMat2dSlant


([in] VARIANT Theta, [in] String Axis, [in] VARIANT Px, [in] VARIANT Py )
void HOperatorSetX.HomMat2dSlant ([in] VARIANT HomMat2D,
[in] VARIANT Theta, [in] VARIANT Axis, [in] VARIANT Px, [in] VARIANT Py,
[out] VARIANT HomMat2DSlant )

Add a slant to a homogeneous 2D transformation matrix.


HomMat2dSlant adds a slant by the angle Theta to the homogeneous 2D transformation matrix HomMat2D
and returns the resulting matrix in HomMat2DSlant. A slant is an affine transformation in which one coordinate
axis remains fixed, while the other coordinate axis is rotated counterclockwise by an angle Theta. The parameter
Axis determines which coordinate axis is slanted. For Axis = ’x’, the x-axis is slanted and the y-axis remains
fixed, while for Axis = ’y’ the y-axis is slanted and the x-axis remains fixed. The slanting is performed relative to
the global (i.e., fixed) coordinate system; this corresponds to the following chains of transformation matrices:

 
cos(Theta) 0 0
Axis = 0 x 0 : HomMat2DSlant = sin(Theta) 1
 0  · HomMat2D
0 0 1
 
1 − sin(Theta) 0
Axis = 0 y 0 : HomMat2DSlant =  0 cos(Theta) 0  · HomMat2D
0 0 1

The point (Px,Py) is the fixed point of the transformation, i.e., this point remains unchanged when transformed
using HomMat2DSlant. To obtain this behavior, first a translation is added to the input transformation matrix
that moves the fixed point onto the origin of the global coordinate system. Then, the slant is added, and finally
a translation that moves the fixed point back to its original position. This corresponds to the following chain of
transformations for Axis = ’x’:
     
1 0 +Px cos(Theta) 0 0 1 0 −Px
HomMat2DSlant =  0 1 +Py  ·  sin(Theta) 1 0 · 0 1 −Py  · HomMat2D
0 0 1 0 0 1 0 0 1

HALCON 8.0.2
1034 CHAPTER 15. TOOLS

To perform the transformation in the local coordinate system, i.e., the one described by HomMat2D, use
HomMat2dSlantLocal.
Attention
It should be noted that homogeneous transformation matrices refer to a general right-handed mathematical coor-
dinate system. If a homogeneous transformation matrix is used to transform images, regions, XLD contours, or
any other data that has been extracted from images, the row coordinates of the transformation must be passed in
the x coordinates, while the column coordinates must be passed in the y coordinates. Consequently, the order of
passing row and column coordinates follows the usual order (Row,Column). This convention is essential to obtain
a right-handed coordinate system for the transformation of iconic data, and consequently to ensure in particular
that rotations are performed in the correct mathematical direction.
Note that homogeneous matrices are stored row-by-row as a tuple; the last row is usually not stored because it
is identical for all homogeneous matrices that describe an affine transformation. For example, the homogeneous
matrix
 
ra rb tc
 rd re tf 
0 0 1
is stored as the tuple [ra, rb, tc, rd, re, tf]. However, it is also possible to process full 3×3 matrices, which represent
a projective 2D transformation.
Parameter

. HomMat2D (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )


Input transformation matrix.
. Theta (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; VARIANT ( real, integer )
Slant angle.
Default Value : 0.78
Suggested values : Theta ∈ {0.1, 0.2, 0.3, 0.4, 0.78, 1.57, 3.14}
Typical range of values : 0 ≤ Theta ≤ 0
. Axis (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Coordinate axis that is slanted.
Default Value : ’x’
List of values : Axis ∈ {’x’, ’y’}
. Px (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .point.x ; VARIANT ( real, integer )
Fixed point of the transformation (x coordinate).
Default Value : 0
Suggested values : Px ∈ {0, 16, 32, 64, 128, 256, 512, 1024}
. Py (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .point.y ; VARIANT ( real, integer )
Fixed point of the transformation (y coordinate).
Default Value : 0
Suggested values : Py ∈ {0, 16, 32, 64, 128, 256, 512, 1024}
. HomMat2DSlant (output control) . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )
Output transformation matrix.
Result
If the parameters are valid, the operator HomMat2dSlant returns TRUE. If necessary, an exception is raised.
Parallelization Information
HomMat2dSlant is reentrant and processed without parallelization.
Possible Predecessors
HomMat2dIdentity, HomMat2dTranslate, HomMat2dScale, HomMat2dRotate,
HomMat2dSlant
Possible Successors
HomMat2dTranslate, HomMat2dScale, HomMat2dRotate, HomMat2dSlant
See also
HomMat2dSlantLocal
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


15.1. 2D-TRANSFORMATIONS 1035

[out] HHomMat2dX HomMat2DSlant HHomMat2dX.HomMat2dSlantLocal


([in] VARIANT Theta, [in] String Axis )
void HOperatorSetX.HomMat2dSlantLocal ([in] VARIANT HomMat2D,
[in] VARIANT Theta, [in] VARIANT Axis, [out] VARIANT HomMat2DSlant )

Add a slant to a homogeneous 2D transformation matrix.


HomMat2dSlantLocal adds a slant by the angle Theta to the homogeneous 2D transformation matrix
HomMat2D and returns the resulting matrix in HomMat2DSlant. A slant is an affine transformation in which
one coordinate axis remains fixed, while the other coordinate axis is rotated counterclockwise by an angle Theta.
The parameter Axis determines which coordinate axis is slanted. For Axis = ’x’, the x-axis is slanted and
the y-axis remains fixed, while for Axis = ’y’ the y-axis is slanted and the x-axis remains fixed. In contrast to
HomMat2dSlant, the slanting is performed relative to the local coordinate system, i.e., the coordinate system
described by HomMat2D; this corresponds to the following chains of transformation matrices:

 
cos(Theta) 0 0
Axis = 0 x 0 : HomMat2DSlant = HomMat2D ·  sin(Theta) 1 0 
0 0 1
 
1 − sin(Theta) 0
Axis = 0 y 0 : HomMat2DSlant = HomMat2D · 0
 cos(Theta) 0 
0 0 1

The fixed point of the transformation is the origin of the local coordinate system, i.e., this point remains unchanged
when transformed using HomMat2DSlant.
Attention
It should be noted that homogeneous transformation matrices refer to a general right-handed mathematical coor-
dinate system. If a homogeneous transformation matrix is used to transform images, regions, XLD contours, or
any other data that has been extracted from images, the row coordinates of the transformation must be passed in
the x coordinates, while the column coordinates must be passed in the y coordinates. Consequently, the order of
passing row and column coordinates follows the usual order (Row,Column). This convention is essential to obtain
a right-handed coordinate system for the transformation of iconic data, and consequently to ensure in particular
that rotations are performed in the correct mathematical direction.
Note that homogeneous matrices are stored row-by-row as a tuple; the last row is usually not stored because it
is identical for all homogeneous matrices that describe an affine transformation. For example, the homogeneous
matrix
 
ra rb tc
 rd re tf 
0 0 1
is stored as the tuple [ra, rb, tc, rd, re, tf]. However, it is also possible to process full 3×3 matrices, which represent
a projective 2D transformation.
Parameter
. HomMat2D (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )
Input transformation matrix.
. Theta (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; VARIANT ( real, integer )
Slant angle.
Default Value : 0.78
Suggested values : Theta ∈ {0.1, 0.2, 0.3, 0.4, 0.78, 1.57, 3.14}
Typical range of values : 0 ≤ Theta ≤ 0
. Axis (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Coordinate axis that is slanted.
Default Value : ’x’
List of values : Axis ∈ {’x’, ’y’}
. HomMat2DSlant (output control) . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )
Output transformation matrix.

HALCON 8.0.2
1036 CHAPTER 15. TOOLS

Result
If the parameters are valid, the operator HomMat2dSlantLocal returns TRUE. If necessary, an exception is
raised.
Parallelization Information
HomMat2dSlantLocal is reentrant and processed without parallelization.
Possible Predecessors
HomMat2dIdentity, HomMat2dTranslateLocal, HomMat2dScaleLocal,
HomMat2dRotateLocal, HomMat2dSlantLocal
Possible Successors
HomMat2dTranslateLocal, HomMat2dScaleLocal, HomMat2dRotateLocal,
HomMat2dSlantLocal
See also
HomMat2dSlant
Module
Foundation

[out] double Sx HHomMat2dX.HomMat2dToAffinePar ([out] double Sy,


[out] double Phi, [out] double Theta, [out] double Tx, [out] double Ty )
void HOperatorSetX.HomMat2dToAffinePar ([in] VARIANT HomMat2D,
[out] VARIANT Sx, [out] VARIANT Sy, [out] VARIANT Phi, [out] VARIANT Theta,
[out] VARIANT Tx, [out] VARIANT Ty )

Compute the affine transformation parameters from a homogeneous 2D transformation matrix.


HomMat2dToAffinePar computes the affine transformation parameters corresponding to the homogeneous 2D
transformation matrix HomMat2D. The parameters Sx and Sy determine how the transformation scales the original
x- and y-axes, respectively. The two scaling factors are always positive. The angle Theta describes whether the
transformed coordinate axes are orthogonal (Theta = 0) or slanted. If |Theta| > π/2, the transformation
contains a reflection. The angle Phi determines the rotation of the transformed x-axis with respect to the original
x-axis. The parameters Tx and Ty determine the translation of the two coordinate systems. The matrix HomMat2D
can be constructed from the six transformation parameters by the following operator sequence:
hom_mat2d_identity (HomMat2DIdentity)
hom_mat2d_scale (HomMat2DIdentity, Sx, Sy, 0, 0, HomMat2DScale)
hom_mat2d_slant (HomMat2DScale, Theta, ’y’, 0, 0, HomMat2DSlant)
hom_mat2d_rotate (HomMat2DSlant, Phi, 0, 0, HomMat2DRotate)
hom_mat2d_translate (HomMat2DRotate, Tx, Ty, HomMat2D)

This is equivalent to the following chain of transformation matrices:


 
     
1 0 +Tx cos(Phi) − sin(Phi) 0 1 − sin(Theta) 0 Sx 0 0
HomMat2D =  0 1 +Ty  ·  sin(Phi) cos(Phi) 0  ·  0 cos(Theta) 0  ·  0 Sy 0 
0 0 1 0 0 1 0 0 1 0 0 1

Parameter

. HomMat2D (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )


Input transformation matrix.
. Sx (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Scaling factor along the x direction.
. Sy (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Scaling factor along the y direction.
. Phi (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; double / VARIANT
Rotation angle.
. Theta (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; double / VARIANT
Slant angle.

HALCON/COM Reference Manual, 2008-5-13


15.1. 2D-TRANSFORMATIONS 1037

. Tx (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; double / VARIANT


Translation along the x direction.
. Ty (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; double / VARIANT
Translation along the y direction.
Result
If the matrix HomMat2D is non-degenerate and represents an affine transformation (i.e., not a projective transfor-
mation), HomMat2dToAffinePar returns TRUE. Otherwise, an exception is raised.
Parallelization Information
HomMat2dToAffinePar is reentrant and processed without parallelization.
Possible Predecessors
VectorToHomMat2d, VectorToRigid, VectorToSimilarity
Possible Successors
HomMat2dTranslate, HomMat2dScale, HomMat2dRotate, HomMat2dSlant
Module
Foundation

[out] HHomMat2dX HomMat2DTranslate HHomMat2dX.HomMat2dTranslate


([in] VARIANT Tx, [in] VARIANT Ty )
void HOperatorSetX.HomMat2dTranslate ([in] VARIANT HomMat2D,
[in] VARIANT Tx, [in] VARIANT Ty, [out] VARIANT HomMat2DTranslate )

Add a translation to a homogeneous 2D transformation matrix.


HomMat2dTranslate adds a translation by the vector t = (Tx,Ty) to the homogeneous 2D transformation
matrix HomMat2D and returns the resulting matrix in HomMat2DTranslate. The translation is performed
relative to the global (i.e., fixed) coordinate system; this corresponds to the following chain of transformation
matrices:
 
1 0  
t  Tx
HomMat2DTranslate =  0 1 · HomMat2D t=
Ty
0 0 1

To perform the transformation in the local coordinate system, i.e., the one described by HomMat2D, use
HomMat2dTranslateLocal.
Attention
It should be noted that homogeneous transformation matrices refer to a general right-handed mathematical coor-
dinate system. If a homogeneous transformation matrix is used to transform images, regions, XLD contours, or
any other data that has been extracted from images, the row coordinates of the transformation must be passed in
the x coordinates, while the column coordinates must be passed in the y coordinates. Consequently, the order of
passing row and column coordinates follows the usual order (Row,Column). This convention is essential to obtain
a right-handed coordinate system for the transformation of iconic data, and consequently to ensure in particular
that rotations are performed in the correct mathematical direction.
Note that homogeneous matrices are stored row-by-row as a tuple; the last row is usually not stored because it
is identical for all homogeneous matrices that describe an affine transformation. For example, the homogeneous
matrix
 
ra rb tc
 rd re tf 
0 0 1
is stored as the tuple [ra, rb, tc, rd, re, tf]. However, it is also possible to process full 3×3 matrices, which represent
a projective 2D transformation.

HALCON 8.0.2
1038 CHAPTER 15. TOOLS

Parameter
. HomMat2D (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )
Input transformation matrix.
. Tx (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; VARIANT ( real, integer )
Translation along the x-axis.
Default Value : 64
Suggested values : Tx ∈ {0, 16, 32, 64, 128, 256, 512, 1024}
. Ty (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; VARIANT ( real, integer )
Translation along the y-axis.
Default Value : 64
Suggested values : Ty ∈ {0, 16, 32, 64, 128, 256, 512, 1024}
. HomMat2DTranslate (output control) . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )
Output transformation matrix.
Result
If the parameters are valid, the operator HomMat2dTranslate returns TRUE. If necessary, an exception is
raised.
Parallelization Information
HomMat2dTranslate is reentrant and processed without parallelization.
Possible Predecessors
HomMat2dIdentity, HomMat2dTranslate, HomMat2dScale, HomMat2dRotate,
HomMat2dSlant
Possible Successors
HomMat2dTranslate, HomMat2dScale, HomMat2dRotate, HomMat2dSlant
See also
HomMat2dTranslateLocal
Module
Foundation

[out] HHomMat2dX HomMat2DTranslate HHomMat2dX.HomMat2dTranslateLocal


([in] VARIANT Tx, [in] VARIANT Ty )
void HOperatorSetX.HomMat2dTranslateLocal ([in] VARIANT HomMat2D,
[in] VARIANT Tx, [in] VARIANT Ty, [out] VARIANT HomMat2DTranslate )

Add a translation to a homogeneous 2D transformation matrix.


HomMat2dTranslateLocal adds a translation by the vector t = (Tx,Ty) to the homogeneous 2D trans-
formation matrix HomMat2D and returns the resulting matrix in HomMat2DTranslate. In contrast to
HomMat2dTranslate, the translation is performed relative to the local coordinate system, i.e., the coordinate
system described by HomMat2D; this corresponds to the following chain of transformation matrices:
 
1 0  
t  Tx
HomMat2DTranslate = HomMat2D ·  0 1 t=
Ty
0 0 1

Attention
It should be noted that homogeneous transformation matrices refer to a general right-handed mathematical coor-
dinate system. If a homogeneous transformation matrix is used to transform images, regions, XLD contours, or
any other data that has been extracted from images, the row coordinates of the transformation must be passed in
the x coordinates, while the column coordinates must be passed in the y coordinates. Consequently, the order of
passing row and column coordinates follows the usual order (Row,Column). This convention is essential to obtain
a right-handed coordinate system for the transformation of iconic data, and consequently to ensure in particular
that rotations are performed in the correct mathematical direction.
Note that homogeneous matrices are stored row-by-row as a tuple; the last row is usually not stored because it
is identical for all homogeneous matrices that describe an affine transformation. For example, the homogeneous
matrix

HALCON/COM Reference Manual, 2008-5-13


15.1. 2D-TRANSFORMATIONS 1039

 
ra rb tc
 rd re tf 
0 0 1
is stored as the tuple [ra, rb, tc, rd, re, tf]. However, it is also possible to process full 3×3 matrices, which represent
a projective 2D transformation.
Parameter

. HomMat2D (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )


Input transformation matrix.
. Tx (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .point.x ; VARIANT ( real, integer )
Translation along the x-axis.
Default Value : 64
Suggested values : Tx ∈ {0, 16, 32, 64, 128, 256, 512, 1024}
. Ty (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .point.y ; VARIANT ( real, integer )
Translation along the y-axis.
Default Value : 64
Suggested values : Ty ∈ {0, 16, 32, 64, 128, 256, 512, 1024}
. HomMat2DTranslate (output control) . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )
Output transformation matrix.
Result
If the parameters are valid, the operator HomMat2dTranslateLocal returns TRUE. If necessary, an exception
is raised.
Parallelization Information
HomMat2dTranslateLocal is reentrant and processed without parallelization.
Possible Predecessors
HomMat2dIdentity, HomMat2dTranslateLocal, HomMat2dScaleLocal,
HomMat2dRotateLocal, HomMat2dSlantLocal
Possible Successors
HomMat2dTranslateLocal, HomMat2dScaleLocal, HomMat2dRotateLocal,
HomMat2dSlantLocal
See also
HomMat2dTranslate
Module
Foundation

HHomMat2dX.HomMat2dTranspose ( )
[out] HHomMat2dX HomMat2DTranspose
void HOperatorSetX.HomMat2dTranspose ([in] VARIANT HomMat2D,
[out] VARIANT HomMat2DTranspose )

Transpose a homogeneous 2D transformation matrix.


HomMat2dTranspose transposes the homogeneous 2D transformation matrix given by HomMat2D. The result
matrix HomMat2DTranspose is always a 3 × 3 matrix, even if the input matrix is represented by a 2 × 3 matrix.
Parameter

. HomMat2D (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )


Input transformation matrix.
. HomMat2DTranspose (output control) . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )
Output transformation matrix.
Result
HomMat2dTranspose always returns TRUE.
Parallelization Information
HomMat2dTranspose is reentrant and processed without parallelization.

HALCON 8.0.2
1040 CHAPTER 15. TOOLS

Possible Predecessors
HomMat2dTranslate, HomMat2dTranslateLocal, HomMat2dScale, HomMat2dScaleLocal,
HomMat2dRotate, HomMat2dRotateLocal, HomMat2dSlant, HomMat2dSlantLocal
Possible Successors
HomMat2dCompose, HomMat2dInvert
Module
Foundation

[out] HHomMat2dX HomMat2D HHomMat3dX.HomMat3dProject


([in] VARIANT PrincipalPointRow, [in] VARIANT PrincipalPointCol,
[in] VARIANT Focus )
void HOperatorSetX.HomMat3dProject ([in] VARIANT HomMat3D,
[in] VARIANT PrincipalPointRow, [in] VARIANT PrincipalPointCol,
[in] VARIANT Focus, [out] VARIANT HomMat2D )

Project an affine 3D transformation matrix to a 2D projective transformation matrix.


HomMat3dProject calculates a homogeneous projection matrix from a homogeneous 3×4 transformation ma-
trix describing an affine transformation in 3D. The result can be used to project a plane, in particular a plane
containing an image. The projection matrix defines a projective transformation between two (two-dimensional)
planes.
This can be used to create perspective distortions, which occur in a projection of a plane rotated around an axis
other than the z axis. Usually, however, projective transformations are determined from point correspondences (see
VectorToProjHomMat2d, HomVectorToProjHomMat2d, and ProjMatchPointsRansac).
Matrices for rotation, scale, and translation can be constructed using the operators HomMat3dIdentity,
HomMat3dScale, HomMat3dRotate, HomMat3dTranslate and PoseToHomMat3d.
Note that for 3D transformations the x-axis represents the column axis while the y-axis represents the row axis (see
also CameraCalibration) while in ProjectiveTransImage, the first row of HomMat2D contains the
transformation of the row axis and the second row contains the transformation of the column axis of the image.
The point (PrincipalPointRow, PrincipalPointCol) is the principal point of the projection and the
point (PrincipalPointRow, PrincipalPointCol, 0) can thus be interpreted as the position of the camera
in a virtual three-dimensional space. The direction of view is along the positive z-axis.
In this virtual space the plane containing the input image as well as the image plane are located at z = Focus,
which is Focus pixels away form the camera. As a result, using the identity matrix as the input matrix HomMat3D
leads to a matrix HomMat2D which also represents the identity in 2D.
Consequently, the parameter Focus is the “focal distance” of the virtual camera used and its unit is pixels. Its
value influences the degree of perspective distortions. The same input matrix at a bigger focal distance results in
weaker distortions than at a low focal distance.
Let H be the affine 3D matrix with elements hij , (r, c) = (PrincipalPointRow, PrincipalPointCol)
and f = Focus.
Then the projective transformation matrix is calculated as follows: First, a 3×4 projection matrix is calculated as:
 
    h11 h12 h13 h14
f 0 c 1 0 0 −c  h21 h22 h23 h24 
Q= 0 f r · 0 1 0 −r  · 
 
h31 h32 h33 h34 
0 0 1 0 0 1 0
0 0 0 1

Since the image of a plane containing points (x, y, f, 1)T is to be calculated the last two columns of Q can be
joined:
 
    1 0 0
r11 r12 r13 q11 q12 f · q13 + q14  0 1 0 
R =  r21 r22 r23  =  q21 q22 f · r23 + q24  = Q · 
 0

0 f 
r31 r32 r33 q31 q32 f · r33 + q34
0 0 1

HALCON/COM Reference Manual, 2008-5-13


15.1. 2D-TRANSFORMATIONS 1041

Finally, the columns and rows of R are swapped in a way that the first row of P contains the transformation of the
row coordinates and the second row contains the transformation of the column coordinates so that P can be used
directly in ProjectiveTransImage:
   
0 1 0 0 1 0
P = 1 0 0  ·R·  1 0 0 
0 0 1 0 0 1

The overall transformation can be written as:


 
      1 0 0  
0 1 0 f 0 c 1 0 0 −c  0 0 1 0
1 0  

P = 1 0 0 · 0 f r · 0 1 0 −r  · H ·
 · 1 0 0 
0 0 f 
0 0 1 0 0 1 0 0 1 0 0 0 1
0 0 1

Parameter
. HomMat3D (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . hom_mat3d ; HHomMat3dX / VARIANT ( real )
3 × 4 3D transformation matrix.
. PrincipalPointRow (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; VARIANT ( real, integer )
Row coordinate of the principal point.
Default Value : 256
Suggested values : PrincipalPointRow ∈ {16, 32, 64, 128, 240, 256, 512}
. PrincipalPointCol (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; VARIANT ( real, integer )
Column coordinate of the principal point.
Default Value : 256
Suggested values : PrincipalPointCol ∈ {16, 32, 64, 128, 256, 320, 512}
. Focus (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Focal length in pixels.
Default Value : 256
Suggested values : Focus ∈ {1, 2, 5, 256, 32768}
. HomMat2D (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )
Homogeneous projective transformation matrix.
Parallelization Information
HomMat3dProject is reentrant and processed without parallelization.
Possible Predecessors
HomMat3dIdentity, HomMat3dRotate, HomMat3dTranslate, HomMat3dScale
Possible Successors
ProjectiveTransImage, ProjectiveTransPoint2D, ProjectiveTransRegion,
ProjectiveTransContourXld, HomMat2dInvert
Module
Foundation

void HHomMat2dX.HomVectorToProjHomMat2d ([in] VARIANT Px,


[in] VARIANT Py, [in] VARIANT Pw, [in] VARIANT Qx, [in] VARIANT Qy,
[in] VARIANT Qw, [in] String Method )
void HOperatorSetX.HomVectorToProjHomMat2d ([in] VARIANT Px,
[in] VARIANT Py, [in] VARIANT Pw, [in] VARIANT Qx, [in] VARIANT Qy,
[in] VARIANT Qw, [in] VARIANT Method, [out] VARIANT HomMat2D )

Compute a homogeneous transformation matrix using given point correspondences.


HomVectorToProjHomMat2d determines the homogeneous projective transformation matrix HomMat2D that
optimally fulfills the following equations given by at least 4 point correspondences
   
Px Qx
HomMat2D ·  Py  =  Qy 
Pw Qw

HALCON 8.0.2
1042 CHAPTER 15. TOOLS

If fewer than 4 pairs of points (Px, Py, Pw), (Qx, Qy, Qw) are given, there exists no unique solution, if exactly 4
pairs are supplied the matrix HomMat2D transforms them in exactly the desired way, and if there are more than 4
point pairs given, HomVectorToProjHomMat2d seeks to minimize the transformation error. To achieve such
a minimization, two different algorithms are available. The algorithm to use can be chosen using the parameter
Method. For conventional geometric problems Method=’normalized_dlt’ usually yields better results. However,
if one of the coordinates Qw or Pw equals 0, Method=’dlt’ must be chosen.
In contrast to VectorToProjHomMat2d, HomVectorToProjHomMat2d uses homogeneous coordinates
for the points, and hence points at infinity (Pw = 0 or Qw = 0) can be used to determine the transformation. If
finite points are used, typically Pw and Qw are set to 1. In this case, VectorToProjHomMat2d can also be
used. VectorToProjHomMat2d has the advantage that one additional optimization method can be used and
that the covariances of the points can be taken into account. If the correspondence between the points has not
been determined, ProjMatchPointsRansac should be used to determine the correspondence as well as the
transformation.
If the points to transform are specified in standard image coordinates, their row coordinates must be passed in Px
and their column coordinates in Py. This is necessary to obtain a right-handed coordinate system for the image. In
particular, this assures that rotations are performed in the correct direction. Note that the (x,y) order of the matrices
quite naturally corresponds to the usual (row,column) order for coordinates in the image.
Attention
It should be noted that homogeneous transformation matrices refer to a general right-handed mathematical coor-
dinate system. If a homogeneous transformation matrix is used to transform images, regions, XLD contours, or
any other data that has been extracted from images, the row coordinates of the transformation must be passed in
the x coordinates, while the column coordinates must be passed in the y coordinates. Consequently, the order of
passing row and column coordinates follows the usual order (Row,Column). This convention is essential to obtain
a right-handed coordinate system for the transformation of iconic data, and consequently to ensure in particular
that rotations are performed in the correct mathematical direction.
Parameter
. Px (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Input points 1 (x coordinate).
. Py (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Input points 1 (y coordinate).
. Pw (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Input points 1 (w coordinate).
. Qx (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real )
Input points 2 (x coordinate).
. Qy (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real )
Input points 2 (y coordinate).
. Qw (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real )
Input points 2 (w coordinate).
. Method (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Estimation algorithm.
Default Value : ’normalized_dlt’
List of values : Method ∈ {’normalized_dlt’, ’dlt’}
. HomMat2D (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )
Homogeneous projective transformation matrix.
Parallelization Information
HomVectorToProjHomMat2d is reentrant and processed without parallelization.
Possible Predecessors
ProjMatchPointsRansac, PointsFoerstner, PointsHarris
Possible Successors
ProjectiveTransImage, ProjectiveTransImageSize, ProjectiveTransRegion,
ProjectiveTransContourXld, ProjectiveTransPoint2D, ProjectiveTransPixel
Alternatives
VectorToProjHomMat2d, ProjMatchPointsRansac
References
Richard Hartley, Andrew Zisserman: “Multiple View Geometry in Computer Vision”; Cambridge University Press,
Cambridge; 2000.

HALCON/COM Reference Manual, 2008-5-13


15.1. 2D-TRANSFORMATIONS 1043

Olivier Faugeras, Quang-Tuan Luong: “The Geometry of Multiple Images: The Laws That Govern the Formation
of Multiple Images of a Scene and Some of Their Applications”; MIT Press, Cambridge, MA; 2001.
Module
Calibration

[out] HHomMat2dX HomMat2D HImageX.ProjMatchPointsRansac


([in] HImageX Image2, [in] VARIANT Rows1, [in] VARIANT Cols1,
[in] VARIANT Rows2, [in] VARIANT Cols2, [in] String GrayMatchMethod,
[in] long MaskSize, [in] long RowMove, [in] long ColMove,
[in] long RowTolerance, [in] long ColTolerance, [in] VARIANT Rotation,
[in] VARIANT MatchThreshold, [in] String EstimationMethod,
[in] double DistanceThreshold, [in] long RandSeed, [out] VARIANT Points1,
[out] VARIANT Points2 )
void HHomMat2dX.ProjMatchPointsRansac ([in] HImageX Image1,
[in] HImageX Image2, [in] VARIANT Rows1, [in] VARIANT Cols1,
[in] VARIANT Rows2, [in] VARIANT Cols2, [in] String GrayMatchMethod,
[in] long MaskSize, [in] long RowMove, [in] long ColMove,
[in] long RowTolerance, [in] long ColTolerance, [in] VARIANT Rotation,
[in] VARIANT MatchThreshold, [in] String EstimationMethod,
[in] double DistanceThreshold, [in] long RandSeed, [out] VARIANT Points1,
[out] VARIANT Points2 )
void HOperatorSetX.ProjMatchPointsRansac ([in] IHObjectX Image1,
[in] IHObjectX Image2, [in] VARIANT Rows1, [in] VARIANT Cols1,
[in] VARIANT Rows2, [in] VARIANT Cols2, [in] VARIANT GrayMatchMethod,
[in] VARIANT MaskSize, [in] VARIANT RowMove, [in] VARIANT ColMove,
[in] VARIANT RowTolerance, [in] VARIANT ColTolerance, [in] VARIANT Rotation,
[in] VARIANT MatchThreshold, [in] VARIANT EstimationMethod,
[in] VARIANT DistanceThreshold, [in] VARIANT RandSeed,
[out] VARIANT HomMat2D, [out] VARIANT Points1, [out] VARIANT Points2 )

Compute a projective transformation matrix between two images by finding correspondences between points.
Given a set of coordinates of characteristic points (Cols1, Rows1) and (Cols2, Rows2) in both input im-
ages Image1 and Image2, ProjMatchPointsRansac automatically determines corresponding points and
the homogeneous projective transformation matrix HomMat2D that best transforms the corresponding points
from the different images into each other. The characteristic points can, for example, be extracted with
PointsFoerstner or PointsHarris.
The transformation is determined in two steps: First, gray value correlations of mask windows around the input
points in the first and the second image are determined and an initial matching between them is generated using
the similarity of the windows in both images.
The size of the mask windows is MaskSize × MaskSize. Three metrics for the correlation can be selected.
If GrayMatchMethod has the value ’ssd’, the sum of the squared gray value differences is used, ’sad’ means
the sum of absolute differences, and ’ncc’ is the normalized cross correlation. This metric is minimized (’ssd’,
’sad’) or maximized (’ncc’) over all possible point pairs. A thus found matching is only accepted if the value of
the metric is below the value of MatchThreshold (’ssd’, ’sad’) or above that value (’ncc’).
To increase the algorithm’s performance, the search area for the matchings can be limited. Only points within a
window of 2 · RowTolerance × 2 · ColTolerance points are considered. The offset of the center of the
search window in the second image with respect to the position of the current point in the first image is given by
RowMove and ColMove.
If the transformation contains a rotation, i.e., if the first image is rotated with respect to the second image, the
parameter Rotation may contain an estimate for the rotation angle or an angle interval in radians. A good guess
will increase the quality of the gray value matching. If the actual rotation differs too much from the specified
estimate the matching will typically fail. The larger the given interval, the slower the operator is since the entire
algorithm is run for all relevant angles within the interval.
Once the initial matching is complete, a randomized search algorithm (RANSAC) is used to determine the transfor-
mation matrix HomMat2D. It tries to find the matrix that is consistent with a maximum number of correspondences.

HALCON 8.0.2
1044 CHAPTER 15. TOOLS

For a point to be accepted, its distance from the coordinates predicted by the transformation must not exceed the
threshold DistanceThreshold.
Once a choice has been made, the matrix is further optimized using all consistent points. For this optimization, the
EstimationMethod can be chosen to either be the slow but mathematically optimal ’gold_standard’ method
or the faster ’normalized_dlt’. Here, the algorithms of VectorToProjHomMat2d are used.
Point pairs that still violate the consistency condition for the final transformation are dropped, the matched points
are returned as control values. Points1 contains the indices of the matched input points from the first image,
Points2 contains the indices of the corresponding points in the second image.
The parameter RandSeed can be used to control the randomized nature of the RANSAC algorithm, and hence to
obtain reproducible results. If RandSeed is set to a positive number, the operator yields the same result on every
call with the same parameters because the internally used random number generator is initialized with the seed
value. If RandSeed = 0, the random number generator is initialized with the current time. Hence, the results
may not be reproducible in this case.
Parameter

. Image1 (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, uint2 )


Input image 1.
. Image2 (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, uint2 )
Input image 2.
. Rows1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; VARIANT ( real, integer )
Row coordinates of characteristic points in image 1.
. Cols1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; VARIANT ( real, integer )
Column coordinates of characteristic points in image 1.
. Rows2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; VARIANT ( real, integer )
Row coordinates of characteristic points in image 2.
. Cols2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; VARIANT ( real, integer )
Column coordinates of characteristic points in image 2.
. GrayMatchMethod (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Gray value comparison metric.
Default Value : ’ssd’
List of values : GrayMatchMethod ∈ {’ssd’, ’sad’, ’ncc’}
. MaskSize (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Size of gray value masks.
Default Value : 10
. RowMove (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Average row coordinate shift.
Default Value : 0
. ColMove (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Average column coordinate shift.
Default Value : 0
. RowTolerance (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Half height of matching search window.
Default Value : 256
. ColTolerance (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Half width of matching search window.
Default Value : 256
. Rotation (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Range of rotation angles.
Default Value : 0.0
Suggested values : Rotation ∈ {0.0, 0.7854, 1.571, 3.142}
. MatchThreshold (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Threshold for gray value matching.
Default Value : 10
Suggested values : MatchThreshold ∈ {10, 20, 50, 100, 0.9, 0.7}

HALCON/COM Reference Manual, 2008-5-13


15.1. 2D-TRANSFORMATIONS 1045

. EstimationMethod (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT


Transformation matrix estimation algorithm.
Default Value : ’normalized_dlt’
List of values : EstimationMethod ∈ {’normalized_dlt’, ’gold_standard’}
. DistanceThreshold (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Threshold for transformation consistency check.
Default Value : 0.2
. RandSeed (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Seed for the random number generator.
Default Value : 0
. HomMat2D (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )
Homogeneous projective transformation matrix.
. Points1 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Indices of matched input points in image 1.
. Points2 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Indices of matched input points in image 2.
Parallelization Information
ProjMatchPointsRansac is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
PointsFoerstner, PointsHarris
Possible Successors
ProjectiveTransImage, ProjectiveTransImageSize, ProjectiveTransRegion,
ProjectiveTransContourXld, ProjectiveTransPoint2D, ProjectiveTransPixel
Alternatives
HomVectorToProjHomMat2d, VectorToProjHomMat2d
References
Richard Hartley, Andrew Zisserman: “Multiple View Geometry in Computer Vision”; Cambridge University Press,
Cambridge; 2000.
Olivier Faugeras, Quang-Tuan Luong: “The Geometry of Multiple Images: The Laws That Govern the Formation
of Multiple Images of a Scene and Some of Their Applications”; MIT Press, Cambridge, MA; 2001.
Module
Matching

[out] VARIANT RowTrans HHomMat2dX.ProjectiveTransPixel


([in] VARIANT Row, [in] VARIANT Col, [out] VARIANT ColTrans )
void HOperatorSetX.ProjectiveTransPixel ([in] VARIANT HomMat2D,
[in] VARIANT Row, [in] VARIANT Col, [out] VARIANT RowTrans,
[out] VARIANT ColTrans )

Project pixel coordinates using a homogeneous projective transformation matrix.


ProjectiveTransPixel applies the homogeneous projective transformation matrix HomMat2D to all input
pixels (Row,Col) and returns an array of output pixels (RowTrans,ColTrans). The transformation is described
by the homogeneous transformation matrix given in HomMat2D.
The difference between ProjectiveTransPixel and ProjectiveTransPoint2D lies in the used co-
ordinate system: ProjectiveTransPixel uses a coordinate system with origin in the upper left corner of
the image, while ProjectiveTransPoint2D uses the standard image coordinate system, whose origin lies
in the middle of the upper left pixel and which is also used by operators like AreaCenter.
ProjectiveTransPixel corresponds to the following steps (input and output points as homogeneous vec-
tors):

   
RTrans Row
 CTrans  = HomMat2D ·  Col 
WTrans 1

HALCON 8.0.2
1046 CHAPTER 15. TOOLS

!

RowTrans
 RTrans
= WTrans
ColTrans CTrans
WTrans

If a point at infinity (WTrans = 0) is created by the transformation, an error is returned.


Parameter
. HomMat2D (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )
Homogeneous projective transformation matrix.
. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( real, integer )
Input pixel(s) (row coordinate).
Default Value : 64
Suggested values : Row ∈ {0, 16, 32, 64, 128, 256, 512, 1024}
. Col (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( real, integer )
Input pixel(s) (column coordinate).
Default Value : 64
Suggested values : Col ∈ {0, 16, 32, 64, 128, 256, 512, 1024}
. RowTrans (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( real )
Output pixel(s) (row coordinate).
. ColTrans (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( real )
Output pixel(s) (column coordinate).
Parallelization Information
ProjectiveTransPixel is reentrant and processed without parallelization.
Possible Predecessors
VectorToProjHomMat2d, HomVectorToProjHomMat2d, ProjMatchPointsRansac,
HomMat3dProject
See also
ProjectiveTransImage, ProjectiveTransImageSize, ProjectiveTransRegion,
ProjectiveTransContourXld, ProjectiveTransPoint2D
Module
Foundation

[out] VARIANT Qx HHomMat2dX.ProjectiveTransPoint2D ([in] VARIANT Px,


[in] VARIANT Py, [in] VARIANT Pw, [out] VARIANT Qy, [out] VARIANT Qw )
void HOperatorSetX.ProjectiveTransPoint2D ([in] VARIANT HomMat2D,
[in] VARIANT Px, [in] VARIANT Py, [in] VARIANT Pw, [out] VARIANT Qx,
[out] VARIANT Qy, [out] VARIANT Qw )

Project a homogeneous 2D point using a projective transformation matrix.


ProjectiveTransPoint2D applies the homogeneous projective transformation matrix HomMat2D to all ho-
mogeneous input points (Px,Py,Pw) and returns an array of homogeneous output points (Qx,Qy,Qw). The trans-
formation is described by the homogeneous transformation matrix given in HomMat2D. This corresponds to the
following equation (input and output points as homogeneous vectors):
   
Qx Px
 Qy  = HomMat2D ·  Py 
Qw Pw

To transform the homogeneous coordinates to Euclidean coordinates, they have to be divided by Qw:
!
  Qx
Ex Qw
= Qy
Ey Qw

If the points to transform are specified in standard image coordinates, their row coordinates must be passed in Px
and their column coordinates in Py. This is necessary to obtain a right-handed coordinate system for the image. In

HALCON/COM Reference Manual, 2008-5-13


15.1. 2D-TRANSFORMATIONS 1047

particular, this assures that rotations are performed in the correct direction. Note that the (x,y) order of the matrices
quite naturally corresponds to the usual (row,column) order for coordinates in the image.
Parameter

. HomMat2D (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )


Homogeneous projective transformation matrix.
. Px (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( real, integer )
Input point (x coordinate).
. Py (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( real, integer )
Input point (y coordinate).
. Pw (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( real, integer )
Input point (w coordinate).
. Qx (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( real )
Output point (x coordinate).
. Qy (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( real )
Output point (y coordinate).
. Qw (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( real )
Output point (w coordinate).
Parallelization Information
ProjectiveTransPoint2D is reentrant and processed without parallelization.
Possible Predecessors
VectorToProjHomMat2d, HomVectorToProjHomMat2d, ProjMatchPointsRansac,
HomMat3dProject
See also
ProjectiveTransImage, ProjectiveTransImageSize, ProjectiveTransRegion,
ProjectiveTransContourXld, ProjectiveTransPixel
Module
Foundation

void HHomMat2dX.VectorAngleToRigid ([in] VARIANT Row1,


[in] VARIANT Column1, [in] VARIANT Angle1, [in] VARIANT Row2,
[in] VARIANT Column2, [in] VARIANT Angle2 )
void HOperatorSetX.VectorAngleToRigid ([in] VARIANT Row1,
[in] VARIANT Column1, [in] VARIANT Angle1, [in] VARIANT Row2,
[in] VARIANT Column2, [in] VARIANT Angle2, [out] VARIANT HomMat2D )

Compute a rigid affine transformation from points and angles.


VectorAngleToRigid computes a rigid affine transformation, i.e., a transformation consisting of a rotation
and a translation, from a point correspondence and two corresponding angles and returns it as the homogeneous
transformation matrix HomMat2D. The matrix consists of 2 components: a rotation matrix R and a translation
vector t (also see HomMat2dRotate and HomMat2dTranslate):
   
  1 0 0
R t t   R
HomMat2D = = 0 1 · 0  = H(t) · H(R)
00 1
0 0 1 00 1

The coordinates of the original point are passed in (Row1,Column1), while the corresponding angle is passed
in Angle1. The coordinates of the transformed point are passed in (Row2,Column2), while the corresponding
angle is passed in Angle2. The following equation describes the transformation of the point using homogeneous
vectors:
   
Row2 Row1
 Column2  = HomMat2D ·  Column1 
1 1

HALCON 8.0.2
1048 CHAPTER 15. TOOLS

In particular, the operator VectorAngleToRigid is useful to construct a rigid affine transformation from
the results of the matching operators (e.g., FindShapeModel or BestMatchRotMg), which transforms a
reference image to the current image or (if the parameters are passed in reverse order) from the current image to
the reference image.
HomMat2D can be used directly with operators that transform data using affine transformations, e.g.,
AffineTransImage.
Parameter

. Row1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; VARIANT ( real, integer )


Row coordinate of the original point.
. Column1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; VARIANT ( real, integer )
Column coordinate of the original point.
. Angle1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; VARIANT ( real, integer )
Angle of the original point.
. Row2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; VARIANT ( real, integer )
Row coordinate of the transformed point.
. Column2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; VARIANT ( real, integer )
Column coordinate of the transformed point.
. Angle2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; VARIANT ( real, integer )
Angle of the transformed point.
. HomMat2D (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )
Output transformation matrix.
Example

draw_rectangle2 (WindowID, RowTempl, ColumnTempl, PhiTempl, Length1, Length2)


gen_rectangle2 (Rectangle, RowTempl, ColumnTempl, PhiTempl, Length1, Length2)
reduce_domain (ImageTempl, Rectangle, ImageReduced)
create_template_rot (ImageReduced, 4, 0, rad(360), rad(1), ’sort’,
’original’, TemplateID)
while (true)
best_match_rot_mg (Image, TemplateID, 0, rad(360), 30, ’true’, 4, Row,
Column, Angle, ErrMatch)
if (ErrMatch<255)
vector_angle_to_rigid (Row, Column, Angle, RowTempl,
ColumnTempl, 0, HomMat2D)
affine_trans_image (Image, ImageAffinTrans, HomMat2D, ’constant’,
’false’)
endif
endwhile
clear_template (TemplateID)

Parallelization Information
VectorAngleToRigid is reentrant and processed without parallelization.
Possible Predecessors
BestMatchRotMg, BestMatchRot
Possible Successors
HomMat2dInvert, AffineTransImage, AffineTransRegion, AffineTransContourXld,
AffineTransPolygonXld, AffineTransPoint2D
See also
VectorFieldToHomMat2d
Alternatives
VectorToRigid
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


15.1. 2D-TRANSFORMATIONS 1049

HImageX.VectorFieldToHomMat2d ( )
[out] HHomMat2dX HomMat2D
void HHomMat2dX.VectorFieldToHomMat2d ([in] HImageX VectorField )
void HOperatorSetX.VectorFieldToHomMat2d
([in] IHObjectX VectorField, [out] VARIANT HomMat2D )

Approximate an affine map from a displacement vector field.


VectorFieldToHomMat2d approximates an affine map from the displacement vector field VectorField.
The affine map is returned in HomMat2D.
If the displacement vector field has been computed from the original image Iorig and the second image Ires ,
the internally stored transformation matrix (see AffineTransImage) contains a map that describes how to
transform the first image Iorig to the second image Ires .
Parameter
. VectorField (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( vector_field )
Input image.
. HomMat2D (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )
Output transformation matrix.
Parallelization Information
VectorFieldToHomMat2d is reentrant and processed without parallelization.
Possible Predecessors
OpticalFlowMg
Possible Successors
AffineTransImage
Alternatives
VectorToHomMat2d
Module
Foundation

void HHomMat2dX.VectorToHomMat2d ([in] VARIANT Px, [in] VARIANT Py,


[in] VARIANT Qx, [in] VARIANT Qy )
void HOperatorSetX.VectorToHomMat2d ([in] VARIANT Px, [in] VARIANT Py,
[in] VARIANT Qx, [in] VARIANT Qy, [out] VARIANT HomMat2D )

Approximate an affine transformation from point correspondences.


VectorToHomMat2d approximates an affine transformation from at least three point correspondences and re-
turns it as the homogeneous transformation matrix HomMat2D (see HomMat2dToAffinePar for the content
of the homogeneous transformation matrix).
The point correspondences are passed in the tuples (Px,Py) and (Qx,Qy), where corresponding points must be at
the same index positions in the tuples. If more than three point correspondences are passed the transformation
is overdetermined. In this case, the returned transformation is the transformation that minimizes the distances
between the input points (Px,Py) and the transformed points (Qx,Qy), as described in the following equation
(points as homogeneous vectors):

    2
X Qx[i] Px[i]


 Qy[i]  − HomMat2D ·  Py[i]  = minimum

i 1 1

HomMat2D can be used directly with operators that transform data using affine transformations, e.g.,
AffineTransImage.
Attention
It should be noted that homogeneous transformation matrices refer to a general right-handed mathematical coor-
dinate system. If a homogeneous transformation matrix is used to transform images, regions, XLD contours, or

HALCON 8.0.2
1050 CHAPTER 15. TOOLS

any other data that has been extracted from images, the row coordinates of the transformation must be passed in
the x coordinates, while the column coordinates must be passed in the y coordinates. Consequently, the order of
passing row and column coordinates follows the usual order (Row,Column). This convention is essential to obtain
a right-handed coordinate system for the transformation of iconic data, and consequently to ensure in particular
that rotations are performed in the correct mathematical direction.
Parameter

. Px (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; VARIANT ( real )


X coordinates of the original points.
. Py (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; VARIANT ( real )
Y coordinates of the original points.
. Qx (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; VARIANT ( real )
X coordinates of the transformed points.
. Qy (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; VARIANT ( real )
Y coordinates of the transformed points.
. HomMat2D (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )
Output transformation matrix.
Parallelization Information
VectorToHomMat2d is reentrant and processed without parallelization.
Possible Successors
AffineTransImage
See also
AffineTransImage, OpticalFlowMg
Alternatives
VectorFieldToHomMat2d
Module
Foundation

void HHomMat2dX.VectorToProjHomMat2d ([in] VARIANT Px,


[in] VARIANT Py, [in] VARIANT Qx, [in] VARIANT Qy, [in] String Method,
[in] VARIANT CovXX1, [in] VARIANT CovYY1, [in] VARIANT CovXY1,
[in] VARIANT CovXX2, [in] VARIANT CovYY2, [in] VARIANT CovXY2,
[out] VARIANT Covariance )
void HOperatorSetX.VectorToProjHomMat2d ([in] VARIANT Px,
[in] VARIANT Py, [in] VARIANT Qx, [in] VARIANT Qy, [in] VARIANT Method,
[in] VARIANT CovXX1, [in] VARIANT CovYY1, [in] VARIANT CovXY1,
[in] VARIANT CovXX2, [in] VARIANT CovYY2, [in] VARIANT CovXY2,
[out] VARIANT HomMat2D, [out] VARIANT Covariance )

Compute a projective transformation matrix using given point correspondences.


VectorToProjHomMat2d determines the homogeneous projective transformation matrix HomMat2D that op-
timally fulfills the following equations given by at least 4 point correspondences
  
Px Qx
HomMat2D ·  Py  =  Qy  .
1 1

If fewer than 4 pairs of points (Px,Py), (Qx,Qy) are given, there exists no unique solution, if exactly 4 pairs
are supplied the matrix HomMat2D transforms them in exactly the desired way, and if there are more than
4 point pairs given, VectorToProjHomMat2d seeks to minimize the transformation error. To achieve
such a minimization, several different algorithms are available. The algorithm to use can be chosen using
the parameter Method. Method=’dlt’ uses a fast and simple, but also rather inaccurate error estimation al-
gorithm while Method=’normalized_dlt’ offers a good compromise between speed and accuracy. Finally,
Method=’gold_standard’ performs a mathematically optimal but slower optimization.

HALCON/COM Reference Manual, 2008-5-13


15.1. 2D-TRANSFORMATIONS 1051

If ’gold_standard’ is used and the input points have been obtained from an operator like PointsFoerstner,
which provides a covariance matrix for each of the points, which specifies the accuracy of the points, this can be
taken into account by using the input parameters CovYY1, CovXX1, CovXY1 for the points in the first image and
CovYY2, CovXX2, CovXY2 for the points in the second image. The covariances are symmetric 2 × 2 matrices.
CovXX1/CovXX2 and CovYY1/CovYY2 are a list of diagonal entries while CovXY1/CovXY2 contains the non-
diagonal entries which appear twice in a symmetric matrix. If a different Method than ’gold_standard’ is used or
the covariances are unknown the covariance parameters can be left empty.
In contrast to HomVectorToProjHomMat2d, points at infinity cannot be used to determine the transformation
in VectorToProjHomMat2d. If this is necessary, HomVectorToProjHomMat2d must be used. If the
correspondence between the points has not been determined, ProjMatchPointsRansac should be used to
determine the correspondence as well as the transformation.
If the points to transform are specified in standard image coordinates, their row coordinates must be passed in Px
and their column coordinates in Py. This is necessary to obtain a right-handed coordinate system for the image. In
particular, this assures that rotations are performed in the correct direction. Note that the (x,y) order of the matrices
quite naturally corresponds to the usual (row,column) order for coordinates in the image.
Attention
It should be noted that homogeneous transformation matrices refer to a general right-handed mathematical coor-
dinate system. If a homogeneous transformation matrix is used to transform images, regions, XLD contours, or
any other data that has been extracted from images, the row coordinates of the transformation must be passed in
the x coordinates, while the column coordinates must be passed in the y coordinates. Consequently, the order of
passing row and column coordinates follows the usual order (Row,Column). This convention is essential to obtain
a right-handed coordinate system for the transformation of iconic data, and consequently to ensure in particular
that rotations are performed in the correct mathematical direction.
Parameter
. Px (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .point.x ; VARIANT ( real, integer )
Input points in image 1 (row coordinate).
. Py (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .point.y ; VARIANT ( real, integer )
Input points in image 1 (column coordinate).
. Qx (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; VARIANT ( real )
Input points in image 2 (row coordinate).
. Qy (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; VARIANT ( real )
Input points in image 2 (column coordinate).
. Method (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Estimation algorithm.
Default Value : ’normalized_dlt’
List of values : Method ∈ {’normalized_dlt’, ’gold_standard’, ’dlt’}
. CovXX1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Row coordinate variance of the points in image 1.
Default Value : []
. CovYY1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Column coordinate variance of the points in image 1.
Default Value : []
. CovXY1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Covariance of the points in image 1.
Default Value : []
. CovXX2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Row coordinate variance of the points in image 2.
Default Value : []
. CovYY2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Column coordinate variance of the points in image 2.
Default Value : []
. CovXY2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Covariance of the points in image 2.
Default Value : []
. HomMat2D (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )
Homogeneous projective transformation matrix.

HALCON 8.0.2
1052 CHAPTER 15. TOOLS

. Covariance (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )


9 × 9 covariance matrix of the projective transformation matrix.
Parallelization Information
VectorToProjHomMat2d is reentrant and processed without parallelization.
Possible Predecessors
ProjMatchPointsRansac, PointsFoerstner, PointsHarris
Possible Successors
ProjectiveTransImage, ProjectiveTransImageSize, ProjectiveTransRegion,
ProjectiveTransContourXld, ProjectiveTransPoint2D, ProjectiveTransPixel
Alternatives
HomVectorToProjHomMat2d, ProjMatchPointsRansac
References
Richard Hartley, Andrew Zisserman: “Multiple View Geometry in Computer Vision”; Cambridge University Press,
Cambridge; 2000.
Olivier Faugeras, Quang-Tuan Luong: “The Geometry of Multiple Images: The Laws That Govern the Formation
of Multiple Images of a Scene and Some of Their Applications”; MIT Press, Cambridge, MA; 2001.
Module
Calibration

void HHomMat2dX.VectorToRigid ([in] VARIANT Px, [in] VARIANT Py,


[in] VARIANT Qx, [in] VARIANT Qy )
void HOperatorSetX.VectorToRigid ([in] VARIANT Px, [in] VARIANT Py,
[in] VARIANT Qx, [in] VARIANT Qy, [out] VARIANT HomMat2D )

Approximate a rigid affine transformation from point correspondences.


VectorToRigid approximates a rigid affine transformation, i.e., a transformation consisting of a rotation and
a translation, from at least two point correspondences and returns it as the homogeneous transformation ma-
trix HomMat2D. The matrix consists of 2 components: a rotation matrix R and a translation vector t (also see
HomMat2dRotate and HomMat2dTranslate):
   
  1 0 0
R t t · R
HomMat2D = = 0 1 0  = H(t) · H(R)
00 1
0 0 1 00 1

The point correspondences are passed in the tuples (Px, Py) and (Qx,Qy), where corresponding points must be
at the same index positions in the tuples. The transformation is always overdetermined. Therefore, the returned
transformation is the transformation that minimizes the distances between the original points (Px,Py) and the
transformed points (Qx,Qy), as described in the following equation (points as homogeneous vectors):
    2
X Qx[i] Px[i]


 Qy[i]  − HomMat2D ·  Py[i]  = minimum

i 1 1

HomMat2D can be used directly with operators that transform data using affine transformations, e.g.,
AffineTransImage.
Attention
It should be noted that homogeneous transformation matrices refer to a general right-handed mathematical coor-
dinate system. If a homogeneous transformation matrix is used to transform images, regions, XLD contours, or
any other data that has been extracted from images, the row coordinates of the transformation must be passed in
the x coordinates, while the column coordinates must be passed in the y coordinates. Consequently, the order of
passing row and column coordinates follows the usual order (Row,Column). This convention is essential to obtain
a right-handed coordinate system for the transformation of iconic data, and consequently to ensure in particular
that rotations are performed in the correct mathematical direction.

HALCON/COM Reference Manual, 2008-5-13


15.1. 2D-TRANSFORMATIONS 1053

Parameter
. Px (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; VARIANT ( real )
X coordinates of the original points.
. Py (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; VARIANT ( real )
Y coordinates of the original points.
. Qx (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; VARIANT ( real )
X coordinates of the transformed points.
. Qy (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; VARIANT ( real )
Y coordinates of the transformed points.
. HomMat2D (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )
Output transformation matrix.
Parallelization Information
VectorToRigid is reentrant and processed without parallelization.
Possible Successors
AffineTransImage, AffineTransRegion, AffineTransContourXld,
AffineTransPolygonXld, AffineTransPoint2D
See also
VectorFieldToHomMat2d
Alternatives
VectorToHomMat2d, VectorToSimilarity
Module
Foundation

void HHomMat2dX.VectorToSimilarity ([in] VARIANT Px, [in] VARIANT Py,


[in] VARIANT Qx, [in] VARIANT Qy )
void HOperatorSetX.VectorToSimilarity ([in] VARIANT Px,
[in] VARIANT Py, [in] VARIANT Qx, [in] VARIANT Qy, [out] VARIANT HomMat2D )

Approximate an similarity transformation from point correspondences.


VectorToSimilarity approximates a similarity transformation, i.e., a transformation consisting of a uni-
form scaling, a rotation, and a translation, from at least two point correspondences and returns it as the homoge-
neous transformation matrix HomMat2D. The matrix consists of 3 components: a scaling matrix S with identical
scaling in th e x and y direction, a rotation matrix R, and a translation vector t (also see HomMat2dScale,
HomMat2dRotate, and HomMat2dTranslate):
     
  1 0 0 0
R·S t t   R · S
HomMat2D = = 0 1 · 0 0  = H(t) · H(R) · H(S)
0 0 1
0 0 1 00 1 00 1

The point correspondences are passed in the tuples (Px, Py) and (Qx,Qy), where corresponding points must be
at the same index positions in the tuples. If more than two point correspondences are passed the transformation
is overdetermined. In this case, the returned transformation is the transformation that minimizes the distances
between the original points (Px,Py) and the transformed points (Qx,Qy), as described in the following equation
(points as homogeneous vectors):
    2
X Qx[i] Px[i]


 Qy[i]  − HomMat2D ·  Py[i]  = minimum

i 1 1

HomMat2D can be used directly with operators that transform data using affine transformations, e.g.,
AffineTransImage.
Attention
It should be noted that homogeneous transformation matrices refer to a general right-handed mathematical coor-
dinate system. If a homogeneous transformation matrix is used to transform images, regions, XLD contours, or

HALCON 8.0.2
1054 CHAPTER 15. TOOLS

any other data that has been extracted from images, the row coordinates of the transformation must be passed in
the x coordinates, while the column coordinates must be passed in the y coordinates. Consequently, the order of
passing row and column coordinates follows the usual order (Row,Column). This convention is essential to obtain
a right-handed coordinate system for the transformation of iconic data, and consequently to ensure in particular
that rotations are performed in the correct mathematical direction.
Parameter

. Px (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; VARIANT ( real )


X coordinates of the original points.
. Py (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; VARIANT ( real )
Y coordinates of the original points.
. Qx (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; VARIANT ( real )
X coordinates of the transformed points.
. Qy (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; VARIANT ( real )
Y coordinates of the transformed points.
. HomMat2D (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )
Output transformation matrix.
Parallelization Information
VectorToSimilarity is reentrant and processed without parallelization.
Possible Successors
AffineTransImage, AffineTransRegion, AffineTransContourXld,
AffineTransPolygonXld, AffineTransPoint2D
See also
VectorFieldToHomMat2d
Alternatives
VectorToHomMat2d, VectorToRigid
Module
Foundation

15.2 3D-Transformations
[out] VARIANT Qx HHomMat3dX.AffineTransPoint3D ([in] VARIANT Px,
[in] VARIANT Py, [in] VARIANT Pz, [out] VARIANT Qy, [out] VARIANT Qz )
void HOperatorSetX.AffineTransPoint3D ([in] VARIANT HomMat3D,
[in] VARIANT Px, [in] VARIANT Py, [in] VARIANT Pz, [out] VARIANT Qx,
[out] VARIANT Qy, [out] VARIANT Qz )

Apply an arbitrary affine 3D transformation to points.


AffineTransPoint3D applies an arbitrary affine 3D transformation, i.e., scaling, rotation, and translation, to
the input points (Px,Py,Pz) and returns the resulting points in (Qx, Qy,Qz). The affine transformation is described
by the homogeneous transformation matrix given in HomMat3D. This corresponds to the following equation (input
and output points as homogeneous vectors):
   
Qx Px
 Qy   Py 
 Qz  = HomMat3D · 
   
Pz 
1 1

The transformation matrix can be created using the operators HomMat3dIdentity, HomMat3dScale,
HomMat3dRotate, HomMat3dTranslate, etc., or be the result of PoseToHomMat3d.
For example, if HomMat3D corresponds to a rigid transformation, i.e., if it consists of a rotation and a translation,
the points are transformed as follows:

HALCON/COM Reference Manual, 2008-5-13


15.2. 3D-TRANSFORMATIONS 1055

       
Qx   Px Px
 Qy  R t  Py   R· Py  + t 
  =
 Qz  ·
 Pz  = 
  
000 1 Pz 
1 1 1

Parameter

. HomMat3D (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . hom_mat3d ; HHomMat3dX / VARIANT ( real )


Input transformation matrix.
. Px (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point3d.x(-array) ; VARIANT ( real, integer )
Input point(s) (x coordinate).
Default Value : 64
Suggested values : Px ∈ {0, 16, 32, 64, 128, 256, 512, 1024}
. Py (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point3d.y(-array) ; VARIANT ( real, integer )
Input point(s) (y coordinate).
Default Value : 64
Suggested values : Py ∈ {0, 16, 32, 64, 128, 256, 512, 1024}
. Pz (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point3d.z(-array) ; VARIANT ( real, integer )
Input point(s) (z coordinate).
Default Value : 64
Suggested values : Pz ∈ {0, 16, 32, 64, 128, 256, 512, 1024}
. Qx (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point3d.x(-array) ; VARIANT ( real )
Output point(s) (x coordinate).
. Qy (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point3d.y(-array) ; VARIANT ( real )
Output point(s) (y coordinate).
. Qz (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point3d.z(-array) ; VARIANT ( real )
Output point(s) (z coordinate).
Result
If the parameters are valid, the operator AffineTransPoint3D returns TRUE. If necessary, an exception is
raised.
Parallelization Information
AffineTransPoint3D is reentrant and processed without parallelization.
Possible Predecessors
HomMat3dTranslate, HomMat3dTranslateLocal, HomMat3dScale, HomMat3dScaleLocal,
HomMat3dRotate, HomMat3dRotateLocal
Possible Successors
HomMat3dTranslate, HomMat3dTranslateLocal, HomMat3dScale, HomMat3dScaleLocal,
HomMat3dRotate, HomMat3dRotateLocal
Module
Foundation

[out] VARIANT PoseOut HPoseX.ConvertPoseType ([in] VARIANT PoseIn,


[in] String OrderOfTransform, [in] String OrderOfRotation,
[in] String ViewOfTransform )
void HOperatorSetX.ConvertPoseType ([in] VARIANT PoseIn,
[in] VARIANT OrderOfTransform, [in] VARIANT OrderOfRotation,
[in] VARIANT ViewOfTransform, [out] VARIANT PoseOut )

Change the representation type of a 3D pose.


ConvertPoseType converts the 3D pose PoseIn into a 3D pose PoseOut with a different representation
type. See CreatePose for details about 3D poses, their representation types, and the meaning of the parameters
OrderOfTransform, OrderOfRotation, and ViewOfTransform.

HALCON 8.0.2
1056 CHAPTER 15. TOOLS

Note that ConvertPoseType only changes the representation of a 3D pose, but not the rigid transformation
described by the pose.
Parameter
. PoseIn (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pose ; VARIANT ( integer, real )
Original 3D pose.
Number of elements : 7
. OrderOfTransform (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Order of rotation and translation.
Default Value : ’Rp+T’
Suggested values : OrderOfTransform ∈ {’Rp+T’, ’R(p-T)’}
. OrderOfRotation (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Meaning of the rotation values.
Default Value : ’gba’
Suggested values : OrderOfRotation ∈ {’gba’, ’abg’, ’rodriguez’}
. ViewOfTransform (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
View of transformation.
Default Value : ’point’
Suggested values : ViewOfTransform ∈ {’point’, ’coordinate_system’}
. PoseOut (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pose ; VARIANT ( integer, real )
3D transformation.
Number of elements : 7
Example

* get pose (exterior camera parameters):


read_pose (’campose.dat’, Pose)
* convert pose to a pose with desired semantic
convert_pose_type (Pose, ’Rp+T’, ’abg’, ’point’, Pose2)

Result
ConvertPoseType returns TRUE if all parameter values are correct. If necessary, an exception handling is
raised.
Parallelization Information
ConvertPoseType is reentrant and processed without parallelization.
Possible Predecessors
CreatePose, HomMat3dToPose, CameraCalibration, HandEyeCalibration
Possible Successors
WritePose
See also
CreatePose, GetPoseType, WritePose, ReadPose
Module
Foundation

[out] VARIANT Pose HPoseX.CreatePose ([in] double TransX,


[in] double TransY, [in] double TransZ, [in] double RotX, [in] double RotY,
[in] double RotZ, [in] String OrderOfTransform, [in] String OrderOfRotation,
[in] String ViewOfTransform )
void HOperatorSetX.CreatePose ([in] VARIANT TransX,
[in] VARIANT TransY, [in] VARIANT TransZ, [in] VARIANT RotX,
[in] VARIANT RotY, [in] VARIANT RotZ, [in] VARIANT OrderOfTransform,
[in] VARIANT OrderOfRotation, [in] VARIANT ViewOfTransform,
[out] VARIANT Pose )

Create a 3D pose.

HALCON/COM Reference Manual, 2008-5-13


15.2. 3D-TRANSFORMATIONS 1057

CreatePose creates the 3D pose Pose. A pose describes a rigid 3D transformation, i.e., a transformation
consisting of an arbitrary translation and rotation, with 6 parameters: TransX, TransY, and TransZ specify the
translation along the x-, y-, and z-axis, respectively, while RotX, RotY, and RotZ describe the rotation.
3D poses are typically used in two ways: First, to describe the position and orientation of one coordinate system
relative to another (e.g., the pose of a part’s coordinate system relative to the camera coordinate system - in short:
the pose of the part relative to the camera) and secondly, to describe how coordinates can be transformed between
two coordinate systems (e.g., to transform points from part coordinates into camera coordinates).

Representation of orientation (rotation)


A 3D rotation around an arbitrary axis can be represented by 3 parameters in multiple ways. HALCON lets you
choose between three of them with the parameter OrderOfRotation: If you pass the value ’gba’, the rotation
is described by the following chain of rotations around the three axes (see HomMat3dRotate for the content for
the rotation matrices Rx , Ry , and Rz ):

Rgba = Rx (RotX) · Ry (RotY) · Rz (RotZ)

Please note that you can “read” this chain in two ways: If you start from the right, the rotations are always
performed relative to the global (i.e., fixed or “old”) coordinate system. Thus, Rgba can be read as follows: First
rotate around the z-axis, then around the “old” y-axis, and finally around the “old” x-axis. In contrast, if you read
from the left to the right, the rotations are performed relative to the local (i.e., “new”) coordinate system. Then,
Rgba corresponds to the following: First rotate around the x-axis, the around the “new” y-axis, and finally around
the “new(est)” z-axis.
Reading Rgba from right to left corresponds to the following sequence of operator calls:
hom_mat3d_identity (HomMat3DIdent)
hom_mat3d_rotate (HomMat3DIdent, RotZ, ’z’, 0, 0, 0, HomMat3DRotZ)
hom_mat3d_rotate (HomMat3DRotZ, RotY, ’y’, 0, 0, 0, HomMat3DRotYZ)
hom_mat3d_rotate (HomMat3DRotYZ, RotX, ’x’, 0, 0, 0, HomMat3DXYZ)

In contrast, reading from left to right corresponds to the following operator sequence:
hom_mat3d_identity (HomMat3DIdent)
hom_mat3d_rotate_local (HomMat3DIdent, RotX, ’x’, 0, 0, 0,
HomMat3DRotX)
hom_mat3d_rotate_local (HomMat3DRotX, RotY, ’y’, 0, 0, 0,
HomMat3DRotXY)
hom_mat3d_rotate_local (HomMat3DRotXY, RotZ, ’z’, 0, 0, 0, HomMat3DXYZ)

When passing ’abg’ in OrderOfRotation, the rotation corresponds to the following chain:

Rabg = Rz (RotZ) · Ry (RotY) · Rx (RotX)

If you pass ’rodriguez’ in OrderOfRotation, the rotation parameters RotX, RotY, and RotZ are interpreted
as the x-, y-, and z-component of the so-called Rodriguez rotation vector. The direction of the vector defines the
(arbitrary) axis of rotation. The length of the vector usually defines the rotation angle with positive orientation.
Here, a variation of the Rodriguez vector is used, where the length of the vector defines the tangent of half the
rotation angle:
 
RotX p
Rrodriguez = rotate around  RotY  by 2 · arctan( RotX2 + RotY2 + RotZ2 )
RotZ

Corresponding homogeneous transformation matrix


You can obtain the homogeneous transformation matrix corresponding to a pose with the operator
PoseToHomMat3d. In the standard definition, this is the following homogeneous transformation matrix which
can be split into two separate matrices, one for the translation (H(t)) and one for the rotation (H(R)):

HALCON 8.0.2
1058 CHAPTER 15. TOOLS

 
  TransX
R t  R(RotX, RotY, RotZ) TransY 
Hpose = = =
000 1  TransZ 
0 0 0 1
   
1 0 0 TransX 0
 0 1 0 TransY  0 
 ·  R(RotX, RotY, RotZ)

=   = H(t) · H(R)
 0 0 1 TransZ   0 
0 0 0 1 0 0 0 1

Transformation of coordinates
The following equation describes how a point can be transformed from coordinate system 1 into coordinate sys-
tem 2 with a pose, or more exactly, with the corresponding homogeneous transformation matrix 2 H1 (input and
output points as homogeneous vectors, see also AffineTransPoint3D). Note that to transform points from
coordinate system 1 into system 2, you use the transformation matrix that describes the pose of coordinate system
1 relative to system 2.
   
TransX
p2 p1
   
 R(RotX, RotY, RotZ) · p1 +  TransY  
= 2 H1 · = 
1 1  TransZ 
1

This corresponds to the following operator calls:


pose_to_hom_mat3d(PoseOf1In2, HomMat3DFrom1In2)
affine_trans_point_3d(HomMat3DFrom1In2, P1X, P1Y, P1Z, P2X, P2Y, P2Z)

Non-standard pose definitions


So far, we described the standard pose definition. To create such poses, you select the (default) values ’Rp+T’
for the parameter OrderOfTransform and ’point’ for ViewOfTransform. By specifying other values for
these parameters, you can create non-standard poses types which we describe briefly below. Please note that these
representation types are only supported for backwards compatibility; we strongly recommend to use the standard
types.
If you select ’R(p-T)’ for OrderOfTransform, the created pose corresponds to the following chain of transfor-
mations, i.e., the sequence of rotation and translation is reversed and the translation is negated:

   
0 1 0 0 −TransX
 R(RotX, RotY, RotZ) 0   0 1 0
  −TransY 
HR(p−T ) =  ·  = H(R) · H(−t)
 0   0 0 1 −TransZ 
0 0 0 1 0 0 0 1

If you select ’coordinate_system’ for ViewOfTransform, the sequence of transformations remains constant,
but the rotation angles are negated. Please note that, contrary to its name, this is not equivalent to transforming a
coordinate system!

   
1 0 0 TransX 0
 0 1 0
 ·  R(−RotX, −RotY, −RotZ)
TransY  0
 
Hcoordinate_system = 
 0 0 1

TransZ   0 
0 0 0 1 0 0 0 1

HALCON/COM Reference Manual, 2008-5-13


15.2. 3D-TRANSFORMATIONS 1059

Returned data structure


The created 3D pose is returned in Pose which is a tuple of length seven. The first three elements hold the
translation parameters TransX, TransY, and TransZ, followed by the rotation parameters RotX, RotY,
and RotZ. The last element codes the representation type of the pose that you selected with the parameters
OrderOfTransform, OrderOfRotation, and ViewOfTransform. The following table lists the possible
combinations. As already noted, we recommend to use only the representation types with OrderOfTransform
= ’Rp+T’ and ViewOfTransform = ’point’ (codes 0, 2, and 4).

OrderOfTransform OrderOfRotation ViewOfTransform Code


’Rp+T’ ’gba’ ’point’ 0
’Rp+T’ ’abg’ ’point’ 2
’Rp+T’ ’rodriguez’ ’point’ 4
’Rp+T’ ’gba’ ’coordinate_system’ 1
’Rp+T’ ’abg’ ’coordinate_system’ 3
’Rp+T’ ’rodriguez’ ’coordinate_system’ 5
’R(p-T)’ ’gba’ ’point’ 8
’R(p-T)’ ’abg’ ’point’ 10
’R(p-T)’ ’rodriguez’ ’point’ 12
’R(p-T)’ ’gba’ ’coordinate_system’ 9
’R(p-T)’ ’abg’ ’coordinate_system’ 11
’R(p-T)’ ’rodriguez’ ’coordinate_system’ 13

You can convert poses into other representation types using ConvertPoseType and query the type using
GetPoseType.
Parameter

. TransX (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT


Translation along the x-axis (in [m]).
Default Value : 0.1
Suggested values : TransX ∈ {-1.0, -0.75, -0.5, -0.25, -0.2, -0.1, -0.5, -0.25, -0.125, -0.01, 0, 0.01, 0.125,
0.25, 0.5, 0.1, 0.2, 0.25, 0.5, 0.75, 1.0}
. TransY (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Translation along the y-axis (in [m]).
Default Value : 0.1
Suggested values : TransY ∈ {-1.0, -0.75, -0.5, -0.25, -0.2, -0.1, -0.5, -0.25, -0.125, -0.01, 0, 0.01, 0.125,
0.25, 0.5, 0.1, 0.2, 0.25, 0.5, 0.75, 1.0}
. TransZ (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Translation along the z-axis (in [m]).
Default Value : 0.1
Suggested values : TransZ ∈ {-1.0, -0.75, -0.5, -0.25, -0.2, -0.1, -0.5, -0.25, -0.125, -0.01, 0, 0.01, 0.125,
0.25, 0.5, 0.1, 0.2, 0.25, 0.5, 0.75, 1.0}
. RotX (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Rotation around x-axis or x component of the Rodriguez vector (in [◦ ] or without unit).
Default Value : 90
Suggested values : RotX ∈ {90, 180, 270}
Typical range of values : 0 ≤ RotX ≤ 0
. RotY (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Rotation around y-axis or y component of the Rodriguez vector (in [◦ ] or without unit).
Default Value : 90
Suggested values : RotY ∈ {90, 180, 270}
Typical range of values : 0 ≤ RotY ≤ 0
. RotZ (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Rotation around z-axis or z component of the Rodriguez vector (in [◦ ] or without unit).
Default Value : 90
Suggested values : RotZ ∈ {90, 180, 270}
Typical range of values : 0 ≤ RotZ ≤ 0

HALCON 8.0.2
1060 CHAPTER 15. TOOLS

. OrderOfTransform (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT


Order of rotation and translation.
Default Value : ’Rp+T’
Suggested values : OrderOfTransform ∈ {’Rp+T’, ’R(p-T)’}
. OrderOfRotation (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Meaning of the rotation values.
Default Value : ’gba’
Suggested values : OrderOfRotation ∈ {’gba’, ’abg’, ’rodriguez’}
. ViewOfTransform (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
View of transformation.
Default Value : ’point’
Suggested values : ViewOfTransform ∈ {’point’, ’coordinate_system’}
. Pose (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pose ; VARIANT ( integer, real )
3D pose.
Number of elements : 7
Example

* goal: calibration with non-standard calibration object


* read start values for interior camera parameters
read_cam_par(’campar.dat’, CamParam)
* (read 3D world points [WorldPointsX,WorldPointsY,WorldPointsZ],
* extract corresponding 2D image points [PixelsRow,PixelsColumn])
* task: create starting value for the exterior camera parameters, i.e., the
* pose of the calibration object in the calibration images
* first image: calibration object placed at a distance of 0.5 and 0.1
* ’below’ the camera coordinate system
* orientation ’read from left to right’: rotated 30 degrees
* around the optical axis of the camera (z-axis),
* then tilted 10 degrees around the new y-axis
create_pose(0.1, 0.0, 0.5, 30, 10, 0, ’Rp+T’, ’abg’, ’point’, StartPose1)
* (accumulate all poses in StartPoses = [StartPose1, StartPose2, ...])
* perform the calibration
camera_calibration(WorldPointsX, WorldPointsY, WorldPointsZ,
PixelsRow, PixelsColumn, CamParam, StartPoses, ’pose’,
FinalCamParam, FinalPoses, Errors)

Result
CreatePose returns TRUE if all parameter values are correct. If necessary, an exception handling is raised.
Parallelization Information
CreatePose is reentrant and processed without parallelization.
Possible Successors
PoseToHomMat3d, WritePose, CameraCalibration, HandEyeCalibration
See also
HomMat3dRotate, HomMat3dTranslate, ConvertPoseType, GetPoseType, HomMat3dToPose,
PoseToHomMat3d, WritePose, ReadPose
Alternatives
ReadPose, HomMat3dToPose
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


15.2. 3D-TRANSFORMATIONS 1061

[out] String OrderOfTransform HPoseX.GetPoseType ([in] VARIANT Pose,


[out] String OrderOfRotation, [out] String ViewOfTransform )
void HOperatorSetX.GetPoseType ([in] VARIANT Pose,
[out] VARIANT OrderOfTransform, [out] VARIANT OrderOfRotation,
[out] VARIANT ViewOfTransform )

Get the representation type of a 3D pose.


With GetPoseType, the representation type of the 3D pose Pose can be queried. See CreatePose for
details about 3D poses, their representation types, and the meaning of the parameters OrderOfTransform,
OrderOfRotation, and ViewOfTransform.
Parameter

. Pose (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pose ; VARIANT ( integer, real )


3D pose.
Number of elements : 7
. OrderOfTransform (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Order of rotation and translation.
. OrderOfRotation (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Meaning of the rotation values.
. ViewOfTransform (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
View of transformation.
Result
CreatePose returns TRUE if all parameter values are correct. If necessary, an exception handling is raised.
Parallelization Information
GetPoseType is reentrant and processed without parallelization.
Possible Predecessors
CreatePose, HomMat3dToPose, CameraCalibration, HandEyeCalibration
Possible Successors
ConvertPoseType
See also
CreatePose, ConvertPoseType, WritePose, ReadPose
Module
Foundation

[out] HHomMat3dX HomMat3DCompose HHomMat3dX.HomMat3dCompose


([in] HHomMat3dX HomMat3DRight )
void HOperatorSetX.HomMat3dCompose ([in] VARIANT HomMat3DLeft,
[in] VARIANT HomMat3DRight, [out] VARIANT HomMat3DCompose )

Multiply two homogeneous 3D transformation matrices.


HomMat3dCompose composes a new 3D transformation matrix by multiplying the two input matrices:

HomMat3DCompose = HomMat3DLeft · HomMat3DRight

For example, if the two input matrices correspond to rigid transformations, i.e., to transformations consisting of a
rotation and a translation, the resulting matrix is calculated as follows:
     
Rl tl Rr tr Rl · Rr Rl ·tr + tl
HomMat3DCompose = · =
000 1 000 1 0 0 0 1

HALCON 8.0.2
1062 CHAPTER 15. TOOLS

Parameter
. HomMat3DLeft (input control) . . . . . . . . . . . . . . . . . . . . . . hom_mat3d ; HHomMat3dX / VARIANT ( real )
Left input transformation matrix.
. HomMat3DRight (input control) . . . . . . . . . . . . . . . . . . . . . hom_mat3d ; HHomMat3dX / VARIANT ( real )
Right input transformation matrix.
. HomMat3DCompose (output control) . . . . . . . . . . . . . . . . . hom_mat3d ; HHomMat3dX / VARIANT ( real )
Output transformation matrix.
Result
If the parameters are valid, the operator HomMat3dCompose returns TRUE. If necessary, an exception is raised.
Parallelization Information
HomMat3dCompose is reentrant and processed without parallelization.
Possible Predecessors
HomMat3dCompose, HomMat3dTranslate, HomMat3dTranslateLocal, HomMat3dScale,
HomMat3dScaleLocal, HomMat3dRotate, HomMat3dRotateLocal, PoseToHomMat3d
Possible Successors
HomMat3dTranslate, HomMat3dTranslateLocal, HomMat3dScale, HomMat3dScaleLocal,
HomMat3dRotate, HomMat3dRotateLocal
See also
AffineTransPoint3D, HomMat3dIdentity, HomMat3dRotate, HomMat3dTranslate,
PoseToHomMat3d, HomMat3dToPose
Module
Foundation

void HHomMat3dX.HomMat3dIdentity ( )
void HOperatorSetX.HomMat3dIdentity ([out] VARIANT HomMat3DIdentity )

Generate the homogeneous transformation matrix of the identical 3D transformation.


HomMat3dIdentity generates the homogeneous transformation matrix HomMat3DIdentity describing the
identical 3D transformation:
 
1 0 0 0
 0 1 0 0 
HomMat3DIdentity =   0 0 1 0 

0 0 0 1

Attention
Note that homogeneous matrices are stored row-by-row as a tuple; the last row is not stored because it is identical
for all homogeneous matrices that describe an affine transformation. Thus, HomMat3DIdentity is stored as the
tuple [1,0,0,0,0,1,0,0,0,0,1,0].
Parameter
. HomMat3DIdentity (output control) . . . . . . . . . . . . . . . . hom_mat3d ; HHomMat3dX / VARIANT ( real )
Transformation matrix.
Result
HomMat3dIdentity always returns TRUE.
Parallelization Information
HomMat3dIdentity is reentrant and processed without parallelization.
Possible Successors
HomMat3dTranslate, HomMat3dTranslateLocal, HomMat3dScale, HomMat3dScaleLocal,
HomMat3dRotate, HomMat3dRotateLocal
Alternatives
PoseToHomMat3d
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


15.2. 3D-TRANSFORMATIONS 1063

HHomMat3dX.HomMat3dInvert ( )
[out] HHomMat3dX HomMat3DInvert
void HOperatorSetX.HomMat3dInvert ([in] VARIANT HomMat3D,
[out] VARIANT HomMat3DInvert )

Invert a homogeneous 3D transformation matrix.


HomMat3dInvert inverts the homogeneous 3D transformation matrix given by HomMat3D. The resulting ma-
trix is returned in HomMat3DInvert.
Parameter
. HomMat3D (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . hom_mat3d ; HHomMat3dX / VARIANT ( real )
Input transformation matrix.
. HomMat3DInvert (output control) . . . . . . . . . . . . . . . . . . hom_mat3d ; HHomMat3dX / VARIANT ( real )
Output transformation matrix.
Result
HomMat3dInvert returns TRUE if the parameters are valid and the input matrix is invertible. Otherwise, an
exception is raised.
Parallelization Information
HomMat3dInvert is reentrant and processed without parallelization.
Possible Predecessors
HomMat3dTranslate, HomMat3dTranslateLocal, HomMat3dScale, HomMat3dScaleLocal,
HomMat3dRotate, HomMat3dRotateLocal, PoseToHomMat3d
Possible Successors
HomMat3dTranslate, HomMat3dTranslateLocal, HomMat3dScale, HomMat3dScaleLocal,
HomMat3dRotate, HomMat3dRotateLocal, HomMat3dToPose
See also
AffineTransPoint3D, HomMat3dIdentity, HomMat3dRotate, HomMat3dTranslate,
PoseToHomMat3d, HomMat3dToPose, HomMat3dCompose
Module
Foundation

[out] HHomMat3dX HomMat3DRotate HHomMat3dX.HomMat3dRotate


([in] VARIANT Phi, [in] VARIANT Axis, [in] VARIANT Px, [in] VARIANT Py,
[in] VARIANT Pz )
void HOperatorSetX.HomMat3dRotate ([in] VARIANT HomMat3D,
[in] VARIANT Phi, [in] VARIANT Axis, [in] VARIANT Px, [in] VARIANT Py,
[in] VARIANT Pz, [out] VARIANT HomMat3DRotate )

Add a rotation to a homogeneous 3D transformation matrix.


HomMat3dRotate adds a rotation by the angle Phi around the axis passed in the parameter Axis to the homo-
geneous 3D transformation matrix HomMat3D and returns the resulting matrix in HomMat3DRotate. The axis
can by specified by passing the strings ’x’, ’y’, or ’z’, or by passing a vector [x,y,z] as a tuple.
The rotation is decribed by a 3×3 rotation matrix R. It is performed relative to the global (i.e., fixed) coordinate
system; this corresponds to the following chain of transformation matrices:
Axis = ’x’:
 
0  
1 0 0
 Rx 0 
HomMat3DRotate =   · HomMat3D Rx =  0 cos(Phi) − sin(Phi) 
 0 
0 sin(Phi) cos(Phi)
000 1

Axis = ’y’:
 
0  
cos(Phi) 0 sin(Phi)
 Ry 0 
 · HomMat3D
HomMat3DRotate =  Ry =  0 1 0 
 0 
− sin(Phi) 0 cos(Phi)
000 1

HALCON 8.0.2
1064 CHAPTER 15. TOOLS

Axis = ’z’:
 
0  
cos(Phi) − sin(Phi) 0
 Rz 0 
 · HomMat3D
HomMat3DRotate =  Rz =  sin(Phi) cos(Phi) 0 
 0 
0 0 1
000 1

Axis = [x,y,z]:
 
0
 Ra 0 
HomMat3DRotate =   · HomMat3D Ra = u · uT + cos(Phi) · (I − u · uT ) + sin(Phi) · S
 0 
000 1

x0 −z 0 y0
     
1 0 0 0
Axis
u= =  y0  I= 0 1 0  S =  z0 0 −x0 
kAxisk
z0 0 0 1 −y 0 x0 0
The point (Px,Py,Pz) is the fixed point of the transformation, i.e., this point remains unchanged when transformed
using HomMat3DRotate. To obtain this behavior, first a translation is added to the input transformation matrix
that moves the fixed point onto the origin of the global coordinate system. Then, the rotation is added, and finally
a translation that moves the fixed point back to its original position. This corresponds to the following chain of
transformations:
     
1 0 0 +Px 0 1 0 0 −Px
 ·  0 1 0 −Py  · HomMat3D
 0 1 0 +Py   R 0   
HomMat3DRotate =   0 0 1 +Pz  · 
 
0   0 0 1 −Pz 
0 0 0 1 000 1 0 0 0 1

To perform the transformation in the local coordinate system, i.e., the one described by HomMat3D, use
HomMat3dRotateLocal.
Attention
Note that homogeneous matrices are stored row-by-row as a tuple; the last row is not stored because it is identical
for all homogeneous matrices that describe an affine transformation. For example, the homogeneous matrix
 
ra rb rc td
 re rf rg th 
 
 ri rj rk tl 
0 0 0 1
is stored as the tuple [ra, rb, rc, td, re, rf, rg, th, ri, rj, rk, tl].
Parameter
. HomMat3D (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . hom_mat3d ; HHomMat3dX / VARIANT ( real )
Input transformation matrix.
. Phi (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; VARIANT ( real, integer )
Rotation angle.
Default Value : 0.78
Suggested values : Phi ∈ {0.1, 0.2, 0.3, 0.4, 0.78, 1.57, 3.14}
Typical range of values : 0 ≤ Phi ≤ 0
. Axis (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string, real, integer )
Axis, to be rotated around.
Default Value : ’x’
Suggested values : Axis ∈ {’x’, ’y’, ’z’}
. Px (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point3d.x ; VARIANT ( real, integer )
Fixed point of the transformation (x coordinate).
Default Value : 0
Suggested values : Px ∈ {0, 16, 32, 64, 128, 256, 512, 1024}
. Py (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point3d.y ; VARIANT ( real, integer )
Fixed point of the transformation (y coordinate).
Default Value : 0
Suggested values : Py ∈ {0, 16, 32, 64, 128, 256, 512, 1024}

HALCON/COM Reference Manual, 2008-5-13


15.2. 3D-TRANSFORMATIONS 1065

. Pz (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point3d.z ; VARIANT ( real, integer )


Fixed point of the transformation (z coordinate).
Default Value : 0
Suggested values : Pz ∈ {0, 16, 32, 64, 128, 256, 512, 1024}
. HomMat3DRotate (output control) . . . . . . . . . . . . . . . . . . hom_mat3d ; HHomMat3dX / VARIANT ( real )
Output transformation matrix.
Result
If the parameters are valid, the operator HomMat3dRotate returns TRUE. If necessary, an exception is raised.
Parallelization Information
HomMat3dRotate is reentrant and processed without parallelization.
Possible Predecessors
HomMat3dIdentity, HomMat3dTranslate, HomMat3dScale, HomMat3dRotate
Possible Successors
HomMat3dTranslate, HomMat3dScale, HomMat3dRotate
See also
HomMat3dInvert, HomMat3dIdentity, HomMat3dRotateLocal, PoseToHomMat3d,
HomMat3dToPose, HomMat3dCompose
Module
Foundation

[out] HHomMat3dX HomMat3DRotate HHomMat3dX.HomMat3dRotateLocal


([in] VARIANT Phi, [in] VARIANT Axis )
void HOperatorSetX.HomMat3dRotateLocal ([in] VARIANT HomMat3D,
[in] VARIANT Phi, [in] VARIANT Axis, [out] VARIANT HomMat3DRotate )

Add a rotation to a homogeneous 3D transformation matrix.


HomMat3dRotateLocal adds a rotation by the angle Phi around the axis passed in the parameter Axis to the
homogeneous 3D transformation matrix HomMat3D and returns the resulting matrix in HomMat3DRotate. The
axis can by specified by passing the strings ’x’, ’y’, or ’z’, or by passing a vector [x,y,z] as a tuple.
The rotation is decribed by a 3×3 rotation matrix R. In contrast to HomMat3dRotate, it is performed relative to
the local coordinate system, i.e., the coordinate system described by HomMat3D; this corresponds to the following
chain of transformation matrices:
Axis = ’x’:
 
0  
1 0 0
 Rx 0 
HomMat3DRotate = HomMat3D ·   Rx =  0 cos(Phi) − sin(Phi) 
 0 
0 sin(Phi) cos(Phi)
000 1
Axis = ’y’:
 
0  
cos(Phi) 0 sin(Phi)
 Ry 0 
HomMat3DRotate = HomMat3D ·   Ry =  0 1 0 
 0 
− sin(Phi) 0 cos(Phi)
000 1
Axis = ’z’:
 
0  
cos(Phi) − sin(Phi) 0
 Rz 0 
HomMat3DRotate = HomMat3D ·   Rz =  sin(Phi) cos(Phi) 0 
 0 
0 0 1
000 1
Axis = [x,y,z]:
 
0
 Ra 0 
HomMat3DRotate = HomMat3D ·   Ra = u · uT + cos(Phi) · (I − u · uT ) + sin(Phi) · S
 0 
000 1

HALCON 8.0.2
1066 CHAPTER 15. TOOLS

 0 
−z 0 y0
   
x 1 0 0 0
Axis
u= =  y0  I= 0 1 0  S =  z0 0 −x0 
kAxisk
z0 0 0 1 −y 0 x0 0

The fixed point of the transformation is the origin of the local coordinate system, i.e., this point remains unchanged
when transformed using HomMat3DRotate.
Attention
Note that homogeneous matrices are stored row-by-row as a tuple; the last row is not stored because it is identical
for all homogeneous matrices that describe an affine transformation. For example, the homogeneous matrix
 
ra rb rc td
 re rf rg th 
 
 ri rj rk tl 
0 0 0 1
is stored as the tuple [ra, rb, rc, td, re, rf, rg, th, ri, rj, rk, tl].
Parameter

. HomMat3D (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . hom_mat3d ; HHomMat3dX / VARIANT ( real )


Input transformation matrix.
. Phi (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; VARIANT ( real, integer )
Rotation angle.
Default Value : 0.78
Suggested values : Phi ∈ {0.1, 0.2, 0.3, 0.4, 0.78, 1.57, 3.14}
Typical range of values : 0 ≤ Phi ≤ 0
. Axis (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string, real, integer )
Axis, to be rotated around.
Default Value : ’x’
Suggested values : Axis ∈ {’x’, ’y’, ’z’}
. HomMat3DRotate (output control) . . . . . . . . . . . . . . . . . . hom_mat3d ; HHomMat3dX / VARIANT ( real )
Output transformation matrix.
Result
If the parameters are valid, the operator HomMat3dRotateLocal returns TRUE. If necessary, an exception is
raised.
Parallelization Information
HomMat3dRotateLocal is reentrant and processed without parallelization.
Possible Predecessors
HomMat3dIdentity, HomMat3dTranslateLocal, HomMat3dScaleLocal,
HomMat3dRotateLocal
Possible Successors
HomMat3dTranslateLocal, HomMat3dScaleLocal, HomMat3dRotateLocal
See also
HomMat3dInvert, HomMat3dIdentity, HomMat3dRotate, PoseToHomMat3d, HomMat3dToPose,
HomMat3dCompose
Module
Foundation

[out] HHomMat3dX HomMat3DScale HHomMat3dX.HomMat3dScale


([in] VARIANT Sx, [in] VARIANT Sy, [in] VARIANT Sz, [in] VARIANT Px,
[in] VARIANT Py, [in] VARIANT Pz )
void HOperatorSetX.HomMat3dScale ([in] VARIANT HomMat3D,
[in] VARIANT Sx, [in] VARIANT Sy, [in] VARIANT Sz, [in] VARIANT Px,
[in] VARIANT Py, [in] VARIANT Pz, [out] VARIANT HomMat3DScale )

Add a scaling to a homogeneous 3D transformation matrix.

HALCON/COM Reference Manual, 2008-5-13


15.2. 3D-TRANSFORMATIONS 1067

HomMat3dScale adds a scaling by the scale factors Sx, Sy, and Sz to the homogeneous 3D transformation
matrix HomMat3D and returns the resulting matrix in HomMat3DScale. The scaling is described by a 3×3
scaling matrix S. It is performed relative to the global (i.e., fixed) coordinate system; this corresponds to the
following chain of transformation matrices:
 
0  
Sx 0 0
 S 0 
 · HomMat3D
HomMat3DScale =  S= 0 Sy 0 
 0 
0 0 Sz
000 1

The point (Px,Py,Pz) is the fixed point of the transformation, i.e., this point remains unchanged when transformed
using HomMat3DScale. To obtain this behavior, first a translation is added to the input transformation matrix
that moves the fixed point onto the origin of the global coordinate system. Then, the scaling is added, and finally
a translation that moves the fixed point back to its original position. This corresponds to the following chain of
transformations:
     
1 0 0 +Px 0 1 0 0 −Px
 ·  0 1 0 −Py  · HomMat3D
 0 1 0 +Py   S 0   
HomMat3DScale =   0 0 1 +Pz  · 
 
0   0 0 1 −Pz 
0 0 0 1 000 1 0 0 0 1

To perform the transformation in the local coordinate system, i.e., the one described by HomMat3D, use
HomMat3dScaleLocal.
Attention
Note that homogeneous matrices are stored row-by-row as a tuple; the last row is not stored because it is identical
for all homogeneous matrices that describe an affine transformation. For example, the homogeneous matrix
 
ra rb rc td
 re rf rg th 
 
 ri rj rk tl 
0 0 0 1
is stored as the tuple [ra, rb, rc, td, re, rf, rg, th, ri, rj, rk, tl].
Parameter
. HomMat3D (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . hom_mat3d ; HHomMat3dX / VARIANT ( real )
Input transformation matrix.
. Sx (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Scale factor along the x-axis.
Default Value : 2
Suggested values : Sx ∈ {0.125, 0.25, 0.5, 1, 2, 4, 8, 112}
Restriction : (Sx 6= 0)
. Sy (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Scale factor along the y-axis.
Default Value : 2
Suggested values : Sy ∈ {0.125, 0.25, 0.5, 1, 2, 4, 8, 112}
Restriction : (Sy 6= 0)
. Sz (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Scale factor along the z-axis.
Default Value : 2
Suggested values : Sz ∈ {0.125, 0.25, 0.5, 1, 2, 4, 8, 112}
Restriction : (Sz 6= 0)
. Px (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point3d.x ; VARIANT ( real, integer )
Fixed point of the transformation (x coordinate).
Default Value : 0
Suggested values : Px ∈ {0, 16, 32, 64, 128, 256, 512, 1024}
. Py (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point3d.y ; VARIANT ( real, integer )
Fixed point of the transformation (y coordinate).
Default Value : 0
Suggested values : Py ∈ {0, 16, 32, 64, 128, 256, 512, 1024}

HALCON 8.0.2
1068 CHAPTER 15. TOOLS

. Pz (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point3d.z ; VARIANT ( real, integer )


Fixed point of the transformation (z coordinate).
Default Value : 0
Suggested values : Pz ∈ {0, 16, 32, 64, 128, 256, 512, 1024}
. HomMat3DScale (output control) . . . . . . . . . . . . . . . . . . . . hom_mat3d ; HHomMat3dX / VARIANT ( real )
Output transformation matrix.
Result
HomMat3dScale returns TRUE if all three scale factors are not 0. If necessary, an exception is raised.
Parallelization Information
HomMat3dScale is reentrant and processed without parallelization.
Possible Predecessors
HomMat3dIdentity, HomMat3dTranslate, HomMat3dScale, HomMat3dRotate
Possible Successors
HomMat3dTranslate, HomMat3dScale, HomMat3dRotate
See also
HomMat3dInvert, HomMat3dIdentity, HomMat3dScaleLocal, PoseToHomMat3d,
HomMat3dToPose, HomMat3dCompose
Module
Foundation

[out] HHomMat3dX HomMat3DScale HHomMat3dX.HomMat3dScaleLocal


([in] VARIANT Sx, [in] VARIANT Sy, [in] VARIANT Sz )
void HOperatorSetX.HomMat3dScaleLocal ([in] VARIANT HomMat3D,
[in] VARIANT Sx, [in] VARIANT Sy, [in] VARIANT Sz,
[out] VARIANT HomMat3DScale )

Add a scaling to a homogeneous 3D transformation matrix.


HomMat3dScaleLocal adds a scaling by the scale factors Sx, Sy, and Sz to the homogeneous 3D transforma-
tion matrix HomMat3D and returns the resulting matrix in HomMat3DScale. The scaling is described by a 3×3
scaling matrix S. In contrast to HomMat3dScale, it is performed relative to the local coordinate system, i.e., the
coordinate system described by HomMat3D; this corresponds to the following chain of transformation matrices:
 
0  
Sx 0 0
 S 0 
HomMat3DScale = HomMat3D ·   S= 0 Sy 0 
 0 
0 0 Sz
000 1

The fixed point of the transformation is the origin of the local coordinate system, i.e., this point remains unchanged
when transformed using HomMat3DScale.
Attention
Note that homogeneous matrices are stored row-by-row as a tuple; the last row is not stored because it is identical
for all homogeneous matrices that describe an affine transformation. For example, the homogeneous matrix
 
ra rb rc td
 re rf rg th 
 
 ri rj rk tl 
0 0 0 1
is stored as the tuple [ra, rb, rc, td, re, rf, rg, th, ri, rj, rk, tl].
Parameter

. HomMat3D (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . hom_mat3d ; HHomMat3dX / VARIANT ( real )


Input transformation matrix.

HALCON/COM Reference Manual, 2008-5-13


15.2. 3D-TRANSFORMATIONS 1069

. Sx (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )


Scale factor along the x-axis.
Default Value : 2
Suggested values : Sx ∈ {0.125, 0.25, 0.5, 1, 2, 4, 8, 112}
Restriction : (Sx 6= 0)
. Sy (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Scale factor along the y-axis.
Default Value : 2
Suggested values : Sy ∈ {0.125, 0.25, 0.5, 1, 2, 4, 8, 112}
Restriction : (Sy 6= 0)
. Sz (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Scale factor along the z-axis.
Default Value : 2
Suggested values : Sz ∈ {0.125, 0.25, 0.5, 1, 2, 4, 8, 112}
Restriction : (Sz 6= 0)
. HomMat3DScale (output control) . . . . . . . . . . . . . . . . . . . . hom_mat3d ; HHomMat3dX / VARIANT ( real )
Output transformation matrix.
Result
HomMat3dScaleLocal returns TRUE if all three scale factors are not 0. If necessary, an exception is raised.
Parallelization Information
HomMat3dScaleLocal is reentrant and processed without parallelization.
Possible Predecessors
HomMat3dIdentity, HomMat3dTranslateLocal, HomMat3dScaleLocal,
HomMat3dRotateLocal
Possible Successors
HomMat3dTranslateLocal, HomMat3dScaleLocal, HomMat3dRotateLocal
See also
HomMat3dInvert, HomMat3dIdentity, HomMat3dScale, PoseToHomMat3d, HomMat3dToPose,
HomMat3dCompose
Module
Foundation

HHomMat3dX.HomMat3dToPose ( )
[out] VARIANT Pose
void HOperatorSetX.HomMat3dToPose ([in] VARIANT HomMat3D,
[out] VARIANT Pose )

Convert a homogeneous transformation matrix into a 3D pose.


HomMat3dToPose converts a homogeneous transformation matrix into the corresponding 3D pose with type
code 0. For details about 3D poses and the corresponding transformation matrices please refer to CreatePose.
A typical application of HomMat3dToPose is that a 3D pose was converted into a homogeneous transformation
matrix to further transform it, e.g., with HomMat3dRotate or HomMat3dTranslate, and now must be
converted back into a pose to use it as input for operators like ImagePointsToWorldPlane.
Parameter

. HomMat3D (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . hom_mat3d ; HHomMat3dX / VARIANT ( real )


Homogeneous transformation matrix.
. Pose (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pose ; VARIANT ( integer, real )
Equivalent 3D pose.
Number of elements : 7
Example

camera_calibration(WorldPointsX, WorldPointsY, WorldPointsZ,


PixelsRow, PixelsColumn, CamParam, StartPose,6,

HALCON 8.0.2
1070 CHAPTER 15. TOOLS

FinalCamParam, FinalPose, Errors)


* transform FinalPose to homogeneous transformation matrix
pose_to_hom_mat3d(FinalPose, cam_H_cal)
* rotate it 90 degree around the y-axis to obtain a world coordinate system
* whose y- and z-axis lie in the plane of the calibration plate while the
* x-axis point ’upwards’: cam_H_w = cam_H_cal * RotY(90)
hom_mat3d_identity(HomMat3DIdent)
hom_mat3d_rotate(HomMat3DIdent, deg(90), ’y’, 0, 0, 0,
HomMat3DRotateY)
hom_mat3d_compose(cam_H_cal, HomMat3DRotateY, cam_H_w)
* transform back to pose
hom_mat3d_to_pose(cam_H_w, cam_P_w)
* use pose to transform an image point into the world coordinate system
image_points_to_world_plane(FinalCamParam, cam_P_w, 87, 23.5, 1,
w_px, w_py)

Result
HomMat3dToPose returns TRUE if all parameter values are correct. If necessary, an exception handling is raised
Parallelization Information
HomMat3dToPose is reentrant and processed without parallelization.
Possible Predecessors
HomMat3dRotate, HomMat3dTranslate, HomMat3dInvert
Possible Successors
CameraCalibration, WritePose, DispCaltab, SimCaltab
See also
CreatePose, CameraCalibration, DispCaltab, SimCaltab, WritePose, ReadPose,
PoseToHomMat3d, Project3DPoint, GetLineOfSight, HomMat3dRotate,
HomMat3dTranslate, HomMat3dInvert, AffineTransPoint3D
Module
Foundation

[out] HHomMat3dX HomMat3DTranslate HHomMat3dX.HomMat3dTranslate


([in] VARIANT Tx, [in] VARIANT Ty, [in] VARIANT Tz )
void HOperatorSetX.HomMat3dTranslate ([in] VARIANT HomMat3D,
[in] VARIANT Tx, [in] VARIANT Ty, [in] VARIANT Tz,
[out] VARIANT HomMat3DTranslate )

Add a translation to a homogeneous 3D transformation matrix.


HomMat3dTranslate adds a translation by the vector t = (Tx,Ty,Tz) to the homogeneous 3D transformation
matrix HomMat3D and returns the resulting matrix in HomMat3DTranslate. The translation is performed
relative to the global (i.e., fixed) coordinate system; this corresponds to the following chain of transformation
matrices:
 
1 0 0  
 0 Tx
1 1 t 
 · HomMat3D
HomMat3DTranslate = 
 0 t =  Ty 
0 1 
Tz
0 0 0 1

To perform the transformation in the local coordinate system, i.e., the one described by HomMat3D, use
HomMat3dTranslateLocal.
Attention
Note that homogeneous matrices are stored row-by-row as a tuple; the last row is not stored because it is identical
for all homogeneous matrices that describe an affine transformation. For example, the homogeneous matrix

HALCON/COM Reference Manual, 2008-5-13


15.2. 3D-TRANSFORMATIONS 1071

 
ra rb rc td
 re rf rg th 
 
 ri rj rk tl 
0 0 0 1
is stored as the tuple [ra, rb, rc, td, re, rf, rg, th, ri, rj, rk, tl].
Parameter

. HomMat3D (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . hom_mat3d ; HHomMat3dX / VARIANT ( real )


Input transformation matrix.
. Tx (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point3d.x ; VARIANT ( real, integer )
Translation along the x-axis.
Default Value : 64
Suggested values : Tx ∈ {0, 16, 32, 64, 128, 256, 512, 1024}
. Ty (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point3d.y ; VARIANT ( real, integer )
Translation along the y-axis.
Default Value : 64
Suggested values : Ty ∈ {0, 16, 32, 64, 128, 256, 512, 1024}
. Tz (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point3d.z ; VARIANT ( real, integer )
Translation along the z-axis.
Default Value : 64
Suggested values : Tz ∈ {0, 16, 32, 64, 128, 256, 512, 1024}
. HomMat3DTranslate (output control) . . . . . . . . . . . . . . hom_mat3d ; HHomMat3dX / VARIANT ( real )
Output transformation matrix.
Result
If the parameters are valid, the operator HomMat3dTranslate returns TRUE. If necessary, an exception is
raised.
Parallelization Information
HomMat3dTranslate is reentrant and processed without parallelization.
Possible Predecessors
HomMat3dIdentity, HomMat3dTranslate, HomMat3dScale, HomMat3dRotate
Possible Successors
HomMat3dTranslate, HomMat3dScale, HomMat3dRotate
See also
HomMat3dInvert, HomMat3dIdentity, HomMat3dTranslateLocal, PoseToHomMat3d,
HomMat3dToPose, HomMat3dCompose
Module
Foundation

[out] HHomMat3dX HomMat3DTranslate HHomMat3dX.HomMat3dTranslateLocal


([in] VARIANT Tx, [in] VARIANT Ty, [in] VARIANT Tz )
void HOperatorSetX.HomMat3dTranslateLocal ([in] VARIANT HomMat3D,
[in] VARIANT Tx, [in] VARIANT Ty, [in] VARIANT Tz,
[out] VARIANT HomMat3DTranslate )

Add a translation to a homogeneous 3D transformation matrix.


HomMat3dTranslateLocal adds a translation by the vector t = (Tx,Ty,Tz) to the homogeneous 3D
transformation matrix HomMat3D and returns the resulting matrix in HomMat3DTranslate. In contrast to
HomMat3dTranslate, the translation is performed relative to the local coordinate system, i.e., the coordinate
system described by HomMat3D; this corresponds to the following chain of transformation matrices:
 
1 0 0  
 0 Tx
1 1 t 
HomMat3DTranslate = HomMat3D · 
 0
 t =  Ty 
0 1 
Tz
0 0 0 1

HALCON 8.0.2
1072 CHAPTER 15. TOOLS

Attention
Note that homogeneous matrices are stored row-by-row as a tuple; the last row is not stored because it is identical
for all homogeneous matrices that describe an affine transformation. For example, the homogeneous matrix
 
ra rb rc td
 re rf rg th 
 
 ri rj rk tl 
0 0 0 1
is stored as the tuple [ra, rb, rc, td, re, rf, rg, th, ri, rj, rk, tl].
Parameter
. HomMat3D (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . hom_mat3d ; HHomMat3dX / VARIANT ( real )
Input transformation matrix.
. Tx (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point3d.x ; VARIANT ( real, integer )
Translation along the x-axis.
Default Value : 64
Suggested values : Tx ∈ {0, 16, 32, 64, 128, 256, 512, 1024}
. Ty (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point3d.y ; VARIANT ( real, integer )
Translation along the y-axis.
Default Value : 64
Suggested values : Ty ∈ {0, 16, 32, 64, 128, 256, 512, 1024}
. Tz (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point3d.z ; VARIANT ( real, integer )
Translation along the z-axis.
Default Value : 64
Suggested values : Tz ∈ {0, 16, 32, 64, 128, 256, 512, 1024}
. HomMat3DTranslate (output control) . . . . . . . . . . . . . . hom_mat3d ; HHomMat3dX / VARIANT ( real )
Output transformation matrix.
Result
If the parameters are valid, the operator HomMat3dTranslateLocal returns TRUE. If necessary, an exception
is raised.
Parallelization Information
HomMat3dTranslateLocal is reentrant and processed without parallelization.
Possible Predecessors
HomMat3dIdentity, HomMat3dTranslateLocal, HomMat3dScaleLocal,
HomMat3dRotateLocal
Possible Successors
HomMat3dTranslateLocal, HomMat3dScaleLocal, HomMat3dRotateLocal
See also
HomMat3dInvert, HomMat3dIdentity, HomMat3dTranslate, PoseToHomMat3d,
HomMat3dToPose, HomMat3dCompose
Module
Foundation

HPoseX.PoseToHomMat3d ([in] VARIANT Pose )


[out] HHomMat3dX HomMat3D
void HOperatorSetX.PoseToHomMat3d ([in] VARIANT Pose,
[out] VARIANT HomMat3D )

Convert a 3D pose into a homogeneous transformation matrix.


PoseToHomMat3d converts a 3D pose Pose, e.g., the exterior camera parameters, into the equivalent homo-
geneous transformation matrix HomMat3D. For details about 3D poses and the corresponding transformation
matrices please refer to CreatePose.
A typical application of PoseToHomMat3d is that you want to further transform the pose, e.g., rotate or translate
it using HomMat3dRotate or HomMat3dTranslate. In case of the exterior camera parameters, this can be
necessary if the calibration plate cannot be placed such that its coordinate system coincides with the desired world
coordinate system.

HALCON/COM Reference Manual, 2008-5-13


15.2. 3D-TRANSFORMATIONS 1073

Parameter
. Pose (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pose ; VARIANT ( integer, real )
3D pose.
Number of elements : 7
. HomMat3D (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . hom_mat3d ; HHomMat3dX / VARIANT ( real )
Equivalent homogeneous transformation matrix.
Example

* read interior camera parameters


read_cam_par(’campar.dat’, CamParam)
* read exterior camera parameters
read_pose(’startpose.dat’, StartPose)
* (read 3D world points [WorldPointsX,WorldPointsY,WorldPointsZ],
* extract corresponding 2D image points [PixelsRow,PixelsColumn])
* calibration of exterior camera parameters:
camera_calibration(WorldPointsX, WorldPointsY, WorldPointsZ,
PixelsRow, PixelsColumn, CamParam, StartPose, ’pose’,
FinalCamParam, FinalPose, Errors)
* transform FinalPose to homogeneous transformation matrix
pose_to_hom_mat3d(FinalPose, cam_H_cal)
* rotate it 90 degree around its y-axis to obtain a world coordinate system
* whose y- and z-axis lie in the plane of the calibration plate while the
* x-axis point ’upwards’: cam_H_w = cam_H_cal * RotY(90)
hom_mat3d_identity(HomMat3DIdent)
hom_mat3d_rotate(HomMat3DIdent, deg(90), ’y’, 0, 0, 0,
HomMat3DRotateY)
hom_mat3d_compose(cam_H_cal, HomMat3DRotateY, cam_H_w)

Result
PoseToHomMat3d returns TRUE if all parameter values are correct. If necessary, an exception handling is raised
Parallelization Information
PoseToHomMat3d is reentrant and processed without parallelization.
Possible Predecessors
CameraCalibration, ReadPose
Possible Successors
AffineTransPoint3D, HomMat3dInvert, HomMat3dTranslate, HomMat3dRotate,
HomMat3dToPose
See also
CreatePose, CameraCalibration, WritePose, ReadPose, HomMat3dToPose,
Project3DPoint, GetLineOfSight, HomMat3dRotate, HomMat3dTranslate,
HomMat3dInvert, AffineTransPoint3D
Module
Foundation

HPoseX.ReadPose ([in] String PoseFile )


[out] VARIANT Pose
void HOperatorSetX.ReadPose ([in] VARIANT PoseFile, [out] VARIANT Pose )

Read a 3D pose from a text file.


ReadPose is used to read the 3D pose Pose from a text file with the name PoseFile.
A pose describes a rigid 3D transformation, i.e., a transformation consisting of an arbitrary translation and rotation,
with 6 parameters, three for the translation, three for the rotation. With a seventh parameter different pose types
can be indicated (see CreatePose).
A suitable file can be generated by the operator WritePose and looks like the following:

HALCON 8.0.2
1074 CHAPTER 15. TOOLS

# 3D POSE PARAMETERS: rotation and translation

# Used representation type:


f 0

# Rotation angles [deg] or Rodriguezvector:


r -17.8134 1.83816 0.288092

# Translation vector (x y z [m]):


t 0.280164 0.150644 1.7554

Parameter
. PoseFile (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.read ; String / VARIANT
File name of the exterior camera parameters.
Default Value : ’campose.dat’
List of values : PoseFile ∈ {’campose.dat’, ’campose.initial’, ’campose.final’}
. Pose (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pose ; VARIANT ( integer, real )
3D pose.
Number of elements : 7
Result
ReadPose returns TRUE if all parameter values are correct and the file has been read successfully. If necessary
an exception handling is raised.
Parallelization Information
ReadPose is reentrant and processed without parallelization.
Possible Predecessors
ReadCamPar
Possible Successors
PoseToHomMat3d, CameraCalibration, DispCaltab, SimCaltab
See also
CreatePose, FindMarksAndPose, CameraCalibration, DispCaltab, SimCaltab, WritePose,
PoseToHomMat3d, HomMat3dToPose
Module
Foundation

[out] VARIANT PoseNewOrigin HPoseX.SetOriginPose ([in] VARIANT PoseIn,


[in] double DX, [in] double DY, [in] double DZ )
void HOperatorSetX.SetOriginPose ([in] VARIANT PoseIn, [in] VARIANT DX,
[in] VARIANT DY, [in] VARIANT DZ, [out] VARIANT PoseNewOrigin )

Translate the origin of a 3D pose.


SetOriginPose translates the origin of the 3D pose PoseIn by the vector given by DX, DY, and DZ and returns
the result in PoseNewOrigin. Note that the translation is performed relative to the local coordinate system of the
pose itself. For example, if PoseIn describes the pose of an object in camera coordinates, PoseNewOrigin is
obtained by translating the object’s coordinate system by DX along its own x-axis (and so on for the other axes) and
not along the x-axis of the camera coordinate system. This corresponds to the following chain of transformations:
   
1 0 0 DX
 0 1 1  DY  
PoseNewOrigin = PoseIn ·   0 0 1

DZ 
0 0 0 1

Thus, SetOriginPose is a shortcut for the following sequence of operator calls:


pose_to_hom_mat3d (PoseIn, HomMat3DIn)
hom_mat3d_translate_local (HomMat3DIn, DX, DY, DZ, HomMat3DNewOrigin)
hom_mat3d_to_pose (HomMat3DNewOrigin, PoseNewOrigin)

HALCON/COM Reference Manual, 2008-5-13


15.2. 3D-TRANSFORMATIONS 1075

A typical application of this operator when defining a world coordinate system by placing the standard cal-
ibration plate on the plane of measurements. In this case, the external camera parameters returned by
CameraCalibration correspond to a coordinate system that lies above the measurement plane, because the
coordinate system of the calibration plate is located on its surface and the plate has a certain thickness. To correct
the pose, call SetOriginPose with the translation vector (0,0,D), where D is the thickness of the calibration
plate.
Parameter
. PoseIn (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pose ; VARIANT ( integer, real )
original 3D pose.
Number of elements : 7
. DX (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
translation of the origin in x-direction.
Default Value : 0
. DY (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
translation of the origin in y-direction.
Default Value : 0
. DZ (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
translation of the origin in z-direction.
Default Value : 0
. PoseNewOrigin (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pose ; VARIANT ( integer, real )
new 3D pose after applying the translation.
Number of elements : 7
Result
SetOriginPose returns TRUE if all parameter values are correct. If necessary, an exception handling is raised.
Parallelization Information
SetOriginPose is reentrant and processed without parallelization.
Possible Predecessors
CreatePose, HomMat3dToPose, CameraCalibration, HandEyeCalibration
Possible Successors
WritePose, PoseToHomMat3d, ImagePointsToWorldPlane, ContourToWorldPlaneXld
See also
HomMat3dTranslateLocal
Module
Foundation

void HPoseX.WritePose ([in] VARIANT Pose, [in] String PoseFile )


void HOperatorSetX.WritePose ([in] VARIANT Pose,
[in] VARIANT PoseFile )

Write a 3D pose to a text file.


WritePose is used to write a 3D pose Pose into a text file with the name PoseFile.
A pose describes a rigid 3D transformation, i.e., a transformation consisting of an arbitrary translation and rotation,
with 6 parameters, three for the translation, three for the rotation. With a seventh parameter different pose types
can be indicated (see CreatePose).
A file generated by WritePose looks like the following:

# 3D POSE PARAMETERS: rotation and translation

# Used representation type:


f 0

# Rotation angles [deg] or Rodriguez vector:


r -17.8134 1.83816 0.288092

HALCON 8.0.2
1076 CHAPTER 15. TOOLS

# Translation vector (x y z [m]):


t 0.280164 0.150644 1.7554

Parameter

. Pose (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pose ; VARIANT ( integer, real )


3D pose.
Number of elements : 7
. PoseFile (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.write ; String / VARIANT
File name of the exterior camera parameters.
Default Value : ’campose.dat’
List of values : PoseFile ∈ {’campose.dat’, ’campose.initial’, ’campose.final’}
Example

* read calibration images


read_image(Image1, ’calib-01’)
read_image(Image2, ’calib-02’)
read_image(Image3, ’calib-03’)
* find calibration pattern
find_caltab(Image1, Caltab1, ’caltab.descr’, 3, 112, 5)
find_caltab(Image2, Caltab2, ’caltab.descr’, 3, 112, 5)
find_caltab(Image3, Caltab3, ’caltab.descr’, 3, 112, 5)
* find calibration marks and start poses
StartCamPar := [0.008, 0.0, 0.000011, 0.000011, 384, 288, 768, 576]
find_marks_and_pose(Image1, Caltab1, ’caltab.descr’, StartCamPar,
128, 10, 18, 0.9, 15.0, 100.0, RCoord1, CCoord1,
StartPose1)
find_marks_and_pose(Image2, Caltab2, ’caltab.descr’, StartCamPar,
128, 10, 18, 0.9, 15.0, 100.0, RCoord2, CCoord2,
StartPose2)
find_marks_and_pose(Image3, Caltab3, ’caltab.descr’, StartCamPar,
128, 10, 18, 0.9, 15.0, 100.0, RCoord3, CCoord3,
StartPose3)
* read 3D positions of calibration marks
caltab_points(’caltab.descr’, NX, NY, NZ)
* camera calibration
camera_calibration(NX, NY, NZ, [RCoord1, RCoord2, RCoord3],
[CCoord1, CCoord2, CCoord3], StartCamPar,
[StartPose1, StartPose2, StartPose3], ’all’,
CamParam, NFinalPose, Errors)
* write exterior camera parameters of first calibration image
write_pose(NFinalPose[0:6], ’campose.dat’)

Result
WritePose returns TRUE if all parameter values are correct and the file has been written successfully. If neces-
sary an exception handling is raised.
Parallelization Information
WritePose is local and processed completely exclusively without parallelization.
Possible Predecessors
CameraCalibration, HomMat3dToPose
See also
CreatePose, FindMarksAndPose, CameraCalibration, DispCaltab, SimCaltab, ReadPose,
PoseToHomMat3d, HomMat3dToPose
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


15.3. BACKGROUND-ESTIMATOR 1077

15.3 Background-Estimator

void HMiscX.CloseAllBgEsti ( )
void HOperatorSetX.CloseAllBgEsti ( )

Delete all background estimation data sets.


CloseAllBgEsti deletes the background estimation data sets and releases all used memory.
Attention
CloseAllBgEsti exists solely for the purpose of implementing the “reset program” functionality in HDevelop.
CloseAllBgEsti must not be used in any application.
Result
If it is possible to close the background estimation data sets the operator CloseAllBgEsti returns the value
TRUE. Otherwise an exception handling is raised.
Parallelization Information
CloseAllBgEsti is local and processed completely exclusively without parallelization.
See also
CreateBgEsti
Alternatives
CloseBgEsti
Module
Foundation

void HOperatorSetX.CloseBgEsti ([in] VARIANT BgEstiHandle )

Delete the background estimation data set.


CloseBgEsti deletes the background estimation data set and releases all used memory.
Parameter
. BgEstiHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . bg_estimation ; HBgEstiX / VARIANT
ID of the BgEsti data set.
Example

/* read Init-Image: */
read_image(InitImage,’Init_Image’)
/* initialize BgEsti-Dataset with
fixed gains and threshold adaption: */
create_bg_esti(InitImage,0.7,0.7,’fixed’,0.002,0.02,
’on’,7,10,3.25,15.0,BgEstiHandle)
/* read the next image in sequence: */
read_image(Image1,’Image_1’)
/* estimate the Background: */
run_bg_esti(Image1,Region1,BgEstiHandle)
/* display the foreground region: */
disp_region(Region1,WindowHandle)
/* read the next image in sequence: */
read_image(Image2,’Image_2’)
/* estimate the Background: */
run_bg_esti(Image2,Region2,BgEstiHandle)
/* display the foreground region: */
disp_region(Region2,WindowHandle)
/* etc. */
/* - end of background estimation - */
/* close the dataset: */
close_bg_est(BgEstiHandle).

HALCON 8.0.2
1078 CHAPTER 15. TOOLS

Result
CloseBgEsti returns TRUE if all parameters are correct.
Parallelization Information
CloseBgEsti is local and processed completely exclusively without parallelization.
Possible Predecessors
RunBgEsti
See also
CreateBgEsti
Module
Foundation

[out] long BgEstiHandle HImageX.CreateBgEsti ([in] double Syspar1,


[in] double Syspar2, [in] String GainMode, [in] double Gain1,
[in] double Gain2, [in] String AdaptMode, [in] double MinDiff,
[in] long StatNum, [in] double ConfidenceC, [in] double TimeC )
void HBgEstiX.CreateBgEsti ([in] HImageX InitializeImage,
[in] double Syspar1, [in] double Syspar2, [in] String GainMode,
[in] double Gain1, [in] double Gain2, [in] String AdaptMode,
[in] double MinDiff, [in] long StatNum, [in] double ConfidenceC,
[in] double TimeC )
void HOperatorSetX.CreateBgEsti ([in] IHObjectX InitializeImage,
[in] VARIANT Syspar1, [in] VARIANT Syspar2, [in] VARIANT GainMode,
[in] VARIANT Gain1, [in] VARIANT Gain2, [in] VARIANT AdaptMode,
[in] VARIANT MinDiff, [in] VARIANT StatNum, [in] VARIANT ConfidenceC,
[in] VARIANT TimeC, [out] VARIANT BgEstiHandle )

Generate and initialize a data set for the background estimation.


CreateBgEsti creates a new data set for the background estimation and initializes it with the appropriate
parameters. The estimated background image is part of this data set. The newly created set automatically becomes
the current set.
InitializeImage is used as an initial prediction for the background image. For a good prediction an image of
the ovserved scene without moving objects should be passed in InitializeImage. That way the foreground
adaptation rate can be held low. If there is no empty scene image available, a homogenous gray image can be used
instead. In that case the adaptation rate for the foreground image must be raised, because initially most of the image
will be detected as foreground. The intialization image must to be of type byte or real. Because of processing
single-channel images, data sets must be created for every channel. Size and region of InitializeImage
determines size and region for all background estimations ( RunBgEsti) that are performed with this data set.
Syspar1 and Syspar2 are the parameters of the Kalman system matrix. The system matrix describes the
system of the gray value changes according to Kalman filter theory. The background estimator implements a
different system for each pixel.
GainMode defines whether a fixed Kalman gain should be used for the estimation or whether the gain should
adapt itself depending on the difference between estimation and actual value. If GainMode is set to ’fixed’, then
Gain1 is used as Kalman gain for pixels predicted as foreground and Gain2 as gain for pixels predicted as
background. Gain1 should be smaller than Gain2, because adaptation of the foreground should be slower than
adaptation of the background. Both Gain1 and Gain2 should be smaller than 1.0.
If GainMode is set to ’frame’, then tables for foreground and background estimation are computed containing
Kalman gains for all the 256 possible grayvalue changes. Gain1 and Gain2 then denote the number of frames
necessary to adapt the difference between estimated value and actual value. So with a fixed time for adaptation
(i.e. number of frames) the needed Kalman gain grows with the grayvalue difference. Gain1 should therefore
be larger than Gain2. Different gains for different grayvalue differences are useful if the background estimator
is used for generating an ’empty’ scene assuming that there are always moving objects in the observated area. In
that case the adaptation time for foreground adaptaion (Gain1) must not be too big. Gain1 and Gain2 should
be bigger than 1.0.

HALCON/COM Reference Manual, 2008-5-13


15.3. BACKGROUND-ESTIMATOR 1079

AdaptMode denotes, whether the foreground/background decision threshold applied to the grayvalue difference
between estimation and actual value is fixed or whether it adapts itself depending on the grayvalue deviation of the
background pixels.
If AdaptMode is set to ’off’, the parameter MinDiff denotes a fixed threshold. The parameters StatNum,
ConfidenceC and TimeC are meaningless in this case.
If AdaptMode is set to ’on’, then MinDiff is interpreted as a base threshold. For each pixel an offset is added
to this threshold depending on the statistical evaluation of the pixel value over time. StatNum holds the number
of data sets (past frames) that are used for computing the grayvalue variance (FIR-Filter). ConfidenceC is used
to determine the confidence interval.
The confidence interval determines the values of the background statistics if background pixels are hidden by
a foreground object and thus are detected as foreground. According to the student t-distribution the confidence
constant is 4.30 (3.25, 2.82, 2.26) for a confidence interval of 99,8% (99,0%, 98,0%, 95,0%). TimeC holds a
time constant for the exp-function that raises the threshold in case of a foreground estimation of the pixel. That
means, the threshold is raised in regions where movement is detected in the foreground. That way larger changes in
illumination are tolerated if the background becomes visible again. The main reason for increasing this tolerance is
the impossibility for a prediction of illumintaion changes while the background is hidden. Therefore no adaptation
of the estimated background image is possible.
Attention
If GainMode was set to ’frame’, the run-time can be extremly long for large values of Gain1 or Gain2, because
the values for the gains’ table are determined by a simple binary search.
Parameter

. InitializeImage (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, real )


initialization image.
. Syspar1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
1. system matrix parameter.
Default Value : 0.7
Suggested values : Syspar1 ∈ {0.65, 0.7, 0.75}
Typical range of values : 0.05 ≤ Syspar1 ≤ 0.05
Recommended Increment : 0.05
. Syspar2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
2. system matrix parameter.
Default Value : 0.7
Suggested values : Syspar2 ∈ {0.65, 0.7, 0.75}
Typical range of values : 0.05 ≤ Syspar2 ≤ 0.05
Recommended Increment : 0.05
. GainMode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Gain type.
Default Value : ’fixed’
List of values : GainMode ∈ {’fixed’, ’frame’}
. Gain1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Kalman gain / foreground adaptation time.
Default Value : 0.002
Suggested values : Gain1 ∈ {10.0, 20.0, 50.0, 0.1, 0.05, 0.01, 0.005, 0.001}
Restriction : (0.0 ≤ Gain1)
. Gain2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Kalman gain / background adaptation time.
Default Value : 0.02
Suggested values : Gain2 ∈ {2.0, 4.0, 8.0, 0.5, 0.1, 0.05, 0.01}
Restriction : (0.0 ≤ Gain2)
. AdaptMode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Threshold adaptation.
Default Value : ’on’
List of values : AdaptMode ∈ {’on’, ’off’}

HALCON 8.0.2
1080 CHAPTER 15. TOOLS

. MinDiff (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT


Foreground/background threshold.
Default Value : 7.0
Suggested values : MinDiff ∈ {3.0, 5.0, 7.0, 9.0, 11.0}
Recommended Increment : 0.2
. StatNum (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of statistic data sets.
Default Value : 10
Suggested values : StatNum ∈ {5, 10, 20, 30}
Recommended Increment : 5
. ConfidenceC (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Confidence constant.
Default Value : 3.25
Suggested values : ConfidenceC ∈ {4.30, 3.25, 2.82, 2.62}
Recommended Increment : 0.01
Restriction : (0.0 < Conf idenceC)
. TimeC (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Constant for decay time.
Default Value : 15.0
Suggested values : TimeC ∈ {10.0, 15.0, 20.0}
Recommended Increment : 5.0
Restriction : (0.0 < T imeC)
. BgEstiHandle (output control) . . . . . . . . . . . . . . . . . . . . . . . . bg_estimation ; long / HBgEstiX / VARIANT
ID of the BgEsti data set.
Example

/* read Init-Image: */
read_image(InitImage,’Init_Image’)
/* initialize 1. BgEsti-Dataset with
fixed gains and threshold adaption: */
create_bg_esti(InitImage,0.7,0.7,’fixed’,0.002,0.02,
’on’,7.0,10,3.25,15.0,BgEstiHandle1)
/* initialize 2. BgEsti-Dataset with
frame orientated gains and fixed threshold */
create_bg_esti(InitImage,0.7,0.7,’frame’,30.0,4.0,
’off’,9.0,10,3.25,15.0,BgEstiHandle2).

Result
CreateBgEsti returns TRUE if all parameters are correct.
Parallelization Information
CreateBgEsti is local and processed completely exclusively without parallelization.
Possible Successors
RunBgEsti
See also
SetBgEstiParams, CloseBgEsti
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


15.3. BACKGROUND-ESTIMATOR 1081

[out] double Syspar1 HBgEstiX.GetBgEstiParams ([out] double Syspar2,


[out] String GainMode, [out] double Gain1, [out] double Gain2,
[out] String AdaptMode, [out] double MinDiff, [out] long StatNum,
[out] double ConfidenceC, [out] double TimeC )
void HOperatorSetX.GetBgEstiParams ([in] VARIANT BgEstiHandle,
[out] VARIANT Syspar1, [out] VARIANT Syspar2, [out] VARIANT GainMode,
[out] VARIANT Gain1, [out] VARIANT Gain2, [out] VARIANT AdaptMode,
[out] VARIANT MinDiff, [out] VARIANT StatNum, [out] VARIANT ConfidenceC,
[out] VARIANT TimeC )

Return the parameters of the data set.


GetBgEstiParams returns the parameters of the data set. The returned parameters are the same as in
CreateBgEsti and SetBgEstiParams (see these for an explanation).
Parameter
. BgEstiHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . bg_estimation ; HBgEstiX / VARIANT
ID of the BgEsti data set.
. Syspar1 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
1. system matrix parameter.
. Syspar2 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
2. system matrix parameter.
. GainMode (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Gain type.
. Gain1 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Kalman gain / foreground adaptation time.
. Gain2 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Kalman gain / background adaptation time.
. AdaptMode (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Threshold adaptation.
. MinDiff (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Foreground / background threshold.
. StatNum (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of statistic data sets.
. ConfidenceC (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Confidence constant.
. TimeC (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Constant for decay time.
Example

/* read Init-Image:*/
read_image(InitImage,’Init_Image’)
/* initialize BgEsti-Dataset with
fixed gains and threshold adaption: */
create_bg_esti(InitImage,0.7,0.7,’fixed’,0.002,0.02,
’on’,7.0,10,3.25,15.0,BgEstiHandle)
/* read the next image in sequence: */
read_image(Image1,’Image_1’)
/* estimate the Background: */
run_bg_esti(Image1,Region1,BgEstiHandle)
/* display the foreground region: */
disp_region(Region1,WindowHandle)
/* read the next image in sequence: */
read_image(Image2,’Image_2’)
/* estimate the Background: */
run_bg_esti(Image2,Region2,BgEstiHandle)
/* display the foreground region: */

HALCON 8.0.2
1082 CHAPTER 15. TOOLS

disp_region(Region2,WindowHandle)
/* etc. */
/* change only the gain parameter in dataset: */
get_bg_esti_params(BgEstiHandle,par1,par2,par3,par4,
par5,par6,par7,par8,par9,par10)
set_bg_esti_params(BgEstiHandle,par1,par2,par3,0.004,
0.08,par6,par7,par8,par9,par10)
/* read the next image in sequence: */
read_image(Image3,’Image_3’)
/* estimate the Background: */
run_bg_esti(Image3,Region3,BgEstiHandle)
/* display the foreground region: */
disp_region(Region3,WindowHandle)
/* etc. */

Result
GetBgEstiParams returns TRUE if all parameters are correct.
Parallelization Information
GetBgEstiParams is reentrant and processed without parallelization.
Possible Predecessors
CreateBgEsti
Possible Successors
RunBgEsti
See also
SetBgEstiParams
Module
Foundation

void HImageX.GiveBgEsti ([in] long BgEstiHandle )


[out] HImageX BackgroundImage HBgEstiX.GiveBgEsti ( )
void HOperatorSetX.GiveBgEsti ([out] HUntypedObjectX BackgroundImage,
[in] VARIANT BgEstiHandle )

Return the estimated background image.


GiveBgEsti returns the estimated background image of the current BgEsti data set. The background image has
the same type and size as the initialization image passed in CreateBgEsti.
Parameter
. BackgroundImage (output iconic) . . . . . . . . . . . . . . . . image ; HImageX / HUntypedObjectX ( byte, real )
Estimated background image of the current data set.
. BgEstiHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . bg_estimation ; long / HBgEstiX / VARIANT
ID of the BgEsti data set.
Example

/* read Init-Image: */
read_image(InitImage,’Init_Image’)
/* initialize BgEsti-Dataset with
fixed gains and threshold adaption: */
create_bg_esti(InitImage,0.7,0.7,’fixed’,0.002,0.02,
’on’,7,10,3.25,15.0,BgEstiHandle)
/* read the next image in sequence: */
read_image(Image1,’Image_1’)
/* estimate the Background: */
run_bg_esti(Image1,Region1,BgEstiHandle)

HALCON/COM Reference Manual, 2008-5-13


15.3. BACKGROUND-ESTIMATOR 1083

/* give the background image from the aktive dataset: */


give_bg_esti(BgImage,BgEstiHandle)
/* display the background image: */
disp_image(BgImage,WindowHandle).

Result
GiveBgEsti returns TRUE if all parameters are correct.
Parallelization Information
GiveBgEsti is reentrant and processed without parallelization.
Possible Predecessors
RunBgEsti
Possible Successors
RunBgEsti, CreateBgEsti, UpdateBgEsti
See also
RunBgEsti, UpdateBgEsti, CreateBgEsti
Module
Foundation

[out] HRegionX ForegroundRegion HImageX.RunBgEsti


([in] long BgEstiHandle )
[out] HRegionX ForegroundRegion HBgEstiX.RunBgEsti
([in] HImageX PresentImage )
void HOperatorSetX.RunBgEsti ([in] IHObjectX PresentImage,
[out] HUntypedObjectX ForegroundRegion, [in] VARIANT BgEstiHandle )

Estimate the background and return the foreground region.


RunBgEsti adapts the background image stored in the BgEsti data set using a Kalman filter on each pixel and
returns a region of the foreground (detected moving objects).
For every pixel an estimation of its grayvalue is computed using the values of the current data set and its stored
background image and the current image (PresentImage). By comparison to the threshold (fixed or adaptive,
see CreateBgEsti) the pixels are classified as either foreground or background.

The background estimation processes only single-channel images. Therefore the background has to be adapted
separately for every channel.

The background estimation should be used on half- or even quarter-sized images. For this, the input images (and
the initialization image!) has to be reduced using ZoomImageFactor. The advantage is a shorter run-time
on one hand and a low-band filtering on the other. The filtering eliminates high frequency noise and results in a
more reliable estimation. As a result the threshold (see CreateBgEsti) can be lowered. The foreground region
returned by RunBgEsti then has to be enlarged again for further processing.
Attention
The passed image (PresentImage) must have the same type and size as the background image of the current
data set (initialized with CreateBgEsti).
Parameter

. PresentImage (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, real )


Current image.
. ForegroundRegion (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX
Region of the detected foreground.
. BgEstiHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . bg_estimation ; long / HBgEstiX / VARIANT
ID of the BgEsti data set.

HALCON 8.0.2
1084 CHAPTER 15. TOOLS

Example

/* read Init-Image: */
read_image(InitImage,’Init_Image’)
/* initialize BgEsti-Dataset with
fixed gains and threshold adaption */
create_bg_esti(InitImage,0.7,0.7,’fixed’,0.002,0.02,
’on’,7,10,3.25,15.0,BgEstiHandle)
/* read the next image in sequence: */
read_image(Image1,’Image_1’)
/* estimate the Background: */
run_bg_esti(Image1,Region1,BgEstiHandle)
/* display the foreground region: */
disp_region(Region1,WindowHandle)
/* read the next image in sequence: */
read_image(Image2,’Image_2’)
/* estimate the Background: */
run_bg_esti(Image2,Region2,BgEstiHandle)
/* display the foreground region: */
disp_region(Region2,WindowHandle)
/* etc. */

Result
RunBgEsti returns TRUE if all parameters are correct.
Parallelization Information
RunBgEsti is reentrant and processed without parallelization.
Possible Predecessors
CreateBgEsti, UpdateBgEsti
Possible Successors
RunBgEsti, GiveBgEsti, UpdateBgEsti
See also
SetBgEstiParams, CreateBgEsti, UpdateBgEsti, GiveBgEsti
Module
Foundation

void HBgEstiX.SetBgEstiParams ([in] double Syspar1,


[in] double Syspar2, [in] String GainMode, [in] double Gain1,
[in] double Gain2, [in] String AdaptMode, [in] double MinDiff,
[in] long StatNum, [in] double ConfidenceC, [in] double TimeC )
void HOperatorSetX.SetBgEstiParams ([in] VARIANT BgEstiHandle,
[in] VARIANT Syspar1, [in] VARIANT Syspar2, [in] VARIANT GainMode,
[in] VARIANT Gain1, [in] VARIANT Gain2, [in] VARIANT AdaptMode,
[in] VARIANT MinDiff, [in] VARIANT StatNum, [in] VARIANT ConfidenceC,
[in] VARIANT TimeC )

Change the parameters of the data set.


SetBgEstiParams is used to change the parameters of the data set. The parameters passed by
SetBgEstiParams are the same as in CreateBgEsti (see there for an explanation).
The image format cannot be changed! To do this, a new data set with an initialization image of the appropriate
format has to be created.
To exchange the background image completely, use UpdateBgEsti. The current image then has to be passed
for both the input image and the update region.
Attention
If GainMode was set to ’frame’, the run-time can be extremly long for large values of Gain1 or Gain2, because
the values for the gains’ table are determined by a simple binary search.

HALCON/COM Reference Manual, 2008-5-13


15.3. BACKGROUND-ESTIMATOR 1085

Parameter

. BgEstiHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . bg_estimation ; HBgEstiX / VARIANT


ID of the BgEsti data set.
. Syspar1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
1. system matrix parameter.
Default Value : 0.7
Suggested values : Syspar1 ∈ {0.65, 0.7, 0.75}
Typical range of values : 0.05 ≤ Syspar1 ≤ 0.05
Recommended Increment : 0.05
. Syspar2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
2. system matrix parameter.
Default Value : 0.7
Suggested values : Syspar2 ∈ {0.65, 0.7, 0.75}
Typical range of values : 0.05 ≤ Syspar2 ≤ 0.05
Recommended Increment : 0.05
. GainMode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Gain type.
Default Value : ’fixed’
List of values : GainMode ∈ {’fixed’, ’frame’}
. Gain1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Kalman gain / foreground adaptation time.
Default Value : 0.002
Suggested values : Gain1 ∈ {10.0, 20.0, 50.0, 0.1, 0.05, 0.01, 0.005, 0.001}
Restriction : (0.0 ≤ Gain1)
. Gain2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Kalman gain / background adaptation time.
Default Value : 0.02
Suggested values : Gain2 ∈ {2.0, 4.0, 8.0, 0.5, 0.1, 0.05, 0.01}
Restriction : (0.0 ≤ Gain2)
. AdaptMode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Threshold adaptation.
Default Value : ’on’
List of values : AdaptMode ∈ {’on’, ’off’}
. MinDiff (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Foreground/background threshold.
Default Value : 7.0
Suggested values : MinDiff ∈ {3.0, 5.0, 7.0, 9.0, 11.0}
Recommended Increment : 0.2
. StatNum (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of statistic data sets.
Default Value : 10
Suggested values : StatNum ∈ {5, 10, 20, 30}
Recommended Increment : 5
. ConfidenceC (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Confidence constant.
Default Value : 3.25
Suggested values : ConfidenceC ∈ {4.30, 3.25, 2.82, 2.62}
Recommended Increment : 0.01
Restriction : (0.0 < Conf idenceC)
. TimeC (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Constant for decay time.
Default Value : 15.0
Suggested values : TimeC ∈ {10.0, 15.0, 20.0}
Recommended Increment : 5.0
Restriction : (0.0 < T imeC)
Example

HALCON 8.0.2
1086 CHAPTER 15. TOOLS

/* read Init-Image:*/
read_image(InitImage,’Init_Image’)
/* initialize BgEsti-Dataset with
fixed gains and threshold adaption: */
create_bg_esti(InitImage,0.7,0.7,’fixed’,0.002,0.02,
’on’,7.0,10,3.25,15.0,BgEstiHandle)
/* read the next image in sequence: */
read_image(Image1,’Image_1’)
/* estimate the Background: */
run_bg_esti(Image1,Region1,BgEstiHandle)
/* display the foreground region: */
disp_region(Region1,WindowHandle)
/* read the next image in sequence: */
read_image(Image2,’Image_2’)
/* estimate the Background: */
run_bg_esti(Image2,Region2,BgEstiHandle)
/* display the foreground region: */
disp_region(Region2,WindowHandle)
/* etc. */
/* change parameter in dataset: */
set_bg_esti_params(BgEstiHandle,0.7,0.7,’fixed’,
0.004,0.08,’on’,9.0,10,3.25,20.0)
/* read the next image in sequence: */
read_image(Image3,’Image_3’)
/* estimate the Background: */
run_bg_esti(Image3,Region3,BgEstiHandle)
/* display the foreground region: */
disp_region(Region3,WindowHandle)
/* etc. */

Result
SetBgEstiParams returns TRUE if all parameters are correct.
Parallelization Information
SetBgEstiParams is reentrant and processed without parallelization.
Possible Predecessors
CreateBgEsti
Possible Successors
RunBgEsti
See also
UpdateBgEsti
Module
Foundation

void HImageX.UpdateBgEsti ([in] HRegionX UpDateRegion,


[in] long BgEstiHandle )
void HBgEstiX.UpdateBgEsti ([in] HImageX PresentImage,
[in] HRegionX UpDateRegion )
void HOperatorSetX.UpdateBgEsti ([in] IHObjectX PresentImage,
[in] IHObjectX UpDateRegion, [in] VARIANT BgEstiHandle )

Change the estimated background image.


UpdateBgEsti overwrites the image stored in the current BgEsti data set with the grayvalues of
PresentImage within the bounds of UpDateRegion. This can be used for a "‘hard"’ adaptation: Image
regions with a sudden change in (known) background can be adapted very fast this way.

HALCON/COM Reference Manual, 2008-5-13


15.4. BARCODE 1087

Attention
The passed image (PresentImage) must have the same type and size as the background image of the current
data set (initialized with CreateBgEsti).
Parameter

. PresentImage (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, real )


Current image.
. UpDateRegion (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
Region describing areas to change.
. BgEstiHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . bg_estimation ; long / HBgEstiX / VARIANT
ID of the BgEsti data set.
Example

/* read Init-Image: */
read_image(InitImage,’Init_Image’)
/* initialize BgEsti-Dataset with
fixed gains and threshold adaption */
create_bg_esti(InitImage,0.7,0.7,’fixed’,0.002,0.02,
’on’,7,10,3.25,15.0,BgEstiHandle)
/* read the next image in sequence: */
read_image(Image1,’Image_1’)
/* estimate the Background: */
run_bg_esti(Image1,Region1,BgEstiHandle)
/* use the Region and the information of a knowledge base */
/* to calculate the UpDateRegion */
update_bg_esti(Image1,UpdateRegion,BgEstiHandle)
/* then read the next image in sequence: */
read_image(,Image2,’Image_2’)
/* estimate the Background: */
run_bg_esti(Image2,Region2,BgEstiHandle)
/* etc. */

Result
UpdateBgEsti returns TRUE if all parameters are correct.
Parallelization Information
UpdateBgEsti is reentrant and processed without parallelization.
Possible Predecessors
RunBgEsti
Possible Successors
RunBgEsti
See also
RunBgEsti, GiveBgEsti
Module
Foundation

15.4 Barcode
void HMiscX.ClearAllBarCodeModels ( )
void HOperatorSetX.ClearAllBarCodeModels ( )

Delete all bar code models and free the allocated memory
The operator ClearAllBarCodeModels deletes all bar code models that were created by
CreateBarCodeModel. All memory used by the models is freed. After the operator call, all bar code
handles are invalid.

HALCON 8.0.2
1088 CHAPTER 15. TOOLS

Attention
ClearAllBarCodeModels exists solely for the purpose of implementing the “reset program” functionality in
HDevelop. ClearAllBarCodeModels must not be used in any application.
Example

Result
The operator ClearAllBarCodeModels returns the value TRUE if all bar code models were freed correctly.
Otherwise, an exception will be raised.
Parallelization Information
ClearAllBarCodeModels is processed completely exclusively without parallelization.
See also
CreateBarCodeModel, FindBarCode
Alternatives
ClearBarCodeModel
Module
Bar Code

void HOperatorSetX.ClearBarCodeModel ([in] VARIANT BarCodeHandle )

Delete a bar code model and free the allocated memory


The operator ClearBarCodeModel deletes a bar code model that was created by CreateBarCodeModel.
All memory used by the model is freed. The handle of the model is passed in BarCodeHandle, which is invalid
after the operator call.
Parameter
. BarCodeHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . barcode ; HBarCodeX / VARIANT
Handle of the bar code model.
Example

Result
The operator ClearBarCodeModel returns the value TRUE if a valid handle was passed and the referred bar
code model can be freed correctly. Otherwise, an exception will be raised.
Parallelization Information
ClearBarCodeModel is processed completely exclusively without parallelization.
See also
FindBarCode
Alternatives
ClearAllBarCodeModels
Module
Bar Code

void HBarCodeX.CreateBarCodeModel ([in] VARIANT GenParamNames,


[in] VARIANT GenParamValues )
void HOperatorSetX.CreateBarCodeModel ([in] VARIANT GenParamNames,
[in] VARIANT GenParamValues, [out] VARIANT BarCodeHandle )

Create a model of a bar code reader.

HALCON/COM Reference Manual, 2008-5-13


15.4. BARCODE 1089

The operator CreateBarCodeModel creates a generic model for reading all types of supported bar code
symbols. The result of this operator is a handle to the bar code model (BarCodeHandle), which is used for
all further operations on the bar code, like modifying the model, reading a symbol, or accessing the results of the
symbol search.
In general, bar codes will be found and decoded without any additional adjustment of the parameters. There-
fore, GenParamNames and GenParamValues are empty tuples by default. In the case of poor image quality
or abnormal geometric characteristics of the bar code, which requires special parameter settings for a successful
decoding of the bar code symbols, parameters can be adjusted already while creating the bar code model. Alterna-
tively, parameters can be changed later on as well by applying the operator SetBarCodeParam. For a detailed
description of the available model parameters see SetBarCodeParam.
Parameter

. GenParamNames (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . attribute.name(-array) ; VARIANT ( string )


Names of the generic parameters that can be adjusted for the bar code model.
Default Value : []
List of values : GenParamNames ∈ {’element_size_min’, ’element_size_max’, ’check_char’,
’meas_thresh’, ’max_diff_orient’, ’composite_code’}
. GenParamValues (input control) . . . . . . . . . . . . attribute.value(-array) ; VARIANT ( integer, string, real )
Values of the generic parameters that can be adjusted for the bar code model.
Default Value : []
Suggested values : GenParamValues ∈ {1.5, 2, 3, 8, ’present’, ’absent’, 0.1, ’none’, ’CC-A/B’}
. BarCodeHandle (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . barcode ; HBarCodeX / VARIANT
Handle for using and accessing the bar code model.
Example

Result
The operator CreateBarCodeModel returns the value TRUE if the given parameters are correct. Otherwise,
an exception will be raised.
Parallelization Information
CreateBarCodeModel is processed completely exclusively without parallelization.
Possible Successors
FindBarCode
See also
ClearBarCodeModel, ClearAllBarCodeModels
Module
Bar Code

[out] HRegionX SymbolRegions HImageX.FindBarCode


([in] HBarCodeX BarCodeHandle, [in] VARIANT CodeType,
[out] VARIANT DecodedDataStrings )
[out] HRegionX SymbolRegions HBarCodeX.FindBarCode ([in] HImageX Image,
[in] VARIANT CodeType, [out] VARIANT DecodedDataStrings )
void HOperatorSetX.FindBarCode ([in] IHObjectX Image,
[out] HUntypedObjectX SymbolRegions, [in] VARIANT BarCodeHandle,
[in] VARIANT CodeType, [out] VARIANT DecodedDataStrings )

Detect and read bar code symbols in an image.


The operator FindBarCode finds and reads bar code symbols in a given image (Image) and returns the decoded
data. In one image an arbitrary number of bar codes of a single type can be read. The type of the desired bar
code symbology is given by CodeType. The decoded strings are returned in DecodedDataStrings and the
corresponding bar code regions in SymbolRegions. For a total of n successfully read bar codes, the indices from

HALCON 8.0.2
1090 CHAPTER 15. TOOLS

0 to (n-1) can be used as candidate handle in the operators GetBarCodeObject and GetBarCodeResult
in order to retrieve the desired data of one specific bar code result.
Before calling FindBarCode a bar code model must be created by calling CreateBarCodeModel. This
operator returns a bar code model BarCodeHandle, which is input to FindBarCode.
The output value DecodedDataStrings contains the decoded string of the symbol for each bar code
result. The contents of the strings are conform to the approriate standard of the symbology. Typically,
DecodedDataStrings contains only data characters. For bar codes with a mandatory check character the
check character is not included in the string. For bar codes with a facultative check character, like for example
Code 39, Codabar, 25 Industrial or 25 Interleaved, the result depends on the value of the ’check_char’ parameter,
which can be set in CreateBarCodeModel or SetBarCodeParam. By default ’check_char’ is ’absent’
and the check character is interpreted as a normal data character and hence included in the decoded string. When
’check_char’ is set to ’present’ the correctness of the check character is primarily tested. If the check character
is correct the decoded string contains just the data characters; if the check character is not correct the bar code is
graded as unreadable. Accordingly, the symbol region and the decoded string do not appear in the list of resulting
strings (DecodedDataStrings) and in the list of resulting regions (SymbolRegions).
The underlying decoded reference data, including start/stop and check characters, can be queried by using the
GetBarCodeResult operator with the option ’decoded_reference’.
Following bar code symbologies are supported: 2/5 Industrial, 2/5 Interleaved, Codabar, Code 39, Code 93, Code
128, EAN-8, EAN-8 Add-On 2, EAN-8 Add-On 5, EAN-13, EAN-13 Add-On 2, EAN-13 Add-On 5, UPC-A,
UPC-A Add-On 2, UPC-A Add-On 5, UPC-E, UPC-E Add-On 2, UPC-E Add-On 5, PharmaCode, RSS-14, RSS-
14 Truncated, RSS-14 Stacked, RSS-14 Stacked Omnidirectional, RSS Limited, RSS Expanded, RSS Expanded
Stacked.
Note, that the PharmaCode can be read in forward and backward direction, both yielding a valid result. Therefore,
both strings are returned and concatenated into a single string in DecodedDataStrings by a separating comma.
Parameter
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, uint2 )
Input image.
. SymbolRegions (output iconic) . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Regions of the successfully decoded bar code symbols.
. BarCodeHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . barcode ; HBarCodeX / VARIANT
Handle of the bar code model.
. CodeType (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Type of the searched barcode.
Default Value : ’EAN-13’
List of values : CodeType ∈ {’2/5 Industrial’, ’2/5 Interleaved’, ’Codabar’, ’Code 39’, ’Code 93’, ’Code
128’, ’EAN-13’, ’EAN-13 Add-On 2’, ’EAN-13 Add-On 5’, ’EAN-8’, ’EAN-8 Add-On 2’, ’EAN-8 Add-On
5’, ’UPC-A’, ’UPC-A Add-On 2’, ’UPC-A Add-On 5’, ’UPC-E’, ’UPC-E Add-On 2’, ’UPC-E Add-On 5’,
’PharmaCode’, ’RSS-14’, ’RSS-14 Truncated’, ’RSS-14 Stacked’, ’RSS-14 Stacked Omnidir’, ’RSS
Limited’, ’RSS Expanded’, ’RSS Expanded Stacked’}
. DecodedDataStrings (output control) . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Data strings of all successfully decoded bar codes.
Example

Result
The operator FindBarCode returns the value TRUE if the given parameters are correct. Otherwise, an exception
will be raised.
Parallelization Information
FindBarCode is reentrant and processed without parallelization.
Possible Predecessors
CreateBarCodeModel, SetBarCodeParam
Possible Successors
GetBarCodeResult, GetBarCodeObject, ClearBarCodeModel
Module
Bar Code

HALCON/COM Reference Manual, 2008-5-13


15.4. BARCODE 1091

[out] HUntypedObjectX BarCodeObjects HBarCodeX.GetBarCodeObject


([in] VARIANT CandidateHandle, [in] String ObjectName )
void HOperatorSetX.GetBarCodeObject
([out] HUntypedObjectX BarCodeObjects, [in] VARIANT BarCodeHandle,
[in] VARIANT CandidateHandle, [in] VARIANT ObjectName )

Access iconic objects that were created during the search or decoding of bar code symbols.
With the operator GetBarCodeObject, iconic objects created during the last call of the operator
FindBarCode can be accessed. Besides the name of the object (ObjectName), the bar code model
(BarCodeHandle) must be passed to GetBarCodeObject. In addition, in CandidateHandle an in-
dex to a single decoded symbol or a single symbol candidate must be passed. Alternatively, CandidateHandle
can be set to ’all’ and then all objects of the decoded symbols or symbol candidates are returned.
Setting ObjectName to ’symbol_regions’ will return regions of successfully decoded symbols. When choosing
’all’ as CandidateHandle, the regions of all decoded symbols are retrieved. The order of the returned objects
is the same as in FindBarCode. If there is a total of n decoded symbols CandidateHandle can be chosen
in between 0 and (n-1) to get the region of the respective decoded symbol.
Setting ObjectName to ’candidate_regions’ will return regions of potential bar codes. If there is a total of n
decoded symbols out of a total of m candidates then CandidateHandle can be chosen between 0 and (m-1).
With CandidateHandle between 0 and (n-1) the original segmented region of the respective decoded symbol
is retrieved. With CandidateHandle between n and (m-1) the region of the potential or undecodable symbol
is returned. In addition, CandidateHandle can be set to ’all’ to retrieve all candidate regions at the same time.
Setting ObjectName to ’scanlines_all’ or ’scanlines_valid’ will return XLD contours representing the partic-
ular detected bars in the scanlines applied on the candidate regions. ’scanlines_all’ represents all scanlines that
FindBarCode whould place in order to decode a barcode. ’scanlines_valid’ represents only those scanlines that
could be successfully decoded. For single row bar codes, there will be at least one ’scanlines_valid’ if the symbol
was successfully decoded. There will be no ’scanlines_valid’ if it was not decoded. For stacked bar codes (e.g.
’RSS-14 Stacked’ and ’RSS Expanded Stacked’) this rule applies similarly, but on a per-symbol-row basis rather
then per-symbol. Note that GetBarCodeObject returns all XLD contours merged into a single array of XLDs
and hence there is no way to identify the contours corresponding to separate scanlines. Furthermore, if ’all’ is used
as CandidateHandle, the output object will contain XLD contours for all symbols and in this case there is no
way to identify the contours corresponding to separate symbols as well. However, the contours still can be used
for visualization purposes.
Parameter

. BarCodeObjects (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . object(-array) ; HUntypedObjectX


Objects that are created as intermediate results during the detection or evaluation of bar codes.
. BarCodeHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . barcode ; HBarCodeX / VARIANT
Handle of the bar code model.
. CandidateHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer, string )
Indicating the bar code results respectively candidates for which the data is required.
Default Value : ’all’
Suggested values : CandidateHandle ∈ {0, 1, 2, ’all’}
. ObjectName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Name of the iconic object to return.
Default Value : ’symbol_regions’
List of values : ObjectName ∈ {’symbol_regions’, ’candidate_regions’, ’scanlines_all’, ’scanlines_valid’}
Example

Result
The operator GetBarCodeObject returns the value TRUE if the given parameters are correct and the requested
objects are available for the last symbol search. Otherwise, an exception will be raised.
Parallelization Information
GetBarCodeObject is reentrant and processed without parallelization.

HALCON 8.0.2
1092 CHAPTER 15. TOOLS

Possible Predecessors
FindBarCode
See also
GetBarCodeResult
Module
Bar Code

[out] VARIANT GenParamValues HBarCodeX.GetBarCodeParam


([in] VARIANT GenParamNames )
void HOperatorSetX.GetBarCodeParam ([in] VARIANT BarCodeHandle,
[in] VARIANT GenParamNames, [out] VARIANT GenParamValues )

Get one or several parameters that describe the bar code model.
The operator GetBarCodeParam allows to query parameters of a bar code model, which are of relevance for a
successful search and decoding of a respective class of bar codes.
The names of the desired parameters are passed in the generic parameter GenParamNames and the corresponding
values are returned in GenParamValues. All of these parameters can be set and changed at any time with the
operator SetBarCodeParam.
The following parameters can be queried – ordered by different categories:
Size of the bar code elements:

’element_size_min’: Minimal size of the bar code elements.

’element_size_max’: Maximal size of the bar code elements.

’element_height_min’: Minimal height of the bar code.

Orientation of bar code elements:

’orientation’: Accepted orientation of the decoded bar codes.

’orientation_tol’: Tolerance of the accepted orientation.

Appearance of the bar code in the image:

’meas_thresh’: Threshold for the detection of edges in the bar code region.

’max_diff_orient’: Maximal difference in the orientation of edges in a bar code region. The difference in oriented
angles, given in degree, refers to neighboring pixels.

Bar code specific values:

’check_char’: Presence of a check character.

’composite_code’: Presence and type of a 2D composite code appended to the barcode.

Further details on the above parameters can be found with the description of SetBarCodeParam operator.

HALCON/COM Reference Manual, 2008-5-13


15.4. BARCODE 1093

Parameter
. BarCodeHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . barcode ; HBarCodeX / VARIANT
Handle of the bar code model.
. GenParamNames (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . attribute.name(-array) ; VARIANT ( string )
Names of the generic parameters that are to be queried for the bar code model.
Default Value : ’element_size_max’
List of values : GenParamNames ∈ {’element_size_min’, ’element_size_max’, ’element_height_min’,
’orientation’, ’orientation_tol’, ’meas_thresh’, ’max_diff_orient’, ’check_char’, ’composite_code’}
. GenParamValues (output control) . . . . . . . . . . . attribute.name(-array) ; VARIANT ( integer, string, real )
Values of the generic parameters.
Example

Result
The operator GetBarCodeParam returns the value TRUE if the given parameters are correct. Otherwise, an
exception will be raised.
Parallelization Information
GetBarCodeParam is reentrant and processed without parallelization.
Possible Predecessors
CreateBarCodeModel, SetBarCodeParam
Possible Successors
SetBarCodeParam
Module
Bar Code

[out] VARIANT BarCodeResults HBarCodeX.GetBarCodeResult


([in] VARIANT CandidateHandle, [in] String ResultName )
void HOperatorSetX.GetBarCodeResult ([in] VARIANT BarCodeHandle,
[in] VARIANT CandidateHandle, [in] VARIANT ResultName,
[out] VARIANT BarCodeResults )

Get the alphanumerical results that were accumulated during the decoding of bar code symbols.
The operator GetBarCodeResult allows to access alphanumeric results of the find and decode process. To
access a result, first the handle of the bar code model (BarCodeHandle) and the index of the resulting symbol
(CandidateHandle) must be passed. CandidateHandle refers to the results, in the same order that is
returned by operator FindBarCode. CandidateHandle can take numbers from 0 to (n-1), where n is the
total number of successfully decoded symbols. Alternatively, CandidateHandle can be set to ’all’ if all results
are desired. The option ’all’ can be chosen only in the case where the return value of a single result is single
valued.
When ResultName is set to ’decoded_strings’ the decoded result is returned as a string in a human readable
format. This decoded string can be returned for a single result, i.e., CandidateHandle is for example 0, or for
all results simultaneously, i.e., CandidateHandle is set to ’all’. Note, that only data characters are comprised
in the decoded string. Start/stop characters are excluded, but can be refered to via ’decoded_reference’. For codes
with a facultative check character it depends on the settings whether the check character is returned or not. When
’check_char’ is set to the default value ’absent’ the decoded string takes the check character as a normal data
character. When ’check_char’ is set to ’present’ and if the check character is correct it will be ignored in the string.
If the check character is wrong the resulting string is an empty string.
When choosing ’decoded_reference’ as ResultName the underlying decoded reference data is returned. It com-
prises all original characters of the symbol, i.e., data characters, potential start or stop characters and check charac-
ters if present. For codes taking only numeric data, like, e.g., the EAN/UPC codes, the RSS-14 and RSS Limited
codes, or the 2/5 codes, the decoded reference data takes the same values as the decoded string data including check
characters. For codes with alphanumeric data, like for example code 39 or code 128 the decoded reference data are

HALCON 8.0.2
1094 CHAPTER 15. TOOLS

the indices of the respective decoding table. For RSS Expanded and RSS Expanded Stacked the reference values
are the ASCII codes of the decoded data, where the special charachter FNC1 appears with value 10. Furthermore,
for all codes from the RSS family the first reference value reprsents a linkage flag with value of 1 if the flag is set
and 0 otherwise. As the decoded reference is a tuple of whole numbers it can only be called for a single result,
meaning that CandidateHandle has to be the handle number of the corresponding decoded symbol.
When ResultName is set to ’composite_strings’ or ’composite_reference’, then the decoded string or the refer-
ence data of a RSS Composite component is returned, respectively. For further details see the description of the
parameter ’composite_code’ of SetBarCodeParam.
When ResultName is set to ’orientation’, the orientation for the specified result is returned. The ’orientation’ of
a bar code is defined as the angle between its reading direction and the horizontal image axis. The angle is positive
in counter clockwise direction and is given in degrees. It can be in the range of [-180.0 . . . 180.0] degrees. Note
that the reading direction is perpendicular to the bars of the bar code. A single angle is returned when only one
result is specified, e.g., by entering 0 for CandidateHandle. Otherwise, when CandidateHandle is set to
’all’, a tuple containing the angles of all results is returned.
Parameter

. BarCodeHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . barcode ; HBarCodeX / VARIANT


Handle of the bar code model.
. CandidateHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer, string )
Indicating the bar code results respectively candidates for which the data is required.
Default Value : ’all’
Suggested values : CandidateHandle ∈ {0, 1, 2, ’all’}
. ResultName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . attribute.name ; String / VARIANT
Names of the resulting data to return.
Default Value : ’decoded_strings’
Suggested values : ResultName ∈ {’decoded_strings’, ’decoded_reference’, ’orientation’,
’composite_strings’, ’composite_reference’}
. BarCodeResults (output control) . . . . . . . . . . . attribute.value(-array) ; VARIANT ( integer, real, string )
List with the results.
Example

Result
The operator GetBarCodeResult returns the value TRUE if the given parameters are correct and the requested
results are available for the last symbol search. Otherwise, an exception will be raised.
Parallelization Information
GetBarCodeResult is reentrant and processed without parallelization.
Possible Predecessors
FindBarCode
See also
GetBarCodeObject
Module
Bar Code

void HBarCodeX.SetBarCodeParam ([in] VARIANT GenParamNames,


[in] VARIANT GenParamValues )
void HOperatorSetX.SetBarCodeParam ([in] VARIANT BarCodeHandle,
[in] VARIANT GenParamNames, [in] VARIANT GenParamValues )

Set selected parameters of the bar code model.


The operator SetBarCodeParam is used to set or change the different parameters of a bar code model in order
to adapt to special properties of the bar codes or to a particular appearance in the image. All parameters can also

HALCON/COM Reference Manual, 2008-5-13


15.4. BARCODE 1095

be set while creating the bar code model with CreateBarCodeModel. The current configuration of the bar
code model can be queried with GetBarCodeParam.
The following overview lists the different generic parameters with the respective value ranges and default values:
Size of bar code elements:

’element_size_min’: Minimal size of bar code elements, i.e. the minimal width of bars and spaces. For small bar
codes the value should be reduced to 1.5. In the case of huge bar codes the value should be increased, which
results in a shorter execution time and fewer candidates.
Typical values: [1.5 . . . 10.0]
Default: 2.0
’element_size_max’: Maximal size of bar code elements, i.e. the maximal width of bars and spaces. The value of
’element_size_max’ should be adequate low such that two neighboring bar codes are not fused into a single
one. On this other hand the value should be sufficiently high in order to find the complete bar code region.
Typical values: [4.0 . . . 60.0]
Default: 8.0
’element_height_min’: Minimal bar code height. The default value of this parameter is -1, meaning that the bar
code reader automatically derives a reasonable height from the other parameters. Just for very flat and very
high bar codes a manual adjustment of this parameter can be necessary. In the case of a bar code with a height
of less than 16 pixels the respective height should be set by the user. Note, that the minimal value is 8 pixels.
If the bar code is very high, i.e. 70 pixels and more, manually adjusting to the respective height can lead to a
speed-up of the subsequent finding and reading operation.
Typical values: [-1, 8 . . . 64]
Default: -1

Orientation of bar code elements:

’orientation’: Expected bar code orientation. A potential (candidate) bar code contains bars with similar ori-
entation. The ’orientation’ and ’orientation_tol’ parameters are used to specify the range [’orientation’-
’orientation_tol’, ’orientation’+’orientation_tol’]. FindBarCode processes a candidate bar code only
when the avarage orientation of its bars lies in this range. If the bar codes are expected to appear only in
certain orientations in the processed images, one can reduce the orientation range adequately. This enables
an early identification of false candidates and hence shorter execution times. This adjustment can be used for
images with a lot of texture, which includes fragments tending to result in false bar code candidates.
The actual orientation angle of a bar code is explained with GetBarCodeResult(...,’orientation’,...) with
the only difference that for the early identification of false candidates the reading direction of the bar codes
is ignored, which results in relevant orientation values only in the range [-90.0 . . . 90.0]. The only exception
to this rule constitutes the bar code symbol PharmaCode, which possesses a forward and a backward reading
direction at the same time: here, ’orientation’ can take values in the range [-180.0 . . . 180.0] and the decoded
result is unique corresponding to just one reading direction.
Typical values: [-90.0 . . . 90.0]
Default: 0.0
’orientation_tol’: Orientation tolerance. See the explanation of ’orientation’ parameter. As explained there, rel-
evant orientation values are only in the range of [-90.0 . . . 90.0], which means that with ’orientation_tol’ =
90 the whole range is spanned. Therefore, valid values for ’orientation_tol’ are only in the range of [0.0
. . . 90.0]. The default value 90.0 means that no restriction on the bar code candidates is performed.
Typical values: [0.0 . . . 90.0]
Default: 90.0

Appearance of the bar code in the image:

’meas_thresh’: The bar-space-sequence of a bar code is determined with a scanline measuring the position of the
edges. Finding these edges requires a threshold. ’meas_thresh’ defines this threshold which is a relative value
with respect to the dynamic range of the scanline pixels. In the case of disturbances in the bar code region or
a high noise level, the value of ’meas_thresh’ should be increased.
Typical values: [0.05 . . . 0.2]
Default: 0.05
’max_diff_orient’: A potential bar code region contains bars, and hence edges, with a similar orientation. The
value max_diff_orient denotes the maximal difference in this orientation between adjacent pixels and is given

HALCON 8.0.2
1096 CHAPTER 15. TOOLS

in degree. If a bar code is of bad quality with jagged edges the parameter max_diff_orient should be set to
bigger values. If the bar code is of good quality max_diff_orient can be set to smaller values, thus reducing
the number of potential but false bar code candidates.
Typical values: [2 . . . 20]
Default: 10

Bar code specific values:

’check_char’: For bar codes with a facultative check character, this parameter determines whether the check char-
acter is taken into account or not. If the bar code has a check character, ’check_char’ should be set to ’present’
and thus the check character is tested. In that case, a bar code result is returned only if the check sum is cor-
rect. For ’check_char’ set to ’absent’ no check sum is computed and bar code results are retunred as long as
they were successfully decoded. Bar codes with a facultative check character are, e.g. Code 39, Codabar, 25
Industrial and 25 Interleaved.
Values: [’absent’, ’present’]
Default: ’absent’
’composite_code’: EAN.UPC bar codes can have an additional 2D Composite code component appended. If
’composite_code’ is set to ’CC-A/B’ the composite component will be found and decoded. By default, ’com-
posite_code’ is set to ’none’ and thus it is disabled. If the searched bar code symbol has no attached composite
component, just the result of the bar code itself is returned by FindBarCode. Composite codes are sup-
ported only for bar codes of the RSS family.
Values: [’none’, ’CC-A/B’]
Default: ’none’

Parameter

. BarCodeHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . barcode ; HBarCodeX / VARIANT


Handle of the bar code model.
. GenParamNames (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . attribute.name(-array) ; VARIANT ( string )
Names of the generic parameters that shall be adjusted for finding and decoding bar codes.
Default Value : ’element_size_max’
List of values : GenParamNames ∈ {’element_size_min’, ’element_size_max’, ’element_height_min’,
’orientation’, ’orientation_tol’, ’meas_thresh’, ’max_diff_orient’, ’check_char’, ’composite_code’}
. GenParamValues (input control) . . . . . . . . . . . . attribute.name(-array) ; VARIANT ( integer, string, real )
Values of the generic parameters that are adjusted for finding and decoding bar codes.
Default Value : 8
Suggested values : GenParamValues ∈ {0.1, 1.5, 2, 8, 32, 45, ’present’, ’absent’, ’none’, ’CC-A/B’}
Example

Result
The operator SetBarCodeParam returns the value TRUE if the given parameters are correct. Otherwise, an
exception will be raised.
Parallelization Information
SetBarCodeParam is reentrant and processed without parallelization.
Possible Predecessors
CreateBarCodeModel
Possible Successors
FindBarCode
Module
Bar Code

HALCON/COM Reference Manual, 2008-5-13


15.5. CALIBRATION 1097

15.5 Calibration
[out] VARIANT X HMiscX.CaltabPoints ([in] String CalTabDescrFile,
[out] VARIANT Y, [out] VARIANT Z )
void HOperatorSetX.CaltabPoints ([in] VARIANT CalTabDescrFile,
[out] VARIANT X, [out] VARIANT Y, [out] VARIANT Z )

Read the mark center points from the calibration plate description file.
CaltabPoints reads the mark center points from the calibration plate description file CalTabDescrFile
(see GenCaltab) and returns their coordinates in X, Y und Z. The mark center points are 3D coordinates in
the calibration plate coordinate system und describe the 3D model of the calibration plate. The calibration plate
coordinate system is located in the middle of the surface of the calibration plate, its z-axis points into the calibration
plate, its x-axis to the right, and it y-axis downwards.
The mark center points are typically used as input parameters for the operator CameraCalibration. This
operator projects the model points into the image, minimizes the distance between the projected points and the
observed 2D coordinates in the image (see FindMarksAndPose), and from this computes the exact values for
the interior and exterior camera parameters.
Parameter
. CalTabDescrFile (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.read ; String / VARIANT
File name of the calibration plate description.
Default Value : ’caltab.descr’
List of values : CalTabDescrFile ∈ {’caltab.descr’, ’caltab_10mm.descr’, ’caltab_30mm.descr’,
’caltab_100mm.descr’, ’caltab_200mm.descr’}
. X (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
X coordinates of the mark center points in the coordinate system of the calibration plate.
. Y (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Y coordinates of the mark center points in the coordinate system of the calibration plate.
. Z (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Z coordinates of the mark center points in the coordinate system of the calibration plate.
Example

* read_image(Image1, ’calib-01’)
* find calibration pattern
find_caltab(Image1, Caltab1, ’caltab.descr’, 3, 112, 5)
* find calibration marks and start poses
StartCamPar := [0.008, 0.0, 0.000011, 0.000011, 384, 288, 768, 576]
find_marks_and_pose(Image1,Caltab1,’caltab.descr’, StartCamPar,
128, 10, 18, 0.9, 15.0, 100.0, RCoord1, CCoord1,
StartPose1)
* read 3D positions of calibration marks
caltab_points(’caltab.descr’, NX, NY, NZ) >
* camera calibration
camera_calibration(NX, NY, NZ, RCoord1, CCoord1, StartCamPar,
StartPose1, ’all’, CamParam, FinalPose, Errors)
* visualize calibration result
disp_image(Image1, WindowHandle)
set_color(WindowHandle, ’red’)
disp_caltab(’caltab.descr’, CamParam, FinalPose, 1.0)

Result
CaltabPoints returns TRUE if all parameter values are correct and the file CalTabDescrFile has been
read successfully. If necessary, an exception handling is raised.
Parallelization Information
CaltabPoints is reentrant and processed without parallelization.
Possible Successors
CameraCalibration

HALCON 8.0.2
1098 CHAPTER 15. TOOLS

See also
FindCaltab, FindMarksAndPose, CameraCalibration, DispCaltab, SimCaltab,
Project3DPoint, GetLineOfSight, GenCaltab
Module
Foundation

[out] VARIANT CamParam HHomMat2dX.CamMatToCamPar ([in] double Kappa,


[in] long ImageWidth, [in] long ImageHeight )
void HOperatorSetX.CamMatToCamPar ([in] VARIANT CameraMatrix,
[in] VARIANT Kappa, [in] VARIANT ImageWidth, [in] VARIANT ImageHeight,
[out] VARIANT CamParam )

Compute the interior camera parameters from a camera matrix.


CamMatToCamPar computes interior camera parameters from the camera matrix CameraMatrix, the radial
distortion coefficient Kappa, the image width ImageWidth, and the image height ImageHeight. The cam-
era parameters are returned in CamParam. The parameters CameraMatrix and Kappa can be determined
with StationaryCameraSelfCalibration. CamMatToCamPar converts this representation of the in-
ternal camera parameters into the representation used by CameraCalibration. The conversion can only be
performed if the skew of the image axes is set to 0 in StationaryCameraSelfCalibration, i.e., if the
parameter ’skew’ is not being determined.
Parameter

. CameraMatrix (input control) . . . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )


3 × 3 projective camera matrix that determines the interior camera parameters.
. Kappa (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Kappa.
. ImageWidth (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Width of the images that correspond to CameraMatrix.
Restriction : (ImageW idth > 0)
. ImageHeight (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Height of the images that correspond to CameraMatrix.
Restriction : (ImageHeight > 0)
. CamParam (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Interior camera parameters.
Number of elements : (CamP aram = 8)
Example

* For the input data to stationary_camera_self_calibration, please


* refer to the example for stationary_camera_self_calibration.
stationary_camera_self_calibration (4, 640, 480, 1, From, To,
HomMatrices2D, Rows1, Cols1,
Rows2, Cols2, NumMatches,
’gold_standard’,
[’focus’,’principal_point’,’kappa’],
’true’, CameraMatrix, Kappa,
RotationMatrices, X, Y, Z, Error)
cam_mat_to_cam_par (CameraMatrix, Kappa, 640, 480, CamParam)

Result
If the parameters are valid, the operator CamMatToCamPar returns the value TRUE. If necessary an exception
handling is raised.
Parallelization Information
CamMatToCamPar is reentrant and processed without parallelization.

HALCON/COM Reference Manual, 2008-5-13


15.5. CALIBRATION 1099

Possible Predecessors
StationaryCameraSelfCalibration
See also
CameraCalibration, CamParToCamMat
Module
Calibration

void HHomMat2dX.CamParToCamMat ([in] VARIANT CamParam,


[out] long ImageWidth, [out] long ImageHeight )
void HOperatorSetX.CamParToCamMat ([in] VARIANT CamParam,
[out] VARIANT CameraMatrix, [out] VARIANT ImageWidth,
[out] VARIANT ImageHeight )

Compute a camera matrix from interior camera parameters.


CamParToCamMat computes the camera matrix CameraMatrix as well as the image width ImageWidth,
and the image height ImageHeight from the internal camera parameters CamParam. The internal
camera parameters CamParam can be determined with CameraCalibration. CamParToCamMat
converts this representation of the internal camera parameters into the representation used by
StationaryCameraSelfCalibration. The conversion can only be performed if the radial distor-
tion coefficient Kappa is 0. If necessary, ChangeRadialDistortionCamPar must be used to achieve
this.
Parameter

. CamParam (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )


Interior camera parameters.
Number of elements : (CamP aram = 8)
. CameraMatrix (output control) . . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )
3 × 3 projective camera matrix that corresponds to CamParam.
. ImageWidth (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Width of the images that correspond to CameraMatrix.
Restriction : (ImageW idth > 0)
. ImageHeight (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Height of the images that correspond to CameraMatrix.
Restriction : (ImageHeight > 0)
Example

* For the input data to camera_calibration, please refer to the


* example for camera_calibration.
camera_calibration (X, Y, Z, Rows, Cols, StartCamParam, StartPoses,
[’all’,’~kappa’], CamParam, FinalPoses, Errors)
cam_par_to_cam_mat (CamParam, CameraMatrix, ImageWidth, ImageHeight)

* Alternatively, the following calls can be used.


camera_calibration (X, Y, Z, Rows, Cols, StartCamParam, StartPoses,
’all’, CamParam, FinalPoses, Errors)
change_radial_distortion_cam_par (’adaptive’, CamParam, 0, CamParamOut)
cam_par_to_cam_mat (CamParamOut, CameraMatrix, ImageWidth, ImageHeight)

Result
If the parameters are valid, the operator CamParToCamMat returns the value TRUE. If necessary an exception
handling is raised.
Parallelization Information
CamParToCamMat is reentrant and processed without parallelization.

HALCON 8.0.2
1100 CHAPTER 15. TOOLS

Possible Predecessors
CameraCalibration
See also
StationaryCameraSelfCalibration, CamMatToCamPar
Module
Calibration

[out] VARIANT CamParam HPoseX.CameraCalibration ([in] VARIANT NX,


[in] VARIANT NY, [in] VARIANT NZ, [in] VARIANT NRow, [in] VARIANT NCol,
[in] VARIANT StartCamParam, [in] VARIANT NStartPose,
[in] VARIANT EstimateParams, [out] VARIANT NFinalPose, [out] VARIANT Errors )
void HOperatorSetX.CameraCalibration ([in] VARIANT NX,
[in] VARIANT NY, [in] VARIANT NZ, [in] VARIANT NRow, [in] VARIANT NCol,
[in] VARIANT StartCamParam, [in] VARIANT NStartPose,
[in] VARIANT EstimateParams, [out] VARIANT CamParam,
[out] VARIANT NFinalPose, [out] VARIANT Errors )

Determine all camera parameters by a simultanous minimization process.


CameraCalibration performs the calibration of a camera. For this, known 3D model points (with coordinates
NX, NY, NZ) are projected in the image and the sum of the squared distance between these projections and the
corresponding image points (with coordinates NRow, NCol) is minimized.
If the minimization converges, the exact interior (CamParam) and exterior (NFinalPose) camera parameters
are determined by this minimization algorithm. The parameters StartCamParam and NStartPose are used as
initial values for the minimization process. Since this algorithm simultaneously handles correspondences between
image and model points from different images, it is also called multi-image calibration.
In general, camera calibration means the exact determination of the parameters that model the (optical) projection
of any 3D world point Pw into a (sub-)pixel [r,c] in the image. This is important, if the original 3D pose of an
object has to be computed using an image (e.g., measuring of industrial parts).

Used 3D camera model


The projection consists of multiple steps: First, the point pw is transformed from world into camera coordinates
(points as homogeneous vectors, compare AffineTransPoint3D):
 
x
pc
     w 
 y  R t p
= 
  = ·
1 z  000 1 1
1

Then, the point is projected into the image plane, i.e., onto the sensor chip.
For the modeling of this projection process that is determined by the used combination of camera, lens, and frame
grabber, HALCON provides the following three 3D camera models:

• Area scan pinhole camera:


The combination of an area scan camera with a lens that effects a perspective projection and that may show
radial distortions.
• Area scan telecentric camera:
The combination of an area scan camera with a telecentric lens that effects a parallel projection and that may
show radial distortions.
• Line scan pinhole camera:
The combination of a line scan camera with a lens that effects a perspective projection and that may show
radial distortions.

For area scan cameras, the projection of the point pc that is given in camera coordinates into a (sub-)pixel [r,c]
in the image consists of the following steps: First, the point is projected into the image plane, i.e., onto the sensor

HALCON/COM Reference Manual, 2008-5-13


15.5. CALIBRATION 1101

chip. If the underlying camera model is an area scan pinhole camera, i.e., if the focal length passed in CamParam
is greater than 0, the projection is described by the following equations:
 
x
pc =  y 
z
x y
u = Focus · and v = Focus ·
z z
In contrast, if the focal length is passed as 0 in CamParam, the camera model of an area scan telecentric camera
is used, i.e., it is assumed that the optics of the lens of the camera performs a parallel projection. In this case, the
corresponding equations are:
 
x
pc =  y 
z

u = x and v=y

The following equations perform the radial distortion of the points:

2u 2v
ũ = p and ṽ = p
1+ 1− 4κ(u2 + v2 ) 1+ 1 − 4κ(u2 + v 2 )

Finally, the point is transformed from the image plane coordinate system into the image coordinate system, i.e.,
the pixel coordinate system:

ũ ṽ
c= + Cx and r= + Cy
Sx Sy

For line scan cameras, also the relative motion between the camera and the object must be modeled. In HALCON,
the following assumptions for this motion are made:

1. the camera moves with constant velocity along a straight line


2. the orientation of the camera is constant
3. the motion is equal for all images

The motion is described by the motion vector V = (Vx , Vy , Vz )T that must be given in [meter/scanline] in the
camera coordinate system. The motion vector describes the motion of the camera, assuming a fixed object. In fact,
this is equivalent to the assumption of a fixed camera with the object travelling along −V .
The camera coordinate system of line scan cameras is defined as follows: The origin of the coordinate system is the
center of projection. The z-axis is identical to the optical axis and directed so that the visible points have positive z
coordinates. The y-axis is perpendicular to the sensor line and to the z-axis. It is directed so that the motion vector
has a positive y-component. The x-axis is perpendicular to the y- and z-axis, so that the x-, y-, and z-axis form a
right-handed coordinate system.
As the camera moves over the object during the image acquisition, also the camera coordinate system moves
relatively to the object, i.e., each image line has been imaged from a different position. This means, there would
be an individual pose for each image line. To make things easier, in HALCON, all transformations from world
coordinates into camera coordinates and vice versa are based on the pose of the first image line only. The motion
V is taken into account during the projection of the point pc into the image. Consequently, only the pose of the
first image line is returned by the operators FindMarksAndPose and CameraCalibration.
For line scan pinhole cameras, the projection of the point pc that is given in the camera coordinate system into a
(sub-)pixel [r,c] in the image is defined as follows:
Assuming
 
x
pc =  y  ,
z

HALCON 8.0.2
1102 CHAPTER 15. TOOLS

the following set of equations must be solved for m, ũ, and t:

m · D · ũ = x − t · Vx
−m · D · pv = y − t · Vy
m · Focus = z − t · Vz

with

1
D =
1 + κ(ũ2 + (pv )2 )
pv = Sy · Cy

This already includes the compensation for radial distortions.


Finally, the point is transformed into the image coordinate system, i.e., the pixel coordinate system:


c= + Cx and r=t
Sx

Camera parameters
The total of 14 camera parameters for area scan cameras and 17 camera parameters for line scan cameras, respec-
tively, can be divided into the interior and exterior camera parameters:

Interior camera parameters: These parameters describe the characteristics of the used camera, especially the
dimension of the sensor itself and the projection properties of the used combination of lens, camera, and
frame grabber.
For area scan cameras, the above described camera model contains the following 8 parameters:
Focus: Focal length of the lens. 0 for telecentric lenses.
Kappa (κ): Distortion coefficient to model the pillow- or barrel-shaped distortions caused by the lens.
Sx : Scale factor. For pinhole cameras, it corresponds to the horizontal distance between two neighbor-
ing cells on the sensor. For telecentric cameras, it represents the horizontal size of a pixel in world
coordinates. Attention: This value increases, if the image is subsampled!
Sy : Scale factor. For pinhole cameras, it corresponds to the vertical distance between two neighboring
cells on the sensor. For telecentric cameras, it respresents the vertical size of a pixel in world coordi-
nates. Since in most cases the image signal is sampled line-synchronously, this value is determined
by the dimension of the sensor and needn’t be estimated for pinhole cameras by the calibration
process. Attention: This value increases, if the image is subsampled!
Cx : Column coordinate of the image center point (center of the radial distortion).
Cy : Row coordinate of the image center point (center of the radial distortion).
ImageWidth: Width of the sampled image. Attention: This value decreases, if the image is subsam-
pled!
ImageHeight: Height of the sampled image. Attention: This value decreases, if the image is subsam-
pled!
For line scan cameras, the above described camera model contains the following 11 parameters:
Focus: Focal length of the lens.
Kappa: Distortion coefficient to model the pin-cushion- or barrel-shaped distortions caused by the lens.
Sx : Scale factor, corresponds to the horizontal distance between two neighboring cells on the sensor.
Attention: This value increases if the image is subsampled!
Sy : Scale factor. During the calibration, it appears only in the form pv = Sy · Cy . pv describes the
distance of the image center point from the sensor line in [meters]. Attention: This value increases
if the image is subsampled!
Cx : Column coordinate of the image center point (center of the radial distortion).
Cy : Distance of the image center point (center of the radial distortion) from the sensor line in [scanlines].
ImageWidth: Width of the sampled image. Attention: This value decreases if the image is subsampled!

HALCON/COM Reference Manual, 2008-5-13


15.5. CALIBRATION 1103

ImageHeight: Height of the sampled image. Attention: This value decreases if the image is subsam-
pled!
Vx : X-component of the motion vector.
Vy : Y-component of the motion vector.
Vz : Z-component of the motion vector.
Note that the term focal length is not quite correct and would be appropriate only for an infinite object
distance. To simplify matters, always the term focal length is used even if the image distance is meant.
Exterior camera parameters: These 6 parameters describe the 3D pose, i.e., the position and orientation, of the
world coordinate system relative to the camera coordinate system. For line scan cameras, the pose of the
world coordinate system refers to the camera coordinate system of the first image line. Three parameters
describe the translation, three the rotation. See CreatePose for more information about 3D poses. Note
that CameraCalibration operates with all types of 3D poses for NStartPose.
When using the standard calibration plate, the world coordinate system is defined by the coordinate system
of the calibration plate which is located in the middle of the surface of the calibration plate, its z-axis pointing
into the calibration plate, its x-axis to the right, and it y-axis downwards.

Additional information about the calibration process


The use of CameraCalibration leads to some questions, which are dealed with in the following sections:

How to generate a appropriate calibration plate? The simplest method to determine the interior parameters of
a camera is the use of the standard calibration plate as generated by the operator GenCaltab. You can
obtain high-precision calibration plates in various sizes and materials from your local distributor. In case of
small distances between object and lens it may be sufficient to print the calibration pattern by a laser printer
and to mount it on a cardboard. Otherwise – especially by using a wide-angle lens – it is possible to print
the PostScript file on a large ink-jet printer and to mount it on a aluminum plate. It is very important that
the mark coordinates in the calibration plate description file correspond to the real ones on the calibration
plate with high accuracy. Thus, the calibration plate description file has to be modified in accordance with
the measurement of the calibration plate!
How to take a set of suitable images? If you use the standard calibration plate, you can proceed in the following
way: With the combination of lens (fixed distance!), camera, and frame grabber to be calibrated a set of
images of the calibration plate has to be taken, see OpenFramegrabber and GrabImage. The following
items have to be considered:
• At least a total of 10 to 20 images should be taken into account.
• The calibration plate has to be completely visible (incl. border!).
• Reflections etc. on the calibration plate should be avoided.
• Within the set of images the calibration plate should appear in different positions and orientations: Once
left in the image, once right, once (left and right) at the bottom, once (left or right) at the top, from
different distances etc. At this, the calibration plate should be rotated around its x- and/or y-axis, so the
perspective distortions of the calibration pattern are clearly visible. Thus, the exterior camera parameters
(camera pose with regard of the calibration plate) should be set to a large variety of different values!
• The calibration plate should fill at least a quarter of the whole image to ensure the robust detection of the
marks.
How to extract the calibration marks in the images? If a standard calibration plate is used, you can use the
operators FindCaltab and FindMarksAndPose to determine the coordinates of the calibration marks
in each image and to compute a rough estimate for the exterior camera parameters. The concatenation of
these values can directly be used as initial values for the exterior camera parameters (NStartPose) in
CameraCalibration.
Obviously, images in which the segmentation of the calibration plate ( FindCaltab) has failed or the
calibration marks haven’t been determined successfully by FindMarksAndPose should not be used.
How to find suitable initial values for the interior camera parameters? The operators
FindMarksAndPose (determination of initial values for the exterior camera parameters) and
CameraCalibration require initial values for the interior camera parameters. These parameters
can be provided by a appropriate text file (see ReadCamPar) which can be generated by WriteCamPar
or can be edited manually.
For area scan cameras, the following should be considered for the initial values of the single parameters:

HALCON 8.0.2
1104 CHAPTER 15. TOOLS

Focus: The initial value is the nominal focal length of the the used lens, e.g., 0.008 m.
Kappa: Use 0.0 as initial value.
Sx : The initial value for the horizontal distance between two neighboring cells depends on the dimen-
sion of the used chip of the camera (see technical specifications of the camera). Generally, common
chips are either 1/3”-Chips (e.g., SONY XC-73, SONY XC-777), 1/2”-Chips (e.g., SONY XC-999,
Panasonic WV-CD50), or 2/3”-Chips (e.g., SONY DXC-151, SONY XC-77). Notice: The value of
Sx increases if the image is subsampled! Appropriate initial values are:
Full image (768*576) Subsampling (384*288)
1/3"-Chip 0.0000055 m 0.0000110 m
1/2"-Chip 0.0000086 m 0.0000172 m
2/3"-Chip 0.0000110 m 0.0000220 m

The value for Sx is calibrated, since the video signal of a camera normally isn’t sampled pixel-
synchronously.
Sy : Since most off-the-shelf cameras have quadratic pixels, the same values for Sy are valid as for Sx .
In contrast to Sx the value for Sy will not be calibrated for pinhole cameras, because the video
signal of a camera normally is sampled line-synchronously. Thus, the initial value is equal to the
final value. Appropriate initial values are:
Full image (768*576) Subsampling (384*288)
1/3"-Chip 0.0000055 m 0.0000110 m
1/2"-Chip 0.0000086 m 0.0000172 m
2/3"-Chip 0.0000110 m 0.0000220 m

Cx and Cy : Initial values for the coordinates of the image center is the half image width and half image
height. Notice: The values of Cx and Cy decrease if the image is subsampled! Appropriate initial
values are:
Full image (768*576) Subsampling (384*288)
Cx 384.0 192.0
Cy 288.0 144.0

ImageWidth and ImageHeight: These two parameters are determined by the the used frame grabber
and therefore are not calibrated. Appropriate initial values are, for example:
Full image (768*576) Subsampling (384*288)
ImageWidth 768 384
ImageHeight 576 288

For line scan cameras, the following should be considered for the initial values of the single parameters:
Focus: The initial value is the nominal focal length of the the used lens, e.g., 0.008 m.
Kappa: Use 0.0 as initial value.
Sx : The initial value for the horizontal distance between two neighboring cells can be taken from the
technical specifications of the camera. Typical initial values are 7e-6 m, 10e-6 m, and 14e-6 m.
Notice: The value of Sx increase, if the image is subsampled!
Sy : The initial value for the size of a cell in the direction perpendicular to the sensor line can also be
taken from the technical specifications of the camera. Typical initial values are 7e-6 m, 10e-6 m,
and 14e-6 m. Notice: The value of Sx increase, if the image is subsampled! In contrast to Sx , the
value for Sy will NOT be calibrated for line scan cameras, because it appears only in the form pv =
Sy · Cy . Therefore, it cannot be determined separately.
Cx : The initial value for the x-coordinate of the image center is the half image width. Notice: The
values of Cx decreases if the image is subsampled! Appropriate initial values are:
Image width: 1024 2048 4096 8192
Cx: 512 1024 2048 4096

Cy : The initial value for the y-coordinate of the image center can normally be set to 0.
ImageWidth and ImageHeight: These two parameters are determined by the used frame grabber and
therefore are not calibrated.

HALCON/COM Reference Manual, 2008-5-13


15.5. CALIBRATION 1105

Vx , Vy , Vz : The initial values for the x-, y-, and z-component of the motion vector depend on the image
acquisition setup. Assuming a camera that looks perpendicularly onto a conveyor belt, and that is
rotated around its optical axis such that the sensor line is perpendicular to the conveyor belt, i.e., the
y-axis of the camera coordinate system is parallel to the conveyor belt, the initial values Vx = Vz =
0. The initial value for Vy can then be determined, e.g., from a line scan image of an object with
known size (e.g., calibration plate, ruler):

Vy = l[m]/l[row]
with:
l[m] = Length of the object in object coordinates [meter]
l[row] = Length of the object in image coordinates [rows]

If, compared to the above setup, the camera is rotated 30 degrees around its optical axis, i.e., around
the z-axis of the camera coordinate system, the above determined initial values must be changed as
follows:

Vxz = sin(30) ∗ Vy
Vyz = cos(30) ∗ Vy
Vzz = Vz = 0

If, compared to the first setup, the camera is rotated -20 degrees around the x-axis of the camera
coordinate system, the following initial values result:

Vxx = Vx = 0
Vyx = cos(−20) ∗ Vy
Vzx = sin(−20) ∗ Vy

The quality of the initial values for Vx , Vy , and Vz are crucial for the success of the whole calibration.
If they are not precise enough, the calibration may fail.
Which camera parameters have to be estimated? The input parameter EstimateParams is used to select
which camera parameters to estimate. Usually this parameter is set to ’all’, i.e., all 6 exterior camera pa-
rameters (translation and rotation) and all interior camera parameters are determined. If the interior camera
parameters already have been determined (e.g., by a previous call to CameraCalibration) it is often
desired to only determine the pose of the world coordinate system in camera coordinates (i.e., the exterior
camera parameters). In this case, EstimateParams can be set to ’pose’. This has the same effect as
EstimateParams = [’alpha’,’beta’,’gamma’,’transx’,’transy’,’transz’]. Otherwise, EstimateParams
contains a tuple of strings indicating the combination of parameters to estimate. In addition, parameters can
be excluded from estimation by using the prefix ~. For example, the values [’pose’,’~transx’] have the same
effect as [’alpha’,’beta’,’gamma’,’transy’,’transz’]. Whereas [’all’,’~focus’] determines all internal and ex-
ternal parameters except the focus, for instance. The prefix ~ can be used with all parameter values except
’all’.
What is the order within the individual parameters? The length of the tuple NStartPose corresponds to the
number of calibration images, e.g., using 15 images leads to a length of the tuple NStartPose equal to
15 · 7 = 105 (15 times the 7 exterior camera parameters). The first 7 values correspond to the pose of the
calibration plate in the first image, the next 7 values to the pose in the second image, etc.
This fixed number of calibration images has to be considered within the tuples with the coordinates of the 3D
model marks and the extracted 2D marks. If 15 images are used, the length of the tuples NRow and NCol
is 15 times the length of the tuples with the coordinates of the 3D model marks (NX, NY, and NZ). If every
image consists 49 marks, the length of the tuples NRow and NCol is 15 · 49 = 735, while the length of the
tuples NX, NY, and NZ is 49. The order of the values in NRow and NCol is “image after image”, i.e., using
49 marks the first 3D model point corresponds to the 1st, 50th, 99th, 148th, 197th, 246th, etc. extracted 2D
mark.
The 3D model points can be read from a calibration plate description file using the operator
CaltabPoints. Initial values for the poses of the calibration plate can be determined by applying
FindMarksAndPose for each image. The tuple NStartPose is set by the concatenation of all these
poses.
What is the meaning of the output parameters? If the camera calibration process is finished successfully, i.e.,
the minimization process has converged, the output parameters CamParam and NFinalPose contain the

HALCON 8.0.2
1106 CHAPTER 15. TOOLS

computed exact values for the interior and exterior camera parameters. The length of the tuple NFinalPose
corresponds to the length of the tuple NStartPose.
The representation types of NFinalPose correspond to the representation type of the first tuple of
NStartPose (see CreatePose). You can convert the representation type by ConvertPoseType.
The computed average errors (Errors) give an impression of the accuracy of the calibration. The error
values (deviations in x and y coordinates) are measured in pixels.
Must I use a planar calibration object? No. The operator CameraCalibration is designed in a way that
the input tuples NX, NY, NZ, NRow, and NCol can contain any 3D/2D correspondences, see the above para-
graph explaining the order of the single parameters.
Thus, it makes no difference how the required 3D model marks and the corresponding extracted 2D marks are
determined. On one hand, it is possible to use a 3D calibration pattern, on the other hand, you also can use any
characteristic points (natural landmarks) with known position in the world. By setting EstimateParams
to ’pose’, it is thus possible to compute the pose of an object in camera coordinates! For this, at least three
3D/2D-correspondences are necessary as input. NStartPose can, e.g., be generated directly as shown in
the program example for CreatePose.

Attention
The minimization process of the calibration depends on the initial values of the interior (StartCamParam) and
exterior (NStartPose) camera parameters. The computed average errors Errors give an impression of the
accuracy of the calibration. The errors (deviations in x and y coordinates) are measured in pixels.
Parameter

. NX (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )


Ordered tuple with all x coordinates of the calibration marks (in meters).
. NY (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Ordered tuple with all y coordinates of the calibration marks (in meters).
. NZ (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Ordered tuple with all z coordinates of the calibration marks (in meters).
. NRow (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT
Ordered tuple with all row coordinates of the extracted calibration marks (in pixels).
. NCol (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT
Ordered tuple with all column coordinates of the extracted calibration marks (in pixels).
. StartCamParam (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( integer, real )
Initial values for the interior camera parameters.
. NStartPose (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pose ; VARIANT ( real, integer )
Ordered tuple with all initial values for the exterior camera parameters.
. EstimateParams (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( string, integer )
Camera parameters to be estimated.
Default Value : ’all’
List of values : EstimateParams ∈ {’all’, ’pose’, ’alpha’, ’beta’, ’gamma’, ’transx’, ’transy’, ’transz’,
’focus’, ’kappa’, ’cx’, ’cy’, ’sx’, ’sy’, ’vx’, ’vy’, ’vz’}
. CamParam (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Interior camera parameters.
. NFinalPose (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pose ; VARIANT ( real, integer )
Ordered tuple with all exterior camera parameters.
. Errors (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT
Average error distances in pixels.
Example

* read calibration images


read_image(Image1, ’calib-01’)
read_image(Image2, ’calib-02’)
read_image(Image3, ’calib-03’)
* find calibration pattern
find_caltab(Image1, Caltab1, ’caltab.descr’, 3, 112, 5)
find_caltab(Image2, Caltab2, ’caltab.descr’, 3, 112, 5)

HALCON/COM Reference Manual, 2008-5-13


15.5. CALIBRATION 1107

find_caltab(Image3, Caltab3, ’caltab.descr’, 3, 112, 5)


* find calibration marks and start poses
find_marks_and_pose(Image1, Caltab1, ’caltab.descr’,
[0.008, 0.0, 0.000011, 0.000011, 384, 288, 768, 576],
128, 10, 18, 0.9, 15.0, 100.0, RCoord1, CCoord1,
StartPose1)
find_marks_and_pose(Image2, Caltab2, ’caltab.descr’,
[0.008, 0.0, 0.000011, 0.000011, 384, 288, 768, 576],
128, 10, 18, 0.9, 15.0, 100.0, RCoord2, CCoord2,
StartPose2)
find_marks_and_pose(Image3, Caltab3, ’caltab.descr’,
[0.008, 0.0, 0.000011, 0.000011, 384, 288, 768, 576],
128, 10, 18, 0.9, 15.0, 100.0, RCoord3, CCoord3,
StartPose3)
* read 3D positions of calibration marks
caltab_points(’caltab.descr’, NX, NY, NZ)
* camera calibration
camera_calibration(NX, NY, NZ, [RCoord1, RCoord2, RCoord3],
[CCoord1, CCoord2, CCoord3],
[0.008, 0.0, 0.000011, 0.000011, 384, 288, 768, 576],
[StartPose1, StartPose2, StartPose3], ’all’,
CamParam, NFinalPose, Errors)
* write interior camera parameters to file
write_cam_par(CamParam, ’campar.dat’)

Result
CameraCalibration returns TRUE if all parameter values are correct and the desired camera parameters have
been determined by the minimization algorithm. If necessary, an exception handling is raised.
Parallelization Information
CameraCalibration is reentrant and processed without parallelization.
Possible Predecessors
FindMarksAndPose, CaltabPoints, ReadCamPar
Possible Successors
WritePose, PoseToHomMat3d, DispCaltab, SimCaltab
See also
FindCaltab, FindMarksAndPose, DispCaltab, SimCaltab, WriteCamPar, ReadCamPar,
CreatePose, ConvertPoseType, WritePose, ReadPose, PoseToHomMat3d, HomMat3dToPose,
CaltabPoints, GenCaltab
Module
Calibration

[out] VARIANT CamParOut HMiscX.ChangeRadialDistortionCamPar


([in] String Mode, [in] VARIANT CamParIn, [in] double Kappa )
void HOperatorSetX.ChangeRadialDistortionCamPar ([in] VARIANT Mode,
[in] VARIANT CamParIn, [in] VARIANT Kappa, [out] VARIANT CamParOut )

Determine new camera parameters in accordance to the specified radial distortion.


ChangeRadialDistortionCamPar modifies the interior camera parameters in accordance to the specified
radial distortion Kappa. Via Mode one of the following modes can be selected:

• ’fixed’: Only Kappa is modified, the other interior camera parameters remain unchanged. In general, this
leads to a change of the visible part of the scene.
• ’fullsize’: The scale factors Sx and Sy and the image center point [Cx , Cy ]T are modified in order to preserve
the visible part of the scene. Thus, all points visible in the original image are also visible in the modified
(rectified) image. In general, this leads to undefined pixels in the modified image.

HALCON 8.0.2
1108 CHAPTER 15. TOOLS

• ’adaptive’: A trade-off between the other modes: The visible part of the scene is slightly reduced to prevent
undefined pixels in the modified image. Similiarly to ’fullsize’, the scale factors and the image center point
are modified.
• ’preserve_resolution’: As in the mode ’fullsize’, all points visible in the original image are also visible in
the modified (rectified) image, i.e., the scale factors Sx and Sy and the image center point [Cx , Cy ]T are
modified. In general, this leads to undefined pixels in the modified image. In contrast to the mode ’fullsize’
additionally the size of the modified image is increased such that the image resolution does not decrease in
any part of the image.

In all modes the radial distortion coefficient κ in CamParOut is set to Kappa. The transformation of a pixel in
the modified image into the image plane using CamParOut results in the same point as the transformation of a
pixel in the original image via CamParIn.
Parameter

. Mode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT


Mode
Default Value : ’adaptive’
Suggested values : Mode ∈ {’fullsize’, ’adaptive’, ’fixed’, ’preserve_resolution’}
. CamParIn (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( integer, real )
Interior camera parameters (original).
. Kappa (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Desired radial distortion.
Default Value : 0.0
. CamParOut (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( integer, real )
Interior camera parameters (modified).
Result
ChangeRadialDistortionCamPar returns TRUE if all parameter values are correct. If necessary, an ex-
ception handling is raised.
Parallelization Information
ChangeRadialDistortionCamPar is reentrant and processed without parallelization.
Possible Predecessors
CameraCalibration, ReadCamPar
Possible Successors
ChangeRadialDistortionImage, ChangeRadialDistortionContoursXld,
GenRadialDistortionMap
See also
CameraCalibration, ReadCamPar, ChangeRadialDistortionImage,
ChangeRadialDistortionContoursXld
Module
Calibration

[out] HXLDContX ContoursRectified


HXLDContX.ChangeRadialDistortionContoursXld
([in] VARIANT CamParIn, [in] VARIANT CamParOut )
void HOperatorSetX.ChangeRadialDistortionContoursXld
([in] IHObjectX Contours, [out] HUntypedObjectX ContoursRectified,
[in] VARIANT CamParIn, [in] VARIANT CamParOut )

Change the radial distortion of contours.


ChangeRadialDistortionContoursXld changes the radial distortion of the input contours Contours
in accordance to the interior camera parameters CamParIn and CamParOut. Each subpixel of an input contour
is transformed into the image plane using CamParIn and subsequently projected into a subpixel of the corre-
sponding contour in ContoursRectified using CamParOut.

HALCON/COM Reference Manual, 2008-5-13


15.5. CALIBRATION 1109

If CamParOut was computed via ChangeRadialDistortionCamPar, the contours


ContoursRectified are equivalent to Contours obtained with a lens with a modified radial distor-
tion. If κ is 0 the contours are rectified. A subsequent pose estimation (determination of the exterior camera
parameters) is not affected by this operation.
Parameter
. Contours (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xld_cont(-array) ; HXLDContX / IHObjectX
Original contours.
. ContoursRectified (output iconic) . . . . . . . . . . . . xld_cont(-array) ; HXLDContX / HUntypedObjectX
Resulting contours with modified radial distortion.
. CamParIn (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( integer, real )
Interior camera parameter for Contours.
. CamParOut (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( integer, real )
Interior camera parameter for ContoursRectified.
Parallelization Information
ChangeRadialDistortionContoursXld is reentrant and processed without parallelization.
Possible Predecessors
ChangeRadialDistortionCamPar, GenContoursSkeletonXld, EdgesSubPix,
SmoothContoursXld
Possible Successors
GenPolygonsXld, SmoothContoursXld
See also
ChangeRadialDistortionCamPar, CameraCalibration, ReadCamPar,
ChangeRadialDistortionImage
Module
Calibration

[out] HImageX ImageRectified HImageX.ChangeRadialDistortionImage


([in] HRegionX Region, [in] VARIANT CamParIn, [in] VARIANT CamParOut )
void HOperatorSetX.ChangeRadialDistortionImage
([in] IHObjectX Image, [in] IHObjectX Region,
[out] HUntypedObjectX ImageRectified, [in] VARIANT CamParIn,
[in] VARIANT CamParOut )

Change the radial distortion of an image.


ChangeRadialDistortionImage changes the radial distortion of the input image Image in accordance to
the interior camera parameters CamParIn and CamParOut. Each pixel of the output image that lies within the
region Region is transformed into the image plane using CamParOut and subsequently projected into a subpixel
of Image using CamParIn. The resulting gray value is determined by bilinear interpolation. If the subpixel is
outside of Image, the corresponding pixel in ImageRectified is set to ’black’ and eliminated from the image
domain.
If the gray values of all pixels in the output image shall be calculated, it is sufficient to pass an empty object in
Region (which must be previously generated by, for example, using GenEmptyObj). This is especially useful
if the size of the output image differs from the size of the input image, and hence, it is not possible to simply pass
the region of the input image in Region.
If CamParOut was computed via ChangeRadialDistortionCamPar, ImageRectified is equivalent
to Image obtained with a lens with a modified radial distortion. If κ is 0 the image is rectified. A subsequent pose
estimation (determination of the exterior camera parameters) is not affected by this operation.
Parameter
. Image (input iconic) . . . . . . . . . . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, uint2 )
Original image.
. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
Region of interest in ImageRectified.

HALCON 8.0.2
1110 CHAPTER 15. TOOLS

. ImageRectified (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX (


byte, uint2 )
Resulting image with modified radial distortion.
. CamParIn (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( integer, real )
Interior camera parameter for Image.
. CamParOut (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( integer, real )
Interior camera parameter for Image.
Result
ChangeRadialDistortionImage returns TRUE if all parameter values are correct. If the input is empty
(no input image is available) the behavior can be set via SetSystem(’noObjectResult’,<Result>). If
necessary, an exception is raised.
Parallelization Information
ChangeRadialDistortionImage is reentrant and processed without parallelization.
Possible Predecessors
ChangeRadialDistortionCamPar, ReadImage, GrabImage
Possible Successors
EdgesImage, Threshold
See also
ChangeRadialDistortionCamPar, CameraCalibration, ReadCamPar,
ChangeRadialDistortionContoursXld
Module
Calibration

[out] HXLDContX ContoursTrans HXLDContX.ContourToWorldPlaneXld


([in] VARIANT CamParam, [in] VARIANT WorldPose, [in] VARIANT Scale )
[out] HXLDContX ContoursTrans HPoseX.ContourToWorldPlaneXld
([in] HXLDContX Contours, [in] VARIANT CamParam, [in] VARIANT WorldPose,
[in] VARIANT Scale )
void HOperatorSetX.ContourToWorldPlaneXld ([in] IHObjectX Contours,
[out] HUntypedObjectX ContoursTrans, [in] VARIANT CamParam,
[in] VARIANT WorldPose, [in] VARIANT Scale )

Transform an XLD contour into the plane z=0 of a world coordinate system.
The operator ContourToWorldPlaneXld transforms contour points given in Contours into the plane z=0
in a world coordinate system and returns the 3D contour points in ContoursTrans. The world coordinate
system is chosen by passing its 3D pose relative to the camera coordinate system in WorldPose. In CamParam
you must pass the interior camera parameters (see WriteCamPar for the sequence of the parameters and the
underlying camera model).
In many cases CamParam and WorldPose are the result of calibrating the camera with the operator
CameraCalibration. See below for an example.
With the parameter Scale you can scale the resulting 3D coordinates. The parameter Scale must be specified
as the ratio desired unit/original unit. The original unit is determined by the coordinates of the calibration object.
If the original unit is meters (which is the case if you use the standard calibration plate), you can set the desired
unit directly by selecting ’m’, ’cm’, ’mm’ or ’µm’ for the parameter Scale.
Internally, the operator first computes the line of sight between the projection center and the image point in the
camera coordinate system, taking into account the radial distortions. The line of sight is then transformed into the
world coordinate system specified in WorldPose. By intersecting the plane z=0 with the line of sight the 3D
coordinates of the transformed contour ContoursTrans are obtained.
Parameter
. Contours (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xld_cont(-array) ; HXLDContX / IHObjectX
Input XLD contours to be transformed in image coordinates.
. ContoursTrans (output iconic) . . . . . . . . . . . . . . . . . xld_cont(-array) ; HXLDContX / HUntypedObjectX
Transformed XLD contours in world coordinates.

HALCON/COM Reference Manual, 2008-5-13


15.5. CALIBRATION 1111

. CamParam (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )


Interior camera parameters.
Number of elements : ((CamP aram = 8) ∨ (CamP aram = 11))
. WorldPose (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pose ; VARIANT ( integer, real )
3D pose of the world coordinate system in camera coordinates.
Number of elements : 7
. Scale (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real, string )
Scale oder dimension
Default Value : ’m’
Suggested values : Scale ∈ {’m’, ’cm’, ’mm’, ’microns’, ’µm’, 1.0, 0.01, 0.001, 1.0e-6, 0.0254, 0.3048,
0.9144}
Example

* perform camera calibration (with standard calibration plate)


camera_calibration(NX, NY, NZ, NRow, NCol, StartCamParam, NStartPose, ’all’,
FinalCamParam, NFinalPose, Errors)
* world coordinate system is defined by calibration plate in first image
FinalPose1 := NFinalPose[0:6]
* compensate thickness of plate
set_origin_pose(FinalPose1, 0, 0, 0.0006, WorldPose)
* transform contours into world coordinate system (unit mm)
contour_to_world_plane_xld(Contours, ContoursTrans,
FinalCamParam, WorldPose, ’mm’)

Result
ContourToWorldPlaneXld returns TRUE if all parameter values are correct. If necessary, an exception
handling is raised.
Parallelization Information
ContourToWorldPlaneXld is reentrant and processed without parallelization.
Possible Predecessors
CreatePose, HomMat3dToPose, CameraCalibration, HandEyeCalibration, SetOriginPose
See also
ImagePointsToWorldPlane
Module
Calibration

void HMiscX.CreateCaltab ([in] double Width,


[in] String CalTabDescrFile, [in] String CalTabFile )
void HOperatorSetX.CreateCaltab ([in] VARIANT Width,
[in] VARIANT CalTabDescrFile, [in] VARIANT CalTabFile )

Generate a calibration plate description file and a corresponding PostScript file. (obsolete)
CreateCaltab has been replaced with the operator GenCaltab. The operator is contained and described for
compatibility reasons only.
CreateCaltab generates the description of a standard calibration plate for HALCON. This calibration plate
consists of 49 black circular marks on a white plane which are surrounded by a black frame. The parameter
Width sets the width (equal to the height) of the whole calibration plate in meters. Using a width of 0.8 m, the
distance between two neighboring marks becomes 10 cm, and the mark radius and the frame width are set to 2.5
cm. The calibration plate coordinate system is located in the middle of the surface of the calibration plate, its z-axis
points into the calibration plate, its x-axis to the right, and it y-axis downwards.
The file CalTabDescrFile contains the calibration plate description, e.g., the number of rows and columns
of the calibration plate, the geometry of the surrounding frame (see FindCaltab), and the coordinates and
the radius of all calibration plate marks given in the calibration plate coordinate system. A file generated by
CreateCaltab looks like the following (comments are marked by a ’#’ at the beginning of a line):

HALCON 8.0.2
1112 CHAPTER 15. TOOLS

#
# Description of the standard calibration plate
# used for the camera calibration in HALCON
#

# 7 rows X 7 columns
# Distance between mark centers [meter]: 0.1

# Number of marks per row


r 7

# Number of marks per column


c 7

# Quadratic frame (with outer and inner border) around calibration plate
w 0.025
o -0.41 0.41 0.41 -0.41
i -0.4 0.4 0.4 -0.4

# calibration marks: x y radius [Meter]

# calibration marks at y = -0.3 m


-0.3 -0.3 0.025
-0.2 -0.3 0.025
-0.1 -0.3 0.025
0 -0.3 0.025
0.1 -0.3 0.025
0.2 -0.3 0.025
0.3 -0.3 0.025

# calibration marks at y = -0.2 m


-0.3 -0.2 0.025
-0.2 -0.2 0.025
-0.1 -0.2 0.025
0 -0.2 0.025
0.1 -0.2 0.025
0.2 -0.2 0.025
0.3 -0.2 0.025

# calibration marks at y = -0.1 m


-0.3 -0.1 0.025
-0.2 -0.1 0.025
-0.1 -0.1 0.025
0 -0.1 0.025
0.1 -0.1 0.025
0.2 -0.1 0.025
0.3 -0.1 0.025

# calibration marks at y = 0 m
-0.3 0 0.025
-0.2 0 0.025
-0.1 0 0.025
0 0 0.025
0.1 0 0.025
0.2 0 0.025
0.3 0 0.025

# calibration marks at y = 0.1 m


-0.3 0.1 0.025

HALCON/COM Reference Manual, 2008-5-13


15.5. CALIBRATION 1113

-0.2 0.1 0.025


-0.1 0.1 0.025
0 0.1 0.025
0.1 0.1 0.025
0.2 0.1 0.025
0.3 0.1 0.025

# calibration marks at y = 0.2 m


-0.3 0.2 0.025
-0.2 0.2 0.025
-0.1 0.2 0.025
0 0.2 0.025
0.1 0.2 0.025
0.2 0.2 0.025
0.3 0.2 0.025

# calibration marks at y = 0.3 m


-0.3 0.3 0.025
-0.2 0.3 0.025
-0.1 0.3 0.025
0 0.3 0.025
0.1 0.3 0.025
0.2 0.3 0.025
0.3 0.3 0.025

The file CalTabFile contains the corresponding PostScript description of the calibration plate.
Attention
Depending on the accuracy of the used output device (e.g., laser printer), the printed calibration plate may not
match the values in the calibration plate descripton file CalTabDescrFile exactly. Thus, the coordinates of the
calibration marks in the calibration plate description file may have to be corrected!
Parameter
. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Width of the calibration plate in meters.
Default Value : 0.8
Suggested values : Width ∈ {1.2, 0.8, 0.6, 0.4, 0.2, 0.1}
Recommended Increment : 0.1
Restriction : (0.0 < W idth)
. CalTabDescrFile (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.write ; String / VARIANT
File name of the calibration plate description.
Default Value : ’caltab.descr’
List of values : CalTabDescrFile ∈ {’caltab.descr’, ’caltab_10mm.descr’, ’caltab_30mm.descr’,
’caltab_100mm.descr’, ’caltab_200mm.descr’}
. CalTabFile (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.write ; String / VARIANT
File name of the PostScript file.
Default Value : ’caltab.ps’
Example

* create calibration plate with width = 80 cm


create_caltab(0.8, ’caltab.descr’, ’caltab.ps’)

Result
CreateCaltab returns TRUE if all parameter values are correct and both files have been written successfully.
If necessary, an exception handling is raised.
Parallelization Information
CreateCaltab is processed completely exclusively without parallelization.
Possible Successors
ReadCamPar, CaltabPoints

HALCON 8.0.2
1114 CHAPTER 15. TOOLS

See also
GenCaltab, FindCaltab, FindMarksAndPose, CameraCalibration, DispCaltab, SimCaltab
Module
Foundation

void HWindowX.DispCaltab ([in] String CalTabDescrFile,


[in] VARIANT CamParam, [in] VARIANT CaltabPose, [in] double ScaleFac )
void HOperatorSetX.DispCaltab ([in] VARIANT WindowHandle,
[in] VARIANT CalTabDescrFile, [in] VARIANT CamParam, [in] VARIANT CaltabPose,
[in] VARIANT ScaleFac )

Project and visualize the 3D model of the calibration plate in the image.
DispCaltab is used to visualize the calibration marks and the connecting lines between the marks of the
used calibration plate (CalTabDescrFile) in the window specified by WindowHandle. Additionally, the
x- and y-axes of the plate’s coordiante system are printed on the plate’s surface. For this, the 3D model of
the calibration plate is projected into the image plane using the interior (CamParam) and exterior camera pa-
rameters (CaltabPose, i.e., the pose of the calibration plate in camera coordinates). The underlying cam-
era model (pinhole, telecentric, or line scan camera with radial distortion) is described in WriteCamPar and
CameraCalibration.
Typically, DispCaltab is used to verify the result of the camera calibration (see CameraCalibration) by
superimposing it onto the original image. The current line width can be set by SetLineWidth, the current color
can be set by SetColor. Additionally, the font type of the labels of the coordinate axes can be set by SetFont.
The parameter ScaleFac influences the number of supporting points to approximate the elliptic contours of the
calibration marks. You should increase the number of supporting points, if the image part in the output window is
displayed with magnification (see SetPart).
Parameter
. WindowHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . window ; HWindowX / VARIANT
Window in which the calibration plate should be visualized.
. CalTabDescrFile (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.read ; String / VARIANT
File name of the calibration plate description.
Default Value : ’caltab.descr’
List of values : CalTabDescrFile ∈ {’caltab.descr’, ’caltab_10mm.descr’, ’caltab_30mm.descr’,
’caltab_100mm.descr’, ’caltab_200mm.descr’}
. CamParam (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Interior camera parameters.
Number of elements : ((CamP aram = 8) ∨ (CamP aram = 11))
. CaltabPose (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pose ; VARIANT ( integer, real )
Exterior camera parameters (3D pose of the calibration plate in camera coordinates).
Number of elements : 7
. ScaleFac (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Scaling factor for the visualization.
Default Value : 1.0
Suggested values : ScaleFac ∈ {0.5, 1.0, 2.0, 3.0}
Recommended Increment : 0.05
Restriction : (0.0 < ScaleF ac)
Example

* read calibration image


read_image(Image1, ’calib-01’)
* find calibration pattern
find_caltab(Image1, Caltab1, ’caltab.descr’, 3, 112, 5)
* find calibration marks and start poses
StartCamPar := [Focus, Kappa, Sx, Sy, Cx, Cy, ImageWidth, ImageHeight]
find_marks_and_pose(Image1, Caltab1, ’caltab.descr’, StartCamPar,

HALCON/COM Reference Manual, 2008-5-13


15.5. CALIBRATION 1115

128, 10, 18, 0.9, 15.0, 100.0, RCoord1, CCoord1,


StartPose1)
* read 3D positions of calibration marks
caltab_points(’caltab.descr’, NX, NY, NZ)
* camera calibration
camera_calibration(NX, NY, NZ, RCoord1, CCoord1, StartCamPar,
StartPose1, 11, CamParam, FinalPose, Errors)
* visualize calibration result
disp_image(Image1, WindowHandle)
set_color(WindowHandle, ’red’)
disp_caltab(’caltab.descr’, CamParam, FinalPose, 1.0)

Result
DispCaltab returns TRUE if all parameter values are correct. If necessary, an exception handling is raised.
Parallelization Information
DispCaltab is reentrant, local, and processed without parallelization.
Possible Predecessors
CameraCalibration, ReadCamPar, ReadPose
See also
FindMarksAndPose, CameraCalibration, SimCaltab, WriteCamPar, ReadCamPar,
CreatePose, WritePose, ReadPose, Project3DPoint, GetLineOfSight
Module
Foundation

[out] HRegionX Caltab HImageX.FindCaltab ([in] String CalTabDescrFile,


[in] long SizeGauss, [in] long MarkThresh, [in] long MinDiamMarks )
void HOperatorSetX.FindCaltab ([in] IHObjectX Image,
[out] HUntypedObjectX Caltab, [in] VARIANT CalTabDescrFile,
[in] VARIANT SizeGauss, [in] VARIANT MarkThresh, [in] VARIANT MinDiamMarks )

Segment the standard calibration plate region in the image.


FindCaltab is used to determine the region of a plane calibration plate with circular marks in the input image
Image. First the input image is smoothed (see GaussImage); the size of the used filter mask is given by
SizeGauss. Afterwards, a thresholding operator (see Threshold) with minimum gray value MarkThresh
and maximum gray value 255 is applied. Among the extracted connected regions the most convex region with
almost correct number of holes (corresponding to the dark marks of the calibration plate) is selected. Holes with
a diameter smaller than the expected size of the marks MinDiamMarks are eliminated to reduce the impact of
noise. The number of marks is read from the calibration plate description file CalTabDescrFile. The complete
explanation of this file can be found within the description of GenCaltab.
Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, uint2 )


Input image.
. Caltab (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX
Output region.
. CalTabDescrFile (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.read ; String / VARIANT
File name of the calibration plate description.
Default Value : ’caltab.descr’
List of values : CalTabDescrFile ∈ {’caltab.descr’, ’caltab_10mm.descr’, ’caltab_30mm.descr’,
’caltab_100mm.descr’, ’caltab_200mm.descr’}
. SizeGauss (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Filter size of the Gaussian.
Default Value : 3
List of values : SizeGauss ∈ {0, 3, 5, 7, 9, 11}

HALCON 8.0.2
1116 CHAPTER 15. TOOLS

. MarkThresh (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT


Threshold value for mark extraction.
Default Value : 112
List of values : MarkThresh ∈ {48, 64, 80, 96, 112, 128, 144, 160}
. MinDiamMarks (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Expected minimal diameter of the marks on the calibration plate.
Default Value : 5
List of values : MinDiamMarks ∈ {3, 5, 9, 15, 30, 50, 70}
Example

* read calibration image


read_image(Image, ’calib-01’)
* find calibration pattern
find_caltab(Image, Caltab, ’caltab.descr’, 3, 112, 5)

Result
FindCaltab returns TRUE if all parameter values are correct and an image region is found. The behavior in case
of empty input (no image given) can be set via SetSystem(::’noObjectResult’,<Result>:) and the
behavior in case of an empty result region via SetSystem(::’storeEmptyRegion’,<true/false>:
). If necessary, an exception handling is raised.
Parallelization Information
FindCaltab is reentrant and processed without parallelization.
Possible Predecessors
ReadImage
Possible Successors
FindMarksAndPose
See also
FindMarksAndPose, CameraCalibration, DispCaltab, SimCaltab, CaltabPoints,
GenCaltab
Module
Foundation

[out] VARIANT RCoord HImageX.FindMarksAndPose


([in] HRegionX CalTabRegion, [in] String CalTabDescrFile,
[in] VARIANT StartCamParam, [in] long StartThresh, [in] long DeltaThresh,
[in] long MinThresh, [in] double Alpha, [in] double MinContLength,
[in] double MaxDiamMarks, [out] VARIANT CCoord, [out] VARIANT StartPose )
void HOperatorSetX.FindMarksAndPose ([in] IHObjectX Image,
[in] IHObjectX CalTabRegion, [in] VARIANT CalTabDescrFile,
[in] VARIANT StartCamParam, [in] VARIANT StartThresh,
[in] VARIANT DeltaThresh, [in] VARIANT MinThresh, [in] VARIANT Alpha,
[in] VARIANT MinContLength, [in] VARIANT MaxDiamMarks, [out] VARIANT RCoord,
[out] VARIANT CCoord, [out] VARIANT StartPose )

Extract the 2D calibration marks from the image and calculate initial values for the exterior camera parameters.
FindMarksAndPose is used to determine the necessary input data for the subsequent camera calibration (see
CameraCalibration): First, the 2D center points [RCoord,CCoord] of the calibration marks within the
region CalTabRegion of the input image Image are extracted and ordered. Secondly, a rough estimate for
the exterior camera parameters (StartPose) is computed, i.e., the 3D pose (= position and orientation) of the
calibration plate relative to the camera coordinate system (see CreatePose for more information about 3D
poses).
In the input image Image an edge detector is applied (see EdgesImage, mode ’lanser2’) to the region
CalTabRegion, which can be found by applying the operator FindCaltab. The filter parameter for this
edge detection can be tuned via Alpha. In the edge image closed contours are searched for: The number of closed

HALCON/COM Reference Manual, 2008-5-13


15.5. CALIBRATION 1117

contours must correspond to the number of calibration marks as described in the calibration plate description file
CalTabDescrFile and the contours have to be ellipticly shaped. Contours shorter than MinContLength are
discarded, just as contours enclosing regions with a diameter larger than MaxDiamMarks (e.g., the border of the
calibration plate).
For the detection of contours a threshold operator is applied on the resulting amplitudes of the edge detector. All
points with a high amplitude (i.e., borders of marks) are selected.
First, the threshold value is set to StartThresh. If the search for the closed contours or the successive pose
estimate fails, this threshold value is successively decreased by DeltaThresh down to a minimum value of
MinThresh.
Each of the found contours is refined with subpixel accuracy (see EdgesSubPix) and subsequently approxi-
mated by an ellipse. The center points of these ellipses represent a good approximation of the desired 2D image
coordinates [RCoord,CCoord] of the calibration mark center points. The order of the values within these two
tuples must correspond to the order of the 3D coordinates of the calibration marks in the calibration plate descrip-
tion file CalTabDescrFile, since this fixes the correspondences between extracted image marks and known
model marks (given by CaltabPoints)! If a triangular orientation mark is defined in a corner of the plate by
the plate description file (see GenCaltab), the mark will be detected and the point order is returned in row-major
order beginning with the corner mark in the (barycentric) negative quadrant with respect to the defined coordinate
system of the plate. Else, if no orientation mark is defined, the order of the center points is in row-major order
beginning at the upper left corner mark in the image.
Based on the ellipse parameters for each calibration mark, a rough estimate for the exterior camera parameters is
finally computed. For this purpose the fixed correspondences between extracted image marks and known model
marks are used. The estimate StartPose describes the pose of the calibration plate in the camera coordinate
system as required by the operator CameraCalibration.
Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, uint2 )


Input image.
. CalTabRegion (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
Region of the calibration plate.
. CalTabDescrFile (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.read ; String / VARIANT
File name of the calibration plate description.
Default Value : ’caltab.descr’
List of values : CalTabDescrFile ∈ {’caltab.descr’, ’caltab_10mm.descr’, ’caltab_30mm.descr’,
’caltab_100mm.descr’, ’caltab_200mm.descr’}
. StartCamParam (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Initial values for the interior camera parameters.
Number of elements : ((StartCamP aram = 8) ∨ (StartCamP aram = 11))
. StartThresh (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; long / VARIANT
Initial threshold value for contour detection.
Default Value : 128
List of values : StartThresh ∈ {80, 96, 112, 128, 144, 160}
. DeltaThresh (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; long / VARIANT
Loop value for successive reduction of StartThresh.
Default Value : 10
List of values : DeltaThresh ∈ {6, 8, 10, 12, 14, 16, 18, 20, 22}
. MinThresh (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; long / VARIANT
Minimum threshold for contour detection.
Default Value : 18
List of values : MinThresh ∈ {8, 10, 12, 14, 16, 18, 20, 22}
. Alpha (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Filter parameter for contour detection, see EdgesImage.
Default Value : 0.9
Suggested values : Alpha ∈ {0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0, 1.1}
Typical range of values : 0.2 ≤ Alpha ≤ 0.2
Restriction : (Alpha > 0.0)

HALCON 8.0.2
1118 CHAPTER 15. TOOLS

. MinContLength (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT


Minimum length of the contours of the marks.
Default Value : 15.0
Suggested values : MinContLength ∈ {10.0, 15.0, 20.0, 30.0, 40.0, 100.0}
Restriction : (M inContLength > 0.0)
. MaxDiamMarks (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Maximum expected diameter of the marks.
Default Value : 100.0
Suggested values : MaxDiamMarks ∈ {50.0, 100.0, 150.0, 200.0, 300.0}
Restriction : (M axDiamM arks > 0.0)
. RCoord (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT
Tuple with row coordinates of the detected marks.
. CCoord (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT
Tuple with column coordinates of the detected marks.
. StartPose (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pose ; VARIANT ( real, integer )
Estimation for the exterior camera parameters.
Number of elements : 7
Example

* read calibration image


read_image(Image, ’calib-01’)
* find calibration pattern
find_caltab(Image,Caltab1, ’caltab.descr’, 3, 112, 5)
* find calibration marks and start pose
find_marks_and_pose(Image, Caltab, ’caltab.descr’ ,
[0.008, 0.0, 0.000011, 0.000011, 384, 288, 768, 576],
128, 10, 18, 0.9, 15.0, 100.0, RCoord, CCoord, StartPose)

Result
FindMarksAndPose returns TRUE if all parameter values are correct and an estimation for the exterior camera
parameters has been determined successfully. If necessary, an exception handling is raised.
Parallelization Information
FindMarksAndPose is reentrant and processed without parallelization.
Possible Predecessors
FindCaltab
Possible Successors
CameraCalibration
See also
FindCaltab, CameraCalibration, DispCaltab, SimCaltab, ReadCamPar, ReadPose,
CreatePose, PoseToHomMat3d, CaltabPoints, GenCaltab, EdgesSubPix, EdgesImage
Module
Foundation

void HMiscX.GenCaltab ([in] long XNum, [in] long YNum,


[in] double MarkDist, [in] double DiameterRatio, [in] String CalTabDescrFile,
[in] String CalTabPSFile )
void HOperatorSetX.GenCaltab ([in] VARIANT XNum, [in] VARIANT YNum,
[in] VARIANT MarkDist, [in] VARIANT DiameterRatio,
[in] VARIANT CalTabDescrFile, [in] VARIANT CalTabPSFile )

Generate a calibration plate description file and a corresponding PostScript file.


GenCaltab generates the description of a standard calibration plate for HALCON. This calibration plate consists
of XNum times YNum black circular marks on a white plane which are surrounded by a black frame. The marks are
arranged in a rectangular grid with YNum and XNum equidistant rows and columns. The distances between these

HALCON/COM Reference Manual, 2008-5-13


15.5. CALIBRATION 1119

rows and columns defines the parameter MarkDist in meter. The marks’ diameter can be set by the parameter
DiameterRatio and is defined by the equation
Diameter = MarkDist ∗ DiameterRatio . Using a distance between marks of 0.01 m and a diameter ratio
of 0.5, the width of the dark surrounding frame becomes 8 cm, and the radius of the marks is set to 2.5 mm.
The coordinate system of the calibration plate is located in the barycenter of all marks, its z-axis points into the
calibration plate, its x-axis to the right, and its y-axis downwards.
The file CalTabDescrFile contains the calibration plate description, e.g., the number of rows and columns of
the calibration plate, the geometry of the surrounding frame (see FindCaltab), the triangular orientation mark,
an offset of the coordinate system to the plate’s surface in z-direction, and the x,y coordinates and the radius of all
calibration plate marks given in the calibration plate coordinate system. The definition of the orientation and the
offset, indicated by t and z, is optional and can be commented out. A file generated by GenCaltab looks like
the following (comments are marked by a ’#’ at the beginning of a line):

# Plate Description Version 2


# HALCON Version 7.1 -- Fri Jun 24 16:41:00 2005
# Description of the standard calibration plate
# used for the CCD camera calibration in HALCON
# (generated by gen\_caltab)
#
#
# 7 rows x 7 columns
# Width, height of the black frame [meter]: 0.1, 0.1
# Distance between mark centers [meter]: 0.0125

# Number of marks in y-dimension (rows)


r 7

# Number of marks in x-dimension (columns)


c 7

# offset of coordinate system in z-dimension [meter] (optional):


z 0

# Rectangular border (rim and black frame) of calibration plate


# rim of the calibration plate (min x, max y, max x, min y) [meter]:
o -0.05125 0.05125 0.05125 -0.05125
# outer border of the black frame (min x, max y, max x, min y) [meter]:
i -0.05 0.05 0.05 -0.05
# triangular corner mark given by two corner points (x,y, x,y) [meter]
# (optional):
t -0.05 -0.0375 -0.0375 -0.05

# width of the black frame [meter]:


w 0.003125

# calibration marks: x y radius [meter]

# calibration marks at y = -0.0375 m


-0.0375 -0.0375 0.003125
-0.025 -0.0375 0.003125
-0.0125 -0.0375 0.003125
-3.46945e-018 -0.0375 0.003125
0.0125 -0.0375 0.003125
0.025 -0.0375 0.003125
0.0375 -0.0375 0.003125

# calibration marks at y = -0.025 m


-0.0375 -0.025 0.003125
-0.025 -0.025 0.003125

HALCON 8.0.2
1120 CHAPTER 15. TOOLS

-0.0125 -0.025 0.003125


-3.46945e-018 -0.025 0.003125
0.0125 -0.025 0.003125
0.025 -0.025 0.003125
0.0375 -0.025 0.003125

# calibration marks at y = -0.0125 m


-0.0375 -0.0125 0.003125
-0.025 -0.0125 0.003125
-0.0125 -0.0125 0.003125
-3.46945e-018 -0.0125 0.003125
0.0125 -0.0125 0.003125
0.025 -0.0125 0.003125
0.0375 -0.0125 0.003125

# calibration marks at y = -3.46945e-018 m


-0.0375 -3.46945e-018 0.003125
-0.025 -3.46945e-018 0.003125
-0.0125 -3.46945e-018 0.003125
-3.46945e-018 -3.46945e-018 0.003125
0.0125 -3.46945e-018 0.003125
0.025 -3.46945e-018 0.003125
0.0375 -3.46945e-018 0.003125

# calibration marks at y = 0.0125 m


-0.0375 0.0125 0.003125
-0.025 0.0125 0.003125
-0.0125 0.0125 0.003125
-3.46945e-018 0.0125 0.003125
0.0125 0.0125 0.003125
0.025 0.0125 0.003125
0.0375 0.0125 0.003125

# calibration marks at y = 0.025 m


-0.0375 0.025 0.003125
-0.025 0.025 0.003125
-0.0125 0.025 0.003125
-3.46945e-018 0.025 0.003125
0.0125 0.025 0.003125
0.025 0.025 0.003125
0.0375 0.025 0.003125

# calibration marks at y = 0.0375 m


-0.0375 0.0375 0.003125
-0.025 0.0375 0.003125
-0.0125 0.0375 0.003125
-3.46945e-018 0.0375 0.003125
0.0125 0.0375 0.003125
0.025 0.0375 0.003125
0.0375 0.0375 0.003125

The file CalTabPSFile contains the corresponding PostScript description of the calibration plate.
Attention
Depending on the accuracy of the used output device (e.g., laser printer), the printed calibration plate may not
match the values in the calibration plate descripton file CalTabDescrFile exactly. Thus, the coordinates of the
calibration marks in the calibration plate description file may have to be corrected!

HALCON/COM Reference Manual, 2008-5-13


15.5. CALIBRATION 1121

Parameter

. XNum (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT


Number of marks in x direction.
Default Value : 7
Suggested values : XNum ∈ {5, 7, 9}
Recommended Increment : 1
Restriction : (XN um > 1)
. YNum (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of marks in y direction.
Default Value : 7
Suggested values : YNum ∈ {5, 7, 9}
Recommended Increment : 1
Restriction : (Y N um > 1)
. MarkDist (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Distance of the marks in meters.
Default Value : 0.0125
Suggested values : MarkDist ∈ {0.1, 0.0125, 0.00375, 0.00125}
Restriction : (0.0 < M arkDist)
. DiameterRatio (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Ratio of the mark diameter to the mark distance.
Default Value : 0.5
Suggested values : DiameterRatio ∈ {0.5, 0.55, 0.6, 0.65}
Restriction : ((0.0 < DiameterRatio) < 1.0)
. CalTabDescrFile (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.write ; String / VARIANT
File name of the calibration plate description.
Default Value : ’caltab.descr’
List of values : CalTabDescrFile ∈ {’caltab.descr’, ’caltab_10mm.descr’, ’caltab_30mm.descr’,
’caltab_100mm.descr’, ’caltab_200mm.descr’}
. CalTabPSFile (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.write ; String / VARIANT
File name of the PostScript file.
Default Value : ’caltab.ps’
Example

* Create calibration plate with width = 80 cm


gen_caltab( 7, 7, 0.1, 0.5, ’caltab.descr’, ’caltab.ps’)

Result
GenCaltab returns TRUE if all parameter values are correct and both files have been written successfully. If
necessary, an exception handling is raised.
Parallelization Information
GenCaltab is processed completely exclusively without parallelization.
Possible Successors
ReadCamPar, CaltabPoints
See also
FindCaltab, FindMarksAndPose, CameraCalibration, DispCaltab, SimCaltab
Module
Foundation

HALCON 8.0.2
1122 CHAPTER 15. TOOLS

void HImageX.GenImageToWorldPlaneMap ([in] VARIANT CamParam,


[in] VARIANT WorldPose, [in] long WidthIn, [in] long HeightIn,
[in] long WidthMapped, [in] long HeightMapped, [in] VARIANT Scale,
[in] String Interpolation )
[out] HImageX Map HPoseX.GenImageToWorldPlaneMap
([in] VARIANT CamParam, [in] VARIANT WorldPose, [in] long WidthIn,
[in] long HeightIn, [in] long WidthMapped, [in] long HeightMapped,
[in] VARIANT Scale, [in] String Interpolation )
void HOperatorSetX.GenImageToWorldPlaneMap
([out] HUntypedObjectX Map, [in] VARIANT CamParam, [in] VARIANT WorldPose,
[in] VARIANT WidthIn, [in] VARIANT HeightIn, [in] VARIANT WidthMapped,
[in] VARIANT HeightMapped, [in] VARIANT Scale, [in] VARIANT Interpolation )

Generate a projection map that describes the mapping between the image plane and a the plane z=0 of a world
coordinate system.
GenImageToWorldPlaneMap generates a projection map Map, which describes the mapping between the im-
age plane and the plane z=0 (plane of measurements) in a world coordinate system. This map can be used to rectify
an image with the operator MapImage. The rectified image shows neither radial nor perspective distortions; it
corresponds to an image acquired by a distortion-free camera that looks perpendicularly onto the plane of measure-
ments. The world coordinate system is chosen by passing its 3D pose relative to the camera coordinate system in
WorldPose. In CamParam you must pass the interior camera parameters (see WriteCamPar for the sequence
of the parameters and the underlying camera model).
In many cases CamParam and WorldPose are the result of calibrating the camera with the operator
CameraCalibration. See below for an example.
The size of the images to be mapped can be specified by the parameters WidthIn and HeightIn. The pixel
position of the upper left corner of the output image is determined by the origin of the world coordinate system.
The size of the output image can be choosen by the parameters WidthMapped, HeightMapped, and Scale.
WidthMapped and HeightMapped must be given in pixels.
With the parameter Scale you can specify the size of a pixel in the transformed image. There are two typical
scenarios: First, you can scale the image such that pixel coordinates in the transformed image directly correspond
to metric units, e.g., that one pixel corresponds to one micron. This is useful if you want to perform measurements
in the transformed image which will then directly result in metric results. The second scenario is to scale the image
such that its content appears in a size similar to the original image. This is useful, e.g., if you want to perform
shape-based matching in the transformed image.
Scale must be specified as the ratio desired pixel size/original unit. A pixel size of 1µm means that a pixel in
the transformed image corresponds to the area 1µm × 1µm in the plane of measurements. The original unit is
determined by the coordinates of the calibration object. If the original unit is meters (which is the case if you use
the standard calibration plate), you can use the parameter values ’m’, ’cm’, ’mm’, ’microns’, or ’µm’ to directly set
the unit of pixel coordinates in the transformed image.
The parameter Interpolation specifies whether bilinear interpolation (’bilinear’) should be applied between
the pixels in the input image or whether the gray value of the nearest neighboring pixel (’none’) should be used.
The mapping function is stored in the output image Map. Map has the same size as the resulting images after
the mapping. If no interpolation is chosen, Map consists of one image containing one channel, in which for each
pixel of the resulting image the linearized coordinate of the pixel of the input image is stored that is the nearest
neighbor to the transformed coordinates. If bilinear interpolation is chosen, Map consists of one image containing
five channels. In the first channel for each pixel in the resulting image the linearized coordinates of the pixel in
the input image is stored that is in the upper left position relative to the transformed coordinates. The four other
channels contain the weights of the four neighboring pixels of the transformed coordinates which are used for the
bilinear interpolation, in the following order:
2 3
4 5
The second channel, for example, contains the weights of the pixels that lie to the upper left relative to
the transformed coordinates. If several images have to be mapped using the same camera parameters,
GenImageToWorldPlaneMap in combination with MapImage is much more efficient than the operator
ImageToWorldPlane because the mapping function needs to be computed only once.

HALCON/COM Reference Manual, 2008-5-13


15.5. CALIBRATION 1123

Parameter
. Map (output iconic) . . . . . . . . . . . . . . . . . (multichannel-)image ; HImageX / HUntypedObjectX ( int4, uint2 )
Image containing the mapping data.
. CamParam (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Interior camera parameters.
Number of elements : ((CamP aram = 8) ∨ (CamP aram = 11))
. WorldPose (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pose ; VARIANT ( integer, real )
3D pose of the world coordinate system in camera coordinates.
Number of elements : 7
. WidthIn (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; long / VARIANT
Width of the images to be transformed.
. HeightIn (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; long / VARIANT
Height of the images to be transformed.
. WidthMapped (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; long / VARIANT
Width of the resulting mapped images in pixels.
. HeightMapped (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; long / VARIANT
Height of the resulting mapped images in pixels.
. Scale (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real, string )
Scale or unit.
Default Value : ’m’
Suggested values : Scale ∈ {’m’, ’cm’, ’mm’, ’microns’, ’µm’, 1.0, 0.01, 0.001, 1.0e-6, 0.0254, 0.3048,
0.9144}
. Interpolation (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Type of interpolation.
Default Value : ’bilinear’
List of values : Interpolation ∈ {’none’, ’bilinear’}
Example

* perform camera calibration (with standard calibration plate)


camera_calibration(NX, NY, NZ, NRow, NCol, StartCamParam, NStartPose, ’all’,
FinalCamParam, NFinalPose, Errors)
* world coordinate system is defined by calibration plate in first image
FinalPose1 := NFinalPose[0:6]
* compensate thickness of plate
set_origin_pose(FinalPose1, 0, 0, 0.000073, WorldPose)
* goal: rectify images
* first determine parameters such that the entire image content is visible
* -> transform image boundary into world plane, determine smallest
* rectangle around it
get_image_pointer1(Image, Pointer, Type, Width, Height)
gen_rectangle1 (ImageRect, 0, 0, Height-1, Width-1)
gen_contour_region_xld (ImageRect, ImageBorder, ’border’)
contour_to_world_plane_xld(ImageBorder, ImageBorderWCS, FinalCamParam,
WorldPose, 1)
smallest_rectangle1_xld (ImageBorderWCS, MinY, MinX, MaxY, MaxX)
* -> move the pose to the upper left corner of the surrounding rectangle
set_origin_pose(WorldPose, MinX, MinY, 0, PoseForEntireImage)
* -> determine the scaling factor such that the center pixel has the same
* size in the original and in the rectified image
* method: transform corner points of the pixel into the world
* coordinate system, compute their distances, and use their
* mean as the scaling factor
image_points_to_world_plane(FinalCamParam, PoseForEntireImage,
[Height/2, Height/2, Height/2+1],
[Width/2, Width/2+1, Width/2],
1, WorldPixelX, WorldPixelY)
distance_pp(WorldPixelY[0], WorldPixelX[0], WorldPixelY[1], WorldPixelX[1],

HALCON 8.0.2
1124 CHAPTER 15. TOOLS

WorldLength1)
distance_pp(WorldPixelY[0], WorldPixelX[0], WorldPixelY[2], WorldPixelX[2],
WorldLength2)
ScaleForSimilarPixelSize := (WorldLength1+WorldLength2)/2
* -> determine output image size such that entire input image fits into it
ExtentX := MaxX-MinX
ExtentY := MaxY-MinY
WidthRectifiedImage := ExtentX/ScaleForSimilarPixelSize
HeightRectifiedImage := ExtentY/ScaleForSimilarPixelSize
* create mapping with the determined parameters
gen_image_to_world_plane_map(Map, FinalCamParam, PoseForEntireImage,
Width, Height,
WidthRectifiedImage, HeightRectifiedImage,
ScaleForSimilarPixelSize, ’bilinear’)
* transform grabbed images with the created map
while(1)
grab_image_async(Image, FGHandle, -1)
map_image(Image, Map, RectifiedImage)
endwhile

Result
GenImageToWorldPlaneMap returns TRUE if all parameter values are correct. If necessary, an exception
handling is raised.
Parallelization Information
GenImageToWorldPlaneMap is reentrant and processed without parallelization.
Possible Predecessors
CreatePose, HomMat3dToPose, CameraCalibration, HandEyeCalibration, SetOriginPose
Possible Successors
MapImage
See also
MapImage, ContourToWorldPlaneXld, ImagePointsToWorldPlane
Alternatives
ImageToWorldPlane
Module
Calibration

void HImageX.GenRadialDistortionMap ([in] VARIANT CamParIn,


[in] VARIANT CamParOut, [in] String Interpolation )
void HOperatorSetX.GenRadialDistortionMap
([out] HUntypedObjectX Map, [in] VARIANT CamParIn, [in] VARIANT CamParOut,
[in] VARIANT Interpolation )

Generate a projection map that describes the mapping of images corresponding to a changing radial distortion.
GenRadialDistortionMap computes the mapping of images corresponding to a changing radial distortion in
accordance to the interior camera parameters CamParIn and CamParOut which can be obtained, e.g., using the
operator CameraCalibration. CamParIn and CamParOut contain the old and the new camera parameters
including the old and the new radial distortion, respectively (also see WriteCamPar for the sequence of the
parameters and the underlying camera model). Each pixel of the potential output image is transformed into the
image plane using CamParOut and subsequently projected into a subpixel position of the potential input image
using CamParIn.
The mapping function is stored in the output image Map. The size of Map is given by the camera parameters
CamParOut and therefore defines the size of the resulting mapped images using MapImage. The size of the
images to be mapped with MapImage is determined by the camera parmaters CamParIn. If no interpolation

HALCON/COM Reference Manual, 2008-5-13


15.5. CALIBRATION 1125

is chosen (Interpolation = ’none’), Map consists of one image containing one channel, in which for each
pixel of the output image the linearized coordinate of the pixel of the input image is stored that is the nearest
neighbor to the transformed coordinates. If bilinear interpolation is chosen (Interpolation = ’bilinear’),
Map consists of one image containing five channels. In the first channel for each pixel in the resulting image
the linearized coordinate of the pixel in the input image is stored that is in the upper left position relative to
the transformed coordinates. The four other channels contain the weights of the four neighboring pixels of the
transformed coordinates which are used for the bilinear interpolation, in the following order:
2 3
4 5
The second channel, for example, contains the weights of the pixels that lie to the upper left relative to the trans-
formed coordinates.
If CamParOut was computed via ChangeRadialDistortionCamPar, the mapping describes the effect of
a lens with a modified radial distortion. If κ is 0, the mapping corresponds to a rectification.
If several images have to be mapped using the same camera parameters, GenRadialDistortionMap in
combination with MapImage is much more efficient than the operator ChangeRadialDistortionImage
because the transformation must be computed only once.
Parameter

. Map (output iconic) . . . . . . . . . . . . . . . . . (multichannel-)image ; HImageX / HUntypedObjectX ( int4, uint2 )


Image containing the mapping data.
. CamParIn (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Old camera parameters.
Number of elements : 8
. CamParOut (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
New camera parameters.
Number of elements : 8
. Interpolation (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Type of interpolation.
Default Value : ’bilinear’
List of values : Interpolation ∈ {’none’, ’bilinear’}
Result
GenRadialDistortionMap returns TRUE if all parameter values are correct. If necessary, an exception
handling is raised.
Parallelization Information
GenRadialDistortionMap is reentrant and processed without parallelization.
Possible Predecessors
ChangeRadialDistortionCamPar, CameraCalibration, HandEyeCalibration
Possible Successors
MapImage
See also
ChangeRadialDistortionContoursXld
Alternatives
ChangeRadialDistortionImage
Module
Calibration

[out] VARIANT Pose1 HXLDX.GetCirclePose ([in] VARIANT CamParam,


[in] VARIANT Radius, [in] String OutputType, [out] VARIANT Pose2 )
void HOperatorSetX.GetCirclePose ([in] IHObjectX Contour,
[in] VARIANT CamParam, [in] VARIANT Radius, [in] VARIANT OutputType,
[out] VARIANT Pose1, [out] VARIANT Pose2 )

Determine the 3D pose of a circle from its perspective 2D projection.

HALCON 8.0.2
1126 CHAPTER 15. TOOLS

Each ellipse in an image can be interpreted as the perspective projection of a circle into the image. In fact, for
a given radius of the circle, there exist two differently oriented circles in 3D that result in the same projection.
GetCirclePose determines the 3D positions and orientations of these two circles. First, each Contour is
approximated by an ellipse. Then, based on the interior camera parameters (CamParam) and the radius of the
circle in 3D (Radius), the 3D positions and orientations (Pose1,Pose2) are determined in camera coordinates.
Depending on the value of the parameter OutputType, the position and orientation is returned as a 3D pose
(OutputType = ’pose’) or in the form of the center of the 3D circle and the normal vector of the plane in which
the circle lies (OutputType = ’center_normal’). In the former case, the angle for the rotation around the z axis
is set to zero, because it cannot be determined. In the latter case, the first three elements of the output parameters
Pose1 and Pose2 contain the position of the center of the circle. The following three elements contain the normal
vector. The normal vectors are normalized and oriented such that they point away from the optical center which
is the origin of the camera coordinate system. If OutputType is set to ’center_normal’, the output parameters
Pose1 and Pose2 contain only six elements which describe the position and orientation of the circle instead of
the seven elements of the 3D pose that are returned if OutputType is set to ’pose’.
If more than one contour is passed in Contour, Radius must either contain a tuple that contains a value for
each contour or only one value which is then used for all contours. The resulting positions and orientations are
stored one after another in Pose1 and Pose2, i.e., Pose1 and Pose2 contain first the pose or the position and
the normal vector of the first contour, followed by the respective values for the second contour and so on.
Attention
The accuracy of the determined poses depends heavily on the accuracy of the extracted contours. The extraction of
curved edges using relatively large filter masks leads to a slightly shifted edge position. Edge extraction approaches
that are based on the first derivative of the image function (e.g., EdgesSubPix) yield edges that are shifted
towards the center of curvature, i.e., extracted ellipses will be slightly to small. Approaches that are based on the
second derivative of the image function ( LaplaceOfGauss followed by ZeroCrossingSubPix) result in
edges that are shifted away from the center of curvature, i.e., extracted ellipses will be slightly too large.
These effects increase with the curvature of the edge and with the size of the filter mask that is used for the
edge extraction. Therefore, to achieve high accuracy, the ellipses should appear large in the image and the filter
parameter should be chosen such that small filter masks are used (see InfoEdges).
Parameter

. Contour (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .xld(-array) ; IHXLDX / IHObjectX


Contours to be examined.
. CamParam (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Interior camera parameters.
Number of elements : (CamP aram = 8)
. Radius (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( real )
Radius of the circle in object space.
Restriction : (Radius > 0.0)
Number of elements : ((Radius = Contour) ∨ (Radius = 1))
. OutputType (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Type of output parameters.
Default Value : ’pose’
List of values : OutputType ∈ {’pose’, ’center_normal’}
. Pose1 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
3D pose of the first circle.
Number of elements : ((P ose1 = (7 · Contour)) ∨ (P ose1 = (6 · Contour)))
. Pose2 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
3D pose of the second circle.
Number of elements : ((P ose2 = (7 · Contour)) ∨ (P ose2 = (6 · Contour)))
Result
GetCirclePose returns TRUE if all parameter values are correct and the position of the circle has been deter-
mined successfully. If necessary, an exception handling is raised.
Parallelization Information
GetCirclePose is reentrant and processed without parallelization.
Possible Predecessors
EdgesSubPix

HALCON/COM Reference Manual, 2008-5-13


15.5. CALIBRATION 1127

See also
GetRectanglePose, FitEllipseContourXld
Alternatives
FindMarksAndPose, CameraCalibration
Module
3D Metrology

[out] VARIANT PX HMiscX.GetLineOfSight ([in] VARIANT Row,


[in] VARIANT Column, [in] VARIANT CamParam, [out] VARIANT PY,
[out] VARIANT PZ, [out] VARIANT QX, [out] VARIANT QY, [out] VARIANT QZ )
void HOperatorSetX.GetLineOfSight ([in] VARIANT Row,
[in] VARIANT Column, [in] VARIANT CamParam, [out] VARIANT PX,
[out] VARIANT PY, [out] VARIANT PZ, [out] VARIANT QX, [out] VARIANT QY,
[out] VARIANT QZ )

Compute the line of sight corresponding to a point in the image.


GetLineOfSight computes the line of sight corresponding to a pixel (Row, Column) in the image. The line
of sight is a (straight) line in the camera coordinate system, which is described by two points (PX,PY,PZ) and
(QX,QY,QZ) on the line. A pinhole or telecentric camera model with radial distortions described by the interior
camera parameters CamParam is used (see WriteCamPar). If a pinhole camera is used, the second point lies
on the focal plane, i.e., for frame cameras, the output parameter QZ is equivalent to the focal length of the camera,
whereas for linescan cameras, QZ also depends on the motion of the camera with respect to the object. The equation
of the line of sight is given by
     
X PX QX − PX
 Y  =  PY  + l ·  QY − PY 
Z PZ QZ − PZ

The advantage of representing the line of sight as two points is that it is easier to transform the line in 3D. To do
so, all that is necessary is to apply the operator AffineTransPoint3D to the two points.
Parameter
. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Row coordinate of the pixel.
. Column (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Column coordinate of the pixel.
. CamParam (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Interior camera parameters.
Number of elements : ((CamP aram = 8) ∨ (CamP aram = 11))
. PX (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
X coordinate of the first point on the line of sight in the camera coordinate system
. PY (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Y coordinate of the first point on the line of sight in the camera coordinate system
. PZ (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Z coordinate of the first point on the line of sight in the camera coordinate system
. QX (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
X coordinate of the second point on the line of sight in the camera coordinate system
. QY (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Y coordinate of the second point on the line of sight in the camera coordinate system
. QZ (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Z coordinate of the second point on the line of sight in the camera coordinate system
Example

* get interior camera parameters

HALCON 8.0.2
1128 CHAPTER 15. TOOLS

read_cam_par(’campar.dat’, CamParam)
* inverse projection
get_line_of_sight([50, 100], [100, 200], CamParam, PX, PY, PZ, QX, QY, QZ)

Result
GetLineOfSight returns TRUE if all parameter values are correct. If necessary, an exception handling is
raised.
Parallelization Information
GetLineOfSight is reentrant and processed without parallelization.
Possible Predecessors
ReadCamPar, CameraCalibration
Possible Successors
AffineTransPoint3D
See also
CameraCalibration, DispCaltab, ReadCamPar, Project3DPoint, AffineTransPoint3D
Module
Calibration

[out] <none>X Pose HXLDX.GetRectanglePose ([in] VARIANT CamParam,


[in] VARIANT Width, [in] VARIANT Height, [in] String WeightingMode,
[in] double ClippingFactor, [out] VARIANT CovPose, [out] VARIANT Error )
void HOperatorSetX.GetRectanglePose ([in] IHObjectX Contour,
[in] VARIANT CamParam, [in] VARIANT Width, [in] VARIANT Height,
[in] VARIANT WeightingMode, [in] VARIANT ClippingFactor, [out] VARIANT Pose,
[out] VARIANT CovPose, [out] VARIANT Error )

Determine the 3D pose of a rectangle from its perspective 2D projection.


A rectangle in space is projected as a general quadrangle into the image. GetRectanglePose determines the
Pose of the rectangle from this projection (Contour).
The algorithm works as follows: First, Contour is segmented into four line segments and their intersections are
considered as corners of the contour. The corners together with the interior camera parameters (CamParam) and
the rectangle size in meters (Width, Height) are used for an initial estimation of the rectangle pose. Then, the
final Pose is refined with a non-linear optimization by minimizing the geometrical distance of the contour points
from the reprojection of the rectangle in the image.
The operator supports only area-scan pinhole (projective) cameras. An error is returned if CamParam specifies a
line-scan or a telecentric camera (see also CameraCalibration).
Width and Height specify the size of the rectangle in x and y dimensions, respectively, in its coordinate system.
The origin of this coordinate system is in the center of the rectangle. The z axis points away from the camera.
The arguments WeightingMode and ClippingFactor can be used to damp the impact of outliers on the
algorithm. If WeightingMode is set to ’tukey’ or ’huber’, the contour points are weighted based on the ap-
proach of Tukey or Huber respectively. In such a case a robust error statistics is used to estimate the standard
deviation of the distances of the contour points from the reprojected rectangle excluding outliers. The parame-
ter ClippingFactor (a scaling factor for the standard deviation) controls the amount of damping outliers: The
smaller the value chosen for ClippingFactor the more outliers are detected. See a discussion about the proper-
ties of the different weighting modes in FitLineContourXld. Note that, unlike by FitLineContourXld,
for the rectangle pose estimation the approach of Huber is recommended.

Output
The resulting Pose is of code-0 (see CreatePose) and represents the pose of the center of the rectangle. You
can compute the pose of the corners of the rectangle as follows:
set_origin_pose (Pose, Width/2, -Height/2, 0, PoseCorner1)
set_origin_pose (Pose, Width/2, Height/2, 0, PoseCorner2)
set_origin_pose (Pose, -Width/2, Height/2, 0, PoseCorner3)
set_origin_pose (Pose, -Width/2, -Height/2, 0, PoseCorner4)

HALCON/COM Reference Manual, 2008-5-13


15.5. CALIBRATION 1129

A rectangle is symmetric with respect to its x, y, and z axis and one and the same contour can represent a rectangle
in 4 different poses. The angles in Pose are normalized to be in the range [−90; 90] degrees and the rest of the 4
possible poses can be computed by combining flips around the corresponding axis:
∗ NOTE: the following code works ONLY for pose of type Code-0
∗ as it is returned by GetRectanglePose

∗ flip around z-axis
PoseFlippedZ := Pose
PoseFlippedZ[5] := PoseFlippedZ[5]+180
∗ flip around y-axis
PoseFlippedY := Pose
PoseFlippedY[4] := PoseFlippedY[4]+180
PoseFlippedY[5] := -PoseFlippedY[5]
∗ flip around x-axis
PoseFlippedX := Pose
PoseFlippedX[3] := PoseFlippedX[3]+180
PoseFlippedX[4] := -PoseFlippedX[4]
PoseFlippedX[5] := -PoseFlippedX[5]

Note that if the rectangle is a square (Width == Height) the number of alternative poses is 8.
If more than one contour are given in Contour, a corresponding tuple of values for both Width and Height
has to be provided as well. Yet, if only one value is provided for each of these arguments, then this value is applied
for each processed contour. A pose is estimated for each processed contour and all poses are concatenated in Pose
(see the example below).

Accuracy of the pose


The accuracy of the estimated pose depends on the following three factors:

• ratio Width/Height
• length of the projected contour
• degree of perspective distortion of the contour

In order to achieve an accurate pose estimation, there are three corresponding criteria that should be considered:
The ratio Width/Height should fulfill

1
< Width/Height < 3
3

For a rectangular object deviating from this criterion, its longer side dominates the determination of its pose. This
causes instability in the estimation of the angle around the longer rectangle’s axis. In the extreme case when one
of the dimensions is 0, the rectangle is in fact a line segment, whose pose cannot be estimated.
Secondly, the lengths of each side of the contour should be at least 20 pixels. An error is returned if a side of the
contour is less than 5 pixels long.
Thirdly, the more the contour appears projectively distorted, the more stable the algorithm works. Therefore, the
pose of a rectangle tilted w.r.t to the image plane can be estimated accurately, whereas the pose of an rectangle
parallel to the image plane of the camera could be unstable. This is further discussed in the next paragraph.
Additionally, there is a rule of thumb that ensures projective distortion: the rectangle should be placed in space
such that its size in x and y dimension in the camera coordinate system should not be less than 1/10th of its
distance from the camera in z direction.
GetRectanglePose provides two measures for the accuracy of the estimated Pose. Error is the average
pixel error between the contour points and the modeled rectangle reprojected on the image. If Error is exceeding
0.5, this is an indication that the algorithm did not converge properly, and the resulting Pose should not be used.
CovPose contains 36 entries representing the 6 × 6 covariance matrix of the first 6 entries of Pose. The above
mentioned case of instability of the angle about the longer rectangle’s axis be detected by checking that the absolute
values of the variances and covariances of the rotations around the x and y axis (CovPose[21],CovPose[28],
and CovPose[22] == CovPose[27]) do not exceed 0.05. Further, unusually increased values of any of the

HALCON 8.0.2
1130 CHAPTER 15. TOOLS

covariances and especially of the variances (the 6 values on the diagonal of CovPose with indices 0, 7, 14, 21, 28
and 35, respectively) indicate a poor quality of Pose.
Parameter

. Contour (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .xld(-array) ; IHXLDX / IHObjectX


Contour(s) to be examined.
. CamParam (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Interior camera parameters.
Number of elements : (CamP aram = 8)
. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( real )
Width of the rectangle in meters.
Restriction : (W idth > 0)
. Height (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( real )
Height of the rectangle in meters.
Restriction : (Height > 0)
. WeightingMode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Weighting mode for the optimization phase.
Default Value : ’nonweighted’
List of values : WeightingMode ∈ {’nonweighted’, ’huber’, ’tukey’}
. ClippingFactor (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Clipping factor for the elimination of outliers (typical: 1.0 for ’huber’ and 3.0 for ’tukey’).
Default Value : 2.0
Suggested values : ClippingFactor ∈ {1.0, 1.5, 2.0, 2.5, 3.0}
Restriction : (ClippingF actor > 0)
. Pose (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pose ; <none>X / VARIANT ( integer, real )
3D pose of the rectangle.
Number of elements : (P ose = (7 · Contour))
. CovPose (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real )
Covariances of the pose values.
Number of elements : (CovP ose = (36 · Contour))
. Error (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT
Root-mean-square value of the final residual error.
Number of elements : (Error = Contour)
Example

* Process an image with several rectangles of the same size appearing


* as light objects
*
*
RectWidth := 0.04
RectHeight := 0.025
read_cam_par (’campar.dat’, CamParam)
read_image (Image, ’tea_boxes’)
* find light objects in the image
mean_image (Image, ImageMean, 201, 201)
dyn_threshold (Image, ImageMean, Region, 5, ’light’)
* fill gaps in the objects
fill_up (Region, RegionFillUp)
* extract rectangular contours
* NOTE: for a real application, this step might require some additional
* pre- or postprocessing
reduce_domain (Image, RegionSelected, ImageReduced)
edges_sub_pix (ImageReduced, Edges, ’canny’, 0.7, 20, 30)
* get the pose of all contours found
get_rectangle_pose (Edges, CamParam, RectWidth, RectHeight, ’huber’, 2,
Poses, CovPose, Error)
NumPoses := |Poses|/7

HALCON/COM Reference Manual, 2008-5-13


15.5. CALIBRATION 1131

for I := 0 to NumPoses-1 by 1
Pose := Poses[I*7:I*7+6]
* use the Pose here
* ...
endfor

Result
GetRectanglePose returns TRUE if all parameter values are correct and the position of the rectangle has been
determined successfully. If the provided contour(s) cannot be segmented as a quadrangle GetRectanglePose
returns H_ERR_FIT_QUADRANGLE. If further necessary, an exception handling is raised.
Parallelization Information
GetRectanglePose is reentrant, local, and processed without parallelization.
Possible Predecessors
EdgesSubPix
See also
GetCirclePose, SetOriginPose, CameraCalibration
References
G.Schweighofer and A.Pinz: “Robust Pose Estimation from a Planar Target”; Transactions on Pattern Analysis
and Machine Intelligence (PAMI), 28(12):2024-2030, 2006
Module
3D Metrology

[out] VARIANT BaseFinalPose HPoseX.HandEyeCalibration ([in] VARIANT NX,


[in] VARIANT NY, [in] VARIANT NZ, [in] VARIANT NRow, [in] VARIANT NCol,
[in] VARIANT MPointsOfImage, [in] VARIANT MRelPoses,
[in] VARIANT BaseStartPose, [in] VARIANT CamStartPose, [in] VARIANT CamParam,
[in] VARIANT ToEstimate, [in] String StopCriterion, [in] long MaxIterations,
[in] double MinError, [out] VARIANT CamFinalPose, [out] VARIANT NumErrors )
void HOperatorSetX.HandEyeCalibration ([in] VARIANT NX,
[in] VARIANT NY, [in] VARIANT NZ, [in] VARIANT NRow, [in] VARIANT NCol,
[in] VARIANT MPointsOfImage, [in] VARIANT MRelPoses,
[in] VARIANT BaseStartPose, [in] VARIANT CamStartPose, [in] VARIANT CamParam,
[in] VARIANT ToEstimate, [in] VARIANT StopCriterion,
[in] VARIANT MaxIterations, [in] VARIANT MinError,
[out] VARIANT BaseFinalPose, [out] VARIANT CamFinalPose,
[out] VARIANT NumErrors )

Perform a hand-eye calibration.


The operator HandEyeCalibration determines the 3D pose of a robot (“hand”) relative to a camera (“eye”).
With this information, the results of image processing can be transformed into the coordinate system of the robot
which can then, e.g., grasp an inspected part. There are two possible configurations of robot-camera (hand-eye)
systems: The camera can be mounted on the robot or be stationary and observe the robot. Note that the term robot
is used in place for a mechanism that moves objects. Thus, you can use HandEyeCalibration to calibrate
many different systems, from pan-tilt heads to multi-axis manipulators.
A hand-eye calibration is performed similarly to the calibration of the external camera parameters (see
CameraCalibration): You acquire a set of images of a calibration object, determine correspondences be-
tween known model points and their projection in the images and pass them to HandEyeCalibration via
the parameters NX, NY, NZ, NRow, NCol, and MPointsOfImage. If you use the standard calibration plate, the
correspondences can be determined very easily with the operators FindCaltab and FindMarksAndPose.
Furthermore, you must specify the internal camera parameters in CamParam.
In contrast to the camera calibration, the calibration object is not moved manually. This task is delegated to
the robot which either moves the camera (mounted camera) or the calibration object (stationary camera). The

HALCON 8.0.2
1132 CHAPTER 15. TOOLS

robot’s movements are assumed to be known and therefore are also used as an input for the calibration (parameter
MRelPoses).
The two hand-eye configurations are discussed in more detail below, followed by general information about the
process of hand-eye calibration.

Moving camera (mounted on a robot)


In this configuration, the calibration object remains stationary and the camera is moved to different positions by the
robot. The main idea behind the hand-eye calibration is that the information extracted from a calibration image,
i.e., the pose of the calibration object relative to the camera (i.e., the external camera parameters), can be seen as a
chain of poses or homogeneous transformation matrices, from the calibration object via the base of the robot to its
tool (end-effector) and finally to the camera:

cam
Moving camera: Hcal = cam Htool · tool Hbase · base Hcal
* 6 YH
H
 H
CamStartPose MRelPoses BaseStartPose
CamFinalPose BaseFinalPose

From the set of calibration images, the operator HandEyeCalibration determines the two transformations
at the ends of the chain, i.e., the pose of the robot tool in camera coordinates (cam Htool ) and the pose of the
calibration object in the robot base coordinate system (base Hcal ). In the input parameters CamStartPose and
BaseStartPose, you must specify suitable starting values for these transformations which are constant over
all calibration images. HandEyeCalibration then returns the calibrated values in CamFinalPose and
BaseFinalPose.
In contrast, the transformation in the middle of the chain, tool Hbase , is known but changes for each calibration
image, because it describes the pose of the robot moving the camera, or to be more exact its inverse pose (pose of
the base coordinate system in robot tool coordinates). You must specify the (inverse) robot poses in the calibration
images in the parameter MRelPoses.
Internally, HandEyeCalibration uses a Newton-type algorithm to minimize an error function based on nor-
mal equations. Analogously to the calibration of the camera itself (see CameraCalibration), the hand-eye
calibration becomes more robust if you use many calibration images that were acquired with different robot poses.

Stationary camera
In this configuration, the robot grasps the calibration object and moves it in front of the camera. Again, the
information extracted from a calibration image, i.e., the pose of the calibration object in camera coordinates (i.e.,
the external camera parameters), are equal to a chain of poses or homogeneous transformation matrices, this time
from the calibration object via the robot’s tool to its base and finally to the camera:

cam
Stationary camera: Hcal = cam Hbase · base Htool · tool Hcal
* 6 YH
H
 H
CamStartPose MRelPoses BaseStartPose
CamFinalPose BaseFinalPose

Analogously to the configuration with a moving camera, the operator HandEyeCalibration determines the
two transformations at the ends of the chain, here the pose of the robot base coordinate system in camera coordi-
nates (cam Hbase ) and the pose of the calibration object relative to the robot tool (tool Hcal ). In the input parame-
ters CamStartPose and BaseStartPose, you must specify suitable starting values for these transformations.
HandEyeCalibration then returns the calibrated values in CamFinalPose and BaseFinalPose. Please
note that the names of the parameters BaseStartPose and BaseFinalPose are misleading for this configu-
ration!
The transformation in the middle of the chain, base Htool , describes the pose of the robot moving the calibration
object, i.e., the pose of the tool relative to the base coordinate system. You must specify the robot poses in the
calibration images in the parameter MRelPoses.

HALCON/COM Reference Manual, 2008-5-13


15.5. CALIBRATION 1133

Additional information about the calibration process


The following sections discuss individual questions arising from the use of HandEyeCalibration. They are
intended to be a guideline for using the operator in an application, as well as to help understanding the operator.

How do I get 3D model points and their projections? 3D model points given in the world coordinate system
(NX, NY, NZ) and their associated projections in the image (NRow, NCol) form the basis of the hand-eye
calibration. In order to be able to perform a successful hand-eye calibration, you need images of the 3D
model points that were obtained for sufficiently many different poses of the manipulator.
In principle, you can use arbitrary known points for the calibration. However, it is usually most convenient
to use the standard calibration plate, e.g., the one that can be generated with GenCaltab. In this case, you
can use the operators FindCaltab and FindMarksAndPose to extract the position of the calibration
plate and of the calibration marks and the operator CaltabPoints to access the 3D coordinates of the
calibration marks (see also the description of CameraCalibration).
The parameter MPointsOfImage specifies the number of 3D model points used for each pose of the
manipulator, i.e., for each image. With this, the 3D model points which are stored in a linearized fashion
in NX, NY, NZ, and their corresponding projections (NRow, NCol) can be associated with the corresponding
pose of the manipulator (MRelPoses). Note that in contrast to the operator CameraCalibration the
3D coordinates of the model points must be specified for each calibration image, not only once.
How do I acquire a suitable set of images? If a standard calibration plate is used, the following procedure
should be used:
• At least 10 to 20 images from different positions should be taken in which the position of the camera
with respect to the calibration plate is sufficiently different. The position of the calibration plate (moving
camera: relative to the robot’s tool; stationary camera: relative to the robot’s base) must not be changed
between images.
• In each image, the calibration plate must be completely visible (including its border).
• No reflections or other disturbances should be visible on the calibration plate.
• The set of images must show the calibration plate from very different positions of the manipulator.
The calibration plate can and should be visible in different parts of the images. Furthermore, it should
be slightly to moderately rotated around its x- or y-axis, in order to clearly exhibit distortions of the
calibration marks. In other words, the corresponding exterior camera parameters (pose of the calibration
plate in camera coordinates) should take on many different values.
• In each image, the calibration plate should fill at least one quarter of the entire image, in order to ensure
the robust detection of the calibration marks.
• The interior camera parameters of the camera to be used must have been determined earlier and must be
passed in CamParam (see CameraCalibration). Note that changes of the image size, the focal
length, the aperture, or the focus effect a change of the interior camera parameters.
• The camera must not be modified between the acquisition of the individual images, i.e., focal length,
aperture, and focus must not be changed, because all calibration images use the same interior camera
parameters. Please make sure that the focus is sufficient for the expected changes of the distance the
camera from the calibration plate. Therefore, bright lighting conditions for the calibration plate are
important, because then you can use smaller apertures which result in larger depth of focus.
How do I obtain suitable starting values? Depending on the used hand-eye configuration, you need starting val-
ues for the following poses:
Moving camera
BaseStartPose = pose of the calibration object in robot base coordinates
CamStartPose = pose of the robot tool in camera coordinates
Stationary camera
BaseStartPose = pose of the calibration object in robot tool coordinates
CamStartPose = pose of the robot base in camera coordinates
The camera’s coordinate system is oriented such that its optical axis corresponds to the z-axis, the x-axis
points to the right, and the y-axis downwards. The coordinate system of the standard calibration plate is
located in the middle of the surface of the calibration plate, its z-axis points into the calibration plate, its
x-axis to the right, and it y-axis downwards.
For more information about creating a 3D pose please refer to the description of CreatePose which also
contains a short example.

HALCON 8.0.2
1134 CHAPTER 15. TOOLS

In fact, you need a starting value only for one of the two poses (BaseStartPose or CamStartPose).
The other can be computed from one of the calibration images. This means that you can pick the pose that is
easier to determine and let HALCON compute the other one for you.
The main idea is to exploit the fact that the two poses for which we need starting values are connected via the
already described chain of transformations, here shown for a configuration with a moving camera:

cam
Moving camera: Hcal = cam Htool · tool Hbase · base Hcal
* 6 YH
H
 H
CamStartPose MRelPoses BaseStartPose

In this configuration, it is typically easy to determine a starting value for cam Htool (CamStartPose). Thus,
we solve the equation for base Hcal (BaseStartPose):

Moving camera: base


Hcal = (cam Htool · tool Hbase )-1 · cam Hcal
base
= Htool · tool Hcam · cam Hcal

Thus, to compute BaseStartPose you need one of the robot poses (e.g., the one in the first image), your
estimate for CamStartPose, and the pose of the calibration object in camera coordinates in the selected
image. If you use the standard calibration plate, you typically already obtained its pose when applying the
operator FindMarksAndPose to determine the projections of the marks. An example program can be
found below.
For a configuration with a stationary camera, the chain of transformations is:

cam
Stationary camera: Hcal = cam Hbase · base Htool · tool Hcal

*
 HH
Y
 6 H
CamStartPose MRelPoses BaseStartPose
tool
In this configuration, it is typically easier to determine a starting value for Hcal (BaseStartPose).
Thus, we solve the equation for cam Hbase (CamStartPose):

Stationary camera: cam


Hbase = cam
Hcal ·(base Htool · tool Hcal )-1
cam
= Hcal · cal Htool · tool Hbase

Thus, to compute CamStartPose you need one of the robot poses (e.g., the one in the first image), your
estimate for BaseStartPose, and the pose of the calibration object in camera coordinates in the selected
image. If you use the standard calibration plate, you typically already obtained its pose when applying the
operator FindMarksAndPose to determine the projections of the marks. An example program can be
found below.
How do I obtain the poses of the robot? In the parameter MRelPoses you must pass the poses of the robot in
the calibration images (moving camera: pose of the robot base in robot tool coordinates; stationary camera:
pose of the robot tool in robot base coordinates) in a linearized fashion. We recommend to create the robot
poses in a separate program and save in files using WritePose. In the calibration program you can then
read and accumulate them in a tuple as shown in the example program below. Besides, we recommend to
save the pose of the robot tool in robot base coordinates independent of the hand-eye configuration. When
using a moving camera, you then invert the read poses before accumulating them. This is also shown in the
example program.
Via the cartesian interface of the robot, you can typically obtain the pose of the tool in base coordinates in
a notation that corresponds to the pose representations with the codes 0 or 2 (OrderOfRotation = ’gba’
or ’abg’, see CreatePose). In this case, you can directly use the pose values obtained from the robot as
input for CreatePose.

HALCON/COM Reference Manual, 2008-5-13


15.5. CALIBRATION 1135

If the cartesian interface of your robot describes the orientation in a different way, e.g., with the representation
ZYZ (Rz (ϕ1) · Ry (ϕ2) · Rz (ϕ3)), you can create the corresponding homogeneous transformation matrix
step by step using the operators HomMat3dRotate and HomMat3dTranslate and then convert the
matrix into a pose using HomMat3dToPose. The following example code creates a pose from the ZYZ
representation described above:
hom_mat3d_identity (HomMat3DIdent)
hom_mat3d_rotate (HomMat3DIdent, ϕ3, ’z’, 0, 0, 0, HomMat3DRotZ)
hom_mat3d_rotate (HomMat3DRotZ, ϕ2, ’y’, 0, 0, 0, HomMat3DRotYZ)
hom_mat3d_rotate (HomMat3DRotYZ, ϕ1, ’z’, 0, 0, 0, HomMat3DRotZYZ)
hom_mat3d_translate (HomMat3DRotZYZ, Tx, Ty, Tz, base_H_tool)
hom_mat3d_to_pose (base_H_tool, RobPose)
Please note that the hand-eye calibration only works if the robot poses MRelPoses are specified with high
accuracy!
How can I exclude individual pose parameters from the estimation? HandEyeCalibration estimates a
maximum of 12 pose parameters, i.e., 6 parameters each for the two computed poses CamFinalPose and
BaseFinalPose. However, it is possible to exclude some of these pose parameters from the estimation.
This means that the starting values of the poses remain unchanged and are assumed constant for the estima-
tion of all other pose parameters. The parameter ToEstimate is used to determine which pose parameters
should be estimated. In ToEstimate, a list of keywords for the parameters to be estimated is passed. The
possible values are:
BaseFinalPose:
’baseTx’ = translation along the x-axis
’baseTy’ = translation along the y-axis
’baseTz’ = translation along the z-axis
’baseRa’ = rotation around the x-axis
’baseRb’ = rotation around the y-axis
’baseRg’ = rotation around the z-axis
’base_pose’ = all 6 BaseFinalPose parameters
CamFinalPose:
’camTx’ = translation along the x-axis
’camTy’ = translation along the y-axis
’camTz’ = translation along the z-axis
’camRa’ = rotation around the x-axis
’camRb’ = rotation around the y-axis
’camRg’ = rotation around the z-axis
’cam_pose’ = all 6 CamFinalPose parameters
In order to estimate all 12 pose parameters, you can pass the keyword ’all’ (or of course a tuple containing
all 12 keywords listed above).
It is useful to exclude individual parameters from estimation if those pose parameters have already been mea-
sured exactly. Therefor define a string tuple of the parameters that should be estimated or prefix the strings
of excluded parameters with a ’~’ sign. For example, ToEstimate = [’all’,’~camTx’] estimates all pose
values except the x translation of the camera. Whereas ToEstimate = [’base_pose’,’~baseRy’] estimates
the pose of the base apart from the rotation around the y-axis. The latter is equivalent to ToEstimate =
[’baseTx’,’baseTy’,’baseTz’,’baseRx’,’baseRz’].
Which terminating criteria can be used for the error minimization? The error minimization terminates either
after a fixed number of iterations or if the error falls below a given minimum error. The parameter
StopCriterion is used to choose between these two alternatives. If ’CountIterations’ is passed, the
algorithm terminates after MaxIterations iterations.
If StopCriterion is passed as ’MinError’, the algorithm runs until the error falls below the error threshold
given in MinError. If, however, the number of iterations reaches the number given in MaxIterations,
the algorithm terminates with an error message.
What is the order of the individual parameters? The length of the tuple MPointsOfImage corresponds to
the number of different positions of the manipulator and thus to the number of calibration images. The
parameter MPointsOfImage determines the number of model points used in the individual positions. If
the standard calibration plate is used, this means 49 points per position (image). If for example 15 images
were acquired, MPointsOfImage is a tuple of length 15, where all elements of the tuple have the value 49.

HALCON 8.0.2
1136 CHAPTER 15. TOOLS

The number of calibration images which is determined by the length of MPointsOfImage, must also be
taken into account for the tuples for the 3D model points and for the extracted 2D marks, respectively. Hence,
for 15 calibration images with 49 model points each, the tuples NX, NY, NZ, NRow, and NCol must contain
15 · 49 = 735 values each. These tuples are ordered according to the image the respective points lie in, i.e.,
the first 49 values correspond to the 49 model points in the first image. The order of the 3D model points and
the extracted 2D model points must be the same in each image.
The length of the tuple MRelPoses also depends on the number of calibration images. If, for example, 15
images and therefore 15 poses are used, the length of the tuple MRelPoses is 15 · 7 = 105 (15 times 7 pose
parameters). The first seven parameters thus determine the pose of the manipulator in the first image, and so
on.
What do the output parameters mean? If StopCriterion was set to ’CountIterations’, the output parame-
ters BaseFinalPose and CamFinalPose are returned even if the algorithm didn’t converge. If, how-
ever, StopCriterion was set to ’MinError’, the error must fall below ’MinError’ in order for output
parameters to be returned.
The representation type of BaseFinalPose and CamFinalPose is the same as in the corresponding
starting values. It can be changed with the operator ConvertPoseType. The description of the dif-
ferent representation types and of their conversion can be found with the documentation of the operator
CreatePose.
The parameter NumErrors contains a list of (numerical) errors from the individual iterations of the algo-
rithm. Based on the evolution of the errors, it can be decided whether the algorithm has converged for the
given starting values. The error values are returned as 3D deviations in meters. Thus, the last entry of the
error list corresponds to an estimate of the accuracy of the returned pose parameters.

Attention
The quality of the calibration depends on the accuracy of the input parameters (position of the calibration marks,
robot poses MRelPoses, and the starting positions BaseStartPose, CamStartPose). Based on the returned
error measures NumErrors, it can be decided, whether the algorithm has converged. Furthermore, the accuracy
of the returned pose can be estimated. The error measures are 3D differences in meters.
Parameter
. NX (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Linear list containing all the x coordinates of the calibration points (in the order of the images).
. NY (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Linear list containing all the y coordinates of the calibration points (in the order of the images).
. NZ (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Linear list containing all the z coordinates of the calibration points (in the order of the images).
. NRow (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT
Linear list containing all row coordinates of the calibration points (in the order of the images).
. NCol (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT
Linear list containing all the column coordinates of the calibration points (in the order of the images).
. MPointsOfImage (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT
Number of the calibration points for each image.
. MRelPoses (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pose ; VARIANT ( integer, real )
Measured 3D pose of the robot for each image (moving camera: robot base in robot tool coordinates;
stationary camera: robot tool in robot base coordinates).
. BaseStartPose (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pose ; VARIANT ( integer, real )
Starting value for the 3D pose of the calibration object in robot base coordinates (moving camera) or in robot
tool coordinates (stationary camera), respectively.
. CamStartPose (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pose ; VARIANT ( integer, real )
Starting value for the 3D pose of the robot tool (moving camera) or robot base (stationary camera),
respectively, in camera coordinates.
. CamParam (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Interior camera parameters.
. ToEstimate (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( string )
Parameters to be estimated (max. 12 degrees of freedom).
Default Value : ’all’
List of values : ToEstimate ∈ {’all’, ’base_pose’, ’cam_pose’, ’baseTx’, ’baseTy’, ’baseTz’, ’baseRa’,
’baseRb’, ’baseRg’, ’camTx’, ’camTy’, ’camTz’, ’camRa’, ’camRb’, ’camRg’}

HALCON/COM Reference Manual, 2008-5-13


15.5. CALIBRATION 1137

. StopCriterion (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT


Type of stopping criterion.
Default Value : ’CountIterations’
List of values : StopCriterion ∈ {’CountIterations’, ’MinError’}
. MaxIterations (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Maximum number of iterations to be executed.
Default Value : 15
Suggested values : MaxIterations ∈ {10, 15, 20, 25, 30}
. MinError (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Minimum error used as the stopping criterion.
Default Value : 0.0005
Suggested values : MinError ∈ {0.0001, 0.0005, 0.001, 0.005, 0.01, 0.05, 0.1}
. BaseFinalPose (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pose ; VARIANT ( integer, real )
Computed 3D pose for the 3D pose of the calibration object in robot base coordinates (moving camera) or in
robot tool coordinates (stationary camera), respectively.
. CamFinalPose (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pose ; VARIANT ( integer, real )
Computed 3D pose of the robot tool (moving camera) or robot base (stationary camera), respectively, in
camera coordinates.
. NumErrors (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT
Error measures for each iteration.
Example

read_cam_par(’campar.dat’, CamParam)
CalDescr := ’caltab.descr’
caltab_points(CalDescr, X, Y, Z)
* process all calibration images
for i := 0 to NumImages-1 by 1
read_image(Image, ’calib_’+i$’02d’)
* find marks on the calibration plate in every image
find_caltab(Image, CalPlate, CalDescr, 3, 150, 5)
find_marks_and_pose(Image, CalPlate, CalDescr, CamParam, 128, 10,
RCoordTmp, CCoordTmp, StartPose)
* accumulate 2D and 3D coordinates of the marks
RCoord := [RCoord, RCoordTmp]
CCoord := [CCoord, CCoordTmp]
XCoord := [XCoord, X]
YCoord := [YCoord, Y]
ZCoord := [ZCoord, Z]
NumMarker := [NumMarker, |RCoordTmp|]
* read pose of the robot tool in robot base coordinates
read_pose(’robpose_’+i$’02d’+’.dat’, RobPose)
* moving camera? invert pose
if (IsMovingCameraConfig=’true’)
pose_to_hom_mat3d(RobPose, base_H_tool)
hom_mat3d_invert(base_H_tool, tool_H_base)
hom_mat3d_to_pose(tool_H_base, RobPose)
endif
* accumulate robot poses
MRelPoses := [MRelPoses, RobPose]
* store the pose of the calibration plate in the first image and the
* corresponding pose of the robot for later use
if (i=0)
cam_P_cal := StartPose
RelPose0 := RobPose
endif
endfor
* obtain starting values: read one, compute the other
if (IsMovingCameraConfig=’true’)

HALCON 8.0.2
1138 CHAPTER 15. TOOLS

* mov. camera: read pose of robot tool in camera coordinates


* compute pose of calibration plate in robot base coordinates
read_pose(’cam_P_tool.dat’, CamStartPose)
* BaseStartPose = inverse(CamStartPose * RelPose0) * cam_P_cal
pose_to_hom_mat3d(CamStartPose, cam_H_tool)
pose_to_hom_mat3d(RelPose0, tool_H_base)
pose_to_hom_mat3d(StartPose, cam_H_cal)
hom_mat3d_compose(cam_H_tool, tool_H_base, cam_H_base)
hom_mat3d_invert(cam_H_base, base_H_cam)
hom_mat3d_compose(base_H_cam, cam_H_cal, base_H_cal)
hom_mat3d_to_pose(base_H_cal, BaseStartPose)
else
* stat. camera: read pose of calibration plate in robot tool coordinates
* compute pose of robot base in camera coordinates
read_pose(’tool_P_cal.dat’, BaseStartPose)
* CamStartPose = cam_P_cal * inverse(RelPose0 * BaseStartPose)
pose_to_hom_mat3d(BaseStartPose, tool_H_cal)
pose_to_hom_mat3d(RelPose0, base_H_tool)
pose_to_hom_mat3d(StartPose, cam_H_cal)
hom_mat3d_compose(base_H_tool, tool_H_cal, base_H_cal)
hom_mat3d_invert(base_H_call, cal_H_base)
hom_mat3d_compose(cam_H_cal, cal_H_base, cam_H_base)
hom_mat3d_to_pose(cam_H_base, CamStartPose)
endif
*
* perform hand-eye calibration
*
hand_eye_calibration(XCoord, YCoord, ZCoord, RCoord, CCoord, NumMarker,
MRelPoses, BaseStartPose, CamStartPose, CamParam,
"all", "CountIterations", 20, 0.000670,
BaseFinalPose, CamFinalPose, NumErrors)
*
* measure some point P in camera coordinates (cam_px, cam_py, cam_pz)
*
* transform point into robot base coordinates: base_p = base_H_cam * cam_p
if (IsMovingCameraConfig=’true’)
* mov. camera: base_H_cam = base_H_tool * tool_H_cam
* base_P_cam = RobPose * inverse(CamFinalPose)
pose_to_hom_mat3d(CamFinalPose, cam_H_tool)
hom_mat3d_invert(cam_H_tool, tool_H_cam)
* obtain current robot pose RobPose from robot
pose_to_hom_mat3d(RobPose, base_H_tool)
hom_mat3d_compose(base_H_tool, tool_H_cam, base_H_cam)
else
* stat. camera: base_P_cam = inverse(CamFinalPose)
pose_to_hom_mat3d(CamFinalPose, cam_H_base)
hom_mat3d_invert(cam_H_base, base_H_cam)
endif
affine_trans_point_3d(base_H_cam, cam_px, cam_py, cam_pz,
base_px, base_py, base_pz)

Result
HandEyeCalibration returns TRUE if all parameter values are correct and the method converges with an error
less than the specified minimum error (if StopCriterion = ’MinError’). If necessary, an exception handling is
raised.
Parallelization Information
HandEyeCalibration is reentrant and processed without parallelization.
Possible Predecessors

HALCON/COM Reference Manual, 2008-5-13


15.5. CALIBRATION 1139

FindMarksAndPose
Possible Successors
WritePose, ConvertPoseType, PoseToHomMat3d, DispCaltab, SimCaltab
See also
FindCaltab, FindMarksAndPose, DispCaltab, SimCaltab, WriteCamPar, ReadCamPar,
CreatePose, ConvertPoseType, WritePose, ReadPose, PoseToHomMat3d, HomMat3dToPose,
CaltabPoints, GenCaltab
Module
Calibration

[out] VARIANT X HMiscX.ImagePointsToWorldPlane ([in] VARIANT CamParam,


[in] VARIANT WorldPose, [in] VARIANT Rows, [in] VARIANT Cols,
[in] VARIANT Scale, [out] VARIANT Y )
void HOperatorSetX.ImagePointsToWorldPlane ([in] VARIANT CamParam,
[in] VARIANT WorldPose, [in] VARIANT Rows, [in] VARIANT Cols,
[in] VARIANT Scale, [out] VARIANT X, [out] VARIANT Y )

Transform image points into the plane z=0 of a world coordinate system.
The operator ImagePointsToWorldPlane transforms image points which are given in Rows and Cols into
the plane z=0 in a world coordinate system and returns their 3D coordinates in X and Y. The world coordinate
system is chosen by passing its 3D pose relative to the camera coordinate system in WorldPose. In CamParam
you must pass the interior camera parameters (see WriteCamPar for the sequence of the parameters and the
underlying camera model).
In many cases CamParam and WorldPose are the result of calibrating the camera with the operator
CameraCalibration. See below for an example.
With the parameter Scale you can scale the resulting 3D coordinates. The parameter Scale must be specified
as the ratio desired unit/original unit. The original unit is determined by the coordinates of the calibration object.
If the original unit is meters (which is the case if you use the standard calibration plate), you can set the desired
unit directly by selecting ’m’, ’cm’, ’mm’ or ’µm’ for the parameter Scale.
Internally, the operator first computes the line of sight between the projection center and the image contour points
in the camera coordinate system, taking into account the radial distortions. The line of sight is then transformed
into the world coordinate system specified in WorldPose. By intersecting the plane z=0 with the line of sight the
3D coordinates X and Y are obtained.
Parameter

. CamParam (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )


Interior camera parameters.
Number of elements : ((CamP aram = 8) ∨ (CamP aram = 11))
. WorldPose (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pose ; VARIANT ( integer, real )
3D pose of the world coordinate system in camera coordinates.
Number of elements : 7
. Rows (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . coordinates.y ; VARIANT ( integer, real )
Row coordinates of the points to be transformed.
Default Value : 100.0
. Cols (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . coordinates.x ; VARIANT ( integer, real )
Column coordinates of the points to be transformed.
Default Value : 100.0
. Scale (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real, string )
Scale or dimension
Default Value : ’m’
Suggested values : Scale ∈ {’m’, ’cm’, ’mm’, ’microns’, ’µm’, 1.0, 0.01, 0.001, 1.0e-6, 0.0254, 0.3048,
0.9144}
. X (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . coordinates.x ; VARIANT ( real )
X coordinates of the points in the world coordinate system.

HALCON 8.0.2
1140 CHAPTER 15. TOOLS

. Y (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . coordinates.y ; VARIANT ( real )


Y coordinates of the points in the world coordinate system.
Example

* perform camera calibration (with standard calibration plate)


camera_calibration(NX, NY, NZ, NRow, NCol, StartCamParam, NStartPose, ’all’,
FinalCamParam, NFinalPose, Errors)
* world coordinate system is defined by calibration plate in first image
FinalPose1 := NFinalPose[0:6]
* compensate thickness of plate
set_origin_pose(FinalPose1, 0, 0, 0.0006, WorldPose)
* transform image points into world coordinate system (unit mm)
image_points_to_world_plane(FinalCamParam, WorldPose, PointRows, PointCols,
’mm’, PointXCoord, PointYCoord)

Result
ImagePointsToWorldPlane returns TRUE if all parameter values are correct. If necessary, an exception
handling is raised.
Parallelization Information
ImagePointsToWorldPlane is reentrant and processed without parallelization.
Possible Predecessors
CreatePose, HomMat3dToPose, CameraCalibration, HandEyeCalibration, SetOriginPose
See also
ContourToWorldPlaneXld
Module
Calibration

[out] HImageX ImageWorld HImageX.ImageToWorldPlane


([in] VARIANT CamParam, [in] VARIANT WorldPose, [in] long Width,
[in] long Height, [in] VARIANT Scale, [in] String Interpolation )
void HOperatorSetX.ImageToWorldPlane ([in] IHObjectX Image,
[out] HUntypedObjectX ImageWorld, [in] VARIANT CamParam,
[in] VARIANT WorldPose, [in] VARIANT Width, [in] VARIANT Height,
[in] VARIANT Scale, [in] VARIANT Interpolation )

Rectify an image by transforming it into the plane z=0 of a world coordinate system.
ImageToWorldPlane rectifies an image Image by transforming it into the plane z=0 (plane of measurements)
in a world coordinate system. The resulting rectified image ImageWorld shows neither radial nor perspective
distortions; it corresponds to an image acquired by a distortion-free camera that looks perpendicularly onto the
plane of measurements. The world coordinate system is chosen by passing its 3D pose relative to the camera coor-
dinate system in WorldPose. In CamParam you must pass the interior camera parameters (see WriteCamPar
for the sequence of the parameters and the underlying camera model).
In many cases CamParam and WorldPose are the result of calibrating the camera with the operator
CameraCalibration. See below for an example.
The pixel position of the upper left corner of the output image ImageWorld is determined by the origin of the
world coordinate system. The size of the output image ImageWorld can be choosen by the parameters Width,
Height, and Scale. Width and Height must be given in pixels.
With the parameter Scale you can specify the size of a pixel in the transformed image. There are two typical
scenarios: First, you can scale the image such that pixel coordinates in the transformed image directly correspond
to metric units, e.g., that one pixel corresponds to one micron. This is useful if you want to perform measurements
in the transformed image which will then directly result in metric results. The second scenario is to scale the image
such that its content appears in a size similar to the original image. This is useful, e.g., if you want to perform
shape-based matching in the transformed image.

HALCON/COM Reference Manual, 2008-5-13


15.5. CALIBRATION 1141

Scale must be specified as the ratio desired pixel size/original unit. A pixel size of 1µm means that a pixel in
the transformed image corresponds to the area 1µm × 1µm in the plane of measurements. The original unit is
determined by the coordinates of the calibration object. If the original unit is meters (which is the case if you use
the standard calibration plate), you can use the parameter values ’m’, ’cm’, ’mm’, ’microns’, or ’µm’ to directly set
the unit of pixel coordinates in the transformed image.
The parameter Interpolation specifies, whether bilinear interpolation (’bilinear’) should be applied between
the pixels in the input image or whether the gray value of the nearest neighboring pixel (’none’) should be used.
If several images have to be rectified using the same parameters, GenImageToWorldPlaneMap in combination
with MapImage is much more efficient than the operator ImageToWorldPlane because the mapping function
needs to be computed only once.
Parameter
. Image (input iconic) . . . . . . . . . . . . . . . (multichannel-)image(-array) ; HImageX / IHObjectX ( byte, uint2 )
Input image.
. ImageWorld (output iconic) . . . . . . (multichannel-)image(-array) ; HImageX / HUntypedObjectX ( byte,
uint2 )
Transformed image.
. CamParam (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Interior camera parameters.
Number of elements : ((CamP aram = 8) ∨ (CamP aram = 11))
. WorldPose (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pose ; VARIANT ( integer, real )
3D pose of the world coordinate system in camera coordinates.
Number of elements : 7
. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; long / VARIANT
Width of the resulting image in pixels.
. Height (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; long / VARIANT
Height of the resulting image in pixels.
. Scale (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real, string )
Scale or unit
Default Value : ’m’
Suggested values : Scale ∈ {’m’, ’cm’, ’mm’, ’microns’, ’µm’, 1.0, 0.01, 0.001, 1.0e-6, 0.0254, 0.3048,
0.9144}
. Interpolation (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Type of interpolation.
Default Value : ’bilinear’
List of values : Interpolation ∈ {’none’, ’bilinear’}
Example

* perform camera calibration (with standard calibration plate)


camera_calibration(NX, NY, NZ, NRow, NCol, StartCamParam, NStartPose, ’all’,
FinalCamParam, NFinalPose, Errors)
* world coordinate system is defined by calibration plate in first image
FinalPose1 := NFinalPose[0:6]
* compensate thickness of plate
set_origin_pose(FinalPose1, 0, 0, 0.0006, WorldPose)
* goal: rectify image
* first determine parameters such that the entire image content is visible
* and that objects have a similar size before and after the rectification
* -> transform image boundary into world plane, determine smallest
* rectangle around it
get_image_pointer1(Image, Pointer, Type, Width, Height)
gen_rectangle1 (ImageRect, 0, 0, Height-1, Width-1)
gen_contour_region_xld (ImageRect, ImageBorder, ’border’)
contour_to_world_plane_xld(ImageBorder, ImageBorderWCS, FinalCamParam,
WorldPose, 1)
smallest_rectangle1_xld (ImageBorderWCS, MinY, MinX, MaxY, MaxX)
* -> move the pose to the upper left corner of the surrounding rectangle

HALCON 8.0.2
1142 CHAPTER 15. TOOLS

set_origin_pose(WorldPose, MinX, MinY, 0, PoseForEntireImage)


* -> determine the scaling factor such that the center pixel has the same
* size in the original and in the rectified image
* method: transform corner points of the pixel into the world
* coordinate system, compute their distances, and use their
* mean as the scaling factor
image_points_to_world_plane(FinalCamParam, PoseForEntireImage,
[Height/2, Height/2, Height/2+1],
[Width/2, Width/2+1, Width/2],
1, WorldPixelX, WorldPixelY)
distance_pp(WorldPixelY[0], WorldPixelX[0], WorldPixelY[1], WorldPixelX[1],
WorldLength1)
distance_pp(WorldPixelY[0], WorldPixelX[0], WorldPixelY[2], WorldPixelX[2],
WorldLength2)
ScaleForSimilarPixelSize := (WorldLength1+WorldLength2)/2
* -> determine output image size such that entire input image fits into it
ExtentX := MaxX-MinX
ExtentY := MaxY-MinY
WidthRectifiedImage := ExtentX/ScaleForSimilarPixelSize
HeightRectifiedImage := ExtentY/ScaleForSimilarPixelSize
* transform the image with the determined parameters
image_to_world_plane(Image, RectifiedImage, FinalCamParam,
PoseForEntireImage, WidthRectifiedImage,
HeightRectifiedImage, ScaleForSimilarPixelSize,
’bilinear’)

Result
ImageToWorldPlane returns TRUE if all parameter values are correct. If necessary, an exception handling is
raised.
Parallelization Information
ImageToWorldPlane is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
CreatePose, HomMat3dToPose, CameraCalibration, HandEyeCalibration, SetOriginPose
See also
ContourToWorldPlaneXld, ImagePointsToWorldPlane
Alternatives
GenImageToWorldPlaneMap, MapImage
Module
Calibration

[out] VARIANT Row HMiscX.Project3DPoint ([in] VARIANT X, [in] VARIANT Y,


[in] VARIANT Z, [in] VARIANT CamParam, [out] VARIANT Column )
void HOperatorSetX.Project3DPoint ([in] VARIANT X, [in] VARIANT Y,
[in] VARIANT Z, [in] VARIANT CamParam, [out] VARIANT Row,
[out] VARIANT Column )

Project 3D points into (sub-)pixel image coordinates.


Project3DPoint projects one or more 3D points (with coordinates X, Y, and Z) into the image plane (in pixels)
and returns the result in Row and Column. The coordinates X, Y, and Z are given in the camera coordinate system,
i.e., they describe the position of the points relative to the camera.
The interior camera parameters CamParam describe the projection characteristics of the camera (see
WriteCamPar).

HALCON/COM Reference Manual, 2008-5-13


15.5. CALIBRATION 1143

Parameter
. X (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
X coordinates of the 3D points to be projected in the camera coordinate system.
. Y (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Y coordinates of the 3D points to be projected in the camera coordinate system.
. Z (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Z coordinates of the 3D points to be projected in the camera coordinate system.
. CamParam (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Interior camera parameters.
Number of elements : ((CamP aram = 8) ∨ (CamP aram = 11))
. Row (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Row coordinates of the projected points (in pixels).
Default Value : ’ProjectedRow’
. Column (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Column coordinates of the projected points (in pixels).
Default Value : ’ProjectedCol’
Example

* read pose of the world coordinate system in camera coordinates


read_pose(worldpose.dat’, WorldPose)
* convert pose into transformation matrix
pose_to_hom_mat3d(WorldPose, HomMat3D)
* transform 3D points from world into the camera coordinate system
affine_trans_point_3d([3.0, 3.2], [4.5, 4.5], [5.8, 6.2], HomMat3D, X, Y, Z)
* read interior camera parameters
read_cam_par(’campar.dat’, CamParam)
* project 3D points into image
project_3d_point(X, Y, Z, CamParam, Row, Column)

Result
Project3DPoint returns TRUE if all parameter values are correct. If necessary, an exception handling is
raised.
Parallelization Information
Project3DPoint is reentrant and processed without parallelization.
Possible Predecessors
ReadCamPar, AffineTransPoint3D
Possible Successors
GenRegionPoints, GenRegionPolygon, DispPolygon
See also
CameraCalibration, DispCaltab, ReadCamPar, GetLineOfSight, AffineTransPoint3D
Module
Calibration

[out] VARIANT InverseResponse HImageX.RadiometricSelfCalibration


([in] VARIANT ExposureRatios, [in] String Features, [in] String FunctionType,
[in] double Smoothness, [in] long PolynomialDegree )
void HOperatorSetX.RadiometricSelfCalibration
([in] IHObjectX Images, [in] VARIANT ExposureRatios, [in] VARIANT Features,
[in] VARIANT FunctionType, [in] VARIANT Smoothness,
[in] VARIANT PolynomialDegree, [out] VARIANT InverseResponse )

Perform a radiometric self-calibration of a camera.


RadiometricSelfCalibration performs a radiometric self-calibration of a camera. For this, at least two
images that show the same image contents (scene) must be passed in Images. All images passed in Images must

HALCON 8.0.2
1144 CHAPTER 15. TOOLS

be acquired with different exposures. Typically, the different exposures are obtained by changing the shutter times
at the camera. It is not recommeded to change the exposure by changing the aperture of the lens since in this case
the exposures cannot be determined accurately enough. The ratio of the exposures of consecutive images is passed
in ExposureRatios. For example, a value of 0.5 specifies that the second image of an image pair has been
acquired with half the exposure of the first image of the pair. The exposure ratio can easily be determined from the
shutter times since the exposure is proportional to the shutter time. The exposure ratio must be greater than 0 and
smaller than 1. This means that the images must be sorted according to descending exposure. ExposureRatios
must contain one element less than the number of images passed in Images. If all exposure ratios are identical,
as a simplification a single value can be passed in ExposureRatios.
As described above, the images passed in Images must show identical image contents. Hence, it is typically
necessary that neither the camera nor the objects in the scene move. If the camera has rotated around the optical
center, the images should be aligned to a reference image (one of the images) using ProjMatchPointsRansac
and ProjectiveTransImage. If the features used for the radiometric calibration are determined from the 2D
gray value histogram of consecutive image pairs (Features = 0 2d _histogram 0 ), it is essential that the images
are aligned and that the objects in the scene do not move. For Features = 0 1d _histograms 0 , the features used
for the radiometric calibration are determined from the 1D gray value histograms of the image pairs. In this mode,
the calibration can theoretically be performed if the 1D histograms of the images do not change by the movement
of the objects in the images. This can, for example, be the case if an object moves in front of a uniformly textured
background. However, it is preferable to use Features = 0 2d _histogram 0 because this mode is more accurate.
The mode Features = 0 1d _histograms 0 should only be used if it is impossible to construct the camera set-up
such that neither the camera nor the objects in the scene move.
Furthermore, care should be taken to cover the range of gray values without gaps by choosing appropriate image
contents. Whether there are gaps in the range of gray values can easily be checked based on the 1D gray value
histograms of the images or the 2D gray value histograms of consecutive images. In the 1D gray value histograms
(see GrayHistoAbs), there should be no areas between the minimum and maximum gray value that have a
frequency of 0 or a very small frequency. In the 2D gray value histograms (see Histo2Dim), a single connected
region having the shape of a “strip” should result from a threshold operation with a lower threshold of 1. If more
than one connected component results, a more suitable image content should be chosen. If the image content can
be chosen such that the gray value range of the image (e.g., 0-255 for byte images) can be covered with two images
with different exposures, and if there are no gaps in the histograms, the two images suffice for the calibration. This,
however, is typically not the case, and hence multiple images must be used to cover the entire gray value range.
As described above, for this multiple images with different exposures must be taken to cover the entire gray value
range as well as possible. For this, normally the first image should be exposed such that the maximum gray value
is slightly below the saturation limit of the camera, or such that the image is significantly overexposed. If the first
image is overexposed, a significant overexposure is necessary to enable RadiometricSelfCalibration to
detect the overexposed areas reliably. If the camera exhibits an unusual saturation behavior (e.g., a saturation limit
that lies significantly below the maximum gray value) the overexposed areas should be masked out by hand with
ReduceDomain in the overexposed image.
RadiometricSelfCalibration returns the inverse gray value response function of the camera in
InverseResponse. The inverse response function can be used to create an image with a linear response
by using InverseResponse as the LUT in LutTrans. The parameter FunctionType determines which
function model is used to model the response function. For FunctionType = 0 discrete 0 , the response func-
tion is described by a discrete function with the relevant number of gray values (256 for byte images). For
FunctionType = 0 polynomial 0 , the response is described by a polynomial of degree PolynomialDegree.
The computation of the response function is slower for FunctionType = 0 discrete 0 . However, since a poly-
nomial tends to oscillate in the areas in which no gray value information can be derived, even if smoothness
constraints are imposed as described below, the discrete model should usually be preferred over the polynomial
model.
The parameter Smoothness defines (in addition to the constraints on the response function that can be de-
rived from the images) constraints on the smoothness of the response function. If, as described above, the gray
value range can be covered completely and without gaps, the default value of 1 should not be changed. Other-
wise, values > 1 can be used to obtain a stronger smoothing of the response function, while values < 1 lead
to a weaker smoothing. The smoothing is particularly important in areas for which no gray value information
can be derived from the images, i.e., in gaps in the histograms and for gray values smaller than the minimum
gray value of all images or larger than the maximum gray value of all images. In these areas, the smoothness
constraints lead to an interpolation or extrapolation of the response function. Because of the nature of the inter-
nally derived constraints, FunctionType = 0 discrete 0 favors an exponential function in the undefined areas,
whereas FunctionType = 0 polynomial 0 favors a straight line. Please note that the interpolation and extrapo-

HALCON/COM Reference Manual, 2008-5-13


15.5. CALIBRATION 1145

lation is always less reliable than to cover the gray value range completely and without gaps. Therefore, in any
case it should be attempted first to acquire the images optimally, before the smoothness constraints are used to
fill in the remaining gaps. In all cases, the response function should be checked for plausibility after the call
to RadiometricSelfCalibration. In particular, it should be checked whether InverseResponse is
monotonic. If this is not the case, a more suitable scene should be used to avoid interpolation, or Smoothness
should be set to a larger value. For FunctionType = 0 polynomial 0 , it may also be necessary to change
PolynomialDegree. If, despite these changes, an implausible response is returned, the saturation behavior
of the camera should be checked, e.g., based on the 2D gray value histogram, and the saturated areas should be
masked out by hand, as described above.
When the inverse gray value response function of the camera is determined, the absolute energy falling on the
camera cannot be determined. This means that InverseResponse can only be determined up to a scale factor.
Therefore, an additional constraint is used to fix the unknown scale factor: the maximum gray value that can occur
should occur for the maximum input gray value, e.g., InverseResponse[255] = 255 for byte images. This
constraint usually leads to the most intuitive results. If, however, a multichannel image (typically an RGB image)
should be radiometrically calibrated (for this, each channel must be calibrated separately), the above constraint
may lead to the result that a different scaling factor is determined for each channel. This may lead to the result that
gray tones no longer appear gray after the correction. In this case, a manual white balancing step must be carried
out by identifying a homogeneous gray area in the original image, and by deriving appropriate scaling factors from
the corrected gray values for two of the three response curves (or, in general, for n − 1 of the n channels). Here,
the response curve that remains invariant should be chosen such that all scaling factors are < 1. With the scaling
factors thus determined, new response functions should be calculated by multiplying each value of a response
function with the scaling factor corresponding to that response function.
Parameter

. Images (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, uint2 )


Input images.
. ExposureRatios (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Ratio of the exposure energies of successive image pairs.
Default Value : 0.5
Suggested values : ExposureRatios ∈ {0.25, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8}
Restriction : ((ExposureRatios > 0) ∧ (ExposureRatios < 1))
. Features (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Features that are used to compute the inverse response function of the camera.
Default Value : 2d_histogram
List of values : Features ∈ {2d_histogram, 1d_histograms}
. FunctionType (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Type of the inverse response function of the camera.
Default Value : ’discrete’
List of values : FunctionType ∈ {’discrete’, ’polynomial’}
. Smoothness (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Smoothness of the inverse response function of the camera.
Default Value : 1.0
Suggested values : Smoothness ∈ {0.3, 0.5, 0.7, 0.8, 1.0, 1.2, 1.5, 2.0, 3.0}
Restriction : (Smoothness > 0)
. PolynomialDegree (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Degree of the polynomial if FunctionType = ’polynomial’.
Default Value : 5
Suggested values : PolynomialDegree ∈ {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
Restriction : ((P olynomialDegree ≥ 1) ∧ (P olynomialDegree ≤ 20))
. InverseResponse (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Inverse response function of the camera.
Example

open_framegrabber (’FirePackage’, 1, 1, 0, 0, 0, 0, ’default’, -1,


’default’, -1, ’default’, ’default’, ’default’,
-1, -1, FGHandle)
* Define appropriate shutter times.

HALCON 8.0.2
1146 CHAPTER 15. TOOLS

Shutters := [1000,750,500,250,125]
Num := |Shutters|
* Grab and accumulate images with the different exposures. In this
* loop, it must be ensured that the scene remains static.
gen_empty_obj (Images)
for I := 0 to Num-1 by 1
set_framegrabber_param (FGHandle, ’shutter’, Shutters[I])
grab_image (Image, FGHandle)
concat_obj (Images, Image, Images)
endfor
* Compute the exposure ratios from the shutter times.
ExposureRatios := real(Shutters[1:Num-1])/real(Shutters[0:Num-2])
radiometric_self_calibration (Images, ExposureRatios, ’2d_histogram’
’discrete’, 1, 5, InverseResponse)
* Note that if the frame grabber supports hardware LUTs, we could
* also call set_framegrabber_lut here instead of lut_trans below.
* This would be more efficient.
while (1)
grab_image_async (Image, FGHandle, -1)
lut_trans (Image, ImageLinear, InverseResponse)
* Process radiometrically correct image.
[...]
endwhile
close_framegrabber (FGHandle)

Result
If the parameters are valid, the operator RadiometricSelfCalibration returns the value TRUE. If neces-
sary an exception handling is raised.
Parallelization Information
RadiometricSelfCalibration is reentrant and processed without parallelization.
Possible Predecessors
ReadImage, GrabImage, GrabImageAsync, SetFramegrabberParam, ConcatObj,
ProjMatchPointsRansac, ProjectiveTransImage
Possible Successors
LutTrans
See also
Histo2Dim, GrayHisto, GrayHistoAbs, ReduceDomain
References

Module
Calibration

HMiscX.ReadCamPar ([in] String CamParFile )


[out] VARIANT CamParam
void HOperatorSetX.ReadCamPar ([in] VARIANT CamParFile,
[out] VARIANT CamParam )

Read the interior camera parameters from text file.


ReadCamPar is used to read the interior camera parameters CamParam from a text file with name
CamParFile. CamParam is a tuple that contains the interior camera parameters in the following sequence
(see WriteCamPar for a description of the corresponding camera models):
For area scan cameras:
[Focus, Kappa, Sx, Sy, Cx, Cy, ImageWidth, ImageHeight]
For line scan cameras:
[Focus, Kappa, Sx, Sy, Cx, Cy, ImageWidth, ImageHeight, Vx, Vy, Vz]

HALCON/COM Reference Manual, 2008-5-13


15.5. CALIBRATION 1147

The format of the text file is a (HALCON-independent) generic parameter description. It allows to group arbitrary
sets of parameters hierarchically. The description of a single parameter within a parameter group consists of the
following 3 lines:

Name : Shortname : Actual value ;


Type : Lower bound (optional) : Upper bound (optional) ;
Description (optional) ;

Comments are marked by a ’#’ at the beginning of a line.


ReadCamPar expects in the file CamParFile one of the two following parameter groups.
The parameter group Camera:Parameter consists of the 8 parameters Focus, Kappa (κ), Sx, Sy, Cx, Cy, Im-
ageWidth and ImageHeight. A suitable file can look like the following:

# INTERNAL CAMERA PARAMETERS

ParGroup: Camera: Parameter;


"Internal camera parameters";

Focus:foc: 0.00806039;
DOUBLE:0.0:;
"Focal length of the lens [meter]";

Kappa:kappa: -2253.5;
DOUBLE::;
"Radial distortion coefficient [1/(meter*meter)]";

Sx:sx: 1.0629e-05;
DOUBLE:0.0:;
"Width of a cell on the chip [meter]";

Sy:sy: 1.1e-05;
DOUBLE:0.0:;
"Height of a cell on the chip [meter]";

Cx:cx: 378.236;
DOUBLE:0.0:;
"X-coordinate of the image center [pixel]";

Cy:cy: 297.587;
DOUBLE:0.0:;
"Y-coordinate of the image center [pixel]";

ImageWidth:imgw: 768;
INT:1:32767;
"Width of the used calibration images [pixel]";

ImageHeight:imgh: 576;
INT:1:32767;
"Height of the used calibration images [pixel]";

In addition to the 8 parameters of the parameter group Camera:Parameter, the parameter group LinescanCamera:
Parameter contains 3 parameters that describe the motion of the camera with respect to the object. With this,
the parameter group LinescanCamera:Parameter consists of the 11 parameters Focus, Kappa (κ), Sx, Sy, Cx, Cy,
ImageWidth, ImageHeight, Vx, Vy und Vz. A suitable file can look like the following:

# INTERNAL CAMERA PARAMETERS

ParGroup: LinescanCamera: Parameter;

HALCON 8.0.2
1148 CHAPTER 15. TOOLS

"Internal camera parameters";

Focus:foc: 0.061;
DOUBLE:0.0:;
"Focal length of the lens [meter]";

Kappa:kappa: -16.9761;
DOUBLE::;
"Radial distortion coefficient [1/(meter*meter)]";

Sx:sx: 1.06903e-05;
DOUBLE:0.0:;
"Width of a cell on the chip [meter]";

Sy:sy: 1e-05;
DOUBLE:0.0:;
"Height of a cell on the chip [meter]";

Cx:cx: 930.625;
DOUBLE:0.0:;
"X-coordinate of the image center [pixel]";

Cy:cy: 149.962;
DOUBLE:0.0:;
"Y-coordinate of the image center [pixel]";

ImageWidth:imgw: 2048;
INT:1:32767;
"Width of the used calibration images [pixel]";

ImageHeight:imgh: 3840;
INT:1:32767;
"Height of the used calibration images [pixel]";

Vx:vx: 1.41376e-06;
DOUBLE::;
"X-component of the motion vector [meter/scanline]";

Vy:vy: 5.45756e-05;
DOUBLE::;
"Y-component of the motion vector [meter/scanline]";

Vz:vz: 3.45872e-06;
DOUBLE::;
"Z-component of the motion vector [meter/scanline]";

Parameter
. CamParFile (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.read ; String / VARIANT
File name of interior camera parameters.
Default Value : ’campar.dat’
List of values : CamParFile ∈ {’campar.dat’, ’campar.initial’, ’campar.final’}
. CamParam (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Interior camera parameters.
Number of elements : ((CamP aram = 8) ∨ (CamP aram = 11))
Example

* get interior camera parameters:


read_cam_par(’campar.dat’, CamParam)

HALCON/COM Reference Manual, 2008-5-13


15.5. CALIBRATION 1149

Result
ReadCamPar returns TRUE if all parameter values are correct and the file has been read successfully. If necessary
an exception handling is raised.
Parallelization Information
ReadCamPar is reentrant and processed without parallelization.
Possible Successors
FindMarksAndPose, SimCaltab, GenCaltab, DispCaltab, CameraCalibration
See also
FindCaltab, FindMarksAndPose, CameraCalibration, DispCaltab, SimCaltab,
WriteCamPar, WritePose, ReadPose, Project3DPoint, GetLineOfSight
Module
Foundation

void HImageX.SimCaltab ([in] String CalTabDescrFile,


[in] VARIANT CamParam, [in] VARIANT CaltabPose, [in] long GrayBackground,
[in] long GrayCaltab, [in] long GrayMarks, [in] double ScaleFac )
void HOperatorSetX.SimCaltab ([out] HUntypedObjectX SimImage,
[in] VARIANT CalTabDescrFile, [in] VARIANT CamParam, [in] VARIANT CaltabPose,
[in] VARIANT GrayBackground, [in] VARIANT GrayCaltab, [in] VARIANT GrayMarks,
[in] VARIANT ScaleFac )

Simulate an image with calibration plate.


SimCaltab is used to generate a simulated calibration image. The calibration plate description is read from the
file CalTabDescrFile and will be projected into the image plane using the given camera parameters (interior
camera parameters CamParam and exterior camera parameters CaltabPose), see also Project3DPoint.
In the simulated image only the calibration plate is shown. The image background is set to the gray value
GrayBackground, the calibration plate background is set to GrayCaltab, and the calibration marks are set
to the gray value GrayMarks. The parameter ScaleFac influences the number of supporting points to approx-
imate the elliptic contours of the calibration marks, see also DispCaltab. Increasing the number of supporting
points causes a more accurate determination of the mark boundary, but increases the computation time, too. For
each pixel of the simulated image which touches a subpixel-boundary of this kind, the gray value is set linearly
between GrayMarks and GrayCaltab dependent on the proportion Inside/Outside.
By applying the operator SimCaltab you can generate synthetic calibration images (with known camera param-
eters!) to test the quality of the calibration algorithm (see CameraCalibration).
Parameter

. SimImage (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / HUntypedObjectX ( byte )


Simulated calibration image.
. CalTabDescrFile (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.read ; String / VARIANT
File name of the calibration plate description.
Default Value : ’caltab.descr’
List of values : CalTabDescrFile ∈ {’caltab.descr’, ’caltab_10mm.descr’, ’caltab_30mm.descr’,
’caltab_100mm.descr’, ’caltab_200mm.descr’}
. CamParam (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Interior camera parameters.
Number of elements : ((CamP aram = 8) ∨ (CamP aram = 11))
. CaltabPose (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pose ; VARIANT ( integer, real )
Exterior camera parameters (3D pose of the calibration plate in camera coordinates).
Number of elements : 7
. GrayBackground (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Gray value of image background.
Default Value : 128
Suggested values : GrayBackground ∈ {0, 32, 64, 96, 128, 160}
Restriction : ((0 ≤ GrayBackground) ≤ 255)

HALCON 8.0.2
1150 CHAPTER 15. TOOLS

. GrayCaltab (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT


Gray value of calibration plate.
Default Value : 224
Suggested values : GrayCaltab ∈ {144, 160, 176, 192, 208, 224, 240}
Restriction : ((0 ≤ GrayCaltab) ≤ 255)
. GrayMarks (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Gray value of calibration marks.
Default Value : 80
Suggested values : GrayMarks ∈ {16, 32, 48, 64, 80, 96, 112}
Restriction : ((0 ≤ GrayM arks) ≤ 255)
. ScaleFac (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Scaling factor to reduce oversampling.
Default Value : 1.0
Suggested values : ScaleFac ∈ {1.0, 0.5, 0.25, 0.125}
Recommended Increment : 0.05
Restriction : (1.0 ≥ ScaleF ac)
Example

* read calibration image


read_image(Image1, ’calib-01’)
* find calibration pattern
find_caltab(Image1, Caltab1, ’caltab.descr’, 3, 112, 5)
* find calibration marks and initial pose
StartCamPar := [Focus, Kappa, Sx, Sy, Cx, Cy, ImageWidth, ImageHeight]
find_marks_and_pose(Image1, Caltab1, ’caltab.descr’, StartCamPar,
128 ,10, 18, 0.9, 15.0, 100.0, RCoord1, CCoord1,
StartPose1)
* read 3D positions of calibration marks
caltab_points(’caltab.descr’, NX, NY, NZ)
* camera calibration
camera_calibration(NX, NY, NZ, RCoord1, CCoord1, StartCamPar,
StartPose1, 11, CamParam, FinalPose, Errors)
* simulate calibration image
sim_caltab(Image1Sim, ’caltab.descr’, CamParam, FinalPose, 128, 224, 80, 1)

Result
SimCaltab returns TRUE if all parameter values are correct. If necessary, an exception handling is raised.
Parallelization Information
SimCaltab is reentrant and processed without parallelization.
Possible Predecessors
CameraCalibration, FindMarksAndPose, ReadPose, ReadCamPar, HomMat3dToPose
Possible Successors
FindCaltab
See also
FindCaltab, FindMarksAndPose, CameraCalibration, DispCaltab, CreatePose,
HomMat3dToPose, Project3DPoint, GenCaltab
Module
Calibration

HALCON/COM Reference Manual, 2008-5-13


15.5. CALIBRATION 1151

[out] HHomMat2dX CameraMatrices


HHomMat2dX.StationaryCameraSelfCalibration ([in] long NumImages,
[in] long ImageWidth, [in] long ImageHeight, [in] long ReferenceImage,
[in] VARIANT MappingSource, [in] VARIANT MappingDest, [in] VARIANT Rows1,
[in] VARIANT Cols1, [in] VARIANT Rows2, [in] VARIANT Cols2,
[in] VARIANT NumCorrespondences, [in] String EstimationMethod,
[in] VARIANT CameraModel, [in] String FixedCameraParams, [out] double Kappa,
[out] HHomMat2dX RotationMatrices, [out] VARIANT X, [out] VARIANT Y,
[out] VARIANT Z, [out] VARIANT Error )
void HOperatorSetX.StationaryCameraSelfCalibration
([in] VARIANT NumImages, [in] VARIANT ImageWidth, [in] VARIANT ImageHeight,
[in] VARIANT ReferenceImage, [in] VARIANT MappingSource,
[in] VARIANT MappingDest, [in] VARIANT HomMatrices2D, [in] VARIANT Rows1,
[in] VARIANT Cols1, [in] VARIANT Rows2, [in] VARIANT Cols2,
[in] VARIANT NumCorrespondences, [in] VARIANT EstimationMethod,
[in] VARIANT CameraModel, [in] VARIANT FixedCameraParams,
[out] VARIANT CameraMatrices, [out] VARIANT Kappa,
[out] VARIANT RotationMatrices, [out] VARIANT X, [out] VARIANT Y,
[out] VARIANT Z, [out] VARIANT Error )

Perform a self-calibration of a stationary projective camera.


StationaryCameraSelfCalibration performs a self-calibration of a stationary projective camera. Here,
stationary means that the camera may only rotate around the optical center and may zoom. Hence, the optical
center may not move. Projective means that the camera model is a pinhole camera that can be described by a
projective 3D-2D transformation. In particular, radial distortions can only be modeled for cameras with constant
parameters. If the lens exhibits significant radial distortions they should be removed, at least approximately, with
ChangeRadialDistortionImage.
The camera model being used can be described as follows:

x = PX .

Here, x is a homogeneous 2D vector, X a homogeneous 3D vector, and P a homogeneous 3×4 projection matrix.
The projection matrix P can be decomposed as follows:

P = K(R|t) .

Here, R is a 3×3 rotation matrix and t is an inhomogeneous 3D vector. These two entities describe
the position (pose) of the camera in 3D space. This convention is analogous to the convention used in
CameraCalibration, i.e., for R = I and t = 0 the x axis points to the right, the y axis downwards, and
the z axis points forward. K is the calibration matrix of the camera (the camera matrix) which can be described as
follows:
 
af sf u
K= 0 f v  .
0 0 1

Here, f is the focal length of the camera in pixels, a the aspect ratio of the pixels, s is a factor that models the
skew of the image axes, and (u, v) is the principal point of the camera in pixels. In this convention, the x axis
corresponds to the column axis and the y axis to the row axis.
Since the camera is stationary, it can be assumed that t = 0. With this convention, it is easy to see that the
fourth coordinate of the homogeneous 3D vector X has no influence on the position of the projected 3D point.
Consequently, the fourth coordinate can be set to 0, and it can be seen that X can be regarded as a point at infinity,
and hence represents a direction in 3D. With this convention, the fourth coordinate of X can be omitted, and hence
X can be regarded as inhomogeneous 3D vector which can only be determined up to scale since it represents a
direction. With this, the above projection equation can be written as follows:

x = KRX .

HALCON 8.0.2
1152 CHAPTER 15. TOOLS

If two images of the same point are taken with a stationary camera, the following equations hold:

x1 = K1 R1 X
x2 = K2 R2 X

and conseqently

x2 = K2 R2 R−1 −1 −1
1 K1 x1 = K2 R12 K1 x1 = H12 x1 .

If the camera parameters do not change when taking the two images, K1 = K2 holds. Because of the above,
the two images of the same 3D point are related by a projective 2D transformation. This transformation can be
determined with ProjMatchPointsRansac. It needs to be taken into account that the order of the coordinates
of the projective 2D transformations in HALCON is the opposite of the above convention. Furthermore, it needs to
be taken into account that ProjMatchPointsRansac uses a coordinate system in which the origin of a pixel
lies in the upper left corner of the pixel, whereas StationaryCameraSelfCalibration uses a coordinate
system that corresponds to the definition used in CameraCalibration, in which the origin of a pixel lies in the
center of the pixel. For projective 2D transformations that are determined with ProjMatchPointsRansac
the rows and columns must be exchanged and a translation of (0.5, 0.5) must be applied. Hence, instead of
H12 = K2 R12 K1−1 the following equations hold in HALCON:
   
0 1 0.5 0 1 −0.5
H12 = 1 0 0.5  K2 R12 K−1
1
 1 0 −0.5 
0 0 1 0 0 1

and
   
0 1 −0.5 0 1 0.5
K2 R12 K1−1 = 1 0 −0.5  H12  1 0 0.5  .
0 0 1 0 0 1

From the above equation, constraints on the camera parameters can be derived in two ways. First, the rotation can
be eliminated from the above equation, leading to equations that relate the camera matrices with the projective 2D
transformation between the two images. Let Hij be the projective transformation from image i to image j. Then,

Kj K>
j = Hij Ki K> >
i Hij

K−> −1
j Kj = H−> −> −1 −1
ij Ki Ki Hij

From the second equation, linear constraints on the camera parameters can be derived. This method is used for
EstimationMethod = ’linear’. Here, all source images i given by MappingSource and all destination
images j given by MappingDest are used to compute constraints on the camera parameters. After the camera
parameters have been determined from these constraints, the rotation of the camera in the respective images can
be determined based on the equation Rij = K−1 j Hij Ki and by constructing a chain of transformations from the
reference image ReferenceImage to the respective image. From the first equation above, a nonlinear method
to determine the camera parameters can be derived by minimizing the following error:

> > 2
X
Kj K>

E= j − Hij Ki Ki Hij F
(i,j)∈{(s,d)}

Here, analogously to the linear method, {(s, d)} is the set of overlapping images specified by MappingSource
and MappingDest. This method is used for EstimationMethod = ’nonlinear’. To start the minimization,
the camera parameters are initialized with the results of the linear method. These two methods are very fast and
return acceptable results if the projective 2D transformations Hij are sufficiently accurate. For this, it is essential
that the images do not have radial distortions. It can also be seen that in the above two methods the camera
parameters are determined independently from the rotation parameters, and consequently the possible constraints
are not fully exploited. In particular, it can be seen that it is not enforced that the projections of the same 3D point

HALCON/COM Reference Manual, 2008-5-13


15.5. CALIBRATION 1153

lie close to each other in all images. Therefore, StationaryCameraSelfCalibration offers a complete
bundle adjustment as a third method (EstimationMethod = ’gold_standard’). Here, the camera parameters
and rotations as well as the directions in 3D corresponding to the image points (denoted by the vectors X above),
are determined in a single optimization by minimizing the following error:

n m
!
X X 2 1 2 2
E= kxij − Ki Ri Xj k + 2 (ui + vi )
i=1 j=1
σ

In this equation, only the terms for which the reconstructed direction Xj is visible in image i are taken into account.
The starting values for the parameters in the bundle adjustment are derived from the results of the nonlinear method.
Because of the high complexity of the minimization the bundle adjustment requires a significantly longer execution
time than the two simpler methods. Nevertheless, because the bundle adjustment results in significantly better
results, it should be preferred.
In each of the three methods the camera parameters that should be computed can be specified. The remaining
parameters are set to a constant value. Which parameters should be computed is determined with the parameter
CameraModel which contains a tuple of values. CameraModel must always contain the value ’focus’ that
specifies that the focal length f is computed. If CameraModel contains the value ’principal_point’ the principal
point (u, v) of the camera is computed. If not, the principal point is set to (ImageWidth/2, ImageHeight/2).
If CameraModel contains the value ’aspect’ the aspect ratio a of the pixels is determined, otherwise it is set to
1. If CameraModel contains the value ’skew’ the skew of the image axes is determined, otherwise it is set to
0. Only the following combinations of the parameters are allowed: ’focus’, [’focus’, ’principal_point’], [’focus’,
’aspect’], [’focus’, ’principal_point’, ’aspect’] und [’focus’, ’principal_point’, ’aspect’, ’skew’].
Additionally, it is possible to determine the parameter Kappa which models radial lens distortions, if
EstimationMethod = ’gold_standard’ has been selected and the camera parameters are assumed constant.
In this case, ’kappa’ can also be included in the parameter CameraModel.
When using EstimationMethod = ’gold_standard’ to determine the principal point, it is possible to penalize
estimations far away from the image center. This can be done by adding a sigma to the parameter ’principal_point:
0.5’. If no sigma is given the penalty term in the above equation for calculating the error is ommited.
The parameter FixedCameraParams determines whether the camera parameters can change in each im-
age or whether they should be assumed constant for all images. To calibrate a camera so that it can later be
used for measuring with the calibrated camera, only FixedCameraParams = ’true’ is useful. The mode
FixedCameraParams = ’false’ is mainly useful to compute spherical mosaics with GenSphericalMosaic
if the camera zoomed or if the focus changed significantly when the mosaic images were taken. If a mosaic with
constant camera parameters should be computed, of course FixedCameraParams = ’true’ should be used. It
should be noted that for FixedCameraParams = ’false’ the camera calibration problem is determined very
badly, especially for long focal lengths. In these cases, often only the focal length can be determined. Therefore,
it may be necessary to use CameraModel = ’focus’ or to constrain the position of the principal point by using a
small Sigma for the penalty term for the principal point.
The number of images that are used for the calibration is passed in NumImages. Based on the number of images,
several constraints for the camera model must be observed. If only two images are used, even under the assumption
of constant parameters not all camera parameters can be determined. In this case, the skew of the image axes should
be set to 0 by not adding ’skew’ to CameraModel. If FixedCameraParams = ’false’ is used, the full set of
camera parameters can never be determined, no matter how many images are used. In this case, the skew should be
set to 0 as well. Furthermore, it should be noted that the aspect ratio can only be determined accurately if at least
one image is rotated around the optical axis (the z axis of the camera coordinate system) with respect to the other
images. If this is not the case the computation of the aspect ratio should be suppressed by not adding ’aspect’ to
CameraModel.
As described above, to calibrate the camera it is necessary that the projective transformation for each overlapping
image pair is determined with ProjMatchPointsRansac. For example, for a 2×2 block of images in the
following layout
1 2
3 4
the following projective transformations should be determined, assuming that all images overlap each other: 17→2,
17→3, 17→4, 27→3, 27→4 und 37→4. The indices of the images that determine the respective transformation are
given by MappingSource and MappingDest. The indices are start at 1. Consequently, in the above example
MappingSource = [1,1,1,2,2,3] and MappingDest = [2,3,4,3,4,4] must be used. The number of images

HALCON 8.0.2
1154 CHAPTER 15. TOOLS

in the mosaic is given by NumImages. It is used to check whether each image can be reached by a chain of
transformations. The index of the reference image is given by ReferenceImage. On output, this image has the
identity matrix as its transformation matrix.
The 3 × 3 projective transformation matrices that correspond to the image pairs are passed in
HomMatrices2D. Additionally, the coordinates of the matched point pairs in the image pairs must
be passed in Rows1, Cols1, Rows2, and Cols2. They can be determined from the output of
ProjMatchPointsRansac with TupleSelect or with the HDevelop function subset. To enable
StationaryCameraSelfCalibration to determine which point pair belongs to which image pair,
NumCorrespondences must contain the number of found point matches for each image pair.
The computed camera matrices Ki are returned in CameraMatrices as 3 × 3 matrices. For
FixedCameraParams = ’false’, NumImages matrices are returned. Since for FixedCameraParams =
’true’ all camera matrices are identical, a single camera matrix is returned in this case. The computed rotations Ri
are returned in RotationMatrices as 3 × 3 matrices. RotationMatrices always contains NumImages
matrices.
If EstimationMethod = ’gold_standard’ is used, (X, Y, Z) contains the reconstructed directions Xj . In ad-
dition, Error contains the average projection error of the reconstructed directions. This can be used to check
whether the optimization has converged to useful values.
If the computed camera parameters are used to project 3D points or 3D directions into the image i the respective
camera matrix should be multiplied with the corresponding rotation matrix (with HomMat2dCompose).
Parameter
. NumImages (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of different images that are used for the calibration.
Restriction : (N umImages ≥ 2)
. ImageWidth (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Width of the images from which the points were extracted.
Restriction : (ImageW idth > 0)
. ImageHeight (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Height of the images from which the points were extracted.
Restriction : (ImageHeight > 0)
. ReferenceImage (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Index of the reference image.
. MappingSource (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Indices of the source images of the transformations.
. MappingDest (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Indices of the target images of the transformations.
. HomMatrices2D (input control) . . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )
Array of 3 × 3 projective transformation matrices.
. Rows1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; VARIANT ( real, integer )
Row coordinates of corresponding points in the respective source images.
. Cols1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; VARIANT ( real, integer )
Column coordinates of corresponding points in the respective source images.
. Rows2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; VARIANT ( real, integer )
Row coordinates of corresponding points in the respective destination images.
. Cols2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; VARIANT ( real, integer )
Column coordinates of corresponding points in the respective destination images.
. NumCorrespondences (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Number of point correspondences in the respective image pair.
. EstimationMethod (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Estimation algorithm for the calibration.
Default Value : ’gold_standard’
List of values : EstimationMethod ∈ {’linear’, ’nonlinear’, ’gold_standard’}
. CameraModel (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( string )
Camera model to be used.
Default Value : [’focus’,’principal_point’]
List of values : CameraModel ∈ {’focus’, ’aspect’, ’skew’, ’principal_point’, ’kappa’}

HALCON/COM Reference Manual, 2008-5-13


15.5. CALIBRATION 1155

. FixedCameraParams (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT


Are the camera parameters identical for all images?
Default Value : ’true’
List of values : FixedCameraParams ∈ {’true’, ’false’}
. CameraMatrices (output control) . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )
(Array of) 3 × 3 projective camera matrices that determine the interior camera parameters.
. Kappa (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Radial distortion of the camera.
. RotationMatrices (output control) . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )
Array of 3 × 3 transformation matrices that determine rotation of the camera in the respective image.
. X (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point3d.x ; VARIANT ( real )
X-Component of the direction vector of each point if EstimationMethod = ’gold_standard’ is used.
. Y (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point3d.y ; VARIANT ( real )
Y-Component of the direction vector of each point if EstimationMethod = ’gold_standard’ is used.
. Z (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point3d.z ; VARIANT ( real )
Z-Component of the direction vector of each point if EstimationMethod = ’gold_standard’ is used.
. Error (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Average error per reconstructed point if EstimationMethod = ’gold_standard’ is used.
Example

* Assume that Images contains four images in the layout given in the
* above description. Then the following example performs the camera
* self-calibration using these four images.
From := [1,1,1,2,2,3]
To := [2,3,4,3,4,4]
HomMatrices2D := []
Rows1 := []
Cols1 := []
Rows2 := []
Cols2 := []
NumMatches := []
for J := 0 to |From|-1 by 1
select_obj (Images, From[J], ImageF)
select_obj (Images, To[J], ImageT)
points_foerstner (ImageF, 1, 2, 3, 100, 0.1, ’gauss’, ’true’,
RowsF, ColsF, _, _, _, _, _, _, _, _)
points_foerstner (ImageT, 1, 2, 3, 100, 0.1, ’gauss’, ’true’,
RowsT, ColsT, _, _, _, _, _, _, _, _)
proj_match_points_ransac (ImageF, ImageT, RowsF, ColsF, RowsT, ColsT,
’ncc’, 10, 0, 0, 480, 640, 0, 0.5,
’gold_standard’, 2, 42, HomMat2D,
Points1, Points2)
HomMatrices2D := [HomMatrices2D,HomMat2D]
Rows1 := [Rows1,subset(RowsF,Points1)]
Cols1 := [Cols1,subset(ColsF,Points1)]
Rows2 := [Rows2,subset(RowsT,Points2)]
Cols2 := [Cols2,subset(ColsT,Points2)]
NumMatches := [NumMatches,|Points1|]
endfor
stationary_camera_self_calibration (4, 640, 480, 1, From, To,
HomMatrices2D, Rows1, Cols1,
Rows2, Cols2, NumMatches,
’gold_standard’,
[’focus’,’principal_point’],
’true’, CameraMatrix, Kappa,
RotationMatrices, X, Y, Z, Error)

HALCON 8.0.2
1156 CHAPTER 15. TOOLS

Result
If the parameters are valid, the operator StationaryCameraSelfCalibration returns the value TRUE. If
necessary an exception handling is raised.
Parallelization Information
StationaryCameraSelfCalibration is reentrant and processed without parallelization.
Possible Predecessors
ProjMatchPointsRansac
Possible Successors
GenSphericalMosaic
See also
GenProjectiveMosaic
References
Lourdes Agapito, E. Hayman, I. Reid: “Self-Calibration of Rotating and Zooming Cameras”; International Journal
of Computer Vision; vol. 45, no. 2; pp. 107–127; 2001.
Module
Calibration

void HMiscX.WriteCamPar ([in] VARIANT CamParam, [in] String CamParFile )


void HOperatorSetX.WriteCamPar ([in] VARIANT CamParam,
[in] VARIANT CamParFile )

Write the interior camera parameters to text file.


WriteCamPar is used to write the interior camera parameters CamParam to a text file with name CamParFile.
CamParam is a tuple that contains the interior camera parameters in the two following sequence:
For area scan cameras:
[Focus, Kappa, Sx, Sy, Cx, Cy, ImageWidth, ImageHeight]
For line scan cameras:
[Focus, Kappa, Sx, Sy, Cx, Cy, ImageWidth, ImageHeight, Vx, Vy, Vz]
The interior camera parameters describe the projection process of the used combination of camera, lens, and frame
grabber; they can be determined calibrating the camera, see CameraCalibration.
For the modeling of this projection process which is determined by the used combination of camera, lens, and
frame grabber, HALCON provides the following three 3D camera models:

• Area scan pinhole camera:


The combination of an area scan camera with a lens that effects a perspective projection and that may show
radial distortions.
• Area scan telecentric camera:
The combination of an area scan camera with a telecentric lens that effects a parallel projection and that may
show radial distortions.
• Line scan pinhole camera:
The combination of a line scan camera with a lens that effects a perspective projection and that may show
radial distortions.

For area scan cameras, the projection of the point pc that is given in camera coordinates into a (sub-)pixel [r,c]
in the image consists of the following steps: First, the point is projected into the image plane, i.e., onto the sensor
chip. If the underlying camera model is an area scan pinhole camera, i.e., if the focal length passed in CamParam
is greater than 0, the projection is described by the following equations:
 
x
pc =  y 
z
x y
u = Focus · and v = Focus ·
z z

HALCON/COM Reference Manual, 2008-5-13


15.5. CALIBRATION 1157

In contrast, if the focal length is passed as 0 in CamParam, the camera model of an area scan telecentric camera
is used, i.e., it is assumed that the optics of the lens of the camera performs a parallel projection. In this case, the
corresponding equations are:
 
x
pc =  y 
z

u = x and v=y

The following equations compensate for radial distortion:

2u 2v
ũ = p and ṽ = p
1+ 1− 4κ(u2 + v2 ) 1+ 1 − 4κ(u2 + v 2 )

Finally, the point is transformed from the image plane coordinate system into the image coordinate system, i.e.,
the pixel coordinate system:

ũ ṽ
c= + Cx and r= + Cy
Sx Sy

For line scan cameras, also the relative motion between the camera and the object must be modeled. In HALCON,
the following assumptions for this motion are made:

1. the camera moves with constant velocity along a straight line


2. the orientation of the camera is constant
3. the motion is equal for all images

The motion is described by the motion vector V = (Vx , Vy , Vz )T that must be given in [meter/scanline] in the
camera coordinate system. The motion vector describes the motion of the camera, assuming a fixed object. In fact,
this is equivalent to the assumption of a fixed camera with the object travelling along −V .
The camera coordinate system of line scan cameras is defined as follows: The origin of the coordinate system is the
center of projection. The z-axis is identical to the optical axis and directed so that the visible points have positive z
coordinates. The y-axis is perpendicular to the sensor line and to the z-axis. It is directed so that the motion vector
has a positive y-component. The x-axis is perpendicular to the y- and z-axis, so that the x-, y-, and z-axis form a
right-handed coordinate system.
As the camera moves over the object during the image acquisition, also the camera coordinate system moves
relatively to the object, i.e., each image line has been imaged from a different position. This means, there would
be an individual pose for each image line. To make things easier, in HALCON, all transformations from world
coordinates into camera coordinates and vice versa are based on the pose of the first image line only. The motion
V is taken into account during the projection of the point pc into the image. Consequently, only the pose of the
first image line is returned by the operators FindMarksAndPose and CameraCalibration.
For line scan pinhole cameras, the projection of the point pc that is given in the camera coordinate system into a
(sub-)pixel [r,c] in the image is defined as follows:
Assuming
 
x
pc =  y  ,
z

the following set of equations must be solved for m, ũ, and t:

m · D · ũ = x − t · Vx
−m · D · pv = y − t · Vy
m · Focus = z − t · Vz

HALCON 8.0.2
1158 CHAPTER 15. TOOLS

with

1
D =
1 + κ(ũ2 + (pv )2 )
pv = Sy · Cy

This already includes the compensation for radial distortions.


Finally, the point is transformed into the image coordinate system, i.e., the pixel coordinate system:


c= + Cx and r=t
Sx

The format of the text file CamParFile is a (HALCON-independent) generic parameter description. It allows to
group arbitrary sets of parameters hierarchically. The description of a single parameter within a parameter group
consists of the following 3 lines:

Name : Shortname : Actual value ;


Type : Lower bound (optional) : Upper bound (optional) ;
Description (optional) ;

Depending on the number of elements of CamParam, the parameter groups Camera:Parameter or LinescanCam-
era:Parameter, respectively, are written into the text file CamParFile (see ReadCamPar for an example). The
parameter group Camera:Parameter consits of the 8 interior camera parameters of the area scan camera. The
parameter group LinescanCamera:Parameter consists of the 11 interior camera parameters of the line scan camera.
Parameter
. CamParam (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Interior camera parameters.
Number of elements : ((CamP aram = 8) ∨ (CamP aram = 11))
. CamParFile (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.write ; String / VARIANT
File name of interior camera parameters.
Default Value : ’campar.dat’
List of values : CamParFile ∈ {’campar.dat’, ’campar.initial’, ’campar.final’}
Example

* read calibration images


read_image(Image1, ’calib-01’)
read_image(Image2, ’calib-02’)
read_image(Image3, ’calib-03’)
* find calibration pattern
find_caltab(Image1, Caltab1, ’caltab.descr’, 3, 112, 5)
find_caltab(Image2, Caltab2, ’caltab.descr’, 3, 112, 5)
find_caltab(Image3, Caltab3, ’caltab.descr’, 3, 112, 5)
* find calibration marks and start poses
StartCamPar := [Focus, Kappa, Sx, Sy, Cx, Cy, ImageWidth, ImageHeight]
find_marks_and_pose(Image1, Caltab1, ’caltab.descr’, StartCamPar,
128, 10, 18, 0.9, 15.0, 100.0, RCoord1, CCoord1,
StartPose1)
find_marks_and_pose(Image2, Caltab2, ’caltab.descr’, StartCamPar,
128, 10, 18, 0.9, 15.0, 100.0, RCoord2, CCoord2,
StartPose2)
find_marks_and_pose(Image3, Caltab3, ’caltab.descr’, StartCamPar,
128, 10, 18, 0.9, 15.0, 100.0, RCoord3, CCoord3,
StartPose3)
* read 3D positions of calibration marks
caltab_points(’caltab.descr’, NX, NY, NZ)
* camera calibration

HALCON/COM Reference Manual, 2008-5-13


15.6. DATACODE 1159

camera_calibration(NX, NY, NZ, [RCoord1, RCoord2, RCoord3],


[CCoord1, CCoord2, CCoord3], StartCamPar,
[StartPose1, StartPose2, StartPose3], ’all’,
CamParam, NFinalPose, Errors)
* write interior camera parameters to file
write_cam_par(CamParam, ’campar.dat’)

Result
WriteCamPar returns TRUE if all parameter values are correct and the file has been written successfully. If
necessary an exception handling is raised.
Parallelization Information
WriteCamPar is local and processed completely exclusively without parallelization.
Possible Predecessors
CameraCalibration
See also
FindCaltab, FindMarksAndPose, CameraCalibration, DispCaltab, SimCaltab,
ReadCamPar, WritePose, ReadPose, Project3DPoint, GetLineOfSight
Module
Foundation

15.6 Datacode
void HMiscX.ClearAllDataCode2DModels ( )
void HOperatorSetX.ClearAllDataCode2DModels ( )
Delete all 2D data code models and free the allocated memory
The operator ClearAllDataCode2DModels deletes all 2D data code models that were created by
CreateDataCode2DModel or ReadDataCode2DModel. All memory used by the models is freed. Af-
ter the operator call all 2D data code handles are invalid.
Attention
ClearAllDataCode2DModels exists solely for the purpose of implementing the “reset program” functional-
ity in HDevelop. ClearAllDataCode2DModels must not be used in any application.
Example

Result
The operator ClearAllDataCode2DModels returns the value TRUE if all 2D data code models were freed
correctly. Otherwise, an exception will be raised.
Parallelization Information
ClearAllDataCode2DModels is processed completely exclusively without parallelization.
See also
CreateDataCode2DModel, ReadDataCode2DModel
Alternatives
ClearDataCode2DModel
Module
Data Code

void HOperatorSetX.ClearDataCode2DModel
([in] VARIANT DataCodeHandle )

Delete a 2D data code model and free the allocated memory

HALCON 8.0.2
1160 CHAPTER 15. TOOLS

The operator ClearDataCode2DModel deletes a 2D data code model that was created by
CreateDataCode2DModel or ReadDataCode2DModel. All memory used by the model is freed. The
handle of the model is passed in DataCodeHandle. After the operator call it is invalid.
Parameter

. DataCodeHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . datacode_2d ; HDataCode2DX / VARIANT


Handle of the 2D data code model.
Example

Result
The operator ClearDataCode2DModel returns the value TRUE if a valid handle was passed and the referred
2D data code model can be freed correctly. Otherwise, an exception will be raised.
Parallelization Information
ClearDataCode2DModel is processed completely exclusively without parallelization.
See also
CreateDataCode2DModel, ReadDataCode2DModel
Alternatives
ClearAllDataCode2DModels
Module
Data Code

void HDataCode2DX.CreateDataCode2DModel ([in] String SymbolType,


[in] VARIANT GenParamNames, [in] VARIANT GenParamValues )
void HOperatorSetX.CreateDataCode2DModel ([in] VARIANT SymbolType,
[in] VARIANT GenParamNames, [in] VARIANT GenParamValues,
[out] VARIANT DataCodeHandle )

Create a model of a 2D data code class.


The operator CreateDataCode2DModel creates a model for a certain class of 2D data codes. In
DataCodeHandle the operator returns a handle to the 2D data code model, which is used for all further op-
erations on the data code, like modifying the model, reading a symbol, or accessing the results of the symbol
search.
Supported symbol types
The parameter SymbolType is used to determine the type of data codes to process. Presently, three types are
supported: ’Data Matrix ECC 200’, ’QR Code’, and ’PDF417’. Data matrix codes of type ECC 000-140 are not
supported. For the QR Code the older Model 1 as well as the new Model 2 can be read. The PDF417 can be read
in its conventional as well as in its compact form (’Compact/Truncated PDF417’).
For all symbol types, the data code reader supports the Extended Channel Interpretation (ECI) protocol. If the
symbol contains an ECI code, all characters with ASCII code 92 (backslash, ’\’) that occur in the normal data
stream are, in compliance with the standard, doubled (’\\’) for the output. This is necessary in order to distinguish
data backslashs from the ECI sequence ’\nnnnnn’.
The information whether the symbol contains ECI codes (and consequently doubled backslashs) or not is stored in
the Symbology Identifier number that can be obtained for every succesfully decoded symbol with the help of the
operator GetDataCode2DResults passing the generic parameter ’symbology_ident’. How the code number
encodes additional information about the symbology and the data code reader, like the ECI support, is defined
in the different symbology specifications. For more information see the appropriate standards and the operator
GetDataCode2DResults.
The Symbology Indentifier code will not be preceded by the data code reader to the output data, even if the symbol
contains an ECI code. If this is needed, e.g., by a subsequent processing unit, the ’symbology_ident’ number
(obtained by the operator GetDataCode2DResults with parameter ’symbology_ident’) can be added to the

HALCON/COM Reference Manual, 2008-5-13


15.6. DATACODE 1161

data stream manually together with the symbology flag and the symbol code: ’]d’, ’]Q’, or ’]L’ for DataMatrix
codes, QR codes, or PDF417 codes, respectively.
Standard default settings of the data code model
The default settings of the model were chosen to read a wide range of common symbols within a reasonable
amount of time. However, for run-time reasons some restrictions apply to the symbol (see the following table).
If the model was modified (as described later), it is at any time possible to reset it to these default settings by
passing the generic parameter ’default_parameters’ together with the value ’standard_recognition’ to the operator
SetDataCode2DParam.
Model parameter ’standard_recognition’ ’enhanced_recognition’

polarity: dark symbols on a light background in addition, light symbols on a dark


background
Minimum contrast: 30 10
Module size:
ECC 200, QR Code: 6 . . . 20 pixels ≥ 4 pixels (for sharp images ≥ 2)
PDF417:
Width: 3 . . . 15 pixels ≥ 3 pixels (for sharp images ≥ 2)
Aspect ratio: 1 ...4 1.0 . . . 10
Module shape: no or small gap between adjacent bigger gaps are also possible (up to
modules (< 10% of the module 50% of the module size) (only for
size) ECC 200, QR Code)
ECC200: Maximum slant: 10◦ (0.1745) 30◦ (0.5235)
ECC200: Module grid: fixed any (fixed or variable)
For QR Code: Number of posi- 3 2
tion detection patterns, that are
necessary for generating a new
candidate

Modify the data code model


If it is known that the symbol does not or may not comply with all of these restrictions (e.g., the symbol is brighter
than the background or the contrast is very low), or if first tests show that some of the symbols cannot be read
with the default settings, it is possible to adapt single model parameters – while others are kept to the default
– or the whole model can be extended in a single step by setting the generic parameter ’default_parameters’ to
the value ’enhanced_recognition’. This will lead to a more general model that covers a wider range of 2D data
code symbols. However, the symbol search with such a general model is more extensive, hence the run-time of
the operator FindDataCode2D may increase significantly. This is true especially in the following cases: no
readable data code is detected, the symbol is printed light on dark, or the modules are very small.
For this reason, the model should always be specified as exactly as possible by setting all known parame-
ters. The model parameters can be set directly during the creation of the model or later with the help of the
operator SetDataCode2DParam. Both operators provide the generic parameters GenParamNames and
GenParamValues for this purpose. A detailed description of all supported generic parameters can be found
with the operator SetDataCode2DParam.
Another way for adapting the model is to train it based on sample images. Passing the parameter ’train’ to the op-
erator FindDataCode2D will cause the find operator to look for a symbol, determine its parameters, and modify
the model accordingly. More details can be found with the description of the operator FindDataCode2D.
It is possible to query the model parameters with the operator GetDataCode2DParam. The names of all sup-
ported parameters for setting or querying the model are returned by the operator QueryDataCode2DParams.
Store the data code model
Furthermore, the operator WriteDataCode2DModel allows to write the model into a file that can be used later
to create (e.g., in a different application) an identical copy of the model. Such a model copy is created directly by
ReadDataCode2DModel (without calling CreateDataCode2DModel).
Free the data code model
Since memory is allocated during CreateDataCode2DModel and the following operations, the model should
be freed explicitly by the operator ClearDataCode2DModel if it is no longer used.

HALCON 8.0.2
1162 CHAPTER 15. TOOLS

Parameter

. SymbolType (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT


Type of the 2D data code.
Default Value : ’Data Matrix ECC 200’
List of values : SymbolType ∈ {’Data Matrix ECC 200’, ’QR Code’, ’PDF417’}
. GenParamNames (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . attribute.name(-array) ; VARIANT ( string )
Names of the generic parameters that can be adjusted for the 2D data code model.
Default Value : []
List of values : GenParamNames ∈ {’default_parameters’, ’strict_model’, ’persistence’, ’polarity’,
’mirrored’, ’contrast_min’, ’model_type’, ’version’, ’version_min’, ’version_max’, ’symbol_size’,
’symbol_size_min’, ’symbol_size_max’, ’symbol_cols’, ’symbol_cols_min’, ’symbol_cols_max’,
’symbol_rows’, ’symbol_rows_min’, ’symbol_rows_max’, ’symbol_shape’, ’module_size’,
’module_size_min’, ’module_size_max’, ’module_width’, ’module_width_min’, ’module_width_max’,
’module_aspect’, ’module_aspect_min’, ’module_aspect_max’, ’module_gap’, ’module_gap_min’,
’module_gap_max’, ’module_gap_col’, ’module_gap_col_min’, ’module_gap_col_max’, ’module_gap_row’,
’module_gap_row_min’, ’module_gap_row_max’, ’slant_max’, ’module_grid’, ’position_pattern_min’}
. GenParamValues (input control) . . . . . . . . . . . . attribute.value(-array) ; VARIANT ( integer, string, real )
Values of the generic parameters that can be adjusted for the 2D data code model.
Default Value : []
Suggested values : GenParamValues ∈ {’standard_recognition’, ’enhanced_recognition’, ’yes’, ’no’,
’any’, ’dark_on_light’, ’light_on_dark’, ’square’, ’rectangle’, ’small’, ’big’, ’fixed’, ’variable’, 0, 1, 2, 3, 4, 5,
6, 7, 8, 10, 30, 50, 70, 90, 12, 14, 16, 18, 20, 22, 24, 26, 32, 36, 40, 44, 48, 52, 64, 72, 80, 88, 96, 104, 120,
132, 144}
. DataCodeHandle (output control) . . . . . . . . . . . . . . . . . . . . . . . datacode_2d ; HDataCode2DX / VARIANT
Handle for using and accessing the 2D data code model.
Example

* Two simple examples that show the use of create_data_code_2d_model


* to detect a Data matrix ECC 200 code and a QR Code.

* (1) Create a model for reading simple QR Codes


* (only dark symbols on a light background will be read)
create_data_code_2d_model (’QR Code’, [], [], DataCodeHandle)
* Read an image
read_image (Image, ’datacode/qrcode/qr_workpiece_01’)
* Read the symbol in the image
find_data_code_2d (Image, SymbolXLDs, DataCodeHandle, [], [],
ResultHandles, DecodedDataStrings)
* Clear the model
clear_data_code_2d_model (DataCodeHandle)

* (2) Create a model for reading a wide range of Data matrix ECC 200 codes
* (this model will also read light symbols on dark background)
create_data_code_2d_model (’Data Matrix ECC 200’, ’default_parameters’,
’enhanced_recognition’, DataCodeHandle)
* Read an image
read_image (Image, ’datacode/ecc200/ecc200_cpu_010’)
* Read the symbol in the image
find_data_code_2d (Image, SymbolXLDs, DataCodeHandle, [], [],
ResultHandles, DecodedDataStrings)
* Clear the model
clear_data_code_2d_model (DataCodeHandle)

Result
The operator CreateDataCode2DModel returns the value TRUE if the given parameters are correct. Other-
wise, an exception will be raised.

HALCON/COM Reference Manual, 2008-5-13


15.6. DATACODE 1163

Parallelization Information
CreateDataCode2DModel is processed completely exclusively without parallelization.
Possible Successors
SetDataCode2DParam, FindDataCode2D
See also
ClearDataCode2DModel, ClearAllDataCode2DModels
Alternatives
ReadDataCode2DModel
Module
Data Code

[out] HXLDContX SymbolXLDs HImageX.FindDataCode2D


([in] HDataCode2DX DataCodeHandle, [in] VARIANT GenParamNames,
[in] VARIANT GenParamValues, [out] VARIANT ResultHandles,
[out] VARIANT DecodedDataStrings )
[out] HXLDContX SymbolXLDs HDataCode2DX.FindDataCode2D
([in] HImageX Image, [in] VARIANT GenParamNames, [in] VARIANT GenParamValues,
[out] VARIANT ResultHandles, [out] VARIANT DecodedDataStrings )
void HOperatorSetX.FindDataCode2D ([in] IHObjectX Image,
[out] HUntypedObjectX SymbolXLDs, [in] VARIANT DataCodeHandle,
[in] VARIANT GenParamNames, [in] VARIANT GenParamValues,
[out] VARIANT ResultHandles, [out] VARIANT DecodedDataStrings )

Detect and read 2D data code symbols in an image or train the 2D data code model.
The operator FindDataCode2D detects 2D data code symbols in the input image (Image) and reads the data
that is coded in the symbol. Before calling FindDataCode2D, a model of a class of 2D data codes that matches
the symbols in the images must be created with CreateDataCode2DModel or ReadDataCode2DModel.
The handle returned by these operators is passed to FindDataCode2D in DataCodeHandle. To look for more
than one symbol in an image, the generic parameter ’stop_after_result_num’ can be passed to GenParamNames
together with the number of requested symbols as GenParamValues.
As a result the operator returns for every successfully decoded symbol the surrounding XLD contour
(SymbolXLDs), a result handle, which refers to a candidate structure that stores additional information about
the symbol as well as the search and decoding process (ResultHandles), and the string that is encoded in
the symbol (DecodedDataStrings). If the string is longer than 1024 characters it is shortened to 1020
characters followed by ’. . . ’. In this case, accessing the complete string is only possible with the operator
GetDataCode2DResults. Passing the candidate handle from ResultHandles together with the generic
parameter ’decoded_data’ GetDataCode2DResults returns a tuple with the ASCII code of all characters of
the string.
Adjusting the model
If there is a symbol in the image that cannot be read, it should be verified, whether the properties of the symbol
fit the model parameters. Special attention should be paid to the correct polarity (’polarity’, light-on-dark or dark-
on-light), the symbol size (’symbol_size’ for ECC 200, ’version’ for QR Code, ’symbol_rows’ and ’symbol_cols’
for PDF417), the module size (’module_size’ for ECC 200 and QR Code, ’module_width’ and ’module_aspect’
for PDF417), the possibility of a mirroring of the symbol (’mirrored’), and the specified minimum contrast (’con-
trast_min’). Further relevant parameters are the gap between neighboring foreground modules and, for ECC 200,
the maximum slant of the L-shaped finder pattern (’slant_max’). The current settings for these parameters are re-
turned by the operator GetDataCode2DParam. If necessary, the appropriate model parameters can be adjusted
with SetDataCode2DParam.
It is recommended to adjust the model as well as possible to the symbols in the images also for run-time reasons.
In general, the run-time of FindDataCode2D is higher for a more general model than for a more specific model.
One should take into account that a general model leads to a high run-time especially if no valid data code can be
found.
Train the model

HALCON 8.0.2
1164 CHAPTER 15. TOOLS

Besides setting the model parameters manually with SetDataCode2DParam, the model can also be trained
with FindDataCode2D based on one or several sample images. For this the generic parameter ’train’ must
be passed in GenParamNames. The corresponding value passed in GenParamValues determines the model
parameters that should be learned. The following values are possible:

• All data code types:


’all’: all model parameters that can be trained,
’symbol_size’: symbol size and for ECC 200 also the symbol shape (rectangle or square); for QR Code it is
also possible to pass ’version’.
’module_size’: size of the modules; for PDF417 this includes the module width and the module aspect ratio.
’polarity’: polarity of the symbols: they may appear dark on a light background or light on a dark back-
ground.
’mirrored’: whether the symbols in the image are mirrored or not.
’contrast’: minimum contrast for detecting the symbols.
’image_proc’: adjusting different internal image processing parameters; until now, only the maximum slant
of the L-shaped finder pattern of the ECC 200 symbols is set; more parameters may follow in future.
• ECC 200 and QR Code only:
’module_shape’: shape of the modules, especially whether there is a gap between neighboring foreground
modules or whether they are connected.
• ECC 200 only:
’module_grid’: algorithm for calculating the module positions (fixed or variable grid).
• QR Code only:
’model_type’: whether the QR Code symbols follow the Model 1 or Model 2 specification.

It is possible to train several of these parameters in one call of FindDataCode2D by passing the generic pa-
rameter ’train’ in a tuple more than once in conjunction with the appropriate parameters: e.g., GenParamNames
= [’train’,’train’] and GenParamValues = [’polarity’,’module_size’]. Furthermore, in conjunction with ’train’
= ’all’ it is possible to exclude single parameters from training explicitly again by passing ’train’ more than once.
The names of the parameters to exclude, however, must be prefixed by ’˜’: GenParamNames = [’train’,’train’]
and GenParamValues = [’all’,’˜contrast’], e.g., trains all parameters except the minimum contrast.
For training the model, the following aspects should be considered:

• To use several images for the training, the operator FindDataCode2D must be called with the parameter
’train’ once for every sample image.
• It is also possible to train the model with several symbols in one image. Here, the generic parameter
’stop_after_result_num’ must be passed as a tuple to GenParamNames together with ’train’. The num-
ber of symbols in the image is passed in GenParamValues together with the training parameters.
• If the training image contains more symbols than the one that shall be used for the training the domain of the
image should be reduced to the symbol of interest with ReduceDomain.
• In an application with very similar images, one image for training may be sufficient if the following assump-
tions are true: The symbol size (in modules) is the same for all symbols used in the application, foreground
and background modules are of the same size and there is no gap between neighboring foreground modules,
the background has no distinct texture; and the contrast of all images is almost the same. Otherwise, several
images should be used for training.
• In applications where the symbol size (in modules) is not fixed, the smallest as well as the biggest symbols
should be used for the training. If this can not be guaranteed, the limits for the symbol size should be adapted
manually after the training, or the symbol size should entirely be excluded from the training.
• During the first call of FindDataCode2D in the training mode, the trained model parameters are restricted
to the properties of the detected symbol. Any successive training call will, where necessary, extend the
parameter range to cover the already trained symbols as well as the new symbols. Resetting the model with
SetDataCode2DParam to one of its default settings (’default_parameters’ = ’standard_recognition’ or
’enhanced_recognition’) will also reset the training state of the model.

HALCON/COM Reference Manual, 2008-5-13


15.6. DATACODE 1165

• If FindDataCode2D is not able to read the symbol in the training image, this will produce no error or
exception handling. This can simply be tested in the program by checking the results of FindDataCode2D:
SymbolXLDs, ResultHandles, DecodedDataStrings. These tuples will be empty, and the model
will not be modified.

Functionality of the symbol search


Depending on the current settings of the 2D data code model (see SetDataCode2DParam), the operator
FindDataCode2D performs several passes for searching the data code symbols. The search starts at the highest
pyramid level, where – according to the maximum module size defined in the data code model – the modules
can be separated. In addition, in every pyramid level the preprocessing can vary depending on the presets for the
module gap. If the data code model enables dark symbols on a light background as well as light symbols on a dark
background, within the current pyramid level the dark symbols are searched first. Then the passes for searching
light symbols follow. A pass consists of two phases: The search phase is used to look for the finder patterns and to
generate a symbol candidate for every detected finder pattern, and the evaluation phase, where in a lower pyramid
level all candidates are investigated and – if possible – read.
The operator call is terminated after that pass in which the requested number of 2D data code symbols was suc-
cessfully decoded. The required number of symbols can be specified with the generic paramter GenParamNames
= ’stop_after_result_num’. The appropriate value is passed in GenParamValues; the default is 1.
While searching for more than one symbol in the image, it may happen that not all symbols are detected in the
same pass. In this case FindDataCode2D automatically continues the search until all symbols are found or
until the last pass was performed. Otherwise, if the input image contains several symbols but not all have to be
read, it is possible (especially if the symbols look similar) that more than the requested number of symbols are
returned as a result.
Query results of the symbol search
With the result handles and the operators GetDataCode2DResults and GetDataCode2DObjects, ad-
ditional data can be requested about the search process, e.g., the number of internal search passes or the number
of investigated candidates, and – together with the ResultHandles – about the symbols, like the symbol and
module size, the contrast, or the raw data coded in the symbol. In addition, these operators provide information
about all investigated candidates that could not be read. In particular, this helps to determine if a candidate was
actually generated at the symbol’s position during the preprocessing and – by the value of a status variable – why
the search or reading was aborted. Further information about the parameters can be found with the operators
GetDataCode2DResults and GetDataCode2DObjects.
Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte )


Input image.
. SymbolXLDs (output iconic) . . . . . . . . . . . . . . . . . . . . . xld_cont(-array) ; HXLDContX / HUntypedObjectX
XLD contours that surround the successfully decoded data code symbols.
. DataCodeHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . datacode_2d ; HDataCode2DX / VARIANT
Handle of the 2D data code model.
. GenParamNames (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . attribute.name(-array) ; VARIANT ( string )
Names of (optional) parameters for controlling the behavior of the operator.
Default Value : []
List of values : GenParamNames ∈ {’train’, ’stop_after_result_num’}
. GenParamValues (input control) . . . . . . . . . . . . attribute.value(-array) ; VARIANT ( integer, real, string )
Values of the optional generic parameters.
Default Value : []
Suggested values : GenParamValues ∈ {’all’, ’model_type’, ’symbol_size’, ’version’, ’module_size’,
’module_shape’, ’polarity’, ’mirrored’, ’contrast’, ’module_grid’, ’image_proc’, 1, 2, 3}
. ResultHandles (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Handles of all successfully decoded 2D data code symbols.
. DecodedDataStrings (output control) . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Decoded data strings of all detected 2D data code symbols in the image.
Example

* Examples showing the use of find_data_code_2d.

HALCON 8.0.2
1166 CHAPTER 15. TOOLS

* First, the operator is used to train the model, afterwards it is used to


* read the symbol in another image.

* Create a model for reading Data matrix ECC 200 codes


create_data_code_2d_model (’QR Code’, [], [], DataCodeHandle)
* Read a training image
read_image (Image, ’datacode/ecc200/ecc200_cpu_008’)
* Train the model with the symbol in the image
find_data_code_2d (Image, SymbolXLDs, DataCodeHandle, ’train’, ’all’,
ResultHandles, DecodedDataStrings)
*
* End of training / begin of normal application
*

* Read an image
read_image (Image, ’datacode/ecc200/ecc200_cpu_010’)
* Read the symbol in the image
find_data_code_2d (Image, SymbolXLDs, DataCodeHandle, [], [],
ResultHandles, DecodedDataStrings)

* Display all symbols, the strings encoded in them, and the module size
dev_set_color (’green’)
for i := 0 to |ResultHandles| - 1 by 1
SymbolXLD := SymbolXLDs[i+1]
dev_display (SymbolXLD)
get_contour_xld (SymbolXLD, Row, Col)
set_tposition (WindowHandle, max(Row), min(Col))
write_string (WindowHandle, DecodedDataStrings[i])
get_data_code_2d_results (DataCodeHandle, ResultHandles[i],
[’module_height’,’module_width’], ModuleSize)
new_line (WindowHandle)
write_string (WindowHandle, ’module size = ’ + ModuleSize[0] + ’x’ +
ModuleSize[1])
endfor

* Clear the model


clear_data_code_2d_model (DataCodeHandle)

Result
The operator FindDataCode2D returns the value TRUE if the given parameters are correct. Otherwise, an
exception will be raised.
Parallelization Information
FindDataCode2D is reentrant and processed without parallelization.
Possible Predecessors
CreateDataCode2DModel, ReadDataCode2DModel, SetDataCode2DParam
Possible Successors
GetDataCode2DResults, GetDataCode2DObjects, WriteDataCode2DModel
See also
CreateDataCode2DModel, SetDataCode2DParam, GetDataCode2DResults,
GetDataCode2DObjects
Module
Data Code

HALCON/COM Reference Manual, 2008-5-13


15.6. DATACODE 1167

[out] HUntypedObjectX DataCodeObjects


HDataCode2DX.GetDataCode2DObjects ([in] VARIANT CandidateHandle,
[in] String ObjectName )
void HOperatorSetX.GetDataCode2DObjects
([out] HUntypedObjectX DataCodeObjects, [in] VARIANT DataCodeHandle,
[in] VARIANT CandidateHandle, [in] VARIANT ObjectName )

Access iconic objects that were created during the search for 2D data code symbols.
The operator GetDataCode2DObjects facilitates to access iconic objects that were created during the last call
of FindDataCode2D while searching and reading the 2D data code symbols. Besides the name of the object
(ObjectName), the 2D data code model (DataCodeHandle) must be passed to GetDataCode2DObjects.
In addition, in CandidateHandle a handle of a result or candidate structure or a string identifying a
group of candidates (see GetDataCode2DResults) must be passed. These handles are returned by
FindDataCode2D for all successfully decoded symbols and by GetDataCode2DResults for a group of
candidates. If these operators return several handles in a tuple, the individual handles can be accessed by normal
tuple operations.
Some objects are not accessible without setting the model parameter ’persistence’ to 1 (see
SetDataCode2DParam). The persistence must be set before calling FindDataCode2D, either while
creating the model with CreateDataCode2DModel or with SetDataCode2DParam.
Currently, the following iconic objects can be retrieved:
Regions of the modules

’module_1_rois’: all modules that were classified as foreground (set).


’module_0_rois’: all modules that were classified as background (not set).

These region arrays correspond to the areas that were used for the classification. The returned object is a region
array. Hence it cannot be requested for a group of candidates. Therefore, a single result handle must be passed in
CandidateHandle. The model persistence must be 1 for this object. In addition, requesting the module ROIs
makes sense only for symbols that were detected as valid symbols. For other candidates, whose processing was
aborted earlier, the module ROIs are not available.
XLD contour

’candidate_xld’: an XLD contour that surrounds the candidate or decoded symbol.

This object can be requested for any group of results or for any single candidate or symbol handle. The persistence
setting is of no relevance.
Pyramid images

’search_image’: pyramid image, in which the candidate was found.


’process_image’: pyramid image, in which the candidate was investigated more closely.

The persistence setting is also not relevant here.


Parameter
. DataCodeObjects (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . object(-array) ; HUntypedObjectX
Objects that are created as intermediate results during the detection or evaluation of 2D data codes.
. DataCodeHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . datacode_2d ; HDataCode2DX / VARIANT
Handle of the 2D data code model.
. CandidateHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer, string )
Handle of the 2D data code candidate or name of a group of candidates for which the iconic data is requested.
Default Value : ’all_candidates’
Suggested values : CandidateHandle ∈ {0, 1, 2, ’all_candidates’, ’all_results’, ’all_undecoded’,
’all_aborted’}
. ObjectName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Name of the iconic object to return.
Default Value : ’candidate_xld’
List of values : ObjectName ∈ {’module_1_rois’, ’module_0_rois’, ’candidate_xld’, ’search_image’,
’process_image’}

HALCON 8.0.2
1168 CHAPTER 15. TOOLS

Example

* Example demonstrating how to access the iconic objects of the data code
* search.

* Create a model for reading Data matrix ECC 200 codes


create_data_code_2d_model (’Data Matrix ECC 200’, [], [], DataCodeHandle)
* Read an image
read_image (Image, ’datacode/ecc200/ecc200_cpu_010’)
* Read the symbol in the image
find_data_code_2d (Image, SymbolXLDs, DataCodeHandle, [], [],
ResultHandles, DecodedDataStrings)

* Get the handles of all candidates that were detected as a symbol but
* could not be read
get_data_code_2d_results (DataCodeHandle, ’all_undecoded’, ’handle’,
HandlesUndecoded)

* For every undecoded symbol, get the contour and the classified
* module regions
for i := 0 to |HandlesUndecoded| - 1 by 1
* Get the contour of the symbol
dev_set_color (’blue’)
get_data_code_2d_objects (SymbolXLD, DataCodeHandle, HandlesUndecoded[i],
’candidate_xld’)
* Get the module regions of the foreground modules
dev_set_color (’green’)
get_data_code_2d_objects (ModuleFG, DataCodeHandle, HandlesUndecoded[i],
’module_1_rois’)
* Get the module regions of the background modules
dev_set_color (’red’)
get_data_code_2d_objects (ModuleBG, DataCodeHandle, HandlesUndecoded[i],
’module_0_rois’)
* Stop for inspecting the image
stop ()
endfor

* Clear the model


clear_data_code_2d_model (DataCodeHandle)

Result
The operator GetDataCode2DObjects returns the value TRUE if the given parameters are correct and the
requested objects are available for the last symbol search. Otherwise, an exception will be raised.
Parallelization Information
GetDataCode2DObjects is reentrant and processed without parallelization.
Possible Predecessors
FindDataCode2D, QueryDataCode2DParams
Possible Successors
GetDataCode2DResults
See also
QueryDataCode2DParams, GetDataCode2DResults, GetDataCode2DParam,
SetDataCode2DParam
Module
Data Code

HALCON/COM Reference Manual, 2008-5-13


15.6. DATACODE 1169

[out] VARIANT GenParamValues HDataCode2DX.GetDataCode2DParam


([in] VARIANT GenParamNames )
void HOperatorSetX.GetDataCode2DParam ([in] VARIANT DataCodeHandle,
[in] VARIANT GenParamNames, [out] VARIANT GenParamValues )

Get one or several parameters that describe the 2D data code model.
The operator GetDataCode2DParam allows to query the parameters that are used to describe the 2D data
code model. The names of the desired parameters are passed in the generic parameter GenParamNames, the
corresponding values are returned in GenParamValues. All these parameters can be set and changed at any
time with the operator SetDataCode2DParam. A list with the names of all parameters that are valid for the
used 2D data code type is returned by the operator QueryDataCode2DParams.
The following parameters can be queried – ordered by different categories and data code types:
Size and shape of the symbol:

• Data matrix ECC 200 (including the finder pattern):


’symbol_cols_min’: minimum number of module columns in the symbol.
’symbol_cols_max’: maximum number of module columns in the symbol.
’symbol_rows_min’: minimum number of module rows in the symbol.
’symbol_rows_max’: maximum number of module rows in the symbol.
’symbol_shape’: possible restrictions concerning the module shape (rectangle and/or square): ’square’, ’rect-
angle’, ’any’. Since HALCON 7.1.1, the same search algorithm is used for both shapes.
• QR Code (including the finder pattern):
’model_type’: type of the QR Code model specification: 1, 2, ’any’
’version_min’: minimum symbol version to be read: [1. . . 40] (Model 1: [1. . . 14])
’version_max’: maximum symbol version to be read: [1. . . 40] (Model 1: [1. . . 14])
’symbol_size_min’: minimum symbol size (this value is directly linked to the version ’version_min’):
[21. . . 177] (Model 1: [21. . . 73])
’symbol_size_max’: maximum symbol size (this value is directly linked to the version ’version_max’):
[21. . . 177] (Model 1: [21. . . 73])
• PDF417:
’symbol_cols_min’: minimum number of data columns in the symbol in codewords, i.e., excluding the code-
words of the start/stop pattern and of the two row indicators.
’symbol_cols_max’: maximum number of data columns in the symbol in codewords, i.e., excluding the
codewords of the start/stop pattern and of the two row indicators.
’symbol_rows_min’: minimum number of module rows in the symbol.
’symbol_rows_max’: maximum number of module rows in the symbol.

Appearance of the modules in the image:

• All data code types:


’polarity’: possible restrictions concerning the polarity of the modules, i.e., if they are printed dark on a light
background or vice versa: ’dark_on_light’, ’light_on_dark’, ’any’.
’mirrored’: describes whether the symbol is or may be mirrored (which is equivalent to swapping the rows
and columns of the symbol): ’yes’, ’no’, ’any’.
’contrast_min’: minimum contrast between the foreground and the background of the symbol (this measure
corresponds to the minimum gradient between the symbol’s foreground and the background).
• Data matrix ECC 200 and QR Code:
’module_size_min’: minimum module size in the image in pixels.
’module_size_max’: maximum module size in the image in pixels.
With the following parameters it is possible to specify whether neighboring foreground modules are con-
nected or whether there is or may be a gap between them (possible values are ’no’ (no gap) < ’small’ <
’big’):

HALCON 8.0.2
1170 CHAPTER 15. TOOLS

’module_gap_col_min’: minimum gap in direction of the symbol columns.


’module_gap_col_max’: maximum gap in direction of the symbol columns.
’module_gap_row_min’: minimum gap in direction of the symbol rows.
’module_gap_row_max’: maximum gap in direction of the symbol rows.
• PDF417:
’module_width_min’: minimum module width in the image in pixels.
’module_width_max’: maximum module width in the image in pixels.
’module_aspect_min’: minimum module aspect ratio (module height to module width).
’module_aspect_max’: maximum module aspect ratio (module height to module width).
• Data matrix ECC 200:
’slant_max’: maximum slant of the L-shaped finder (the angle is returned in radians and corresponds to the
distortion that occurs when the symbol is printed or during the image acquisition).
’module_grid’: describes whether the size of the modules may vary (in a specific range) or not. Dependent
on the parameter different algorithms are used for the calculation of the module’s center positions. If
it is set to ’fixed’, an equidistant grid is used. Allowing a variable module size (’variable’), the grid is
aligned only to the alternating side of the finder pattern. With ’any’ both approaches are tested one after
the other.
• QR Code:
’position_pattern_min’: Number of position detection patterns that have to be visible for generating a new
symbol candidate (2 or 3).

General model behavior:

• All data code types:


’persistence’: controls whether certain intermediate results of the symbol search with FindDataCode2D
are stored only temporarily or persistently in the model: 0 (temporary), 1 (persistent).
’strict_model’: controls the behavior of FindDataCode2D while detecting symbols that could be read but
that do not fit the model restrictions concerning the size of the symbols: ’yes’ (strict: such symbols are
rejected), ’no’ (not strict: all readable symbols are returned as a result independent of their size and the
size specified in the model).

It is possible to query the values of several or all parameters with a single operator call by passing a tuple con-
taining the names of all desired parameters to GenParamNames. As a result a tuple of the same length with the
corresponding values is returned in GenParamValues.
Parameter

. DataCodeHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . datacode_2d ; HDataCode2DX / VARIANT


Handle of the 2D data code model.
. GenParamNames (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . attribute.name(-array) ; VARIANT ( string )
Names of the generic parameters that are to be queried for the 2D data code model.
Default Value : ’contrast_min’
List of values : GenParamNames ∈ {’strict_model’, ’persistence’, ’polarity’, ’mirrored’, ’contrast_min’,
’model_type’, ’version_min’, ’version_max’, ’symbol_size_min’, ’symbol_size_max’, ’symbol_cols_min’,
’symbol_cols_max’, ’symbol_rows_min’, ’symbol_rows_max’, ’symbol_shape’, ’module_size_min’,
’module_size_max’, ’module_width_min’, ’module_width_max’, ’module_aspect_min’,
’module_aspect_max’, ’module_gap_col_min’, ’module_gap_col_max’, ’module_gap_row_min’,
’module_gap_row_max’, ’slant_max’, ’module_grid’, ’position_pattern_min’}
. GenParamValues (output control) . . . . . . . . . . . attribute.value(-array) ; VARIANT ( integer, string, real )
Values of the generic parameters.
Example

HALCON/COM Reference Manual, 2008-5-13


15.6. DATACODE 1171

Result
The operator GetDataCode2DParam returns the value TRUE if the given parameters are correct. Otherwise,
an exception will be raised.
Parallelization Information
GetDataCode2DParam is reentrant and processed without parallelization.
Possible Predecessors
QueryDataCode2DParams, SetDataCode2DParam, FindDataCode2D
Possible Successors
FindDataCode2D, WriteDataCode2DModel
See also
QueryDataCode2DParams, SetDataCode2DParam, GetDataCode2DResults,
GetDataCode2DObjects, FindDataCode2D
Alternatives
WriteDataCode2DModel
Module
Data Code

[out] VARIANT ResultValues HDataCode2DX.GetDataCode2DResults


([in] VARIANT CandidateHandle, [in] VARIANT ResultNames )
void HOperatorSetX.GetDataCode2DResults
([in] VARIANT DataCodeHandle, [in] VARIANT CandidateHandle,
[in] VARIANT ResultNames, [out] VARIANT ResultValues )

Get the alphanumerical results that were accumulated during the search for 2D data code symbols.
The operator GetDataCode2DResults allows to access several alphanumerical results that were calculated
while searching and reading the 2D data code symbols. These results describe the search process in general or one
of the investigated candidates – independently of whether it could be read or not. The results are in most cases
not related to the symbol with the highest resolution but depend on the pyramid level that was investigated when
the reading process was aborted. To access a result, the name of the parameter (ResultNames) and the 2D data
code model (DataCodeHandle) must be passed. In addition, in CandidateHandle a handle of a result or
candidate structure or a string identifying a group of candidates must be passed. These handles are returned by
FindDataCode2D for all successfully decoded symbols and by GetDataCode2DResults for a group of
candidates. If these operators return several handles in a tuple, the individual handles can be accessed by normal
tuple operations.
Most results consist of one value. Several of these results can be queried for a specific candidate in a single call.
The values returned in ResultValues correspond to the appropriate parameter names in the ResultNames
tuple. As an alternative, these results can also be queried for a group of candidates (see below). In this case, only
one parameter can be requested per call, and ResultValues contains one value for every candidate.
Furthermore, there exists another group of results that consist of more than one value (e.g., ’bin_module_data’),
which are returned as a tuple. These parameters must always be queried exclusively: one result for one specific
candidate.
Apart from the candidate-specific results there are a number of results referring to the search process in general.
This is indicated by passing the string ’general’ in CandidateHandle instead of a candidate handle.
Candidate groups
The following candidate group names are predefined and can be passed as CandidateHandle instead of a
single handle:

’general’: This value is used for results that refer to the last FindDataCode2D call in general but not to a
specific candidate.
’all_candidates’: All candidates (including the successfully decoded symbols) that were investigated during the
last call of FindDataCode2D.
’all_results’: All symbols that were successfully decoded during the last call of FindDataCode2D.

HALCON 8.0.2
1172 CHAPTER 15. TOOLS

’all_undecoded’: All candidates of the last call of FindDataCode2D that were detected as 2D data code sym-
bols, but could not be decoded. For these candidates the error correction detected too many errors, or there
was an failure while decoding the error-corrected data because of inconsistent data.
’all_aborted’: All candidates of the last call of FindDataCode2D that could not be identified as valid 2D data
code symbols and for which the processing was aborted.

Supported results
Currently, the access to the following results, which are returned in ResultValues, is supported:
General results that do not depend on specific candidates (all data code types) – ’general’:

’min_search_level’: lowest pyramid level that is searched for symbols.


’max_search_level’: highest pyramid level that is searched for symbols.
’pass_num’: number of passes that were completed.
’result_num’: number of successfully decoded symbols.
’candidate_num’: number of all investigated candidates.
’undecoded_num’: number of candidates that were identified as symbols but could not be read.
’aborted_num’: number of candidates that could not be identified as valid 2D data code symbols.

Results associated with a specific candidate:


Please consider that some of the following results will not return a useful value if the investigation of the candidate
was aborted.
Results that contain exactly one value and hence can be applied to a tuple of candidates:

• All data code types:


’handle’: handle to the candidate. This parameter is used to receive the handles of all candidates of the
specified group.
’pass’: number of the pass in which the candidate was generated and processed.
’status’: indicates whether the decoding was successful or why the processing was aborted.
’search_level’: pyramid level on which the finder pattern was found.
’process_level’: pyramid level on which the candidate was processed and decoded.
’polarity’: polarity of the symbol. This is the assumption about the polarity that was used for searching the
candidate.
’mirrored’: indicates whether a successfully decoded symbol is mirrored or not. For candidates that could
not be read, the parameter returns the mirroring specification of the model.
’symbol_rows’, ’symbol_cols’: ECC 200 and QR Code: detected size of the symbol in modules: number of
rows and columns including the finder pattern; PDF417: detected number of rows and data columns
(each 17 modules wide) within the symbol (excluding the start/stop patterns and the row indicators).
’module_height’, ’module_width’: height and width of the modules in pixels.
’contrast’: estimation of the symbol’s contrast. This value is based on the gradient of the edge between the
finder pattern and the background.
’decoded_string’: result string that is encoded in the symbol – this query is useful only for successfully
decoded strings. It returns the same string as FindDataCode2D and is subjected to the same restric-
tions concerning the maximum length of 1024 characters. If the result string is longer, the parameter
’decoded_data’ can be used to get a tuple with all ASCII characters of the decoded string.
’decoding_error’: decoding error – for successfully decoded symbols this is the number of errors that were
detected and corrected by the error correction. The number of errors corresponds here to the number of
code words that lead to errors when trying to read them. If the error correction failed, a negative error
code is returned.
’symbology_ident’: The Symbology Identifier is used to indicate that the data code contains the FNC1 and/or
ECI characters.
FNC1 (Function 1 Character) is used if the data formating conforms to specific predefined industry
standards.
The ECI protocol (Extended Channel Interpretation) is used to change the default interpretation of the
encoded data. A 6-digit code number after the ECI character switches the interpretation of the following

HALCON/COM Reference Manual, 2008-5-13


15.6. DATACODE 1173

characters from the default to a specific code page like an international character set. In the output stream
the ECI switch is coded as ’\nnnnnn’. Therefore all backslashs (’\’, ASCII code 92), that occur in the
normal output stream have to be doubled.
The ’symbology_ident’ parameter returns only the actual identifier value m (m ∈ [0, 6] (ECC 200 and QR
Code) and m ∈ [0, 2] (PDF417)) according to the specification of Data matrix, QR Codes, and PDF417
but not the identifier prefixes ’]d’, ’]Q’, and ’]L’ for Data matrix, QR Codes, and PDF417 respectively.
If required, this Symbology Identifier composed of the prefix and the value m has to be preceded the
decoded string (normally only if m > 1) manually. Symbols that contain ECI codes (and hence doubled
backslashs) can be recognised by the following identifier values: ECC 200: 4, 5, and 6, QR Code: 2, 4,
and 6, PDF417: 1.

• Data matrix ECC200 and QR Code:


’module_gap’: assumption about the module gap that was used for searching the candidate.

• Data Matrix ECC200:


’slant’: slant of the L-shaped finder pattern in radians. This is the difference between the angle of the ’L’ and
the right angle.
’module_grid’: For symbols that could be decoded, this parameter informs about the algorithm that was used
for calculating the module grid: If a variable grid was used it returns ’variable’, and otherwise ’fixed’.
For symbols that could not be decoded, it returns the method that was used during the last decoding trial
or, if the candidate was rejected before the decoding, the corresponding model setting.

• QR Codes:
’version’: version number that corresponds to the size of the symbol (version 1 = 21 × 21, version 2 = 25 ×
25, . . . , version 40 = 177 × 177).
’symbol_size’: detected size of the symbol in modules.
’model_type’: Type of the QR Code Model. In HALCON the older, original specification for QR Codes
Model 1 as well as the newer, enhanced form Model 2 are supported.
’mask_pattern_ref’, ’error_correction_level’: If a candidate is recognized as an QR Code the first step is
to read the format information encoded in the symbol. This includes a code for the pattern that was
used for masking the data modules (0 ≤ ’mask_pattern_ref’ ≤ 7) and the level of the error correction
(’error_correction_level’ ∈ [’L’, ’M’, ’Q’, ’H’]).

• PDF417:
’module_aspect’: module aspect ratio; this corresponds to the ratio of ’module_height’ to ’module_width’.
’error_correction_level’: If a candidate is recognized as a PDF417 the first step is to read the format infor-
mation encoded in the symbol. This includes the error correction level, which was used during encoding
(’error_correction_level’ ∈ [0, 8]).

Results that return a tuple of values and hence can be requested only separately and only for a single candidate:

• All data code types:


’bin_module_data’: binary symbol data that is read from the modules row by row – a value of 0 means that
the module was classified as background and 100 indicates that the module belongs to the foreground.
Values between 0 and 100 can be interpreted as foreground or background.
’raw_coded_data’: data obtained by mapping the binary data to data words according to the particular coding
scheme. Single bits may still be erroneous, and the words that are used for the error correction are still
included.
’corr_coded_data’: data obtained after applying the error correction: erroneous bits are corrected and all
redundant words are removed, but the words are still encoded according to the coding scheme that is
specific for the data code type
’decoded_data’: tuple with the decoded data words (= characters of the decoded data string) as ASCII code
or – for QR Code – as JIS8 and Shift JIS characters. In contrast to the decoded data string, there is no
restriction concerning the maximum length of 1024 characters.
’quality_isoiec15415’: tuple with the assessment of print quality in compliance with the international stan-
dard ISO/IEC 15415. The first element always contains the overall print quality of the symbol; the
length of the tuple and the denotation of the remaining elements depend on the specific data code type.

HALCON 8.0.2
1174 CHAPTER 15. TOOLS

According to the standard the grades are whole numbers from 0 to 4, where 0 is the lowest and 4 the
highest grade. It is important to note that, even though the implementation is strictly based on the stan-
dard, the computation of the print quality grades depends on the preceding decoding algorithm. Thus,
different data code readers (of different vendors) can potentially produce slightly different results in the
print quality assessment.
For the 2D data codes ECC200 and QR Code, the print quality is described in a tuple with eight ele-
ments: (overall quality, contrast, modulation, fixed pattern damage, decode, axial nonuniformity, grid
nonuniformity, unused error correction).
The definition of the respective elements is as follows: The overall quality is the minimum of all indi-
vidual grades. The contrast is the range between the minimal and the maximal pixel intensity in the data
code domain, and a strong contrast results in a good grading. The modulation indicates how strong the
amplitudes of the data code modules are. Big amplitudes make the assignment of the modules to black
or white more certain, resulting in a high modulation grade. It is to note that the computation of the
modulation grade is influenced by the specific level of error correction capacity, meaning that the mod-
ulation degrades less for codes with higher error correction capacity. The fixed pattern of both ECC200
and QR Code is of high importance for detecting and decoding the codes. Degradation or damage of the
fixed pattern, or the respective quiet zones, is assessed with the fixed pattern damage quality. The decode
quality always takes the grade 4, meaning that the code could be decoded. Naturally, codes which can
not be decoded can not be assessed concerning print quality either. Originally, data codes have squared
modules, i.e. the width and height of the modules are the same. Due to a potentially oblique view
of the camera onto the data code or a defective fabrication of the data code itself, the width to height
ratio can be distorted. This deterioration results in a degraded axial nonuniformity. If apart from an
affine distortion the data code is subject to perspective or any other distortions too this degrades the grid
nonuniformity quality. As data codes are redundant codes, errors in the modules or codewords can be
corrected. The amount of error correcting capacities which is not already used by the present data code
symbol is expressed in the unused error correction quality. In a way, this grade reflects the reliability of
the decoding process. Note, that even codes with an unused error correction grading of 0, which could
possibly mean a false decoding result, can be decoded by the FindDataCode2D operator in a reliable
way, because the implemented decoding functionality is more sophisticated and robust compared to the
reference decode algorithm proposed by the standard.
For the 2D stacked code PDF417 the print quality is described in a tuple with seven elements: (overall
quality, start/stop pattern, codeword yield, unused error correction, modulation, decodability, defects).
The definition of the respective elements is as follows: The overall quality is the minimum of all individ-
ual grades. As the PDF417 data code is a stacked code, which can be read by line scan devices as well,
print quality assessment is basically based on techniques for linear bar codes: a set of scan reflectance
profiles is generated across the symbol followed by the evaluation of the respective print qualities within
each scan, which are finally subsumed as overall print qualities. For more details the user is referred
to the standard for linear symbols ISO/IEC 14516. In start/stop pattern the start and stop patterns are
assessed concerning the quality of the reflectance profile and the correctness of the bar and space se-
quence. The grade codeword yield counts and evaluates the relative number of correct decoded words
acquired by the set of scan profiles. For the grade unused error correction the relative number of false
decoded words within the error correction blocks are counted. As for 2D data codes, the modulation
grade indicates how strong the amplitudes, i.e. the extremal intensities, of the bars and spaces are. The
grade decodability measures the deviation of the actual length of bars and spaces with respect to their
reference length. And finally, the grade defects refers to a measurement of how perfect the reflectance
profiles of bars and spaces are.

• Data Matrix ECC200 and QR Code:


’structured_append’: if the symbol is part of a group of symbols (“Structured Append”), this parameter
contains (1) the index of the symbol in the group, (2) the number of symbols that belong to the group,
and (3) a number that serves as a group identifier.

• PDF417:
’macro_exist’: symbols that are part of a group of symbols are called "‘Macro PDF417"’ symbols. These
symbols contain additional information within a control block. For macro symbols ’macro_exist’ returns
the value 1 while for conventional symbols 0 is returned.
’macro_segment_index’: returns the index of the symbol in the group. For macro symbols this information
is obligatory.
’macro_file_id’: returns the group identifier as a string. For macro symbols this information is obligatory.

HALCON/COM Reference Manual, 2008-5-13


15.6. DATACODE 1175

’macro_segment_count’: returns the number of symbols that belong to the group. For macro symbols this
information is optional.
’macro_time_stamp’: returns the time stamp on the source file expressed as the elapsed time in seconds since
1970:01:01:00:00:00 GMT as a string. For macro symbols this information is optional.
’macro_checksum’: returns the CRC checksum computed over the entire source file using the CCITT-16
polynomial. For macro symbols this information is optional.
’macro_last_symbol’: returns 1 if the symbol is the last one within the group of symbols. Otherwise 0 is
returned. For macro symbols this information is optional.

Status message
The status parameter that can be queried for all candidates reveals why and where in the evaluation phase a candi-
date was discarded. The following list shows the most important status messages in the order of their generation
during the evaluation phase:

• Data matrix ECC 200:


’aborted: too close to image border’ – The symbol candidate is too close to the border. Only symbols that
are completely within the image can be read.
’aborted adjusting: ...’ – It is not possible to determine the exact position of the finder pattern in the process-
ing image.
’aborted finder pattern: ...’ – It is not possible to determine the width of one of the two legs of the L-shaped
finder pattern.
’aborted leg widths: widths of the finder pattern legs differ too much’ – The widths of the two legs of the L-
shaped finder pattern differ too much.
’aborted alternating side: ...’ – For one dimension of the candidate, two opposite borders were found during
the symbol search phase. However, it is not possible to determine which is the alternating and which the
solid side of the finder pattern.
’aborted border search: ...’ – For one dimension of the candidate, only the border that belongs to the solid
side of the finder patten was found during the symbol search phase. Searching the opposite (the alternat-
ing) side failed.
’aborted symbol: invalid size’ – The number of rows and columns of the symbol that was deduced from the
alternating pattern does not yield in a valid ECC 200 code.
’aborted symbol: size does not fit strict model definition’ – Although the deduced symbol size is a valid ECC
200 size, it is not inside the range predefined by the model.
’aborted symbol: rectangular symbol does not fit strict mirror definition of model’ – The symbol was identi-
fied as a rectangular ECC 200 code. In conjunction with the mirroring parameter of the model, however,
the symbol’s rows and columns are swapped such that no valid ECC 200 code is achieved. This test is
of course not possible for square symbols. There, a wrong mirroring specification will effect the reading
of the symbol data and, in general, lead to the following error:
’error correction failed’ – The error correction failed because there are too many modules that couldn’t be
interpreted correctly. Normally, this indicates that the print and/or image quality is too bad, but it may
also be provoked by a wrong mirroring specification in the model.
’decoding failed: special decoding reader requested’ – The decoded data contains a message for program-
ming the data code reader. This feature is not supported.
’decoding failed: inconsistent data’ – The data coded in the symbol is not consistent and therefore cannot
be read.

• QR Code:
’aborted: too close to image border’ – The symbol candidate is too close to the border. Only symbols that
are completely within the image can be read.
’aborted adjusting: finder patterns’ – It is not possible to determine the exact position of the finder pattern
in the processing image.
’aborted symbol: different number of rows and columns’ – It is not possible to determine for both dimen-
sions a consistent symbol size by the size and the position of the detected finder pattern. When reading
Model 2 symbols, this error may occur only with small symbols (< version 7 or 45 × 45 modules). For
bigger symbols the size is coded within the symbol in the version information region. The estimated size
is used only as a hint for finding the version information region.

HALCON 8.0.2
1176 CHAPTER 15. TOOLS

’aborted symbol: invalid size’ – The size determined by the size and the position of the detected finder pat-
tern is too small or (only Model 1) too big.
’decoding of version information failed’ – While processing a Model 2 symbol, the symbol version as deter-
mined by the finder pattern is at least 7 (≥ 45 × 45 modules). However, reading the version from the
appropriate region in the symbol failed.
’aborted symbol: size does not fit strict model definition’ – Although the deduced symbol size is valid, it is
not inside the range predefined by the model.
’decoding of format information failed’ – Reading the format information (mask pattern and error correction
level) from the appropriate region in the symbol failed.
’error correction failed’ – The error correction failed because there are too many modules that couldn’t be
interpreted correctly. Normally, this indicates that the print and/or image quality is too bad, but it may
also be provoked by a wrong mirroring specification in the model.
’decoding failed: inconsistent data’ – The data coded in the symbol is not consistent and therefore cannot
be read.

• PDF417:
’aborted: too close to image border’ – The symbol candidate is too close to the border. Only symbols that
are completely within the image can be read.
’aborted symbol: size does not fit strict model definition’ – Although the deduced symbol size is valid, it is
not inside the range predefined by the model.
’error correction failed’ – The error correction failed because there are too many modules that couldn’t be
interpreted correctly. Normally, this indicates that the print and/or image quality is too bad, but it may
also be provoked by a wrong mirroring specification in the model.
’decoding failed: special decoding reader requested’ – The decoded data contains a message for program-
ming the data code reader. This feature is not supported.
’decoding failed: inconsistent data’ – The data coded in the symbol is not consistent and therefore cannot
be read.

While processing a candidate, it is possible that internally several iterations for reading the symbol are performed.
If all attempts fail, normally the last abortion state is stored in the candidate structure. E.g., if the QR Code model
enables symbols with Model 1 and Model 2 specification, FindDataCode2D tries first to interpret the symbol
as Model 2 type. If this fails, Model 1 interpretation is performed. If this also fails, the status variable is set to
the latest failure state of the Model 1 interpretation. In order to get the error state of the Model 2 branch, the
’model_type’ parameter of the data code model must be restricted accordingly (with SetDataCode2DParam).
Parameter

. DataCodeHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . datacode_2d ; HDataCode2DX / VARIANT


Handle of the 2D data code model.
. CandidateHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer, string )
Handle of the 2D data code candidate or name of a group of candidates for which the data is required.
Default Value : ’all_candidates’
Suggested values : CandidateHandle ∈ {0, 1, 2, ’general’, ’all_candidates’, ’all_results’,
’all_undecoded’, ’all_aborted’}
. ResultNames (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . attribute.name(-array) ; VARIANT ( string )
Names of the results of the 2D data code to return.
Default Value : ’status’
Suggested values : ResultNames ∈ {’min_search_level’, ’max_search_level’, ’pass_num’, ’result_num’,
’candidate_num’, ’undecoded_num’, ’aborted_num’, ’handle’, ’pass’, ’status’, ’search_level’, ’process_level’,
’polarity’, ’module_gap’, ’mirrored’, ’model_type’, ’symbol_rows’, ’symbol_cols’, ’symbol_size’, ’version’,
’module_height’, ’module_width’, ’module_aspect’, ’slant’, ’contrast’, ’module_grid’, ’decoded_string’,
’decoding_error’, ’symbology_ident’, ’mask_pattern_ref’, ’error_correction_level’, ’bin_module_data’,
’raw_coded_data’, ’corr_coded_data’, ’decoded_data’, ’quality_isoiec15415’, ’structured_append’,
’macro_exist’, ’macro_segment_index’, ’macro_file_id’, ’macro_segment_count’, ’macro_time_stamp’,
’macro_checksum’, ’macro_last_symbol’}
. ResultValues (output control) . . . . . . . . . . . . . . attribute.value(-array) ; VARIANT ( integer, real, string )
List with the results.

HALCON/COM Reference Manual, 2008-5-13


15.6. DATACODE 1177

Example

* Example demonstrating how to access the results of the data code search.

* Create a model for reading Data matrix ECC 200 codes


create_data_code_2d_model (’Data Matrix ECC 200’, [], [], DataCodeHandle)
* Read an image
read_image (Image, ’datacode/ecc200/ecc200_cpu_010’)
* Read the symbol in the image
find_data_code_2d (Image, SymbolXLDs, DataCodeHandle, [], [],
ResultHandles, DecodedDataStrings)

* Get the number of passes


get_data_code_2d_results (DataCodeHandle, ’general’, ’pass_num’, Passes)

* Get a tuple with the status of all candidates


get_data_code_2d_results (DataCodeHandle, ’all_candidates’, ’status’,
AllStatus)
* Get the handles of all candidates that were detected as a symbol but
* could not be read
get_data_code_2d_results (DataCodeHandle, ’all_undecoded’, ’handle’,
HandlesUndecoded)

* For every undecoded symbol, get the contour, the symbol size, and
* the binary module data
dev_set_color (’red’)
for i := 0 to |HandlesUndecoded| - 1 by 1
* Get the contour of the symbol
get_data_code_2d_objects (SymbolXLD, DataCodeHandle, HandlesUndecoded[i],
’candidate_xld’)
* Get the symbol size
get_data_code_2d_results (DataCodeHandle, HandlesUndecoded[i],
[’symbol_rows’,’symbol_cols’], SymbolSize)
* Get the binary module data (has to be queried exclusively)
get_data_code_2d_results (DataCodeHandle, HandlesUndecoded[i],
’bin_module_data’, BinModuleData)
* Stop for inspecting the data
stop ()
endfor

* Clear the model


clear_data_code_2d_model (DataCodeHandle)

Result
The operator GetDataCode2DResults returns the value TRUE if the given parameters are correct and the
requested results are available for the last symbol search. Otherwise, an exception will be raised.
Parallelization Information
GetDataCode2DResults is reentrant and processed without parallelization.
Possible Predecessors
FindDataCode2D, QueryDataCode2DParams
Possible Successors
GetDataCode2DObjects
See also
QueryDataCode2DParams, GetDataCode2DObjects, GetDataCode2DParam,
SetDataCode2DParam
Module
Data Code

HALCON 8.0.2
1178 CHAPTER 15. TOOLS

[out] VARIANT GenParamNames HDataCode2DX.QueryDataCode2DParams


([in] String QueryName )
void HOperatorSetX.QueryDataCode2DParams
([in] VARIANT DataCodeHandle, [in] VARIANT QueryName,
[out] VARIANT GenParamNames )

Get for a given 2D data code model the names of the generic parameters or objects that can be used in the other
2D data code operators.
The operator QueryDataCode2DParams returns the names of the generic parameters that are supported
by the 2D data code operators SetDataCode2DParam, GetDataCode2DParam, FindDataCode2D,
GetDataCode2DResults, and GetDataCode2DObjects. The parameter QueryName is used to select
the desired parameter group:

’get_model_params’: GetDataCode2DParam – parameters for querying the 2D data code model.


’set_model_params’: SetDataCode2DParam – parameters for adjusting the 2D data code model.
’find_params’: FindDataCode2D – parameters used while searching and reading the 2D data code symbols.
’get_result_params’: GetDataCode2DResults – parameters for querying the alphanumerical results of the
symbol search.
’get_result_objects’: GetDataCode2DObjects – parameters for accessing the iconic objects of the symbol
search.

The returned parameter list depends only on the type of the data code and not on the current state of the model or
its results.
Parameter

. DataCodeHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . datacode_2d ; HDataCode2DX / VARIANT


Handle of the 2D data code model.
. QueryName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . attribute.name ; String / VARIANT
Name of the parameter group.
Default Value : ’get_result_params’
List of values : QueryName ∈ {’get_model_params’, ’set_model_params’, ’find_params’,
’get_result_params’, ’get_result_objects’}
. GenParamNames (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . attribute.value ; VARIANT ( string )
List containing the names of the supported generic parameters.
Example

* This example demonstrates how the names of all available model parameters
* can be queried. This is used to request first the settings of the
* untrained and then the settings of the trained model.

* Create a model for reading Data matrix ECC 200 codes


create_data_code_2d_model (’Data Matrix ECC 200’, [], [], DataCodeHandle)
* Query all the names of the generic parameters that can be passed to the
* operator get_data_code_2d_param to request the model
query_data_code_2d_params (DataCodeHandle, ’get_model_params’, GenParamNames)
* Request the current settings of the (untrained) model
get_data_code_2d_param(DataCodeHandle, GenParamNames, ModelParams)

* Read a training image


read_image (Image, ’datacode/ecc200/ecc200_cpu_008’)
* train the model with the symbol in the image
find_data_code_2d (Image, SymbolXLDs, DataCodeHandle, ’train’, ’all’,
ResultHandles, DecodedDataStrings)
* Request the current settings of the (now trained) model
get_data_code_2d_param(DataCodeHandle, GenParamNames, TrainedModelParams)
* Create a tuple that demonstrates the changings

HALCON/COM Reference Manual, 2008-5-13


15.6. DATACODE 1179

ModelAdaption := GenParamNames + ’: ’ + ModelParams + ’ -> ’ +


TrainedModelParams

* Clear the model


clear_data_code_2d_model (DataCodeHandle)

Result
The operator QueryDataCode2DParams returns the value TRUE if the given parameters are correct. Other-
wise, an exception will be raised.
Parallelization Information
QueryDataCode2DParams is reentrant and processed without parallelization.
Possible Predecessors
CreateDataCode2DModel
Possible Successors
GetDataCode2DParam, GetDataCode2DResults, GetDataCode2DObjects
Module
Data Code

void HDataCode2DX.ReadDataCode2DModel ([in] String FileName )


void HOperatorSetX.ReadDataCode2DModel ([in] VARIANT FileName,
[out] VARIANT DataCodeHandle )

Read a 2D data code model from a file and create a new model.
The operator ReadDataCode2DModel reads the 2D data code model file FileName and creates a new model
that is an identical copy of the saved model. The parameter DataCodeHandle returns the handle of the new
model. The model file FileName must be created by the operator WriteDataCode2DModel.
Parameter
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.read ; String / VARIANT
Name of the 2D data code model file.
Default Value : ’data_code_model.dcm’
. DataCodeHandle (output control) . . . . . . . . . . . . . . . . . . . . . . . datacode_2d ; HDataCode2DX / VARIANT
Handle of the created 2D data code model.
Example

* This example demonstrates how a model that was saved in an earlier


* session can be used again by reading the model file

* Create a model by reading by reading a data code model file


read_data_code_2d_model (’ecc200_trained_model.dcm’, DataCodeHandle)
* Read a symbol image
read_image (Image, ’datacode/ecc200/ecc200_cpu_010’)
* Read the symbol in the image
find_data_code_2d (Image, SymbolXLDs, DataCodeHandle, [], [],
ResultHandles, DecodedDataStrings)
* Clear the model
clear_data_code_2d_model (DataCodeHandle)

Result
The operator ReadDataCode2DModel returns the value TRUE if the named 2D data code file was found and
correctly read. Otherwise, an exception will be raised.
Parallelization Information
ReadDataCode2DModel is processed completely exclusively without parallelization.

HALCON 8.0.2
1180 CHAPTER 15. TOOLS

Possible Successors
FindDataCode2D
See also
WriteDataCode2DModel, ClearDataCode2DModel, ClearAllDataCode2DModels
Alternatives
CreateDataCode2DModel
Module
Data Code

void HDataCode2DX.SetDataCode2DParam ([in] VARIANT GenParamNames,


[in] VARIANT GenParamValues )
void HOperatorSetX.SetDataCode2DParam ([in] VARIANT DataCodeHandle,
[in] VARIANT GenParamNames, [in] VARIANT GenParamValues )

Set selected parameters of the 2D data code model.


The operator SetDataCode2DParam is used to set or change the different parameters of a 2D data code model
in order to adapt the model to a particular symbol appearance. All parameters can also be set while creating a 2D
data code model with CreateDataCode2DModel. The current configuration of the data code model can be
queried with GetDataCode2DParam. A list with the names of all parameters that can be set for the given 2D
data code type is returned by QueryDataCode2DParams.
The following overview lists the different generic parameters with the respective value ranges and default values
in standard mode (’standard_recognition’) and, if differing, in enhanced mode (’enhanced_recognition’):
Basic default settings:

• All data code types:


’default_parameters’: reset all model parameters to one of the two basic default settings standard or en-
hanced (see the following summary and CreateDataCode2DModel). In addition to the parameter
values, the training state of the model is reset. Values: ’standard_recognition’, ’enhanced_recognition’
Default: ’standard_recognition’
Attention: If this parameter is set together with a list of other parameters, this parameter must be at the
first position.

Size and shape of the symbol:

• Data matrix ECC 200 (including the finder pattern):


’symbol_cols_min’: minimum number of module columns in the symbol.
Value range: [10 . . . 144] – even
Default: 10
’symbol_cols_max’: maximum number of module columns in the symbol.
Value range: [10 . . . 144] – even
Default: 144
’symbol_rows_min’: minimum number of module rows in the symbol.
Value range: [8 . . . 144] – even
Default: 8
’symbol_rows_max’: maximum number of module rows in the symbol.
Value range: [8 . . . 144] – even
Default: 144
’symbol_shape’: possible restrictions on the module shape (rectangle and/or square). Attention: setting the
symbol shape all previously made restrictions concerning the symbol size are lost. Since HALCON
7.1.1 the same search algorithm is used for both shapes. Thus, the parameter has no relevance for the
symbol search anymore.
Values: ’rectangle’, ’square’, ’any’
Default: ’any’
’symbol_cols’: set ’symbol_cols_min’ and ’symbol_cols_max’ to the same value.

HALCON/COM Reference Manual, 2008-5-13


15.6. DATACODE 1181

’symbol_rows’: set ’symbol_rows_min’ and ’symbol_rows_max’ to the same value.


’symbol_size_min’: set ’symbol_cols_min’ and ’symbol_rows_min’ to the same value.
’symbol_size_max’: set ’symbol_cols_max’ and ’symbol_rows_max’ to the same value.
’symbol_size’: set ’symbol_cols_min’, ’symbol_cols_max’, ’symbol_rows_min’ and ’symbol_rows_max’ to
the same value and ’symbol_shape’ to ’square’.
• QR-Code (including the finder pattern):
’model_type’: type of the QR Code model. The old QR Code Model 1 and the newer Model 2 are supported.
Values: 1, 2, ’any’
Default: ’any’
’version_min’: minimum symbol version. The symbol version is directly linked to the symbol size. Symbols
of version 1 are 21×21 moduls in size, version 2 = 25×25 moduls, etc. up to version 40 = 177×177
moduls. The maximum size of Model 1 symbols is 73×73 = version 14.
Value range: [1 . . . 40] (Model 1: [1 . . . 14])
Default: 1
’version_max’: maximum symbol version.
Value range: [1 . . . 40] (Model 1: [1 . . . 14])
Default: 40
’version’: set ’version_min’ and ’version_max’ to the same value.
’symbol_size_min’: minimum size of the symbol in modules. This parameter can be used as an alternative
to ’version_min’.
Value range: [21 . . . 177] (Model 1: [21 . . . 73])
Default: 21
’symbol_size_max’: maximum size of the symbol in modules. This parameter can be used as an alternative
to ’version_max’:
Value range: [21 . . . 177] (Model 1: [21 . . . 73])
Default: 177
’symbol_size’: set ’symbol_size_min’ and ’symbol_size_max’ to the same value.
• PDF417:
’symbol_cols_min’: minimum number of data columns in the symbol in codewords, i.e., excluding the code-
words of the start/stop pattern and of the two row indicators.
Value range: [1 . . . 30]
Default: 1
’symbol_cols_max’: maximum number of data columns in the symbol in codewords, i.e., excluding the two
codewords of the start/stop pattern and of the two indicators.
Value range: [1 . . . 30]
Default: 20 (enhanced: 30)
’symbol_rows_min’: minimum number of module rows in the symbol.
Value range: [3 . . . 90]
Default: 5 (enhanced: 3)
’symbol_rows_max’: maximum number of module rows in the symbol.
Value range: [3 . . . 90]
Default: 45 (enhanced: 90)
’symbol_cols’: set ’symbol_cols_min’ and ’symbol_cols_max’ to the same value.
’symbol_rows’: set ’symbol_rows_min’ and ’symbol_rows_max’ to the same value.

Appearance of the modules in the image:

• All data code types:


’polarity’: describes the polarity of the symbol in the image, i.e., the parameter determines if the symbol
appears light on a dark background or dark on a light background.
Values: ’dark_on_light’, ’light_on_dark, ’any’.
Default: ’dark_on_light’ (enhanced: ’any’)
’mirrored’: describes whether the symbol is or may be mirrored (which is equivalent to swapping rows and
columns of the symbol).
Values: ’no’, ’yes’, ’any’
Default: ’any’

HALCON 8.0.2
1182 CHAPTER 15. TOOLS

’contrast_min’: minimum contrast between the foreground and the background of the symbol (this measure
corresponds with the minimum gradient between the symbol’s foreground and the background).
Values: [1 . . . 100]
Default: 30 (enhanced: 10)
• Datamatrix ECC 200 und QR-Code:
’module_size_min’: minimum size of the modules in the image in pixels.
Values: [2 . . . 100]
Default: 6 (enhanced: 2)
’module_size_max’: maximum size of the modules in the image in pixels.
Values: [2 . . . 100]
Default: 20 (enhanced: 100)
’module_size’: set ’module_size_min’ and ’module_size_max’ to the same value.
It is possible to specify whether neighboring foreground modules are connected or whether there is or may be
a gap between them. If the foreground modules are connected and fill the module space completely the gap
parameter can be set to ’no’. The parameter is set to ’small’ if there is a very small gap between two modules;
it can be set to ’big’ if the gap is slightly bigger. The last two settings may also be useful if the foreground
modules – although being connected – appear thinner as their entitled space (e.g., as a result of blooming
caused by a bright illuminant). If the foreground modules appear only as very small dots (in relation to the
module size: < 50%), in general, an appropriate preprocessing of the image for detecting or enlarging the
modules will be necessary (e.g., by GrayErosionShape or GrayDilationShape):
’module_gap_col_min’: minimum gap in direction of the symbol columns.
Values: ’no’, ’small’, ’big’
Default: ’no’
’module_gap_col_max’: maximum gap in direction of the symbol columns.
Values: ’no’, ’small’, ’big’
Default: ’small’ (enhanced: ’big’)
’module_gap_row_min’: minimum gap in direction of the symbol rows.
Values: ’no’, ’small’, ’big’
Default: ’no’
’module_gap_row_max’: maximum gap in direction of the symbol rows.
Values: ’no’, ’small’, ’big’
Default: ’small’ (enhanced: ’big’)
’module_gap_col’: set ’module_gap_col_min’ and ’module_gap_col_max’ to the same value.
’module_gap_row’: set ’module_gap_row_min’ and ’module_gap_row_max’ to the same value.
’module_gap_min’: set ’module_gap_col_min’ and ’module_gap_row_min’ to the same value.
’module_gap_max’: set ’module_gap_col_max’ and ’module_gap_row_max’ to the same value.
’module_gap’: set ’module_gap_col_min’, ’module_gap_col_max’, ’module_gap_row_min’, and ’mod-
ule_gap_row_max’ to the same value.
• PDF417:
’module_width_min’: minimum module width in the image in pixels.
Values: [2 . . . 100]
Default: 3 (enhanced: 2)
’module_width_max’: maximum module width in the image in pixels.
Values: [2 . . . 100]
Default: 15 (enhanced: 100)
’module_width’: set ’module_width_min’ and ’module_width_max’ to the same value.
’module_aspect_min’: minimum module aspect ratio (module height to module width).
Values: [0.5 . . . 20.0]
Default: 1.0
’module_aspect_max’: maximum module aspect ratio (module height to module width).
Values: [0.5 . . . 20.0]
Default: 4.0 (enhanced: 10.0)
’module_aspect’: set ’module_aspect_min’ and ’module_aspect_max’ to the same value.
• Data matrix ECC 200:

HALCON/COM Reference Manual, 2008-5-13


15.6. DATACODE 1183

’slant_max’: maximum deviation of the angle of the L-shaped finder pattern from the (ideal) right angle (the
angle is specified in radians and corresponds to the distortion that occurs when the symbol is printed or
during the image acquisition).
Value range: [0.0 . . . 0.5235]
Default: 0.1745 = 10◦ (enhanced: 0.5235 = 30◦ )
’module_grid’: describes whether the size of the modules may vary (in a specific range) or not. Dependent
on this parameter different algorithms are used for calculating the module’s center positions. If it is set to
’fixed’, an equidistant grid is used. Allowing a variable module size (’variable’), the grid is aligned only
to the alternating side of the finder pattern. With ’any’ both approaches are tested one after the other.
Values: ’fixed’, ’variable’, ’any’
Default: ’fixed’ (enhanced: ’any’)
• QR Code:
’position_pattern_min’: Number of position detection patterns that have to be visible for generating a new
symbol candidate.
Value range: [2, 3]
Default: 3 (enhanced: 2)

General model behavior:

• All data code types:


’persistence’: controls whether certain intermediate results of the symbol search with FindDataCode2D
are stored temporarily or persistently in the model. The memory requirements of FindDataCode2D
are significantly smaller if the data is stored temporarily (default). On the other hand, by using the
persistent storage it is possible to access some of the data for debugging reasons after searching for
symbols, e.g., to investigate why a symbol could not be read.
Values: 0 (temporary), 1 (persistent)
Default: 0
’strict_model’: controls the behavior of FindDataCode2D while detecting symbols that could be read but
that do not fit the model restrictions on the size of the symbols. They can be rejected (strict model, set
to ’yes’) or returned as a result independent of their size and the size specified in the model (lax model,
set to ’no’).
Values: ’yes’ (strict), ’no’ (not strict)
Default: ’yes’

When setting the model parameters, attention should be payed especially to the following issues:

• Symbols whose size does not comply with the size restrictions made in the model (with the generic parameters
’symbol_rows*’, ’symbol_cols*’, ’symbol_size*’, or ’version*’) will not be read if ’strict_model’ is set to
’yes’, which is the default. This behavior is useful if symbols of a specific size have to be detected while
other symbols should be ignored. On the other hand, neglecting this parameter can lead to problems, e.g.,
if one symbol of an image sequence is used to adjust the model (including the symbol size), but later in the
application the symbol size varies, which is quite common in practice.
• The run-time of FindDataCode2D depends mostly on the following model parameters, namely in cases
where the requested number of symbols cannot be found in the image: ’polarity’, ’module_size_min’ (ECC
200 and QR Code) and ’module_size_min’ together with ’module_aspect_min’ (PDF417), and if the mini-
mum module size is very small also the parameters ’module_gap_*’ (ECC 200 and QR Code), for QR Code
also ’position_pattern_min’.

Parameter
. DataCodeHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . datacode_2d ; HDataCode2DX / VARIANT
Handle of the 2D data code model.
. GenParamNames (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . attribute.name(-array) ; VARIANT ( string )
Names of the generic parameters that shall be adjusted for the 2D data code.
Default Value : ’polarity’
List of values : GenParamNames ∈ {’default_parameters’, ’strict_model’, ’persistence’, ’polarity’,
’mirrored’, ’contrast_min’, ’model_type’, ’version’, ’version_min’, ’version_max’, ’symbol_size’,
’symbol_size_min’, ’symbol_size_max’, ’symbol_cols’, ’symbol_cols_min’, ’symbol_cols_max’,
’symbol_rows’, ’symbol_rows_min’, ’symbol_rows_max’, ’symbol_shape’, ’module_size’,

HALCON 8.0.2
1184 CHAPTER 15. TOOLS

’module_size_min’, ’module_size_max’, ’module_width_min’, ’module_width_max’, ’module_aspect_min’,


’module_aspect_max’, ’module_gap’, ’module_gap_min’, ’module_gap_max’, ’module_gap_col’,
’module_gap_col_min’, ’module_gap_col_max’, ’module_gap_row’, ’module_gap_row_min’,
’module_gap_row_max’, ’slant_max’, ’module_grid’, ’position_pattern_min’}
. GenParamValues (input control) . . . . . . . . . . . . attribute.value(-array) ; VARIANT ( integer, string, real )
Values of the generic parameters that are adjusted for the 2D data code.
Default Value : ’light_on_dark’
Suggested values : GenParamValues ∈ {’standard_recognition’, ’enhanced_recognition’, ’yes’, ’no’,
’any’, ’dark_on_light’, ’light_on_dark’, ’square’, ’rectangle’, ’small’, ’big’, ’fixed’, ’variable’, 0, 1, 2, 3, 4, 5,
6, 7, 8, 10, 30, 50, 70, 90, 12, 14, 16, 18, 20, 22, 24, 26, 32, 36, 40, 44, 48, 52, 64, 72, 80, 88, 96, 104, 120,
132, 144}
Example

* This examples shows how a model can be adapted to a specific symbol if


* the symbol parameters are known

* Create a model for reading Data matrix ECC 200 codes


create_data_code_2d_model (’Data Matrix ECC 200’, [], [], DataCodeHandle)
* Restrict the model by setting the module size
set_data_code_2d_param (DataCodeHandle,
[’module_size_min’,’module_size_max’], [4,7])
* Change the polarity setting of the model from ’dark_on_light’ to
* ’light_on_dark’ and, at the same time, specify a new minimum contrast
set_data_code_2d_param (DataCodeHandle, [’polarity’,’contrast_min’],
[’light_on_dark’,10])

* Read an image
read_image (Image, ’datacode/ecc200/ecc200_cpu_010’)
* Read the symbol in the image
find_data_code_2d (Image, SymbolXLDs, DataCodeHandle, [], [],
ResultHandles, DecodedDataStrings)
* Clear the model
clear_data_code_2d_model (DataCodeHandle)

Result
The operator SetDataCode2DParam returns the value TRUE if the given parameters are correct. Otherwise,
an exception will be raised.
Parallelization Information
SetDataCode2DParam is reentrant and processed without parallelization.
Possible Predecessors
CreateDataCode2DModel, ReadDataCode2DModel
Possible Successors
GetDataCode2DParam, FindDataCode2D, WriteDataCode2DModel
See also
QueryDataCode2DParams, GetDataCode2DParam, GetDataCode2DResults,
GetDataCode2DObjects
Alternatives
ReadDataCode2DModel
Module
Data Code

HALCON/COM Reference Manual, 2008-5-13


15.6. DATACODE 1185

void HDataCode2DX.WriteDataCode2DModel ([in] String FileName )


void HOperatorSetX.WriteDataCode2DModel
([in] VARIANT DataCodeHandle, [in] VARIANT FileName )

Writes a 2D data code model into a file.


The operator WriteDataCode2DModel writes a 2D data code model, which was created by
CreateDataCode2DModel, into a file with the name FileName. This facilitates creating an identical copy
of the saved model in a later session with the operator ReadDataCode2DModel. The handle of the model to
write is passed in DataCodeHandle.
Parameter

. DataCodeHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . datacode_2d ; HDataCode2DX / VARIANT


Handle of the 2D data code model.
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.write ; String / VARIANT
Name of the 2D data code model file.
Default Value : ’data_code_model.dcm’
Example

* This example demonstrates how a trained model can be saved for


* a future session

* Create a model for reading Data matrix ECC 200 codes


create_data_code_2d_model (’Data Matrix ECC 200’, [], [], DataCodeHandle)
* Read a training image
read_image (Image, ’datacode/ecc200/ecc200_cpu_008’)
* Train the model with the symbol in the image
find_data_code_2d (Image, SymbolXLDs, DataCodeHandle, ’train’, ’all’,
ResultHandles, DecodedDataStrings)
* Write the model into a file
write_data_code_2d_model (DataCodeHandle, ’ecc200_trained_model.dcm’)
* Clear the model
clear_data_code_2d_model (DataCodeHandle)

Result
The operator WriteDataCode2DModel returns the value TRUE if the passed handle is valid and if the model
can be written into the named file. Otherwise, an exception will be raised.
Parallelization Information
WriteDataCode2DModel is reentrant and processed without parallelization.
Possible Predecessors
SetDataCode2DParam, FindDataCode2D
See also
CreateDataCode2DModel, SetDataCode2DParam, FindDataCode2D
Alternatives
GetDataCode2DParam
Module
Data Code

HALCON 8.0.2
1186 CHAPTER 15. TOOLS

15.7 Fourier-Descriptor

[out] VARIANT RealAbsInvar HMiscX.AbsInvarFourierCoeff


([in] VARIANT RealInvar, [in] VARIANT ImaginaryInvar, [in] long CoefP,
[in] long CoefQ, [in] String AZInvar, [out] VARIANT ImaginaryAbsInvar )
void HOperatorSetX.AbsInvarFourierCoeff ([in] VARIANT RealInvar,
[in] VARIANT ImaginaryInvar, [in] VARIANT CoefP, [in] VARIANT CoefQ,
[in] VARIANT AZInvar, [out] VARIANT RealAbsInvar,
[out] VARIANT ImaginaryAbsInvar )

Normalizing of the Fourier coefficients with respect to the displacment of the starting point.
The operator AbsInvarFourierCoeff normalizes the Fourier coefficients with regard to the displacements
of the starting point. These occur when an object is rotated. The contour tracer GetRegionContour starts with
recording the contour in the upper lefthand corner of the region and follows the contour clockwise. If the object
is rotated, the starting value for the contour point chain is different which leads to a phase shift in the frequency
space. The following two kinds of normalizing are available:

abs_amount: The phase information will be eliminated; the normalizing does not retain the structure, i.e. if the
AZ-invariants are backtransformed, no similarity with the pattern can be recognized anymore.
az_invar1: AZ-invariants of the 1st order execute the normalizing with respect to displacing the starting point so
that the structure is retained; they are however more prone to local and global disturbances, in particular to
projective distortions.

Parameter

. RealInvar (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )


Real parts of the normalized Fourier coefficients.
. ImaginaryInvar (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Imaginary parts of the normalized Fourier coefficients.
. CoefP (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Normalizing coefficients p.
Default Value : 1
Suggested values : CoefP ∈ {1, 2}
Restriction : (Coef P ≥ 1)
. CoefQ (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Normalizing coefficients q.
Default Value : 1
Suggested values : CoefQ ∈ {1, 2}
Restriction : ((Coef Q ≥ 1) ∧ (Coef Q 6= Coef P ))
. AZInvar (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Order of the AZ-invariants.
Default Value : ’abs_amount’
List of values : AZInvar ∈ {’abs_amount’, ’az_invar1’}
. RealAbsInvar (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Real parts of the normalized Fourier coefficients.
. ImaginaryAbsInvar (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Imaginary parts of the normalized Fourier coefficients.
Parallelization Information
AbsInvarFourierCoeff is reentrant and processed without parallelization.
Possible Predecessors
InvarFourierCoeff
Possible Successors
Fourier1DimInv, MatchFourierCoeff
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


15.7. FOURIER-DESCRIPTOR 1187

[out] VARIANT RealCoef HMiscX.Fourier1Dim ([in] VARIANT Rows,


[in] VARIANT Columns, [in] VARIANT ParContour, [in] long MaxCoef,
[out] VARIANT ImaginaryCoef )
void HOperatorSetX.Fourier1Dim ([in] VARIANT Rows,
[in] VARIANT Columns, [in] VARIANT ParContour, [in] VARIANT MaxCoef,
[out] VARIANT RealCoef, [out] VARIANT ImaginaryCoef )

Calculate the Fourier coefficients of a parameterized contour.


The operator Fourier1Dim calculates the Fourier coefficients of a parameterized contour by using a
valid parameter scale. This parameter scale may, for instance, be created with the help of the procedure
PrepContourFourier. This function serves to calculate the Fourier coefficients of closed contours which are
treated like complex-valued curves. Therefore, in order to determine the Fourier coefficients, the Fourier transform
for periodical functions is used. Hereby the parameter MaxCoef determines the absolutevalue+1 of the maximal
number of Fourier coefficients, i.e. if n coefficients are indicated, the procedure will calculate coefficients ranging
from −n to n. The contour will be approximated without loss, if n = numberof thecontourpoints, whereby
n = 100 approximates the contour so well that an error can hardly be distinguished; n ∈ [40, 50] however is
sufficient for most applications. If the parameter MaxCoef is set to 0, all coefficients will be determined.
Parameter
. Rows (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . contour.y ; VARIANT ( integer )
Row coordinates of the contour.
. Columns (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . contour.x ; VARIANT ( integer )
Column coordinates of the contour.
. ParContour (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Parameter scale.
. MaxCoef (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Desired number of Fourier coefficients or all of them (0).
Default Value : 50
Suggested values : MaxCoef ∈ {0, 5, 10, 15, 20, 30, 40, 50, 60, 70, 80, 90, 100, 150, 200, 400}
Restriction : (M axCoef ≥ 0)
. RealCoef (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Real parts of the Fourier coefficients.
. ImaginaryCoef (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Imaginary parts of the Fourier coefficients.
Parallelization Information
Fourier1Dim is reentrant and processed without parallelization.
Possible Predecessors
PrepContourFourier
Possible Successors
InvarFourierCoeff, DispPolygon
Module
Foundation

[out] VARIANT Rows HMiscX.Fourier1DimInv ([in] VARIANT RealCoef,


[in] VARIANT ImaginaryCoef, [in] long MaxCoef, [out] VARIANT Columns )
void HOperatorSetX.Fourier1DimInv ([in] VARIANT RealCoef,
[in] VARIANT ImaginaryCoef, [in] VARIANT MaxCoef, [out] VARIANT Rows,
[out] VARIANT Columns )

One dimensional Fourier synthesis (inverse Fourier transform).


Backtransformation of Fourier coefficients respectively of Fourier descriptors. The number of values to be back-
transformed should not exceed the length of the transformed contour.

HALCON 8.0.2
1188 CHAPTER 15. TOOLS

Parameter
. RealCoef (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Real parts.
. ImaginaryCoef (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Imaginary parts.
. MaxCoef (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Input of the steps for the backtransformation.
Default Value : 100
Suggested values : MaxCoef ∈ {5, 10, 15, 20, 30, 40, 50, 60, 70, 80, 90, 100, 150, 200, 400}
Restriction : (M axCoef ≥ 1)
. Rows (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . contour.y ; VARIANT ( real )
Row coordinates.
. Columns (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . contour.x ; VARIANT ( real )
Column coordinates.
Parallelization Information
Fourier1DimInv is reentrant and processed without parallelization.
Possible Predecessors
InvarFourierCoeff, Fourier1Dim
Possible Successors
DispPolygon
Module
Foundation

[out] VARIANT RealInvar HMiscX.InvarFourierCoeff


([in] VARIANT RealCoef, [in] VARIANT ImaginaryCoef, [in] long NormPar,
[in] String InvarType, [out] VARIANT ImaginaryInvar )
void HOperatorSetX.InvarFourierCoeff ([in] VARIANT RealCoef,
[in] VARIANT ImaginaryCoef, [in] VARIANT NormPar, [in] VARIANT InvarType,
[out] VARIANT RealInvar, [out] VARIANT ImaginaryInvar )

Normalize the Fourier coefficients.


Elimination of affine information from the Fourier coefficients, determination of affine invariants. The Fourier
coefficients will be normalized suitably so that all affine correlated contours will be projected to one and the same
contour. The following levels of affine mappings are available:

1. Translations (InvarType = ’transl_invar’)


2. + Rotations (InvarType = ’congr_invar’)
3. + Scalings (InvarType = ’simil_invar’)
4. + Slanting (InvarType = ’affine_invar’)

The control parameter InvarType indicates up to which level the affine representation shall be normalized.
Please note that indicating a certain level implies that the normalizing is executed with regard to all levels below.
For most applications a subsequent normalizing of the starting point is recommended!
Parameter
. RealCoef (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Real parts of the Fourier coefficients.
. ImaginaryCoef (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Imaginary parts of the Fourier coefficients.
. NormPar (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Input of the normalizing coefficients.
Default Value : 1
Suggested values : NormPar ∈ {1, 2}
Restriction : (N ormP ar ≥ 1)

HALCON/COM Reference Manual, 2008-5-13


15.7. FOURIER-DESCRIPTOR 1189

. InvarType (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT


Indicates the level of the affine mappings.
Default Value : ’affine_invar’
List of values : InvarType ∈ {’affine_invar’, ’simil_invar’, ’congr_invar’, ’transl_invar’}
. RealInvar (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Real parts of the normalized Fourier coefficients.
. ImaginaryInvar (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Imaginary parts of the normalized Fourier coefficients.
Parallelization Information
InvarFourierCoeff is reentrant and processed without parallelization.
Possible Predecessors
Fourier1Dim
Possible Successors
InvarFourierCoeff
Module
Foundation

[out] double Distance HMiscX.MatchFourierCoeff ([in] VARIANT RealCoef1,


[in] VARIANT ImaginaryCoef1, [in] VARIANT RealCoef2,
[in] VARIANT ImaginaryCoef2, [in] long MaxCoef, [in] String Damping )
void HOperatorSetX.MatchFourierCoeff ([in] VARIANT RealCoef1,
[in] VARIANT ImaginaryCoef1, [in] VARIANT RealCoef2,
[in] VARIANT ImaginaryCoef2, [in] VARIANT MaxCoef, [in] VARIANT Damping,
[out] VARIANT Distance )

Similarity of two contours.


The operator MatchFourierCoeff calculates the Euclidean distance between two contours which are available
as Fourier coefficients. In order to avoid that the higher frequencies are in some way too dominant, the following
attenuation can be used:
none: No attenuation.
1/index: Absolute amounts of the Fourier coefficients will be divided by their index.
1/(index*index): Absolute amounts of the Fourier coefficients will be divided by their square index.
The higher the result value, the greater the differences between the pattern and the test contour. If the number of
coefficients is not the same, only the first n coefficients will be compared. The parameter MaxCoef indicates the
number of the coefficients to be compared. If MaxCoef is set to zero, all coefficients will be used.
Parameter
. RealCoef1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Real parts of the pattern Fourier coefficients.
. ImaginaryCoef1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Imaginary parts of the pattern Fourier coefficients.
. RealCoef2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Real parts of the Fourier coefficients to be compared.
. ImaginaryCoef2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Imaginary parts of the Fourier coefficients to be compared.
. MaxCoef (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Total number of Fourier coefficients.
Default Value : 50
Suggested values : MaxCoef ∈ {0, 5, 10, 15, 20, 30, 40, 50, 70, 100, 200, 400}
Restriction : (M axCoef ≥ 0)
. Damping (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Kind of attenuation.
Default Value : ’1/index’
Suggested values : Damping ∈ {’none’, ’1/index’, ’1/(index*index)’}

HALCON 8.0.2
1190 CHAPTER 15. TOOLS

. Distance (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT


Similarity of the contours.
Parallelization Information
MatchFourierCoeff is reentrant and processed without parallelization.
Possible Predecessors
InvarFourierCoeff
Module
Foundation

[out] VARIANT RowsMoved HMiscX.MoveContourOrig ([in] VARIANT Rows,


[in] VARIANT Columns, [out] VARIANT ColumnsMoved )
void HOperatorSetX.MoveContourOrig ([in] VARIANT Rows,
[in] VARIANT Columns, [out] VARIANT RowsMoved, [out] VARIANT ColumnsMoved )

Transformation of the origin into the centre of gravity.


The operator MoveContourOrig relocates the input contour so that the origin lies in the centre of gravity.
Parameter
. Rows (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . contour.y ; VARIANT ( integer )
Row coordinates of the contour.
. Columns (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . contour.x ; VARIANT ( integer )
Column coordinates of the contour.
. RowsMoved (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . contour.y ; VARIANT ( integer )
Row coordinates of the displaced contour.
. ColumnsMoved (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . contour.x ; VARIANT ( integer )
Column coordinates of the displaced contour.
Parallelization Information
MoveContourOrig is processed completely exclusively without parallelization.
Possible Predecessors
GetRegionContour
Possible Successors
PrepContourFourier
Module
Foundation

[out] VARIANT ParContour HMiscX.PrepContourFourier ([in] VARIANT Rows,


[in] VARIANT Columns, [in] String TransMode )
void HOperatorSetX.PrepContourFourier ([in] VARIANT Rows,
[in] VARIANT Columns, [in] VARIANT TransMode, [out] VARIANT ParContour )

Parameterize the passed contour.


The operator PrepContourFourier parameterizes the transmitted contour in order to prepare it for the one di-
mensional Fourier transformation. Hereby the contour must be available in closed form. Three parameter functions
are available for the control parameter TransMode:
arc: Parameterization by the radian.
signed_area: Parameterization by the signed area.
unsigned_area: Parameterization by the absolute area.
Please note that in contrast to the signed or unsigned area the affine mapping of the radian will not be transformed
linearly.

HALCON/COM Reference Manual, 2008-5-13


15.8. FUNCTION 1191

Parameter

. Rows (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . contour.y ; VARIANT ( integer )


Row indices of the contour.
. Columns (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . contour.x ; VARIANT ( integer )
Column indices of the contour.
. TransMode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Kind of parameterization.
Default Value : ’signed_area’
Suggested values : TransMode ∈ {’arc’, ’unsigned_area’, ’signed_area’}
. ParContour (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Parameterized contour.
Parallelization Information
PrepContourFourier is reentrant and processed without parallelization.
Possible Predecessors
MoveContourOrig
Possible Successors
Fourier1Dim
Module
Foundation

15.8 Function
[out] HFunction1dX FunctionAbsolute HFunction1dX.AbsFunct1D ( )
void HOperatorSetX.AbsFunct1D ([in] VARIANT Function,
[out] VARIANT FunctionAbsolute )

Absolute value of the y values.


AbsFunct1D calculates the absolute values of all y values of Function.
Parameter

. Function (input control) . . . . . . . . . . . . . . . . . . . . function_1d ; HFunction1dX / VARIANT ( real, integer )


Input function.
. FunctionAbsolute (output control) . . . . . . . . function_1d ; HFunction1dX / VARIANT ( real, integer )
Function with the absolute values of the y values.
Parallelization Information
AbsFunct1D is reentrant and processed without parallelization.
Possible Predecessors
CreateFunct1DPairs, CreateFunct1DArray
Module
Foundation

[out] HFunction1dX ComposedFunction HFunction1dX.ComposeFunct1D


([in] HFunction1dX Function1, [in] String Border )
void HOperatorSetX.ComposeFunct1D ([in] VARIANT Function1,
[in] VARIANT Function2, [in] VARIANT Border, [out] VARIANT ComposedFunction )

Compose two functions.


ComposeFunct1D composes two functions, i.e., calculates

ComposedFunction(x) = Function2(Function1(x)) .

HALCON 8.0.2
1192 CHAPTER 15. TOOLS

ComposedFunction has the same domain (x-range) as Function1. If the range (y-value range) of
Function1 is larger than the domain of Function2, the parameter Border determines the border treatment of
Function2. For Border=’zero’ values outside the domain of Function2 are set to 0, for Border=’constant’
they are set to the corresponding value at the border, for Border=’mirror’ they are mirrored at the border, and for
Border=’cyclic’ they are continued cyclically. To obtain y-values, Function2 is interpolated linearly.
Parameter
. Function1 (input control) . . . . . . . . . . . . . . . . . . . function_1d ; HFunction1dX / VARIANT ( real, integer )
Input function 1.
. Function2 (input control) . . . . . . . . . . . . . . . . . . . function_1d ; HFunction1dX / VARIANT ( real, integer )
Input function 2.
. Border (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Border treatment for the input functions.
Default Value : ’constant’
List of values : Border ∈ {’zero’, ’constant’, ’mirror’, ’cyclic’}
. ComposedFunction (output control) . . . . . . . . function_1d ; HFunction1dX / VARIANT ( real, integer )
Composed function.
Parallelization Information
ComposeFunct1D is reentrant and processed without parallelization.
Possible Predecessors
CreateFunct1DPairs, CreateFunct1DArray
Module
Foundation

void HFunction1dX.CreateFunct1DArray ([in] VARIANT YValues )


void HOperatorSetX.CreateFunct1DArray ([in] VARIANT YValues,
[out] VARIANT Function )

Create a function from a sequence of y-values.


CreateFunct1DArray creates a one-dimensional function from a set of y-values YValues. The resulting
function can then be processed and analyzed with the operators for 1d functions. YValues is interpreted as
follows: the first value of YValues is the function value at zero, the second value is the function value at one, etc.
Thus, the values define a function at equidistant x values (with distance 1), starting at 0.
Alternatively, the operator CreateFunct1DPairs can be used to create a function.
CreateFunct1DPairs also allows to define a function with non-equidistant x valus by specifiying
them explicitely. Thus to get the same definition as with CreateFunct1DArray, one would pass a tuple of
x values to CreateFunct1DPairs that has the same length as YValues and contains values starting at 0
and increasing by 1 in each position. Note, however, that CreateFunct1DPairs leads to a different internal
representation of the function which needs more storage (because all (x,y) pairs are stored) and sometimes cannot
be processed as efficiently as functions created by CreateFunct1DArray.
Parameter
. YValues (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( real, integer )
X value for function points.
. Function (output control) . . . . . . . . . . . . . . . . . . . function_1d ; HFunction1dX / VARIANT ( real, integer )
Created function.
Parallelization Information
CreateFunct1DArray is reentrant and processed without parallelization.
Possible Successors
WriteFunct1D, GnuplotPlotFunct1D, YRangeFunct1D, GetPairFunct1D,
TransformFunct1D
See also
Funct1DToPairs
Alternatives
CreateFunct1DPairs, ReadFunct1D

HALCON/COM Reference Manual, 2008-5-13


15.8. FUNCTION 1193

Module
Foundation

void HFunction1dX.CreateFunct1DPairs ([in] VARIANT XValues,


[in] VARIANT YValues )
void HOperatorSetX.CreateFunct1DPairs ([in] VARIANT XValues,
[in] VARIANT YValues, [out] VARIANT Function )

Create a function from a set of (x,y) pairs.


CreateFunct1DPairs creates a one-dimensional function from a set of pairs of (x,y) values. The XValues
of the functions have to be passed in ascending order. The resulting function can then be processed and analyzed
with the operators for 1d functions.
Alternatively, functions can be created with the operator CreateFunct1DArray. In contrast to this operator,
x values with arbitrary positions can be specified with CreateFunct1DPairs. Hence, it is the more general
operator. It should be noted, however, that because of this generality the processing of a function created with
CreateFunct1DPairs cannot be carried out as efficiently as for equidistant functions. In particular, not all
operators accept such functions. If necessary, a function can be transformed into an equidistant function with the
operator SampleFunct1D.
Parameter

. XValues (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( real, integer )


X value for function points.
. YValues (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( real, integer )
Y-value for function points.
. Function (output control) . . . . . . . . . . . . . . . . . . . function_1d ; HFunction1dX / VARIANT ( real, integer )
Created function.
Parallelization Information
CreateFunct1DPairs is reentrant and processed without parallelization.
Possible Successors
WriteFunct1D, GnuplotPlotFunct1D, YRangeFunct1D, GetPairFunct1D
See also
Funct1DToPairs
Alternatives
CreateFunct1DArray, ReadFunct1D
Module
Foundation

[out] HFunction1dX Derivative HFunction1dX.DerivateFunct1D


([in] String Mode )
void HOperatorSetX.DerivateFunct1D ([in] VARIANT Function,
[in] VARIANT Mode, [out] VARIANT Derivative )

Calculate the derivatives of a function.


DerivateFunct1D calculates the derivatives of the function Function up to the second degree. It uses a
finite difference approximation of order O(h2 ). The derivative is also a function with the same sampling points as
Function. With the parameter Mode, ’first’ and ’second’ derivatives can be selected.
Parameter

. Function (input control) . . . . . . . . . . . . . . . . . . . . function_1d ; HFunction1dX / VARIANT ( real, integer )


Input function

HALCON 8.0.2
1194 CHAPTER 15. TOOLS

. Mode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT


Type of derivative
Default Value : ’first’
List of values : Mode ∈ {’first’, ’second’}
. Derivative (output control) . . . . . . . . . . . . . . . . function_1d ; HFunction1dX / VARIANT ( real, integer )
Derivative of the input function
Parallelization Information
DerivateFunct1D is reentrant and processed without parallelization.
Possible Predecessors
CreateFunct1DPairs, CreateFunct1DArray, SmoothFunct1DGauss, SmoothFunct1DMean
Module
Foundation

[out] VARIANT Distance HFunction1dX.DistanceFunct1D


([in] HFunction1dX Function2, [in] VARIANT Mode, [in] VARIANT Sigma )
void HOperatorSetX.DistanceFunct1D ([in] VARIANT Function1,
[in] VARIANT Function2, [in] VARIANT Mode, [in] VARIANT Sigma,
[out] VARIANT Distance )

Compute the distance of two functions.


DistanceFunct1D calculates the distance of two functions. The two functions may differ in length.
Parameter

. Function1 (input control) . . . . . . . . . . . . . . . . . . . function_1d ; HFunction1dX / VARIANT ( real, integer )


Input function 1.
. Function2 (input control) . . . . . . . . . . . . . . . . . . . function_1d ; HFunction1dX / VARIANT ( real, integer )
Input function 2.
. Mode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Modes of invariants.
Default Value : ’length’
List of values : Mode ∈ {’length’, ’mean’}
. Sigma (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( real )
Variance of the optional smoothing with a Gaussian filter.
Default Value : 0.0
Suggested values : Sigma ∈ {0.0, 0.5, 1.0, 1.5, 2.0, 3.0, 4.0, 5.0, 7.0, 10.0, 15.0, 20.0, 25.0, 30.0, 40.0, 50.0}
. Distance (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real, integer )
Distance of the functions.
Parallelization Information
DistanceFunct1D is reentrant and processed without parallelization.
Module
Foundation

[out] VARIANT XValues HFunction1dX.Funct1DToPairs


([out] VARIANT YValues )
void HOperatorSetX.Funct1DToPairs ([in] VARIANT Function,
[out] VARIANT XValues, [out] VARIANT YValues )

Access to the x/y values of a function.


Funct1DToPairs splits the input function Function into tuples for the x and y values.

HALCON/COM Reference Manual, 2008-5-13


15.8. FUNCTION 1195

Parameter
. Function (input control) . . . . . . . . . . . . . . . . . . . . function_1d ; HFunction1dX / VARIANT ( real, integer )
Input function.
. XValues (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
X values of the function.
. YValues (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Y values of the function.
Parallelization Information
Funct1DToPairs is reentrant and processed without parallelization.
Possible Predecessors
CreateFunct1DPairs, CreateFunct1DArray
Module
Foundation

[out] VARIANT X HFunction1dX.GetPairFunct1D ([in] VARIANT Index,


[out] VARIANT Y )
void HOperatorSetX.GetPairFunct1D ([in] VARIANT Function,
[in] VARIANT Index, [out] VARIANT X, [out] VARIANT Y )

Access a function value using the index of the control points.


GetPairFunct1D accesses a function value of Function. This is done by specifying the index of one or more
control points of the function.
Parameter
. Function (input control) . . . . . . . . . . . . . . . . . . . . function_1d ; HFunction1dX / VARIANT ( real, integer )
Input function.
. Index (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Index of the control points.
. X (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( real )
X value at the given control points.
. Y (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( real )
Y value at the given control points.
Parallelization Information
GetPairFunct1D is reentrant and processed without parallelization.
Possible Predecessors
CreateFunct1DPairs, CreateFunct1DArray
Module
Foundation

[out] VARIANT Y HFunction1dX.GetYValueFunct1D ([in] VARIANT X,


[in] String Border )
void HOperatorSetX.GetYValueFunct1D ([in] VARIANT Function,
[in] VARIANT X, [in] VARIANT Border, [out] VARIANT Y )

Return the value of a function at an arbitrary position.


GetYValueFunct1D returns the y value of the function Function at the x coordinates specified by X. To
obtain the y values, the input function is interpolated linearly. The parameter Border determines the values of the
function Function outside of its domain. For Border=’zero’ these values are set to 0, for Border=’constant’
they are set to the corresponding value at the border, for Border=’mirror’ they are mirrored at the border, for
Border=’cyclic’ they are continued cyclically, and for Border=’error’ an exception handling is raised.

HALCON 8.0.2
1196 CHAPTER 15. TOOLS

Parameter
. Function (input control) . . . . . . . . . . . . . . . . . . . . function_1d ; HFunction1dX / VARIANT ( real, integer )
Input function.
. X (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( real )
X coordinate at which the function should be evaluated.
. Border (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Border treatment for the input function.
Default Value : ’constant’
List of values : Border ∈ {’zero’, ’constant’, ’mirror’, ’cyclic’, ’error’}
. Y (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( real )
Y value at the given x value.
Parallelization Information
GetYValueFunct1D is reentrant and processed without parallelization.
Possible Predecessors
CreateFunct1DPairs, CreateFunct1DArray
Module
Foundation

[out] double Positive HFunction1dX.IntegrateFunct1D


([out] VARIANT Negative )
void HOperatorSetX.IntegrateFunct1D ([in] VARIANT Function,
[out] VARIANT Positive, [out] VARIANT Negative )

Compute the positive and negative areas of a function.


IntegrateFunct1D integrates the function Function (see CreateFunct1DArray and
CreateFunct1DPairs) and returns the integral of the positive and negative parts of the function in
Positive and Negative, respectively. Hence, the integral of the function is the difference Positive -
Negative. The integration is done on the interval on which the function is defined. For the integration, the
function is interpolated linearly.
Parameter
. Function (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . function_1d ; HFunction1dX / VARIANT ( real )
Input function.
. Positive (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Area under the positive part of the function.
. Negative (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real )
Area under the negative part of the function.
Parallelization Information
IntegrateFunct1D is reentrant and processed without parallelization.
Possible Predecessors
CreateFunct1DPairs, CreateFunct1DArray
See also
CreateFunct1DArray, CreateFunct1DPairs
Module
Foundation

HFunction1dX.InvertFunct1D ( )
[out] HFunction1dX InverseFunction
void HOperatorSetX.InvertFunct1D ([in] VARIANT Function,
[out] VARIANT InverseFunction )

Calculate the inverse of a function.

HALCON/COM Reference Manual, 2008-5-13


15.8. FUNCTION 1197

InvertFunct1D calculates the inverse function of the input function Function and returns it in
InverseFunction. The function Function must be monotonic. If this is not the case an error message
is returned.
Parameter

. Function (input control) . . . . . . . . . . . . . . . . . . . . function_1d ; HFunction1dX / VARIANT ( real, integer )


Input function.
. InverseFunction (output control) . . . . . . . . . . function_1d ; HFunction1dX / VARIANT ( real, integer )
Inverse of the input function.
Parallelization Information
InvertFunct1D is reentrant and processed without parallelization.
Possible Predecessors
CreateFunct1DPairs, CreateFunct1DArray
Module
Foundation

[out] VARIANT Min HFunction1dX.LocalMinMaxFunct1D ([in] String Mode,


[in] String Interpolation, [out] VARIANT Max )
void HOperatorSetX.LocalMinMaxFunct1D ([in] VARIANT Function,
[in] VARIANT Mode, [in] VARIANT Interpolation, [out] VARIANT Min,
[out] VARIANT Max )

Calculate the local minimum and maximum points of a function.


LocalMinMaxFunct1D searches for the local minima Min and maxima Max of the function Function.
Since the function values are only known at discrete sampling points, the function can interpolated by parabolas be-
tween these points. Setting the parameter Interpolation to ’true’, enables this feature. If Interpolation
is ’false’, extrema are always sampling points.
If Mode is set to ’strict_min_max’, extrema are only calculated close to points with a function value that is strictly
smaller or strictly greater than the values of its direct neighbors.
If Mode is set to ’plateaus_center’, areas with a function value that is constant throughout several sampling points
are also considered. If such an area is identified as being a flat extremum, its center coordinate is returned.
Parameter

. Function (input control) . . . . . . . . . . . . . . . . . . . . function_1d ; HFunction1dX / VARIANT ( real, integer )


Input function
. Mode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Handling of plateaus
Default Value : ’strict_min_max’
List of values : Mode ∈ {’strict_min_max’, ’plateaus_center’}
. Interpolation (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Interpolation of the input function
Default Value : ’true’
List of values : Interpolation ∈ {’true’, ’false’}
. Min (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Minimum points of the input function
. Max (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Maximum points of the input function
Parallelization Information
LocalMinMaxFunct1D is reentrant and processed without parallelization.
Possible Predecessors
CreateFunct1DPairs, CreateFunct1DArray, SmoothFunct1DGauss, SmoothFunct1DMean
Module
Foundation

HALCON 8.0.2
1198 CHAPTER 15. TOOLS

[out] VARIANT Params HFunction1dX.MatchFunct1DTrans


([in] HFunction1dX Function2, [in] String Border, [in] VARIANT ParamsConst,
[in] VARIANT UseParams, [out] double ChiSquare, [out] VARIANT Covar )
void HOperatorSetX.MatchFunct1DTrans ([in] VARIANT Function1,
[in] VARIANT Function2, [in] VARIANT Border, [in] VARIANT ParamsConst,
[in] VARIANT UseParams, [out] VARIANT Params, [out] VARIANT ChiSquare,
[out] VARIANT Covar )

Calculate transformation parameters between two functions.


MatchFunct1DTrans calculates the transformation parameters between two functions given as the tuples
Function1 and Function2 (see CreateFunct1DArray und CreateFunct1DPairs). The follow-
ing model is used for the transformation between the two functions:

y1 (x) = a1 y2 (a3 x + a4 ) + a2 .

The transformation parameters are determined by a least-squares minimization of the following function:

n−1
X 2
y1 (xi ) − a1 y2 (a3 xi + a4 ) + a2 .
i=0

The values of the function y2 are obtained by linear interpolation. The parameter Border determines the val-
ues of the function Function2 outside of its domain. For Border=’zero’ these values are set to 0, for
Border=’constant’ they are set to the corresponding value at the border, for Border=’mirror’ they are mirrored
at the border, and for Border=’cyclic’ they are continued cyclically. The calculated transformation parameters
are returned as a 4-tuple in Params. If some of the parameter values are known, the respective parameters can
be excluded from the least-squares adjustment by setting the corresponding value in the tuple UseParams to the
value ’false’. In this case, the tuple ParamsConst must contain the known value of the respective parameter. If
a parameter is used for the adjustment (UseParams = ’true’), the corresponding parameter in ParamsConst
is ignored. On output, MatchFunct1DTrans additionally returns the sum of the squared errors ChiSquare
of the resulting function, i.e., the function obtained by transforming the input function with the transformation
parameters, as well as the covariance matrix Covar of the transformation parameters Params. These parameters
can be used to decide whether a successful matching of the functions was possible.
Parameter
. Function1 (input control) . . . . . . . . . . . . . . . . . . . function_1d ; HFunction1dX / VARIANT ( real, integer )
Function 1.
. Function2 (input control) . . . . . . . . . . . . . . . . . . . function_1d ; HFunction1dX / VARIANT ( real, integer )
Function 2.
. Border (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Border treatment for function 2.
Default Value : ’constant’
List of values : Border ∈ {’zero’, ’constant’, ’mirror’, ’cyclic’}
. ParamsConst (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real )
Values of the parameters to remain constant.
Default Value : [1.0,0.0,1.0,0.0]
Number of elements : 4
. UseParams (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( string )
Should a parameter be adapted for it?
Default Value : [’true’,’true’,’true’,’true’]
List of values : UseParams ∈ {’true’, ’false’}
Number of elements : 4
. Params (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real )
Transformation parameters between the functions.
Number of elements : 4
. ChiSquare (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Quadratic error of the output function.

HALCON/COM Reference Manual, 2008-5-13


15.8. FUNCTION 1199

. Covar (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real )


Covariance Matrix of the transformation parameters.
Number of elements : 16
Parallelization Information
MatchFunct1DTrans is reentrant and processed without parallelization.
Possible Predecessors
CreateFunct1DArray, CreateFunct1DPairs
See also
GrayProjections
Module
Foundation

HFunction1dX.NegateFunct1D ( )
[out] HFunction1dX FunctionInverted
void HOperatorSetX.NegateFunct1D ([in] VARIANT Function,
[out] VARIANT FunctionInverted )

Negation of the y values.


NegateFunct1D negates all y values of Function.
Parameter

. Function (input control) . . . . . . . . . . . . . . . . . . . . function_1d ; HFunction1dX / VARIANT ( real, integer )


Input function.
. FunctionInverted (output control) . . . . . . . . function_1d ; HFunction1dX / VARIANT ( real, integer )
Function with the negated y values.
Parallelization Information
NegateFunct1D is reentrant and processed without parallelization.
Possible Predecessors
CreateFunct1DPairs, CreateFunct1DArray
Module
Foundation

HFunction1dX.NumPointsFunct1D ( )
[out] long Length
void HOperatorSetX.NumPointsFunct1D ([in] VARIANT Function,
[out] VARIANT Length )

Number of control points of the function.


NumPointsFunct1D calculates the number of control points of Function.
Parameter

. Function (input control) . . . . . . . . . . . . . . . . . . . . function_1d ; HFunction1dX / VARIANT ( real, integer )


Input function.
. Length (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of control points.
Parallelization Information
NumPointsFunct1D is reentrant and processed without parallelization.
Possible Predecessors
CreateFunct1DPairs, CreateFunct1DArray
Module
Foundation

HALCON 8.0.2
1200 CHAPTER 15. TOOLS

void HFunction1dX.ReadFunct1D ([in] String FileName )


void HOperatorSetX.ReadFunct1D ([in] VARIANT FileName,
[out] VARIANT Function )

Read a function from a file.


The operator ReadFunct1D reads the contents of FileName and converts it into the function Function. The
file has be generated by WriteFunct1D.
Parameter
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.read ; String / VARIANT
Name of the file to be read.
. Function (output control) . . . . . . . . . . . . function_1d(-array) ; HFunction1dX / VARIANT ( real, integer )
Function from the file.
Result
If the parameters are correct the operator ReadFunct1D returns the value TRUE. Otherwise an exception han-
dling is raised.
Parallelization Information
ReadFunct1D is reentrant and processed without parallelization.
See also
WriteFunct1D, GnuplotPlotCtrl, WriteImage, WriteRegion, OpenFile
Alternatives
FreadString, ReadTuple
Module
Foundation

[out] HFunction1dX SampledFunction HFunction1dX.SampleFunct1D


([in] VARIANT XMin, [in] VARIANT XMax, [in] VARIANT XDist,
[in] String Border )
void HOperatorSetX.SampleFunct1D ([in] VARIANT Function,
[in] VARIANT XMin, [in] VARIANT XMax, [in] VARIANT XDist, [in] VARIANT Border,
[out] VARIANT SampledFunction )

Sample a function equidistantly in an interval.


SampleFunct1D samples the input function Function in the interval [XMin,XMax] at equidistant points with
the distance XDist. The last point lies in the interval if XMax-XMin is not an integer multiple of XDist. To
obtain the samples, the input function is interpolated linearly. The parameter Border determines the values of the
function Function outside of its domain. For Border=’zero’ these values are set to 0, for Border=’constant’
they are set to the corresponding value at the border, for Border=’mirror’ they are mirrored at the border, and for
Border=’cyclic’ they are continued cyclically.
Parameter
. Function (input control) . . . . . . . . . . . . . . . . . . . . function_1d ; HFunction1dX / VARIANT ( real, integer )
Input function.
. XMin (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Minimum x value of the output function.
. XMax (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Maximum x value of the output function.
Restriction : (XM ax > XM in)
. XDist (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Distance of the samples.
Restriction : (XDist > 0)
. Border (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Border treatment for the input function.
Default Value : ’constant’
List of values : Border ∈ {’zero’, ’constant’, ’mirror’, ’cyclic’}

HALCON/COM Reference Manual, 2008-5-13


15.8. FUNCTION 1201

. SampledFunction (output control) . . . . . . . . . . function_1d ; HFunction1dX / VARIANT ( real, integer )


Sampled function.
Parallelization Information
SampleFunct1D is reentrant and processed without parallelization.
Possible Predecessors
TransformFunct1D, CreateFunct1DArray, CreateFunct1DPairs
Module
Foundation

[out] HFunction1dX FunctionScaled HFunction1dX.ScaleYFunct1D


([in] double Mult, [in] double Add )
void HOperatorSetX.ScaleYFunct1D ([in] VARIANT Function,
[in] VARIANT Mult, [in] VARIANT Add, [out] VARIANT FunctionScaled )

Multiplication and addition of the y values.


ScaleYFunct1D multiplies and adds the y values of Function with the parameters Mult and Add.
Parameter

. Function (input control) . . . . . . . . . . . . . . . . . . . . function_1d ; HFunction1dX / VARIANT ( real, integer )


Input function.
. Mult (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Factor for scaling of the y values.
Default Value : 2
Suggested values : Mult ∈ {0.1, 0.3, 0.5, 1, 2, 5, 10}
. Add (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Constant which is added to the y values.
Default Value : 0
Suggested values : Add ∈ {-10, -5, 1, 0, 5, 10}
. FunctionScaled (output control) . . . . . . . . . . . function_1d ; HFunction1dX / VARIANT ( real, integer )
Transformed function.
Parallelization Information
ScaleYFunct1D is reentrant and processed without parallelization.
Possible Predecessors
CreateFunct1DPairs, CreateFunct1DArray
Module
Foundation

[out] HFunction1dX SmoothedFunction HFunction1dX.SmoothFunct1DGauss


([in] double Sigma )
void HOperatorSetX.SmoothFunct1DGauss ([in] VARIANT Function,
[in] VARIANT Sigma, [out] VARIANT SmoothedFunction )

Smooth an equidistant 1D function with a Gaussian function.


The operator SmoothFunct1DGauss smooths a one-dimensional function with a Gaussian function. The
function must be equidistant, i.e., created with CreateFunct1DArray, SampleFunct1D or similar.
Parameter

. Function (input control) . . . . . . . . . . . . . . . . . . . . function_1d ; HFunction1dX / VARIANT ( real, integer )


Function to be smoothed.

HALCON 8.0.2
1202 CHAPTER 15. TOOLS

. Sigma (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT


Sigma of the Gaussian function for the smoothing.
Default Value : 2.0
Suggested values : Sigma ∈ {0.5, 1.0, 2.0, 3.0, 4.0, 5.0}
Typical range of values : 0.1 ≤ Sigma ≤ 0.1(lin)
Minimum Increment : 0.01
Recommended Increment : 0.2
. SmoothedFunction (output control) . . . . . . . . function_1d ; HFunction1dX / VARIANT ( real, integer )
Smoothed function.
Parallelization Information
SmoothFunct1DGauss is reentrant and processed without parallelization.
Possible Predecessors
CreateFunct1DPairs, CreateFunct1DArray
Possible Successors
MatchFunct1DTrans, DistanceFunct1D
Module
Foundation

[out] HFunction1dX SmoothedFunction HFunction1dX.SmoothFunct1DMean


([in] long SmoothSize, [in] long Iterations )
void HOperatorSetX.SmoothFunct1DMean ([in] VARIANT Function,
[in] VARIANT SmoothSize, [in] VARIANT Iterations,
[out] VARIANT SmoothedFunction )

Smooth an equidistant 1D function by averaging its values.


The operator SmoothFunct1DMean smooths a one dimensional function by applying an average (mean)
filter multiple times. The function must be equidistant, i.e., created with CreateFunct1DArray,
SampleFunct1D or similar.
Parameter

. Function (input control) . . . . . . . . . . . . . . . . . . . . function_1d ; HFunction1dX / VARIANT ( real, integer )


1D function.
. SmoothSize (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Size of the averaging mask.
Default Value : 10
Suggested values : SmoothSize ∈ {1, 3, 5, 7, 9, 11, 13, 15, 21, 31, 51}
Typical range of values : 1 ≤ SmoothSize ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 1
Restriction : (SmoothSize > 0)
. Iterations (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of iterations for the smoothing.
Default Value : 3
Suggested values : Iterations ∈ {1, 2, 3, 4, 5, 6, 7, 8, 9}
Typical range of values : 1 ≤ Iterations ≤ 1(lin)
Minimum Increment : 1
Recommended Increment : 1
Restriction : (Iterations ≥ 1)
. SmoothedFunction (output control) . . . . . . . . function_1d ; HFunction1dX / VARIANT ( real, integer )
Smoothed function.
Parallelization Information
SmoothFunct1DMean is reentrant and processed without parallelization.
Possible Predecessors
CreateFunct1DArray

HALCON/COM Reference Manual, 2008-5-13


15.8. FUNCTION 1203

Alternatives
SmoothFunct1DGauss
Module
Foundation

[out] HFunction1dX TransformedFunction HFunction1dX.TransformFunct1D


([in] VARIANT Params )
void HOperatorSetX.TransformFunct1D ([in] VARIANT Function,
[in] VARIANT Params, [out] VARIANT TransformedFunction )

Transform a function using given transformation parameters.


TransformFunct1D transforms the input function Function using the transformation parameters
given in Params. The function Function is passed as a tuple (see CreateFunct1DArray und
CreateFunct1DPairs). The following model is used for the transformation between the two functions (see
MatchFunct1DTrans):

yt (x) = a1 y(a3 x + a4 ) + a2 .

The output function TransformedFunction is obtained by transforming the x and y values of the input func-
tion separately with the above formula, i.e., the output function is not sampled again. Therefore, the parameter a3
is restricted to a3 6= 0.0 . To resample a function, the operator SampleFunct1D can be used.
Parameter

. Function (input control) . . . . . . . . . . . . . . . . . . . . function_1d ; HFunction1dX / VARIANT ( real, integer )


Input function.
. Params (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real )
Transformation parameters between the functions.
Number of elements : 4
. TransformedFunction (output control) . . . . function_1d ; HFunction1dX / VARIANT ( real, integer )
Transformed function.
Parallelization Information
TransformFunct1D is reentrant and processed without parallelization.
Possible Predecessors
CreateFunct1DPairs, CreateFunct1DArray, MatchFunct1DTrans
Module
Foundation

void HFunction1dX.WriteFunct1D ([in] String FileName )


void HOperatorSetX.WriteFunct1D ([in] VARIANT Function,
[in] VARIANT FileName )

Write a function to a file.


The operator WriteFunct1D writes the contents of Function to a file. The data is written in an ASCII
format. Therefore, the file can be exchanged between different architectures. The data can be read by the operator
ReadFunct1D. There is no specific extension for this kind of file.
Parameter

. Function (input control) . . . . . . . . . . . . . . . . . . . . function_1d ; HFunction1dX / VARIANT ( real, integer )


Function to be written.
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.write ; String / VARIANT
Name of the file to be written.

HALCON 8.0.2
1204 CHAPTER 15. TOOLS

Result
If the parameters are correct the operator WriteFunct1D returns the value TRUE. Otherwise an exception
handling is raised.
Parallelization Information
WriteFunct1D is reentrant and processed without parallelization.
Possible Predecessors
CreateFunct1DPairs, CreateFunct1DArray
See also
ReadFunct1D, WriteImage, WriteRegion, OpenFile
Alternatives
WriteTuple, FwriteString
Module
Foundation

HFunction1dX.XRangeFunct1D ([out] double XMax )


[out] double XMin
void HOperatorSetX.XRangeFunct1D ([in] VARIANT Function,
[out] VARIANT XMin, [out] VARIANT XMax )

Smallest and largest x value of the function.


XRangeFunct1D calculates the smallest and the largest x value of Function.
Parameter
. Function (input control) . . . . . . . . . . . . . . . . . . . . function_1d ; HFunction1dX / VARIANT ( real, integer )
Input function.
. XMin (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Smallest x value.
. XMax (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Largest x value.
Parallelization Information
XRangeFunct1D is reentrant and processed without parallelization.
Possible Predecessors
CreateFunct1DPairs, CreateFunct1DArray
Module
Foundation

HFunction1dX.YRangeFunct1D ([out] double YMax )


[out] double YMin
void HOperatorSetX.YRangeFunct1D ([in] VARIANT Function,
[out] VARIANT YMin, [out] VARIANT YMax )

Smallest and largest y value of the function.


YRangeFunct1D calculates the smallest and the largest y value of Function.
Parameter
. Function (input control) . . . . . . . . . . . . . . . . . . . . function_1d ; HFunction1dX / VARIANT ( real, integer )
Input function.
. YMin (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Smallest y value.
. YMax (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Largest y value.
Parallelization Information
YRangeFunct1D is reentrant and processed without parallelization.

HALCON/COM Reference Manual, 2008-5-13


15.9. GEOMETRY 1205

Possible Predecessors
CreateFunct1DPairs, CreateFunct1DArray
Module
Foundation

HFunction1dX.ZeroCrossingsFunct1D ( )
[out] VARIANT ZeroCrossings
void HOperatorSetX.ZeroCrossingsFunct1D ([in] VARIANT Function,
[out] VARIANT ZeroCrossings )

Calculate the zero crossings of a function.


ZeroCrossingsFunct1D calculates the zero crossings ZeroCrossings of the function Function. A
linear interpolation is applied to the function between its sampling points so that the coordinates of the zero crossing
can be calculated exactly. If an entire line segment between two sampling points has a value of 0, only the end
points of its supporting interval are returned.
Parameter

. Function (input control) . . . . . . . . . . . . . . . . . . . . function_1d ; HFunction1dX / VARIANT ( real, integer )


Input function
. ZeroCrossings (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Zero crossings of the input function
Parallelization Information
ZeroCrossingsFunct1D is reentrant and processed without parallelization.
Possible Predecessors
CreateFunct1DPairs, CreateFunct1DArray, SmoothFunct1DGauss, SmoothFunct1DMean
Module
Foundation

15.9 Geometry

[out] VARIANT Angle HMiscX.AngleLl ([in] VARIANT RowA1,


[in] VARIANT ColumnA1, [in] VARIANT RowA2, [in] VARIANT ColumnA2,
[in] VARIANT RowB1, [in] VARIANT ColumnB1, [in] VARIANT RowB2,
[in] VARIANT ColumnB2 )
void HOperatorSetX.AngleLl ([in] VARIANT RowA1, [in] VARIANT ColumnA1,
[in] VARIANT RowA2, [in] VARIANT ColumnA2, [in] VARIANT RowB1,
[in] VARIANT ColumnB1, [in] VARIANT RowB2, [in] VARIANT ColumnB2,
[out] VARIANT Angle )

Calculate the angle between two lines.


The operator AngleLl calculates the angle between two lines. As input the coordinates of to points on the first
line (RowA1,ColumnA1, RowA2,ColumnA2) and on the second line (RowB1,ColumnB1, RowB2,ColumnB2)
are expected. The calculation is performed as follows: We interpret the lines as vectors with starting points
RowA1,ColumnA1 and RowB1,ColumnB1 and end points RowA2,ColumnA2 and RowB2,ColumnB2, respec-
tively. Rotating the vector A counter clockwise onto the vector B (the center of rotation is the intersection point
of the two lines) yields the angle. The result depends on the order of the points and on the order of the lines. The
parameter Angle returns the angle in radians, ranging from −π ≤ Angle ≤ π.
Parameter

. RowA1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( real, integer )


Row coordinate of the first point of the first line.
. ColumnA1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( real, integer )
Column coordinate of the first point of the first line.

HALCON 8.0.2
1206 CHAPTER 15. TOOLS

. RowA2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( real, integer )


Row coordinate of the second point of the first line.
. ColumnA2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( real, integer )
Column coordinate of the second point of the first line.
. RowB1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( real, integer )
Row coordinate of the first point of the second line.
. ColumnB1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( real, integer )
Column coordinate of the first point of the second line.
. RowB2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( real, integer )
Row coordinate of the second point of the second line.
. ColumnB2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( real, integer )
Column coordinate of the second point of the second line.
. Angle (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT
Angle between the lines [rad].
Example

RowA1 := 255
ColumnA1 := 10
RowA2 := 255
ColumnA2 := 501
disp_line (WindowHandle, RowA1, ColumnA1, RowA2, ColumnA2)
RowB1 := 255
ColumnB1 := 255
for i := 1 to 360 by 1
RowB2 := 255 + sin(rad(i)) * 200
ColumnB2 := 255 + cos(rad(i)) * 200
disp_line (WindowHandle, RowB1, ColumnB1, RowB2, ColumnB2)
angle_ll (RowA1, ColumnA1, RowA2, ColumnA2,
RowB1, ColumnB1, RowB2, ColumnB2, Angle)
endfor

Result
AngleLl returns TRUE.
Parallelization Information
AngleLl is reentrant and processed without parallelization.
Alternatives
AngleLx
Module
Foundation

[out] VARIANT Angle HMiscX.AngleLx ([in] VARIANT Row1,


[in] VARIANT Column1, [in] VARIANT Row2, [in] VARIANT Column2 )
void HOperatorSetX.AngleLx ([in] VARIANT Row1, [in] VARIANT Column1,
[in] VARIANT Row2, [in] VARIANT Column2, [out] VARIANT Angle )

Calculate the angle between one line and the vertical axis.
The operator AngleLx calculates the angle between one line and the abscissa. As input the coordinates of two
points on the line (Row1,Column1, Row2,Column2) are expected. The calculation is performed as follows: We
interprete the line as a vector with starting point Row1,Column1 and end point Row2,Column2. Rotating the
vector counter clockwise onto the abscissa (center of rotation is the intersection point of the abscissa) yields the
angle. The result depends of the order of the points on line. The parameter Angle returns the angle in radians,
ranging from −π ≤ Angle ≤ π.

HALCON/COM Reference Manual, 2008-5-13


15.9. GEOMETRY 1207

Parameter
. Row1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( real, integer )
Row coordinate the first point of the line.
. Column1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( real, integer )
Column coordinate of the first point of the line.
. Row2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( real, integer )
Row coordinate of the second point of the line.
. Column2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( real, integer )
Column coordinate of the second point of the line.
. Angle (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT
Angle between the line and the abscissa [rad].
Example

RowX1 := 255
ColumnX1 := 10
RowX2 := 255
ColumnX2 := 501
disp_line (WindowHandle, RowX1, ColumnX1, RowX2, ColumnX2)
Row1 := 255
Column1 := 255
for i := 1 to 360 by 1
Row2 := 255 + sin(rad(i)) * 200
Column2 := 255 + cos(rad(i)) * 200
disp_line (WindowHandle, Row1, Column1, Row2, Column2)
angle_lx (Row1, Column1, Row2, Column2, Angle)
endfor

Result
AngleLx returns TRUE.
Parallelization Information
AngleLx is reentrant and processed without parallelization.
Alternatives
AngleLl
Module
Foundation

[out] VARIANT DistanceMin HXLDContX.DistanceCc ([in] HXLDContX Contour2,


[in] String Mode, [out] VARIANT DistanceMax )
void HOperatorSetX.DistanceCc ([in] IHObjectX Contour1,
[in] IHObjectX Contour2, [in] VARIANT Mode, [out] VARIANT DistanceMin,
[out] VARIANT DistanceMax )

Calculate the distance between two contours.


The operator DistanceCc calculates the minimum and maximum distance between the base points of two con-
tours ( Contour1 and Contour2). The parameters DistanceMin and DistanceMax contain the resulting
distance.
The parameter Mode sets the type of computing the distance: ’point_to_point’ only determines the minimum
and maximum distance between the base points of the contours. This results in faster algorithm but may lead to
inaccurate minimum distances. In contrast, ’point_to_segment’ determines the actual minimum distance of the
contour segments.
In both cases, the search algorithm has a quadratic complexitity (n*n). If only the minimum distance is required,
the operator DistanceCcMin can be used alternatively since it offers algorithms with a complexity of n*log(n).

HALCON 8.0.2
1208 CHAPTER 15. TOOLS

Parameter

. Contour1 (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xld_cont(-array) ; HXLDContX / IHObjectX


First input contour.
. Contour2 (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xld_cont(-array) ; HXLDContX / IHObjectX
Second input contour.
. Mode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Distance calculation mode.
Default Value : ’point_to_point’
List of values : Mode ∈ {’point_to_point’, ’point_to_segment’}
. DistanceMin (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT
Minimum distance between both contours.
. DistanceMax (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT
Maximum distance between both contours.
Result
DistanceCc returns TRUE.
Parallelization Information
DistanceCc is reentrant and processed without parallelization.
See also
DistanceSr, DistancePr
Alternatives
DistanceSc, DistancePc, DistanceCcMin
Module
Foundation

[out] VARIANT DistanceMin HXLDContX.DistanceCcMin


([in] HXLDContX Contour2, [in] String Mode )
void HOperatorSetX.DistanceCcMin ([in] IHObjectX Contour1,
[in] IHObjectX Contour2, [in] VARIANT Mode, [out] VARIANT DistanceMin )

Calculate the minimum distance between two contours.


DistanceCcMin calculates the minimum distance between two contours Contour1 and Contour2. The
minimum distance is returned in DistanceMin.
The parameter Mode sets the type of computing the distance. ’point_to_point’ determines the distance of the
closest contour points, ’fast_point_to_segment’ calculates the distance of the line segments adjacent to these points,
and ’point_to_segment’ determines the actual minimum distance of the contour segments.
While ’point_to_point’ and ’fast_point_to_segment’ are efficient algorithms with a complexity of n*log(n),
’point_to_segment’ has quadratic complexity and thus takes a longer time to execute, especially for contours with
many line segments.
Parameter

. Contour1 (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xld_cont(-array) ; HXLDContX / IHObjectX


First input contour.
. Contour2 (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xld_cont(-array) ; HXLDContX / IHObjectX
Second input contour.
. Mode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Distance calculation mode.
Default Value : ’fast_point_to_segment’
List of values : Mode ∈ {’point_to_point’, ’point_to_segment’, ’fast_point_to_segment’}
. DistanceMin (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT
Minimum distance between the two contours.
Result
DistanceCcMin returns TRUE.

HALCON/COM Reference Manual, 2008-5-13


15.9. GEOMETRY 1209

Parallelization Information
DistanceCcMin is reentrant and processed without parallelization.
See also
DistanceSr, DistancePr
Alternatives
DistanceSc, DistancePc, DistanceCc
Module
Foundation

[out] VARIANT DistanceMin HXLDContX.DistanceLc ([in] VARIANT Row1,


[in] VARIANT Column1, [in] VARIANT Row2, [in] VARIANT Column2,
[out] VARIANT DistanceMax )
void HOperatorSetX.DistanceLc ([in] IHObjectX Contour,
[in] VARIANT Row1, [in] VARIANT Column1, [in] VARIANT Row2,
[in] VARIANT Column2, [out] VARIANT DistanceMin, [out] VARIANT DistanceMax )

Calculate the distance between a line and one contour.


The operator DistanceLc calculates the orthogonal distance between a line and the segments of one contour.
As input the coordinates of two points on a line (Row1,Column1, Row2,Column2) and one contour (Contour)
are expected. The parameters DistanceMin and DistanceMax return the result of the calculation.
Parameter

. Contour (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xld_cont ; HXLDContX / IHObjectX


Input contour.
. Row1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( real, integer )
Row coordinate of the first point of the line.
. Column1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( real, integer )
Column coordinate of the first point of the line.
. Row2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( real, integer )
Row coordinate of the second point of the line.
. Column2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( real, integer )
Column coordinate of the second point of the line.
. DistanceMin (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT
Minimum distance between the line and the contour.
. DistanceMax (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT
Maximum distance between the line and the contour.
Result
DistanceLc returns TRUE.
Parallelization Information
DistanceLc is reentrant and processed without parallelization.
See also
DistanceLr, DistancePr, DistanceSr
Alternatives
DistancePc, DistanceSc, DistanceCc, DistanceCcMin
Module
Foundation

HALCON 8.0.2
1210 CHAPTER 15. TOOLS

[out] VARIANT DistanceMin HRegionX.DistanceLr ([in] VARIANT Row1,


[in] VARIANT Column1, [in] VARIANT Row2, [in] VARIANT Column2,
[out] VARIANT DistanceMax )
void HOperatorSetX.DistanceLr ([in] IHObjectX Region,
[in] VARIANT Row1, [in] VARIANT Column1, [in] VARIANT Row2,
[in] VARIANT Column2, [out] VARIANT DistanceMin, [out] VARIANT DistanceMax )

Calculate the distance between a line and a region.


The operator DistanceLr calculates the orthogonal distance between a line and one region. As input the coor-
dinates of two points on a line (Row1,Column1, Row2,Column2) and one region are expected. The parameters
DistanceMin and DistanceMax return the result of the calculation.
Attention
Due to efficiency of DistanceLr holes are ignored.
Parameter

. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX


Input region.
. Row1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( real, integer )
Row coordinate of the first point of the line.
. Column1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( real, integer )
Column coordinate of the first point of the line.
. Row2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( real, integer )
Row coordinate of the second point of the line.
. Column2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( real, integer )
Column coordinate of the second point of the line.
. DistanceMin (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT
Minimum distance between the line and the region
. DistanceMax (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT
Maximum distance between the line and the region
Example

dev_close_window ()
read_image (Image, ’fabrik’)
dev_open_window (0, 0, 512, 512, ’white’, WindowHandle)
threshold (Image, Region, 180, 255)
connection (Region, ConnectedRegions)
select_shape (ConnectedRegions, SelectedRegions, ’area’, ’and’,
5000, 100000000)
dev_clear_window ()
dev_set_color (’black’)
dev_display (SelectedRegions)
dev_set_color (’red’)
Row1 := 100
Row2 := 400
for Col := 50 to 400 by 4
disp_line (WindowHandle, Row1, Col+100, Row2, Col)
distance_lr (SelectedRegions, Row1, Col+100, Row2, Col,
DistanceMin, DistanceMax)
endfor

Result
DistanceLr returns TRUE.
Parallelization Information
DistanceLr is reentrant and processed without parallelization.

HALCON/COM Reference Manual, 2008-5-13


15.9. GEOMETRY 1211

See also
HammingDistance, SelectRegionPoint, TestRegionPoint, SmallestRectangle2
Alternatives
DistanceLc, DistancePr, DistanceSr, DiameterRegion
Module
Foundation

[out] VARIANT DistanceMin HXLDContX.DistancePc ([in] VARIANT Row,


[in] VARIANT Column, [out] VARIANT DistanceMax )
void HOperatorSetX.DistancePc ([in] IHObjectX Contour,
[in] VARIANT Row, [in] VARIANT Column, [out] VARIANT DistanceMin,
[out] VARIANT DistanceMax )

Calculate the distance between a point and one contour.


The operator DistancePc calculates the distance between points and one contour. As input the coordinates
of the points (Row,Column) and one contour (Contour) are expected. The parameters DistanceMin and
DistanceMax return the result of the calculation.
Parameter
. Contour (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xld_cont ; HXLDContX / IHObjectX
Input contour.
. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( real, integer )
Row coordinate of the point.
. Column (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( real, integer )
Column coordinate of the point.
. DistanceMin (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT
Minimum distance between the point and the contour.
. DistanceMax (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT
Maximum distance between the point and the contour.
Result
DistancePc returns TRUE.
Parallelization Information
DistancePc is reentrant and processed without parallelization.
See also
DistancePr, DistanceLr, DistanceSr, HammingDistance, SelectXldPoint, TestXldPoint
Alternatives
DistanceLc, DistanceSc, DistanceCc, DistanceCcMin
Module
Foundation

[out] VARIANT Distance HMiscX.DistancePl ([in] VARIANT Row,


[in] VARIANT Column, [in] VARIANT Row1, [in] VARIANT Column1,
[in] VARIANT Row2, [in] VARIANT Column2 )
void HOperatorSetX.DistancePl ([in] VARIANT Row, [in] VARIANT Column,
[in] VARIANT Row1, [in] VARIANT Column1, [in] VARIANT Row2,
[in] VARIANT Column2, [out] VARIANT Distance )

Calculate the distance between one point and one line.


The operator DistancePl calculates the orthogonal distance between points (Row,Column) and lines, given
by two arbitrary points on the line. The result is passed in Distance.
DistancePl calculates the distances between a set of n points and one line as well as the distances between a
set of n points and n lines.

HALCON 8.0.2
1212 CHAPTER 15. TOOLS

Parameter

. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( real, integer )


Row coordinate of the point.
. Column (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( real, integer )
Column of the point.
. Row1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( real, integer )
Row coordinate of the first point of the line.
. Column1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( real, integer )
Column coordinate of the first point of the line.
. Row2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( real, integer )
Row coordinate of the second point of the line.
. Column2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( real, integer )
Column coordinate of the second point of the line.
. Distance (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT
Distance between the points.
Example

read_image (Image, ’mreut’)


dev_open_window (0, 0, 512, 512, ’white’, WindowHandle)
dev_display (Image)
dev_set_color (’black’)
threshold (Image, Region, 180, 255)
dev_clear_window ()
dev_display (Region)
connection (Region, ConnectedRegions)
select_shape (ConnectedRegions, SelectedRegions, ’area’, ’and’,
10000, 100000000)
get_region_contour (SelectedRegions, Rows, Columns)
RowLine1 := 5
ColLine1 := 300
RowLine2 := 300
ColLine2 := 400
NumberTuple := |Rows|
dev_set_color (’red’)
disp_line (WindowHandle, RowLine1, ColLine1, RowLine2, ColLine2)
dev_set_color (’green’)
for i := 1 to NumberTuple by 5
disp_line (WindowHandle, Rows[i], Columns[i]-2, Rows[i], Columns[i]+2)
disp_line (WindowHandle, Rows[i]-2, Columns[i], Rows[i]+2, Columns[i])
distance_pl (Rows[i], Columns[i], RowLine1, ColLine1,
RowLine2, ColLine2, Distance)
endfor

Result
DistancePl returns TRUE.
Parallelization Information
DistancePl is reentrant and processed without parallelization.
See also
DistancePp, DistancePr
Alternatives
DistancePs
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


15.9. GEOMETRY 1213

[out] VARIANT Distance HMiscX.DistancePp ([in] VARIANT Row1,


[in] VARIANT Column1, [in] VARIANT Row2, [in] VARIANT Column2 )
void HOperatorSetX.DistancePp ([in] VARIANT Row1, [in] VARIANT Column1,
[in] VARIANT Row2, [in] VARIANT Column2, [out] VARIANT Distance )

Calculate the distance between two points.


The operator DistancePp calculates the distance between pairs of points according to the following formula:
p
Distance = ((Row1 − Row2)2 + (Column1 − Column2)2 )

The result is returned in Distance.


Parameter
. Row1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( real, integer )
Row coordinate of the first point.
. Column1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( real, integer )
Column coordinate of the first point.
. Row2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( real, integer )
Row coordinate of the second point.
. Column2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( real, integer )
Column coordinate of the second point.
. Distance (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT
Distance between the points.
Example

dev_close_window ()
read_image (Image, ’mreut’)
dev_open_window (0, 0, 512, 512, ’white’, WindowHandle)
dev_display (Image)
dev_set_color (’black’)
threshold (Image, Region, 180, 255)
dev_clear_window ()
dev_display (Region)
connection (Region, ConnectedRegions)
select_shape (ConnectedRegions, SelectedRegions, ’area’, ’and’, 10000, 100000000)
get_region_contour (SelectedRegions, Rows, Columns)
RowPoint := 80
ColPoint := 250
NumberTuple := |Rows|
dev_set_color (’red’)
set_draw (WindowHandle, ’margin’)
disp_circle (WindowHandle, RowPoint, ColPoint, 10)
dev_set_color (’green’)
for i := 1 to NumberTuple by 10
disp_line (WindowHandle, Rows[i], Columns[i]-2, Rows[i], Columns[i]+2)
disp_line (WindowHandle, Rows[i]-2, Columns[i], Rows[i]+2, Columns[i])
distance_pp (RowPoint, ColPoint, Rows[i], Columns[i], Distance)
endfor

Result
DistancePp returns TRUE.
Parallelization Information
DistancePp is reentrant and processed without parallelization.
See also
DistancePl, DistancePr

HALCON 8.0.2
1214 CHAPTER 15. TOOLS

Alternatives
DistancePs
Module
Foundation

[out] VARIANT DistanceMin HRegionX.DistancePr ([in] VARIANT Row,


[in] VARIANT Column, [out] VARIANT DistanceMax )
void HOperatorSetX.DistancePr ([in] IHObjectX Region, [in] VARIANT Row,
[in] VARIANT Column, [out] VARIANT DistanceMin, [out] VARIANT DistanceMax )

Calculate the distance between a point and a region.


The operator DistancePr calculates the distance between a point and one region. As input the coordinates of
the points (Row,Column) and one region are expected. If a point is inside of the region, its minimum distance is
zero. The parameters DistanceMin and DistanceMax return the result of the calculation.
Parameter

. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX


Input region.
. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( real, integer )
Row coordinate of the point.
. Column (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( real, integer )
Column coordinate of the point.
. DistanceMin (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT
Minimum distance between the point and the region.
. DistanceMax (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT
Maximum distance between the point and the region.
Example

dev_close_window ()
read_image (Image, ’mreut’)
dev_open_window (0, 0, 512, 512, ’white’, WindowHandle)
dev_set_color (’black’)
threshold (Image, Region, 180, 255)
connection (Region, ConnectedRegions)
select_shape (ConnectedRegions, SelectedRegions, ’area’, ’and’,
10000, 100000000)
Row1 := 255
Column1 := 255
dev_clear_window ()
dev_display (SelectedRegions)
dev_set_color (’red’)
for i := 1 to 360 by 1
Row2 := 255 + sin(rad(i)) * 200
Column2 := 255 + cos(rad(i)) * 200
disp_line (WindowHandle, Row1, Column1, Row2, Column2)
distance_pr (SelectedRegions, Row2, Column2,
DistanceMin, DistanceMax)
endfor

Result
DistancePr returns TRUE.
Parallelization Information
DistancePr is reentrant and processed without parallelization.

HALCON/COM Reference Manual, 2008-5-13


15.9. GEOMETRY 1215

See also
HammingDistance, SelectRegionPoint, TestRegionPoint, SmallestRectangle2
Alternatives
DistancePc, DistanceLr, DistanceSr, DiameterRegion
Module
Foundation

[out] VARIANT DistanceMin HMiscX.DistancePs ([in] VARIANT Row,


[in] VARIANT Column, [in] VARIANT Row1, [in] VARIANT Column1,
[in] VARIANT Row2, [in] VARIANT Column2, [out] VARIANT DistanceMax )
void HOperatorSetX.DistancePs ([in] VARIANT Row, [in] VARIANT Column,
[in] VARIANT Row1, [in] VARIANT Column1, [in] VARIANT Row2,
[in] VARIANT Column2, [out] VARIANT DistanceMin, [out] VARIANT DistanceMax )

Calculate the distances between a point and a line segment.


The operator DistancePs calculates the minimum and maximum distance between a point (Row,Column) and
a line segment which is represented by the start point (Row1,Column1) and the end point (Row2,Column2).
DistanceMax is the maximum distance between the point and the end points of the line segment.
DistanceMin is identical to DistancePl in the case that the point is “between” the two endpoints. Oth-
erwise, the minimum distance to one of the end points is used.
Parameter

. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( real, integer )


Row coordinate of the first point.
. Column (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( real, integer )
Column coordinate of the first point.
. Row1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( real, integer )
Row coordinate of the first point of the line segment.
. Column1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( real, integer )
Column coordinate of the first point of the line segment.
. Row2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( real, integer )
Row coordinate of the second point of the line segment.
. Column2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( real, integer )
Column coordinate of the second point of the line segment.
. DistanceMin (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT
Minimum distance between the point and the line segment.
. DistanceMax (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT
Maximum distance between the point and the line segment.
Example

read_image (Image, ’mreut’)


dev_open_window (0, 0, 512, 512, ’white’, WindowHandle)
dev_display (Image)
dev_set_color (’black’)
threshold (Image, Region, 180, 255)
dev_clear_window ()
dev_display (Region)
connection (Region, ConnectedRegions)
select_shape (ConnectedRegions, SelectedRegions, ’area’, ’and’,
10000, 100000000)
get_region_contour (SelectedRegions, Rows, Columns)
RowLine1 := 400
ColLine1 := 50
RowLine2 := 50

HALCON 8.0.2
1216 CHAPTER 15. TOOLS

ColLine2 := 450
NumberTuple := |Rows|
dev_set_color (’red’)
disp_line (WindowHandle, RowLine1, ColLine1, RowLine2, ColLine2)
dev_set_color (’green’)
for i := 1 to NumberTuple by 10
disp_line (WindowHandle, Rows[i], Columns[i]-2, Rows[i], Columns[i]+2)
disp_line (WindowHandle, Rows[i]-2, Columns[i], Rows[i]+2, Columns[i])
distance_ps (Rows[i], Columns[i], RowLine1, ColLine1, RowLine2, ColLine2,
DistanceMin, DistanceMax)
endfor

Result
DistancePs returns TRUE.
Parallelization Information
DistancePs is reentrant and processed without parallelization.
See also
DistancePp, DistancePr
Alternatives
DistancePl
Module
Foundation

[out] VARIANT MinDistance HRegionX.DistanceRrMin


([in] HRegionX Regions2, [out] VARIANT Row1, [out] VARIANT Column1,
[out] VARIANT Row2, [out] VARIANT Column2 )
void HOperatorSetX.DistanceRrMin ([in] IHObjectX Regions1,
[in] IHObjectX Regions2, [out] VARIANT MinDistance, [out] VARIANT Row1,
[out] VARIANT Column1, [out] VARIANT Row2, [out] VARIANT Column2 )

Minimum distance between the contour pixels of two regions each.


The operator DistanceRrMin calculates the minimum distance of pairs of regions. If several regions are passed
in Regions1 and Regions2 the distance between the contour pixels of each i-th element is calculated and then
forms the i-th entry in the output parameter MinDistance. The Euclidean distance is used. The parameters
(Row1, Column1) and (Row2, Column2) indicate the position on the contour of Regions1 and Regions2,
respectively, that have the minimum distance.
The calculation is carried out by comparing all contour pixels (see GetRegionContour). This means in
particular that each region must consist of exactly one connected component and that holes in the regions are
ignored. Furthermore, it is not checked whether one region lies completely within the other region. In this case, a
minimum distance > 0 is returned. It is also not checked whether both regions contain a nonempty intersection. In
the latter case, a minimum distance of 0 or > 0 can be returned, depending on whether the contours of the regions
contain a common point or not.
Attention
Both input parameters must contain the same number of regions. The regions must not be empty.
Parameter

. Regions1 (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX


Regions to be examined.
. Regions2 (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Regions to be examined.
. MinDistance (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Minimum distance between contours of the regions.
Restriction : (0 ≤ M inDistance)

HALCON/COM Reference Manual, 2008-5-13


15.9. GEOMETRY 1217

. Row1 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( integer )


Line index on contour in Regions1.
. Column1 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( integer )
Column index on contour in Regions1.
. Row2 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( integer )
Line index on contour in Regions2.
. Column2 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( integer )
Column index on contour in Regions2.
Complexity
If N 1,N 2 are the lengths of the contours the runtime complexity is O(N 1 ∗ N 2).
Result
The operator DistanceRrMin returns the value TRUE if the input is not empty. Otherwise an exception
handling is raised.
Parallelization Information
DistanceRrMin is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Threshold, Regiongrowing, Connection
Alternatives
DistanceRrMinDil, Dilation1, Intersection
Module
Foundation

[out] VARIANT MinDistance HRegionX.DistanceRrMinDil


([in] HRegionX Regions2 )
void HOperatorSetX.DistanceRrMinDil ([in] IHObjectX Regions1,
[in] IHObjectX Regions2, [out] VARIANT MinDistance )

Minimum distance between two regions with the help of dilatation.


The operator DistanceRrMinDil calculates the minimum distance between pairs of regions. If several regions
are passed in Regions1 and Regions2 the distance between the i-th elements in each case is calculated. It then
forms the i-th entry in the output parameter MinDistance. The calculation is carried out with the help of
dilatation with the Golay element ’h’. The result is:

N umberiterations ∗ 2 − 1

.
The mask ’h’ has the effect that precisely the maximum metrics are calculated.
Attention
Both parameters must contain the same number of regions. The regions must not be empty.
Parameter
. Regions1 (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Regions to be examined.
. Regions2 (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / IHObjectX
Regions to be examined.
. MinDistance (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Minimum distances of the regions.
Restriction : (−1 ≤ M inDistance)
Result
The operator DistanceRrMinDil returns the value TRUE if the input is not empty. Otherwise an exception
handling is raised.
Parallelization Information
DistanceRrMinDil is reentrant and automatically parallelized (on tuple level).

HALCON 8.0.2
1218 CHAPTER 15. TOOLS

Possible Predecessors
Threshold, Regiongrowing, Connection
Alternatives
DistanceRrMin, Dilation1, Intersection
Module
Foundation

[out] VARIANT DistanceMin HXLDContX.DistanceSc ([in] VARIANT Row1,


[in] VARIANT Column1, [in] VARIANT Row2, [in] VARIANT Column2,
[out] VARIANT DistanceMax )
void HOperatorSetX.DistanceSc ([in] IHObjectX Contour,
[in] VARIANT Row1, [in] VARIANT Column1, [in] VARIANT Row2,
[in] VARIANT Column2, [out] VARIANT DistanceMin, [out] VARIANT DistanceMax )

Calculate the distance between a line segment and one contour.


The operator DistanceSc calculates the distance between a line segment and the line segments of one contour.
Row1, Column1, Row2, Column2 are the start and end coordinates of a line segment, Contour represents the
input contour. The parameters DistanceMin and DistanceMax contain the resulting distances.
Parameter

. Contour (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xld_cont ; HXLDContX / IHObjectX


Input contour.
. Row1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( real, integer )
Row coordinate of the first point of the line segment.
. Column1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( real, integer )
Column coordinate of the first point of the line segment.
. Row2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( real, integer )
Row coordinate of the second point of the line segment.
. Column2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( real, integer )
Column coordinate of the second point of the line segment.
. DistanceMin (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT
Minimum distance between the line segment and the contour.
. DistanceMax (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT
Maximum distance between the line segment and the contour.
Result
DistanceSr returns TRUE.
Parallelization Information
DistanceSc is reentrant and processed without parallelization.
See also
DistanceSr, DistanceLr, DistancePr, SelectXldPoint, TestXldPoint
Alternatives
DistanceLc, DistancePc, DistanceCc, DistanceCcMin
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


15.9. GEOMETRY 1219

[out] VARIANT DistanceMin HMiscX.DistanceSl ([in] VARIANT RowA1,


[in] VARIANT ColumnA1, [in] VARIANT RowA2, [in] VARIANT ColumnA2,
[in] VARIANT RowB1, [in] VARIANT ColumnB1, [in] VARIANT RowB2,
[in] VARIANT ColumnB2, [out] VARIANT DistanceMax )
void HOperatorSetX.DistanceSl ([in] VARIANT RowA1,
[in] VARIANT ColumnA1, [in] VARIANT RowA2, [in] VARIANT ColumnA2,
[in] VARIANT RowB1, [in] VARIANT ColumnB1, [in] VARIANT RowB2,
[in] VARIANT ColumnB2, [out] VARIANT DistanceMin, [out] VARIANT DistanceMax )

Calculate the distances between a line segment and a line.


The operator DistanceSl calculates the minimum and maximum orthogonal distance between a line segment
and a line. As input the coordinates of two points on the line segment (RowA1,ColumnA1,RowA2,ColumnA2)
and on the line (RowB1,ColumnB1,RowB2,ColumnB2) are expected. The parameters DistanceMin and
DistanceMax return the result of the calculation. If the line segments are intersecting, DistanceMin returns
zero.
Parameter
. RowA1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( real, integer )
Row coordinate of the first point of the line segment.
. ColumnA1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( real, integer )
Column coordinate of the first point of the line segment.
. RowA2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( real, integer )
Row coordinate of the second point of the line segment.
. ColumnA2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( real, integer )
Column coordinate of the second point of the line segment.
. RowB1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( real, integer )
Row coordinate of the first point of the line.
. ColumnB1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( real, integer )
Column coordinate of the first point of the line.
. RowB2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( real, integer )
Row coordinate of the second point of the line.
. ColumnB2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( real, integer )
Column coordinate of the second point of the line.
. DistanceMin (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT
Minimum distance between the line segment and the line.
. DistanceMax (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT
Maximum distance between the line segment and the line.
Example

dev_set_color (’black’)
RowLine1 := 400
ColLine1 := 200
RowLine2 := 200
ColLine2 := 400
Rows := 300
Columns := 50
disp_line (WindowHandle, RowLine1, ColLine1, RowLine2, ColLine2)
dev_set_color (’green’)
n := 0
for Rows := 40 to 200 by 4
disp_line (WindowHandle, Rows+n, Columns+n, Rows, Columns+n)
distance_sl (Rows+n, Columns+n, Rows, Columns+n, RowLine1, ColLine1,
RowLine2, ColLine2,DistanceMin, DistanceMax)
n := n+10
endfor

HALCON 8.0.2
1220 CHAPTER 15. TOOLS

Result
DistanceSl returns TRUE.
Parallelization Information
DistanceSl is reentrant and processed without parallelization.
See also
DistancePs, DistancePp
Alternatives
DistancePl
Module
Foundation

[out] VARIANT DistanceMin HRegionX.DistanceSr ([in] VARIANT Row1,


[in] VARIANT Column1, [in] VARIANT Row2, [in] VARIANT Column2,
[out] VARIANT DistanceMax )
void HOperatorSetX.DistanceSr ([in] IHObjectX Region,
[in] VARIANT Row1, [in] VARIANT Column1, [in] VARIANT Row2,
[in] VARIANT Column2, [out] VARIANT DistanceMin, [out] VARIANT DistanceMax )

Calculate the distance between a line segment and one region.


The operator DistanceSr calculates the distance between a line segment and one region. Row1, Column1,
Row2, Column2 are the start and end coordinates of a line segment. The parameters DistanceMin and
DistanceMax contain the resulting distances.
Attention
To enhance DistanceSr, holes are ignored.
Parameter
. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
Input region.
. Row1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( real, integer )
Row coordinate of the first point of the line segment.
. Column1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( real, integer )
Column coordinate of the first point of the line segment.
. Row2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( real, integer )
Row coordinate of the second point of the line segment.
. Column2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( real, integer )
Column coordinate of the second point of the line segment.
. DistanceMin (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT
Minimum distance between the line segment and the region.
. DistanceMax (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT
Maximum distance between the line segment and the region.
Example

read_image (Image, ’fabrik’)


dev_open_window (0, 0, 512, 512, ’white’, WindowHandle)
dev_display (Image)
threshold (Image, Region, 180, 255)
connection (Region, ConnectedRegions)
select_shape (ConnectedRegions, SelectedRegions, ’area’, ’and’,
5000, 100000000)
dev_clear_window ()
dev_set_color (’black’)
dev_display (SelectedRegions)
dev_set_color (’red’)
Row1 := 100

HALCON/COM Reference Manual, 2008-5-13


15.9. GEOMETRY 1221

Row2 := 400
n := 0
for Col := 50 to 400 by 5
disp_line (WindowHandle, Row1+n, Col, Row2-n, Col+100)
distance_sr (SelectedRegions, Row1+n, Col, Row2-n, Col+100,
DistanceMin, DistanceMax)
n := n+5
endfor

Result
DistanceSr returns TRUE.
Parallelization Information
DistanceSr is reentrant and processed without parallelization.
See also
HammingDistance, SelectRegionPoint, TestRegionPoint, SmallestRectangle2
Alternatives
DistanceSc, DistanceLr, DistancePr, DiameterRegion
Module
Foundation

[out] VARIANT DistanceMin HMiscX.DistanceSs ([in] VARIANT RowA1,


[in] VARIANT ColumnA1, [in] VARIANT RowA2, [in] VARIANT ColumnA2,
[in] VARIANT RowB1, [in] VARIANT ColumnB1, [in] VARIANT RowB2,
[in] VARIANT ColumnB2, [out] VARIANT DistanceMax )
void HOperatorSetX.DistanceSs ([in] VARIANT RowA1,
[in] VARIANT ColumnA1, [in] VARIANT RowA2, [in] VARIANT ColumnA2,
[in] VARIANT RowB1, [in] VARIANT ColumnB1, [in] VARIANT RowB2,
[in] VARIANT ColumnB2, [out] VARIANT DistanceMin, [out] VARIANT DistanceMax )

Calculate the distances between two line segments.


The operator DistanceSs calculates the minimum and maximum distance between two line segments. As input
the coordinates of the start and end point of the first line segment (RowA1,ColumnA1, RowA2,ColumnA2) and
of the second line segment (RowB1,ColumnB1,RowB2,ColumnB2) are used. The parameters DistanceMin
and DistanceMax return the result of the calculation. If the line segments are intersecting, DistanceMin
returns zero.
Parameter

. RowA1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( real, integer )


Row coordinate of the first point of the line segment.
. ColumnA1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( real, integer )
Column coordinate of the first point of the line segment.
. RowA2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( real, integer )
Row coordinate of the second point of the line segment.
. ColumnA2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( real, integer )
Column coordinate of the second point of the line segment.
. RowB1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( real, integer )
Row coordinate of the first point of the line.
. ColumnB1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( real, integer )
Column of the first point of the line.
. RowB2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( real, integer )
Row coordinate of the second point of the line.
. ColumnB2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( real, integer )
Column coordinate of the second point of the line.

HALCON 8.0.2
1222 CHAPTER 15. TOOLS

. DistanceMin (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT


Minimum distance between the line segments.
. DistanceMax (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT
Maximum distance between the line segments.
Example

dev_set_color (’black’)
RowLine1 := 400
ColLine1 := 200
RowLine2 := 240
ColLine2 := 400
Rows := 300
Columns := 50
disp_line (WindowHandle, RowLine1, ColLine1, RowLine2, ColLine2)
dev_set_color (’red’)
n := 0
for Rows := 40 to 200 by 4
disp_line (WindowHandle, Rows, Columns, Rows+n, Columns+n)
distance_ss (Rows, Columns, Rows+n, Columns+n, RowLine1, ColLine1,
RowLine2, ColLine2, DistanceMin, DistanceMax)
n := n+8
endfor

Result
DistanceSs returns TRUE.
Parallelization Information
DistanceSs is reentrant and processed without parallelization.
See also
DistancePl, DistancePs
Alternatives
DistancePp
Module
Foundation

[out] VARIANT RowPoint HMiscX.GetPointsEllipse ([in] VARIANT Angle,


[in] double Row, [in] double Column, [in] double Phi, [in] double Radius1,
[in] double Radius2, [out] VARIANT ColPoint )
void HOperatorSetX.GetPointsEllipse ([in] VARIANT Angle,
[in] VARIANT Row, [in] VARIANT Column, [in] VARIANT Phi, [in] VARIANT Radius1,
[in] VARIANT Radius2, [out] VARIANT RowPoint, [out] VARIANT ColPoint )

Calculate a point of an ellipse corresponding to a specific angle.


GetPointsEllipse returns the point (RowPoint,ColPoint) on the specified ellipse corresponding to the
angle in Angle, which refers to the main axis of the ellipse. The ellipse itself is characterized by the center (Row,
Column), the orientation of the main axis Phi relative to the horizontal axis, the length of the larger (Radius1)
and the smaller half axis (Radius2). The angles are measured counter clockwise in radiants.
Parameter
. Angle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Angle corresponding to the resulting point [rad].
Default Value : 0
Restriction : ((Angle ≥ 0) ∧ (Angle ≤ 6.283185307))
. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ellipse.center.y ; double / VARIANT
Row coordinate of the center of the ellipse.

HALCON/COM Reference Manual, 2008-5-13


15.9. GEOMETRY 1223

. Column (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ellipse.center.x ; double / VARIANT


Column coordinate of the center of the ellipse.
. Phi (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ellipse.angle.rad ; double / VARIANT
Orientation of the main axis [rad].
Restriction : ((P hi ≥ 0) ∧ (P hi ≤ 6.283185307))
. Radius1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ellipse.radius1 ; double / VARIANT
Length of the larger half axis.
Restriction : (Radius1 > 0)
. Radius2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ellipse.radius2 ; double / VARIANT
Length of the smaller half axis.
Restriction : (Radius2 ≥ 0)
. RowPoint (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( real )
Row coordinate of the point on the ellipse.
. ColPoint (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( real )
Column coordinates of the point on the ellipse.
Example

draw_ellipse(WindowHandle,Row,Column,Phi,Radius1,Radius2)
get_points_ellipse([0,3.14],Row,Column,Phi,Radius1,Radius2,RowPoint,ColPoint)

Result
GetPointsEllipse returns TRUE if all parameter values are correct. If necessary, an exception is raised.
Parallelization Information
GetPointsEllipse is reentrant and processed without parallelization.
Possible Predecessors
FitEllipseContourXld, DrawEllipse, GenEllipseContourXld
See also
GenEllipseContourXld
Module
Foundation

[out] VARIANT Row HMiscX.IntersectionLl ([in] VARIANT RowA1,


[in] VARIANT ColumnA1, [in] VARIANT RowA2, [in] VARIANT ColumnA2,
[in] VARIANT RowB1, [in] VARIANT ColumnB1, [in] VARIANT RowB2,
[in] VARIANT ColumnB2, [out] VARIANT Column, [out] VARIANT IsParallel )
void HOperatorSetX.IntersectionLl ([in] VARIANT RowA1,
[in] VARIANT ColumnA1, [in] VARIANT RowA2, [in] VARIANT ColumnA2,
[in] VARIANT RowB1, [in] VARIANT ColumnB1, [in] VARIANT RowB2,
[in] VARIANT ColumnB2, [out] VARIANT Row, [out] VARIANT Column,
[out] VARIANT IsParallel )

Calculate the intersection point of two lines.


The operator IntersectionLl calculates the intersection point of two lines. As input the two points on each
line are expected (RowA1,ColumnA1, RowA2,ColumnA2) and (RowB1,ColumnB1, RowB2,ColumnB2). The
parameters Row and Column return the result of the calculation. If the lines are parallel, the values of Row and
Column are undefined and IsParallel is 1. Otherwise, IsParallel is 0.
Attention
If the lines are parallel the values of Row and Column are undefined.

HALCON 8.0.2
1224 CHAPTER 15. TOOLS

Parameter

. RowA1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( real, integer )


Row coordinate of the first point of the first line.
. ColumnA1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( real, integer )
Column coordinate of the first point of the first line.
. RowA2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( real, integer )
Row coordinate of the second point of the first line.
. ColumnA2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( real, integer )
Column coordinate of the second point of the first line.
. RowB1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( real, integer )
Row coordinate of the first point of the second line.
. ColumnB1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( real, integer )
Column coordinate of the first point of the second line.
. RowB2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( real, integer )
Row coordinate of the second point of the second line.
. ColumnB2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( real, integer )
Column coordinate of the second point of the second line.
. Row (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT
Row coordinate of the intersection point.
. Column (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT
Column coordinate of the intersection point.
. IsParallel (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT
Are the two lines parallel?
Example

dev_set_color (’black’)
RowLine1 := 350
ColLine1 := 250
RowLine2 := 300
ColLine2 := 300
Rows := 300
Columns := 50
disp_line (WindowHandle, RowLine1, ColLine1, RowLine2, ColLine2)
n := 0
for Rows := 40 to 200 by 4
dev_set_color (’red’)
disp_line (WindowHandle, Rows, Columns, Rows+n, Columns+n)
intersection_ll (Rows, Columns, Rows+n, Columns+n, RowLine1, ColLine1,
RowLine2, ColLine2, Row, Column, IsParallel)
dev_set_color (’blue’)
disp_line (WindowHandle, Row, Column-2, Row, Column+2)
disp_line (WindowHandle, Row-2, Column, Row+2, Column)
n := n+8
endfor

Result
IntersectionLl returns TRUE.
Parallelization Information
IntersectionLl is reentrant and processed without parallelization.
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


15.9. GEOMETRY 1225

[out] VARIANT RowProj HMiscX.ProjectionPl ([in] VARIANT Row,


[in] VARIANT Column, [in] VARIANT Row1, [in] VARIANT Column1,
[in] VARIANT Row2, [in] VARIANT Column2, [out] VARIANT ColProj )
void HOperatorSetX.ProjectionPl ([in] VARIANT Row, [in] VARIANT Column,
[in] VARIANT Row1, [in] VARIANT Column1, [in] VARIANT Row2,
[in] VARIANT Column2, [out] VARIANT RowProj, [out] VARIANT ColProj )

Calculate the projection of a point onto a line.


The operator ProjectionPl calculates the projection of a point (Row,Column) onto a line which is represented
by the two points (Row1,Column1) and (Row2,Column2). The coordinates of the projected point are returned
in RowProj and ColProj.
Parameter
. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( real, integer )
Row coordinate of the point.
. Column (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( real, integer )
Column coordinate of the point.
. Row1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( real, integer )
Row coordinate of the first point on the line.
. Column1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( real, integer )
Column coordinate of the first point on the line.
. Row2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y(-array) ; VARIANT ( real, integer )
Row coordinate of the second point on the line.
. Column2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x(-array) ; VARIANT ( real, integer )
Column coordinate of the second point on the line.
. RowProj (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT
Row coordinate of the projected point.
. ColProj (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT
Column coordinate of the projected point
Example

dev_set_color (’black’)
RowLine1 := 400
ColLine1 := 200
RowLine2 := 240
ColLine2 := 400
Rows := 300
Columns := 50
disp_line (WindowHandle, RowLine1, ColLine1, RowLine2, ColLine2)
n := 0
for Rows := 40 to 200 by 4
dev_set_color (’red’)
disp_circle (WindowHandle, Rows+n, Columns, 2)
projection_pl (Rows+n, Columns, RowLine1, ColLine1, RowLine2, ColLine2,
RowProj, ColProj)
dev_set_color (’blue’)
disp_line (WindowHandle, RowProj-2, ColProj, RowProj+2, ColProj)
disp_line (WindowHandle, RowProj, ColProj-2, RowProj, ColProj+2)
n := n+8
endfor

Result
ProjectionPl returns TRUE.
Parallelization Information
ProjectionPl is reentrant and processed without parallelization.

HALCON 8.0.2
1226 CHAPTER 15. TOOLS

Module
Foundation

15.10 Grid-Rectification
[out] HUntypedObjectX ConnectingLines HImageX.ConnectGridPoints
([in] VARIANT Row, [in] VARIANT Col, [in] VARIANT Sigma,
[in] VARIANT MaxDist )
void HOperatorSetX.ConnectGridPoints ([in] IHObjectX Image,
[out] HUntypedObjectX ConnectingLines, [in] VARIANT Row, [in] VARIANT Col,
[in] VARIANT Sigma, [in] VARIANT MaxDist )

Establish connections between the grid points of the rectification grid.


ConnectGridPoints searches for connecting lines between the grid points (Row,Col) of the rectification
grid. The connecting lines are extracted from the input image Image by a combination of an edge detector, a
smoothing filter, and a line detector, each of size σ. The σ to be used is determined as follows: When a single
value is passed in Sigma, this value is used. When a tuple of three values (sigma_min, sigma_max, sigma_step)
is passed, ConnectGridPoints tests every σ within a range from sigma_min to sigma_max with a step width
of sigma_step and chooses the σ that causes the greatest number of connecting lines. The same happens when a
tuple of only two values sigma_min and sigma_max is passed. However, in this case a fixed step width of 0.05 is
used.
Then, the extracted connecting lines are split at the grid points and those line segments are selected that start as
well as end at a grid point. Note that edge detectors typically don’t work very accurately in the proximity of edge
junctions, and thus in general the connecting lines will not hit the grid points. Therefore, actually those connecting
lines are split and selected that start at, end at, or pass a grid point at a maximum distance of MaxDist. The
connecting lines are modified in order to start and end exactly in the corresponding grid points, and are returned in
ConnectingLines as XLD contours.
Additionally, ConnectGridPoints calculates for each output XLD contour its type of transition and stores it
in its global attribute ’bright_dark’. The attribute is set to 1.0, if the connecting line forms a bright-dark transition
(left to right, viewed from start point to end point), otherwise it is set to 0.0.
Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, uint2 )


Input image.
. ConnectingLines (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xld ; HUntypedObjectX
Output contours.
. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; VARIANT ( real )
Row coordinates of the grid points.
. Col (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; VARIANT ( real )
Column coordinates of the grid points.
Restriction : (Row = number)
. Sigma (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( real, integer )
Size of the applied Gaussians.
Default Value : 0.9
Suggested values : Sigma ∈ {0.7, 0.9, 1.1, 1.3, 1.5}
Restriction : (0.7 ≤ Sigma)
Number of elements : ((1 ≤ Sigma) ∧ (Sigma ≤ 3))
. MaxDist (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Maximum distance of the connecting lines from the grid points.
Default Value : 5.5
Suggested values : MaxDist ∈ {1.5, 3.5, 5.5, 7.5, 9.5}
Restriction : (0.0 ≤ M axDist)
Result
ConnectGridPoints returns TRUE if all parameter values are correct. If necessary, an exception handling is
raised.

HALCON/COM Reference Manual, 2008-5-13


15.10. GRID-RECTIFICATION 1227

Parallelization Information
ConnectGridPoints is reentrant and processed without parallelization.
Possible Predecessors
SaddlePointsSubPix
Possible Successors
GenGridRectificationMap
Module
Calibration

void HMiscX.CreateRectificationGrid ([in] double Width,


[in] long NumSquares, [in] String GridFile )
void HOperatorSetX.CreateRectificationGrid ([in] VARIANT Width,
[in] VARIANT NumSquares, [in] VARIANT GridFile )

Generate a PostScript file, which describes the rectification grid.


CreateRectificationGrid generates a checkered pattern with NumSquares × NumSquares alternat-
ing black and white squares. This pattern is Width meters wide (and high). Around the pattern there is an
inner frame of 0.3 times the width of one square, which continues the checkered pattern. The pattern is com-
pleted by a solid white outer frame of 0.7 times the width of one square. In the center of the pattern there are
two circular marks, one black on a white square and one white on a black square. These marks are used by
GenGridRectificationMap to rotate the detected layout of the grid points into the correct orientation. It
is assumed that the black mark is positioned to the left of the white mark, when oriented correctly. The file
GridFile contains the PostScript description of the rectification grid.
Parameter

. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT


Width of the checkered pattern in meters (without the two frames).
Default Value : 0.17
Suggested values : Width ∈ {1.2, 0.8, 0.6, 0.4, 0.2, 0.1}
Recommended Increment : 0.1
Restriction : (0.0 < W idth)
. NumSquares (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of squares per row and column.
Default Value : 17
Suggested values : NumSquares ∈ {11, 13, 15, 17, 19, 21, 23, 25, 27}
Recommended Increment : 2
Restriction : (2 ≤ N umSquares)
. GridFile (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.write ; String / VARIANT
File name of the PostScript file.
Default Value : ’rectification_grid.ps’
Result
FindRectificationGrid returns TRUE if all parameter values are correct and the file has been written
successfully. If necessary, an exception handling is raised.
Parallelization Information
CreateRectificationGrid is processed completely exclusively without parallelization.
See also
FindRectificationGrid, SaddlePointsSubPix, ConnectGridPoints,
GenGridRectificationMap
Module
Foundation

HALCON 8.0.2
1228 CHAPTER 15. TOOLS

[out] HRegionX GridRegion HImageX.FindRectificationGrid


([in] VARIANT MinContrast, [in] VARIANT Radius )
void HOperatorSetX.FindRectificationGrid ([in] IHObjectX Image,
[out] HUntypedObjectX GridRegion, [in] VARIANT MinContrast,
[in] VARIANT Radius )

Segment the rectification grid region in the image.


FindRectificationGrid searches in the image Image for image parts that contain the rectification grid
and returns them in the region GridRegion. To do so, essentially image areas with a contrast of at least
MinContrast are extracted and the holes in these areas are filled up. Then, an opening with the radius Radius
is applied to these areas to eliminate smaller areas of high contrast.
During grid-rectification, a careful reduction of the input region to those image parts that actually contain
the rectification grid is useful for two purposes: First, the computing time can be reduced and secondly,
SaddlePointsSubPix and ConnectGridPoints can be prevented from detecting false grid points and
connecting lines.
Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, uint2 )


Input image.
. GridRegion (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX
Output region containing the rectification grid.
. MinContrast (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Minimum contrast.
Default Value : 8.0
Suggested values : MinContrast ∈ {2.0, 4.0, 8.0, 16.0, 32.0}
Restriction : (M inContrast ≥ 0)
. Radius (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real, integer )
Radius of the circular structuring element.
Default Value : 7.5
Suggested values : Radius ∈ {1.5, 2.5, 3.5, 4.5, 5.5, 7.5, 9.5, 12.5, 15.5, 19.5, 25.5, 33.5, 45.5, 60.5, 110.5}
Restriction : (Radius ≥ 0.5)
Example

find_rectification_grid (Image, GridRegion, 8, 10)


dilation_circle (GridRegion, GridRegionDilated, 5.5)
reduce_domain (Image, GridRegionDilated, ImageReduced)
saddle_points_sub_pix (ImageReduced, ’facet’, 1.5, 5, Row, Col)
connect_grid_points (ImageReduced, ConnectingLines, Row, Col, 1.1, 5.5)
gen_grid_rectification_map (ImageReduced, ConnectingLines, Map, Meshes, 20,
’auto’, Row, Col)
map_image (Image, Map, ImageMapped)

Result
FindRectificationGrid returns TRUE if all parameter values are correct. If necessary, an exception han-
dling is raised.
Parallelization Information
FindRectificationGrid is reentrant and processed without parallelization.
Possible Successors
DilationCircle, ReduceDomain
Module
Calibration

HALCON/COM Reference Manual, 2008-5-13


15.10. GRID-RECTIFICATION 1229

[out] HImageX Map HMiscX.GenArbitraryDistortionMap


([in] long GridSpacing, [in] VARIANT Row, [in] VARIANT Col,
[in] long GridWidth, [in] long ImageWidth, [in] long ImageHeight )
void HOperatorSetX.GenArbitraryDistortionMap
([out] HUntypedObjectX Map, [in] VARIANT GridSpacing, [in] VARIANT Row,
[in] VARIANT Col, [in] VARIANT GridWidth, [in] VARIANT ImageWidth,
[in] VARIANT ImageHeight )

Generate a projection map that describes the mapping between an arbitrarily distorted image and the rectified
image.
GenArbitraryDistortionMap computes the mapping Map between an arbitrarily distorted image and the
rectified image. Assuming that the points (Row,Col) form a regular grid in the rectified image, each grid cell,
which is defined by the coordinates (Row,Col) of its four corners in the distorted image, is projected onto a square
of GridSpacing×GridSpacing pixels. The coordinates of the grid points must be passed line by line in Row
and Col. GridWidth is the width of the point grid in grid points. To compute the mapping Map, additionally
the width ImageWidth and height ImageHeight of the images to be rectified must be passed.
Map consists of one image containing five channels. In the first channel for each pixel in the resulting image, the
linearized coordinates of the pixel in the input image that is in the upper left position relative to the transformed co-
ordinates are stored. The four other channels contain the weights of the four neighboring pixels of the transformed
coordinates, which are used for the bilinear interpolation, in the following order:
2 3
4 5
The second channel, for example, contains the weights of the pixels that lie to the upper left relative to the trans-
formed coordinates.
In contrary to GenGridRectificationMap, GenArbitraryDistortionMap is used when the coor-
dinates (Row,Col) of the grid points in the distorted image are already known or the relevant part of the image
consist of regular grid structures, which the coordinates can be derived from.
Parameter

. Map (output iconic) . . . . . . . . . . . . . multichannel-image-array ; HImageX / HUntypedObjectX ( int4, uint2 )


Image containing the mapping data.
. GridSpacing (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Distance of the grid points in the rectified image.
Restriction : (GridSpacing > 0)
. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; VARIANT ( real )
Row coordinates of the grid points in the distorted image.
. Col (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; VARIANT ( real )
Column coordinates of the grid points in the distorted image.
Restriction : (Col = number)
. GridWidth (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Width of the point grid (number of grid points).
. ImageWidth (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; long / VARIANT
Width of the images to be rectified.
Restriction : (ImageW idth > 0)
. ImageHeight (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; long / VARIANT
Height of the images to be rectified.
Restriction : (ImageHeight > 0)
Result
GenArbitraryDistortionMap returns TRUE if all parameter values are correct. If necessary, an exception
handling is raised.
Parallelization Information
GenArbitraryDistortionMap is reentrant and processed without parallelization.
Possible Successors
MapImage

HALCON 8.0.2
1230 CHAPTER 15. TOOLS

See also
CreateRectificationGrid, FindRectificationGrid, ConnectGridPoints,
GenGridRectificationMap
Module
Calibration

[out] HImageX Map HImageX.GenGridRectificationMap


([in] IHXLDX ConnectingLines, [out] HUntypedObjectX Meshes,
[in] long GridSpacing, [in] VARIANT Rotation, [in] VARIANT Row,
[in] VARIANT Col )
[out] HImageX Map HXLDX.GenGridRectificationMap ([in] HImageX Image,
[out] HUntypedObjectX Meshes, [in] long GridSpacing, [in] VARIANT Rotation,
[in] VARIANT Row, [in] VARIANT Col )
void HOperatorSetX.GenGridRectificationMap ([in] IHObjectX Image,
[in] IHObjectX ConnectingLines, [out] HUntypedObjectX Map,
[out] HUntypedObjectX Meshes, [in] VARIANT GridSpacing,
[in] VARIANT Rotation, [in] VARIANT Row, [in] VARIANT Col )

Compute the mapping between the distorted image and the rectified image based upon the points of a regular grid.
GenGridRectificationMap calculates the mapping between the grid points (Row,Col), which have been
actually detected in the distorted image Image (typically using SaddlePointsSubPix), and the correspond-
ing grid points of the ideal regular point grid. First, all paths that lead from their initial point via exactly four differ-
ent connecting lines back to the initial point are assembled from the grid points (Row,Col) and the connecting lines
ConnectingLines (detected by ConnectGridPoints). In case that the input of grid points (Row,Col)
and of connecting lines ConnectingLines was meaningful, one such ’mesh’ corresponds to exactly one grid
cell in the rectification grid. Afterwards, the meshes are combined to the point grid. According to the value of
Rotation, the point grid is rotated by 0, 90, 180 or 270 degrees. Note that the point grid does not necessarily have
the correct orientation. When passing ’auto’ in Rotation, the point grid is rotated such that the black circular
mark in the rectification grid is positioned to the left of the white one (see also CreateRectificationGrid).
Finally, the mapping Map between the distorted image and the rectified image is calculated by interpolation be-
tween the grid points. Each grid cell, for which the coordinates (Row,Col) of all four corner points are known, is
projected onto a square of GridSpacing × GridSpacing pixels.
Map consists of one image containing five channels. In the first channel for each pixel in the resulting image, the
linearized coordinates of the pixel in the input image that is in the upper left position relative to the transformed co-
ordinates are stored. The four other channels contain the weights of the four neighboring pixels of the transformed
coordinates, which are used for the bilinear interpolation, in the following order:
2 3
4 5
The second channel, for example, contains the weights of the pixels that lie to the upper left relative to the trans-
formed coordinates.
GenGridRectificationMap additionally returns the calculated meshes as XLD contours in Meshes.
In contrary to GenArbitraryDistortionMap, GenGridRectificationMap and its predecessors are
used when the coordinates (Row,Col) of the grid points in the distorted image are neither known nor can be derived
from the image contents.
Attention
Each input XLD contour ConnectingLines must own the global attribute ’bright_dark’, as it is described with
ConnectGridPoints!
Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, uint2 )


Input image.
. ConnectingLines (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xld ; IHXLDX / IHObjectX
Input contours.

HALCON/COM Reference Manual, 2008-5-13


15.11. HOUGH 1231

. Map (output iconic) . . . . . . . . . . . . . multichannel-image-array ; HImageX / HUntypedObjectX ( int4, uint2 )


Image containing the mapping data.
. Meshes (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xld ; HUntypedObjectX
Output contours.
. GridSpacing (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Distance of the grid points in the rectified image.
Restriction : (GridSpacing > 0)
. Rotation (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; VARIANT ( string, integer )
Rotation to be applied to the point grid.
Default Value : ’auto’
List of values : Rotation ∈ {’auto’, 0, 90, 180, 270}
. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; VARIANT ( real )
Row coordinates of the grid points.
. Col (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; VARIANT ( real )
Column coordinates of the grid points.
Restriction : (Row = number)
Result
GenGridRectificationMap returns TRUE if all parameter values are correct. If necessary, an exception
handling is raised.
Parallelization Information
GenGridRectificationMap is reentrant and processed without parallelization.
Possible Predecessors
ConnectGridPoints
Possible Successors
MapImage
See also
GenArbitraryDistortionMap
Module
Calibration

15.11 Hough

[out] HImageX HoughImage HRegionX.HoughCircleTrans


([in] VARIANT Radius )
void HOperatorSetX.HoughCircleTrans ([in] IHObjectX Region,
[out] HUntypedObjectX HoughImage, [in] VARIANT Radius )

Return the Hough-Transform for circles with a given radius.


The operator HoughCircleTrans calculates the Hough transform for circles with a certain Radius in the
regions passed by Region. Hereby the centres of all possible circles in the parameter space (the Hough or accu-
mulator space respectively) will be accumulated for each point in the image space. Circle hypotheses supported by
many points in the input region thereby generate a maximum in the area showing the circle’s centre in the output
image (HoughImage). The circles’ centres in the image space can be deduced from the coordinates of these
maximums by subtracting the Radius. If more than one radius is transmitted, all Hough images will be shifted
according to the maximal radius.
Parameter

. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX


Binary edge image in which the circles are to be detected.
. HoughImage (output iconic) . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX ( int2 )
Hough transform for circles with a given radius.
Number of elements : (HoughImage = Radius)

HALCON 8.0.2
1232 CHAPTER 15. TOOLS

. Radius (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )


Radius of the circle to be searched in the image.
Default Value : 12
(lin)Minimum Increment : 1
Recommended Increment : 1
Number of elements : ((1 ≤ Radius) ≤ 500)
Result
The operator HoughCircleTrans returns the value TRUE if the input is not empty. The be-
havior in case of empty input (no input regions available) is set via the operator SetSystem
(’noObjectResult’,<Result>), the behavior in case of empty region is set via SetSystem
(’emptyRegionResult’,<Result>). If necessary an exception handling is raised.
Parallelization Information
HoughCircleTrans is reentrant and processed without parallelization.
Module
Foundation

[out] HRegionX RegionOut HRegionX.HoughCircles ([in] VARIANT Radius,


[in] VARIANT Percent, [in] VARIANT Mode )
void HOperatorSetX.HoughCircles ([in] IHObjectX RegionIn,
[out] HUntypedObjectX RegionOut, [in] VARIANT Radius, [in] VARIANT Percent,
[in] VARIANT Mode )

Centres of circles for a specific radius.


HoughCircleTrans detects the centres of circles in regions with the help of the Hough transform for circles
with a specific radius.
Parameter

. RegionIn (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX


Binary edge image in which the circles are to be detected.
. RegionOut (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Centres of those circles which are included in the edge image by Percent percent.
Number of elements : (RegionOut = ((Radius · P ercent) · M ode))
. Radius (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Radius of the circle to be searched in the image.
Default Value : 12
Typical range of values : 2 ≤ Radius ≤ 2(lin)
Minimum Increment : 1
Recommended Increment : 1
Number of elements : ((1 ≤ Radius) ≤ 500)
. Percent (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
Indicates the percentage (approximately) of the (ideal) circle which must be present in the edge image
RegionIn.
Default Value : 60
Typical range of values : 10 ≤ Percent ≤ 10(lin)
Minimum Increment : 1
Recommended Increment : 5
Number of elements : ((1 ≤ P ercent) ≤ 100)
. Mode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer(-array) ; VARIANT ( integer )
The modus defines the position of the circle in question:
0 - the radius is equivalent to the outer border of the set pixels.
1 - the radius is equivalent to the centres of the circle lines´ pixels.
2 - both 0 and 1 (a little more fuzzy, but more reliable in contrast to circles set slightly differently, necessitates
50 % more processing capacity compared to 0 or 1 alone).
List of values : Mode ∈ {0, 1, 2}
Number of elements : ((1 ≤ M ode) ≤ 3)

HALCON/COM Reference Manual, 2008-5-13


15.11. HOUGH 1233

Result
The operator HoughCircles returns the value TRUE if the input is not empty. The behavior in case of empty
input (no input regions available) is set via the operator SetSystem(’noObjectResult’,<Result>), the
behavior in case of empty region is set via SetSystem(’emptyRegionResult’,<Result>). If necessary
an exception handling is raised.
Parallelization Information
HoughCircles is reentrant and processed without parallelization.
Module
Foundation

[out] HImageX HoughImage HRegionX.HoughLineTrans


([in] long AngleResolution )
void HOperatorSetX.HoughLineTrans ([in] IHObjectX Region,
[out] HUntypedObjectX HoughImage, [in] VARIANT AngleResolution )

Produce the Hough transform for lines within regions.


The operator HoughLineTrans calculates the Hough transform for lines in those regions transmitted by
Region. Thereby the angles and the lengths of the lines´ normal vectors are registered in the parameter space
(the Hough- or accumulator space respectively). This means that the parameterization is executed according to the
HNF.
The result is registered in a newly generated Int2-Image (HoughImage), whereby the x-axis is equivalent to the
angle between the normal vector and the x-axis (in the original image), and the y-axis is equivalent to the distance
of the line from the origin.
The angle ranges from -90 to 180 degrees and will be registered with a resolution of 1/AngleResolution,
which means that one pixel in x-direction is equivalent to 1/AngleResolution and that the HoughImage has
a width of 270 ∗ AngleResolution + 1 pixel. The height of the HoughImage corresponds to the distance
between the lower right corner of the surrounding rectangle of the input region and the origin.
The maxima in the result image are equivalent to the parameter values of the lines in the original image.
Parameter
. Region (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
Binary edge image in which lines are to be detected.
. HoughImage (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / HUntypedObjectX ( int2 )
Hough transform for lines.
. AngleResolution (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Adjusting the resolution in the angle area.
Default Value : 4
List of values : AngleResolution ∈ {1, 2, 4, 8}
Result
The operator HoughLineTrans returns the value TRUE if the input is not empty. The behavior in case of empty
input (no input regions available) is set via the operator SetSystem(’noObjectResult’,<Result>), the
behavior in case of empty region is set via SetSystem(’emptyRegionResult’,<Result>). If necessary
an exception handling is raised.
Parallelization Information
HoughLineTrans is reentrant and processed without parallelization.
Possible Predecessors
Threshold, Skeleton
Possible Successors
Threshold, LocalMax
See also
HoughCircleTrans, GenRegionHline
Module
Foundation

HALCON 8.0.2
1234 CHAPTER 15. TOOLS

[out] HImageX HoughImage HImageX.HoughLineTransDir


([in] long DirectionUncertainty, [in] long AngleResolution )
void HOperatorSetX.HoughLineTransDir ([in] IHObjectX ImageDir,
[out] HUntypedObjectX HoughImage, [in] VARIANT DirectionUncertainty,
[in] VARIANT AngleResolution )

Compute the Hough transform for lines using local gradient direction.
The operator HoughLineTransDir calculates the Hough transform for lines in those regions passed in the
domain of ImageDir. To do so, the angles and the lengths of the lines’ normal vectors are registered in the
parameter space (the so-called Hough or accumulator space).
In contrast to HoughLineTrans, additionally the edge direction in ImageDir (e.g., returned by SobelDir
or EdgesImage) is taken into account. This results in a more efficient computation and in a reduction of the
noise in the Hough space.
The parameter DirectionUncertainty describes how much the edge direction of the individual points
within a line is allowed to vary. For example, with DirectionUncertainty = 10 a horizontal line
(i.e., edge direction = 0 degrees) may contain points with an edge direction between -10 and +10 de-
grees. The higher DirectionUncertainty is chosen, the higher the computation time will be. For
DirectionUncertainty = 180 HoughLineTransDir shows the same behavior as HoughLineTrans,
i.e., the edge direction is ignored. DirectionUncertainty should be chosen at least as high as the step width
of the edge direction stored in ImageDir. The minimum step width is 2 degrees (defined by the image type
’direction’).
The result is stored in a newly generated UINT2-Image (HoughImage), where the x-axis (i.e., columns) repre-
sents the angle between the normal vector and the x-axis of the original image, and the y-axis (i.e., rows) represents
the distance of the line from the origin.
The angle ranges from -90 to 180 degrees and will be stored with a resolution of 1/AngleResolution, which
means that one pixel in x-direction is equivalent to 1/AngleResolution degrees and that the HoughImage
has a width of 270∗AngleResolution+1 pixels. The height of the HoughImage corresponds to the distance
between the lower right corner of the surrounding rectangle of the input region and the origin.
The local maxima in the result image are equivalent to the parameter values of the lines in the original image.
Parameter
. ImageDir (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( direction )
Image containing the edge direction. The edges must be described by the image domain.
. HoughImage (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / HUntypedObjectX ( uint2 )
Hough transform.
. DirectionUncertainty (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.deg ; long / VARIANT
Uncertainty of the edge direction (in degrees).
Default Value : 2
Typical range of values : 2 ≤ DirectionUncertainty ≤ 2
Minimum Increment : 2
. AngleResolution (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Resolution in the angle area (in 1/degrees).
Default Value : 4
List of values : AngleResolution ∈ {1, 2, 4, 8}
Result
The operator HoughLineTransDir returns the value TRUE if the input is not empty. The behavior in case of
empty input is set via the operator SetSystem(’noObjectResult’,<Result>). If necessary an excep-
tion handling is raised.
Parallelization Information
HoughLineTransDir is reentrant and processed without parallelization.
Possible Predecessors
EdgesImage, SobelDir, Threshold, HysteresisThreshold, NonmaxSuppressionDir,
ReduceDomain
Possible Successors
BinomialFilter, GaussImage, Threshold, LocalMax, PlateausCenter

HALCON/COM Reference Manual, 2008-5-13


15.11. HOUGH 1235

See also
HoughLineTrans, HoughLines, HoughLinesDir
Module
Foundation

[out] VARIANT Angle HRegionX.HoughLines ([in] long AngleResolution,


[in] long Threshold, [in] long AngleGap, [in] long DistGap,
[out] VARIANT Dist )
void HOperatorSetX.HoughLines ([in] IHObjectX RegionIn,
[in] VARIANT AngleResolution, [in] VARIANT Threshold, [in] VARIANT AngleGap,
[in] VARIANT DistGap, [out] VARIANT Angle, [out] VARIANT Dist )

Detect lines in edge images with the help of the Hough transform and returns it in HNF.
The operator HoughLines allows the selection of linelike structures in a region, whereby it is not necessary that
the individual points of a line are connected. This process is based on the Hough transform. The lines are returned
in HNF, that is by the direction and length of their normal vector.
The parameter AngleResolution defines the degree of exactness concerning the determination of the angles.
It amounts to 1/AngleResolution degree. The parameter Threshold determines by how many points
of the original region a line’s hypothesis has to be supported at least in order to be taken over into the output.
The parameters AngleGap and DistGap define a neighborhood of the points in the Hough image in order to
determine the local maxima. The lines are returned in HNF.
Parameter
. RegionIn (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX
Binary edge image in which the lines are to be detected.
. AngleResolution (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Adjusting the resolution in the angle area.
Default Value : 4
List of values : AngleResolution ∈ {1, 2, 4, 8}
. Threshold (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Threshold value in the Hough image.
Default Value : 100
. AngleGap (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Minimal distance of two maxima in the Hough image (direction: angle).
Default Value : 5
. DistGap (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Minimal distance of two maxima in the Hough image (direction: distance).
Default Value : 5
. Angle (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . hesseline.angle.rad ; VARIANT ( real )
Angles (in radians) of the detected lines’ normal vectors.
Typical range of values : -1.5707963 ≤ Angle ≤ -1.5707963
. Dist (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . hesseline.distance ; VARIANT ( real )
Distance of the detected lines from the origin.
Number of elements : (Dist = Angle)
Result
The operator HoughLines returns the value TRUE if the input is not empty. The behavior in case of empty
input (no input regions available) is set via the operator SetSystem(’noObjectResult’,<Result>),
the behavior in case of empty region is set via SetSystem(’emptyRegionResult’,<Result>). If
necessary an exception handling is raised.
Parallelization Information
HoughLines is reentrant and processed without parallelization.
Possible Predecessors
Threshold, Skeleton
Possible Successors
SelectMatchingLines

HALCON 8.0.2
1236 CHAPTER 15. TOOLS

See also
HoughLineTrans, GenRegionHline, HoughCircles
Module
Foundation

[out] HImageX HoughImage HImageX.HoughLinesDir ([out] HRegionX Lines,


[in] long DirectionUncertainty, [in] long AngleResolution,
[in] String Smoothing, [in] long FilterSize, [in] long Threshold,
[in] long AngleGap, [in] long DistGap, [in] String GenLines,
[out] VARIANT Angle, [out] VARIANT Dist )
void HOperatorSetX.HoughLinesDir ([in] IHObjectX ImageDir,
[out] HUntypedObjectX HoughImage, [out] HUntypedObjectX Lines,
[in] VARIANT DirectionUncertainty, [in] VARIANT AngleResolution,
[in] VARIANT Smoothing, [in] VARIANT FilterSize, [in] VARIANT Threshold,
[in] VARIANT AngleGap, [in] VARIANT DistGap, [in] VARIANT GenLines,
[out] VARIANT Angle, [out] VARIANT Dist )

Detect lines in edge images with the help of the Hough transform using local gradient direction and return them in
normal form.
The operator HoughLinesDir selects line-like structures in a region based on the Hough transform. The
individual points of a line can be unconnected. The region is given by the domain of ImageDir. The lines are
returned in Hessian normal form (HNF), that is by the direction and length of their normal vector.
In contrast to HoughLines, additionally the edge direction in ImageDir (e.g., returned by SobelDir or
EdgesImage) is taken into account. This results in a more efficient computation and in a reduction of the noise
in the Hough space.
The parameter DirectionUncertainty describes how much the edge direction of the individual points
within a line is allowed to vary. For example, with DirectionUncertainty = 10 a horizontal line
(i.e., edge direction = 0 degrees) may contain points with an edge direction between -10 and +10 de-
grees. The higher DirectionUncertainty is chosen, the higher the computation time will be. For
DirectionUncertainty = 180 HoughLinesDir shows the same behavior as HoughLines, i.e., the
edge direction is ignored. DirectionUncertainty should be chosen at least as high as the step width of the
edge direction stored in ImageDir. The minimum step width is 2 degrees (defined by the image type ’direction’).
The parameter AngleResolution defines how accurately the angles are determined. The accuracy amounts to
1/AngleResolution degrees. A subsequent smoothing of the Hough space results in an increased stability.
The smoothing filter can be selected by Smoothing, the degree of smoothing by the parameter FilterSize
(see MeanImage or GaussImage for details). The parameter Threshold determines by how many points of
the original region a line’s hypothesis must at least be supported in order to be selected into the output. The param-
eters AngleGap and DistGap define a neighborhood of the points in the Hough image in order to determine the
local maxima: AngleGap describes the minimum distance of two maxima in the Hough image in angle direction
and DistGap in distance direction, respectively. Thus, maxima exceeding Threshold but lying close to an
even higher maximum are eliminated. This can particularly be helpful when searching for short and long lines
simultaneously. Besides the unsmoothed Hough image HoughImage, the lines are returned in HNF (Angle,
Dist). If the parameter GenLines is set to ’true’, additionally those regions in ImageDir are returned that
contributed to the local maxima in Hough space. They are stored in the parameter Lines.
Parameter

. ImageDir (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( direction )


Image containing the edge direction. The edges are described by the image domain.
. HoughImage (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / HUntypedObjectX ( uint2 )
Hough transform.
. Lines (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / HUntypedObjectX
Regions of the input image that contributed to the local maxima.

HALCON/COM Reference Manual, 2008-5-13


15.11. HOUGH 1237

. DirectionUncertainty (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.deg ; long / VARIANT


Uncertainty of edge direction (in degrees).
Default Value : 2
Typical range of values : 2 ≤ DirectionUncertainty ≤ 2
Minimum Increment : 2
. AngleResolution (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Resolution in the angle area (in 1/degrees).
Default Value : 4
List of values : AngleResolution ∈ {1, 2, 4, 8}
. Smoothing (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Smoothing filter for hough image.
Default Value : ’mean’
List of values : Smoothing ∈ {’none’, ’mean’, ’gauss’}
. FilterSize (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Required smoothing filter size.
Default Value : 5
List of values : FilterSize ∈ {3, 5, 7, 9, 11}
. Threshold (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Threshold value in the Hough image.
Default Value : 100
. AngleGap (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Minimum distance of two maxima in the Hough image (direction: angle).
Default Value : 5
. DistGap (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Minimum distance of two maxima in the Hough image (direction: distance).
Default Value : 5
. GenLines (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Create line regions if ’true’.
Default Value : ’true’
List of values : GenLines ∈ {’true’, ’false’}
. Angle (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . hesseline.angle.rad ; VARIANT ( real )
Angles (in radians) of the detected lines’ normal vectors.
Typical range of values : -1.5707963 ≤ Angle ≤ -1.5707963
. Dist (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . hesseline.distance ; VARIANT ( real )
Distance of the detected lines from the origin.
Number of elements : (Dist = Angle)
Result
The operator HoughLines returns the value TRUE if the input is not empty. The behavior in case of empty
input (no input regions available) is set via the operator SetSystem(’noObjectResult’,<Result>). If
necessary an exception handling is raised.
Parallelization Information
HoughLinesDir is reentrant and processed without parallelization.
Possible Predecessors
EdgesImage, SobelDir, Threshold, NonmaxSuppressionDir, ReduceDomain, Skeleton
Possible Successors
GenRegionHline, SelectMatchingLines
See also
HoughLineTransDir, HoughLineTrans, GenRegionHline, HoughCircles
Module
Foundation

HALCON 8.0.2
1238 CHAPTER 15. TOOLS

[out] HRegionX RegionLines HRegionX.SelectMatchingLines


([in] VARIANT AngleIn, [in] VARIANT DistIn, [in] long LineWidth,
[in] long Thresh, [out] VARIANT AngleOut, [out] VARIANT DistOut )
void HOperatorSetX.SelectMatchingLines ([in] IHObjectX RegionIn,
[out] HUntypedObjectX RegionLines, [in] VARIANT AngleIn, [in] VARIANT DistIn,
[in] VARIANT LineWidth, [in] VARIANT Thresh, [out] VARIANT AngleOut,
[out] VARIANT DistOut )

Select those lines from a set of lines (in HNF) which fit best into a region.
Lines which fit best into a region can be selected from a set of lines which are available in HNF with the help of
the operator SelectMatchingLines; the region itself is also transmitted as a parameter (RegionIn). The
width of the lines can be indicated by the parameter LineWidth. The selected lines will be returned in HNF and
as regions (RegionLines).
The lines are selected iteratively in a loop: At first, the line showing the greatest overlap with the input region
is selected from the set of input lines. This line will then be taken over into the output set whereby all points
belonging to that line will not be considered in the further steps determining overlaps. The loop will be left when
the maximum overlap value of the region and the lines falls below a certain threshold value (Thresh). The
selected lines will be returned as regions as well as in HNF.
Parameter

. RegionIn (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region ; HRegionX / IHObjectX


Region in which the lines are to be matched.
. RegionLines (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Region array containing the matched lines.
. AngleIn (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . hesseline.angle.rad(-array) ; VARIANT ( real )
Angles (in radians) of the normal vectors of the input lines.
Typical range of values : -1.5707963 ≤ AngleIn ≤ -1.5707963
. DistIn (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . hesseline.distance(-array) ; VARIANT ( real )
Distances of the input lines form the origin.
Number of elements : (DistIn = AngleIn)
. LineWidth (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Widths of the lines.
Default Value : 7
. Thresh (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Threshold value for the number of line points in the region.
Default Value : 100
. AngleOut (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . hesseline.angle.rad(-array) ; VARIANT ( real )
Angles (in radians) of the normal vectors of the selected lines.
Typical range of values : -1.5707963 ≤ AngleOut ≤ -1.5707963
Number of elements : (AngleOut ≤ AngleIn)
. DistOut (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . hesseline.distance(-array) ; VARIANT ( real )
Distances of the selected lines from the origin.
Number of elements : (DistOut = AngleOut)
Result
The operator SelectMatchingLines returns the value TRUE if the input is not empty. The
behavior in case of empty input (no input regions available) is set via the operator SetSystem
(’noObjectResult’,<Result>), the behavior in case of empty region is set via SetSystem
(’emptyRegionResult’,<Result>). If necessary an exception handling is raised.
Parallelization Information
SelectMatchingLines is reentrant and processed without parallelization.
Possible Predecessors
HoughLines
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


15.12. IMAGE-COMPARISON 1239

15.12 Image-Comparison

void HMiscX.ClearAllVariationModels ( )
void HOperatorSetX.ClearAllVariationModels ( )

Free the memory of all variation models.


ClearAllVariationModels frees the memory of all variation models that were created by calling
CreateVariationModel. After calling ClearAllVariationModels, no model can be used any longer.
Attention
ClearAllVariationModels exists solely for the purpose of implementing the “reset program” functionality
in HDevelop. ClearAllVariationModels must not be used in any application.
Result
ClearAllVariationModels always returns TRUE.
Parallelization Information
ClearAllVariationModels is processed completely exclusively without parallelization.
Possible Predecessors
CreateVariationModel
Alternatives
ClearVariationModel
Module
Matching

void HVariationModelX.ClearTrainDataVariationModel ( )
void HOperatorSetX.ClearTrainDataVariationModel
([in] VARIANT ModelID )

Free the memory of the training data of a variation model.


ClearTrainDataVariationModel frees the memory of a variation model that was created by
CreateVariationModel. ClearTrainDataVariationModel can be used to reduce the amount
of memory required for the variation model (in main memory as well as when writing the model to file
with WriteVariationModel). ClearTrainDataVariationModel can only be called if the model
has been prepared for comparison with an image with PrepareVariationModel. After the call to
ClearTrainDataVariationModel the variation model can only be used for image comparision with
CompareVariationModel or CompareExtVariationModel. The model cannot be trained any further.
Furthermore, the images used for the image comparison can no longer be read with GetVariationModel. If
they are required, GetVariationModel must be called before ClearTrainDataVariationModel is
called.
Parameter

. ModelID (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . variation_model ; HVariationModelX / VARIANT


ID of the variation model.
Result
ClearTrainDataVariationModel returns TRUE if all parameters are correct.
Parallelization Information
ClearTrainDataVariationModel is processed completely exclusively without parallelization.
Possible Predecessors
PrepareVariationModel
Possible Successors
CompareVariationModel, CompareExtVariationModel, WriteVariationModel
Module
Matching

HALCON 8.0.2
1240 CHAPTER 15. TOOLS

void HOperatorSetX.ClearVariationModel ([in] VARIANT ModelID )

Free the memory of a variation model.


ClearVariationModel frees the memory of a variation model that was created by
CreateVariationModel. After calling CreateVariationModel, the model can no longer be
used. The handle ModelID becomes invalid.
Parameter

. ModelID (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . variation_model ; HVariationModelX / VARIANT


ID of the variation model.
Result
ClearVariationModel returns TRUE if all parameters are correct.
Parallelization Information
ClearVariationModel is processed completely exclusively without parallelization.
Possible Predecessors
CreateVariationModel
Alternatives
ClearAllVariationModels
Module
Matching

[out] HRegionX Region HImageX.CompareExtVariationModel


([in] HVariationModelX ModelID, [in] String Mode )
[out] HRegionX Region HVariationModelX.CompareExtVariationModel
([in] HImageX Image, [in] String Mode )
void HOperatorSetX.CompareExtVariationModel ([in] IHObjectX Image,
[out] HUntypedObjectX Region, [in] VARIANT ModelID, [in] VARIANT Mode )

Compare an image to a variation model.


CompareExtVariationModel compares the input image Image to the variation model given by ModelID.
CompareExtVariationModel is an extension of CompareVariationModel that provides more
modes for the image comparison. Before CompareExtVariationModel can be called, the two inter-
nal threshold images of the variation model must have been created with PrepareVariationModel or
PrepareDirectVariationModel. Let c(x, y) denote the input image Image and tu,l denote the two thresh-
old images (see PrepareVariationModel or PrepareDirectVariationModel). Then, for Mode =
’absolute’ the output region Region contains all points that differ substantially from the model, i.e., the points
that fulfill the following condition:

c(x, y) > tu (x, y) ∨ c(x, y) < tl (x, y) .

This mode is identical to CompareVariationModel. For Mode = ’light’, Region contains all points that
are too bright:
c(x, y) > tu (x, y) .
For Mode = ’dark’, Region contains all points that are too dark:

c(x, y) < tl (x, y) .

Finally, for Mode = ’light_dark’ two regions are returned in Region. The first region contains the result of Mode
= ’light’, while the second region contains the result of Mode = ’dark’. The respective regions can be selected
with SelectObj.

HALCON/COM Reference Manual, 2008-5-13


15.12. IMAGE-COMPARISON 1241

Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte, int2, uint2 )


Image of the object to be trained.
. Region (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Region containing the points that differ substantially from the model.
. ModelID (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . variation_model ; HVariationModelX / VARIANT
ID of the variation model.
. Mode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Method used for comparing the variation model.
Default Value : ’absolute’
Suggested values : Mode ∈ {’absolute’, ’light’, ’dark’, ’light_dark’}
Example

open_framegrabber (’File’, 1, 1, 0, 0, 0, 0, ’default’, -1,


’default’, -1, ’default’, ’model.seq’, ’default’,
-1, -1, FGHandle)
read_region (Region, ’model.reg’)
area_center (Region, Area, RowRef, ColumnRef)
read_shape_model (’model.shm’, TemplateID)
read_variation_model (’model.var’, ModelID)
for K := 1 to 10000 by 1
grab_image (Image, FGHandle)
find_shape_model (Image, TemplateID, 0, rad(360), 0.5, 1, 0.5,
’true’, 4, 0.9, Row, Column, Angle, Score)
disp_obj (Image, WindowHandle)
if (|Score| = 1)
vector_angle_to_rigid (Row, Column, Angle, RowRef,
ColumnRef, 0, HomMat2D)
affine_trans_image (Image, ImageTrans, HomMat2D, ’constant’,
’false’)
compare_ext_variation_model (ImageTrans, RegionDiff, ModelID,
’light’)
disp_obj (RegionDiff, WindowHandle)
endif
endfor
clear_shape_model (TemplateID)
clear_variation_model (ModelID)
close_framegrabber (FGHandle)

Result
CompareExtVariationModel returns TRUE if all parameters are correct and if the internal threshold images
have been generated with PrepareVariationModel or PrepareDirectVariationModel.
Parallelization Information
CompareExtVariationModel is reentrant and automatically parallelized (on tuple level, domain level).
Possible Predecessors
PrepareVariationModel, PrepareDirectVariationModel
Possible Successors
SelectObj, Connection
See also
GetThreshImagesVariationModel
Alternatives
CompareVariationModel, DynThreshold
Module
Matching

HALCON 8.0.2
1242 CHAPTER 15. TOOLS

[out] HRegionX Region HImageX.CompareVariationModel


([in] HVariationModelX ModelID )
[out] HRegionX Region HVariationModelX.CompareVariationModel
([in] HImageX Image )
void HOperatorSetX.CompareVariationModel ([in] IHObjectX Image,
[out] HUntypedObjectX Region, [in] VARIANT ModelID )

Compare an image to a variation model.


CompareVariationModel compares the input image Image to the variation model given by ModelID. Be-
fore CompareVariationModel can be called, the two internal threshold images of the variation model must
have been created with PrepareVariationModel or PrepareDirectVariationModel. Let c(x, y)
denote the input image Image and tu,l denote the two threshold images (see PrepareVariationModel or
PrepareDirectVariationModel). Then the output region Region contains all points that differ substan-
tially from the model, i.e., the points that fulfill the following condition:
c(x, y) > tu (x, y) ∨ c(x, y) < tl (x, y) .
If only too bright or too dark errors should be segmented the operator CompareExtVariationModel can be
used.
Parameter
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte, int2, uint2 )
Image of the object to be trained.
. Region (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . region(-array) ; HRegionX / HUntypedObjectX
Region containing the points that differ substantially from the model.
. ModelID (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . variation_model ; HVariationModelX / VARIANT
ID of the variation model.
Example

open_framegrabber (’File’, 1, 1, 0, 0, 0, 0, ’default’, -1,


’default’, -1, ’default’, ’model.seq’, ’default’,
-1, -1, FGHandle)
read_region (Region, ’model.reg’)
area_center (Region, Area, RowRef, ColumnRef)
read_shape_model (’model.shm’, TemplateID)
read_variation_model (’model.var’, ModelID)
for K := 1 to 10000 by 1
grab_image (Image, FGHandle)
find_shape_model (Image, TemplateID, 0, rad(360), 0.5, 1, 0.5,
’true’, 4, 0.9, Row, Column, Angle, Score)
disp_obj (Image, WindowHandle)
if (|Score| = 1)
vector_angle_to_rigid (Row, Column, Angle, RowRef,
ColumnRef, 0, HomMat2D)
affine_trans_image (Image, ImageTrans, HomMat2D, ’constant’,
’false’)
compare_variation_model (ImageTrans, RegionDiff, ModelID)
disp_obj (RegionDiff, WindowHandle)
endif
endfor
clear_shape_model (TemplateID)
clear_variation_model (ModelID)
close_framegrabber (FGHandle)

Result
CompareVariationModel returns TRUE if all parameters are correct and if the internal threshold images
have been generated with PrepareVariationModel or PrepareDirectVariationModel.

HALCON/COM Reference Manual, 2008-5-13


15.12. IMAGE-COMPARISON 1243

Parallelization Information
CompareVariationModel is reentrant and automatically parallelized (on tuple level, domain level).
Possible Predecessors
PrepareVariationModel, PrepareDirectVariationModel
Possible Successors
Connection
See also
GetThreshImagesVariationModel
Alternatives
CompareExtVariationModel, DynThreshold
Module
Matching

void HVariationModelX.CreateVariationModel ([in] long Width,


[in] long Height, [in] String Type, [in] String Mode )
void HOperatorSetX.CreateVariationModel ([in] VARIANT Width,
[in] VARIANT Height, [in] VARIANT Type, [in] VARIANT Mode,
[out] VARIANT ModelID )

Create a variation model for image comparison.


CreateVariationModel creates a variation model that can be used for image comparison. The handle for the
variation model is returned in ModelID.
Typically, the variation model is used to discriminate correctly manufactured objects (“good objects”) from incor-
rectly manufactured objects (“bad objects”). It is assumed that the discrimination can be done solely based on the
gray values of the object.
The variation model consists of an ideal image of the object to which the images of the objects to be tested are
compared later on with CompareVariationModel or CompareExtVariationModel, and an image
that represents the amount of gray value variation at every point of the object. The size of the images with which
the object model is trained and with which the model is compared later on is passed in Width and Height,
respectively. The image type of the images used for training and comparison is passed in Type.
The variation model is trained using multiple images of good objects. Therefore, it is essential that the training
images show the objects in the same position and rotation. If this cannot be guarateed by external means, the pose
of the object can, for example, be determined by using matching (see FindShapeModel). The image can then
be transformed to a reference pose with AffineTransImage.
The parameter Mode is used to determine how the image of the ideal object and the corresponding variation
image are computed. For Mode=’standard’, the ideal image of the object is computed as the mean of all training
images at the respective image positions. The corresponding variation image is computed as the standard deviation
of the training images at the respective image positions. This mode has the advantage that the variation model
can be trained iteratively, i.e., as soon as an image of a good object becomes available, it can be trained with
TrainVariationModel. The disadvantage of this mode is that great care must be taken to ensure that only
images of good objects are trained, because the mean and standard deviation are not robust against outliers, i.e., if
an image of a bad object is trained inadvertently, the accuracy of the ideal object image and that of the variation
image might be degraded.
If it cannot be avoided that the variation model is trained with some images of objects that can contain errors, Mode
can be set to ’robust’. In this mode, the image of the ideal object is computed as the median of all training images
at the respective image positions. The corresponding variation image is computed as a suitably scaled median
absolute deviation of the training images and the median image at the respective image positions. This mode has
the advantage that it is robust against outliers. It has the disadvantage that it cannot be trained iteratively, i.e., all
training images must be accumulated using ConcatObj and be trained with TrainVariationModel in a
single call.
In some cases, it is impossible to acquire multiple training images. In this case, a useful variation image cannot
be trained from the single training image. To solve this problem, variations of the training image can be created
synthetically, e.g., by shifting the training image by ±1 pixel in the row and column directions or by using gray

HALCON 8.0.2
1244 CHAPTER 15. TOOLS

value morphology (e.g., GrayErosionShape und GrayDilationShape), and then training the syntheti-
cally modified images. A different possibility to create the variation model from a single image is to create the
model with Mode=’direct’. In this case, the variation model can only be trained by specifying the ideal image and
the variation image directly with PrepareDirectVariationModel. Since the variation typically is large at
the edges of the object, edge operators like SobelAmp, EdgesImage, or GrayRangeRect should be used
to create the variation image.
Parameter

. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; long / VARIANT


Width of the images to be compared.
Default Value : 640
Suggested values : Width ∈ {160, 192, 320, 384, 640, 768}
. Height (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; long / VARIANT
Height of the images to be compared.
Default Value : 480
Suggested values : Height ∈ {120, 144, 240, 288, 480, 576}
. Type (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Type of the images to be compared.
Default Value : ’byte’
Suggested values : Type ∈ {’byte’, ’int2’, ’uint2’}
. Mode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Method used for computing the variation model.
Default Value : ’standard’
Suggested values : Mode ∈ {’standard’, ’robust’, ’direct’}
. ModelID (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . variation_model ; HVariationModelX / VARIANT
ID of the variation model.
Complexity
A variation model created with CreateVariationModel requires 12 ∗ Width ∗ Height bytes of mem-
ory for Mode = ’standard’ and Mode = ’robust’ for Type = ’byte’. For Type = ’uint2’ and Type =
’int2’, 14 ∗ Width ∗ Height are required. For Mode = ’direct’ and after the training data has been cleared
with ClearTrainDataVariationModel, 2 ∗ Width ∗ Height bytes are required for Type = ’byte’ and
4 ∗ Width ∗ Height for the other image types.
Result
CreateVariationModel returns TRUE if all parameters are correct.
Parallelization Information
CreateVariationModel is processed completely exclusively without parallelization.
Possible Successors
TrainVariationModel, PrepareDirectVariationModel
See also
PrepareVariationModel, ClearVariationModel, ClearTrainDataVariationModel,
FindShapeModel, AffineTransImage
Module
Matching

[out] HImageX MinImage


HVariationModelX.GetThreshImagesVariationModel
([out] HImageX MaxImage )
void HOperatorSetX.GetThreshImagesVariationModel
([out] HUntypedObjectX MinImage, [out] HUntypedObjectX MaxImage,
[in] VARIANT ModelID )

Return the threshold images used for image comparison by a variation model.
GetThreshImagesVariationModel returns the threshold images of the variation model ModelID in
MaxImage and MinImage. The threshold images must be computed with PrepareVariationModel or

HALCON/COM Reference Manual, 2008-5-13


15.12. IMAGE-COMPARISON 1245

PrepareDirectVariationModel before they can be read out. The formula used for calculating the thresh-
old images is described with PrepareVariationModel or PrepareDirectVariationModel. The
threshold images are used in CompareVariationModel and CompareExtVariationModel to detect
too large deviations of an image with respect to the model. As described with CompareVariationModel
and CompareExtVariationModel, gray values outside the interval given by MinImage and MaxImage
are regarded as errors.
Parameter
. MinImage (output iconic) . . . . . . . . . . . . . . . . . . . image ; HImageX / HUntypedObjectX ( byte, int2, uint2 )
Threshold image for the lower threshold.
. MaxImage (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / HUntypedObjectX ( real )
Threshold image for the upper threshold.
. ModelID (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . variation_model ; HVariationModelX / VARIANT
ID of the variation model.
Result
GetThreshImagesVariationModel returns TRUE if all parameters are correct.
Parallelization Information
GetThreshImagesVariationModel is reentrant and processed without parallelization.
Possible Predecessors
PrepareVariationModel, PrepareDirectVariationModel
See also
CompareVariationModel, CompareExtVariationModel
Module
Matching

[out] HImageX Image HVariationModelX.GetVariationModel


([out] HImageX VarImage )
void HOperatorSetX.GetVariationModel ([out] HUntypedObjectX Image,
[out] HUntypedObjectX VarImage, [in] VARIANT ModelID )

Return the images used for image comparison by a variation model.


GetVariationModel returns the image of the ideal object and the corresponding variation image of the varia-
tion model ModelID in Image and VarImage, respectively. The returned images can be used to check whether
an image of a bad object has been trained with TrainVariationModel. This can be seen from the variation
image. If an image of a bad object has been trained, the variation image typically has large variations in areas that
should exhibit no variations.
Parameter
. Image (output iconic) . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / HUntypedObjectX ( byte, int2, uint2 )
Image of the trained object.
. VarImage (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / HUntypedObjectX ( real )
Variation image of the trained object.
. ModelID (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . variation_model ; HVariationModelX / VARIANT
ID of the variation model.
Result
GetVariationModel returns TRUE if all parameters are correct.
Parallelization Information
GetVariationModel is reentrant and processed without parallelization.
Possible Predecessors
TrainVariationModel
See also
PrepareVariationModel, CompareVariationModel, CompareExtVariationModel
Module
Matching

HALCON 8.0.2
1246 CHAPTER 15. TOOLS

void HVariationModelX.PrepareDirectVariationModel
([in] HImageX RefImage, [in] HImageX VarImage, [in] VARIANT AbsThreshold,
[in] VARIANT VarThreshold )
void HOperatorSetX.PrepareDirectVariationModel
([in] IHObjectX RefImage, [in] IHObjectX VarImage, [in] VARIANT ModelID,
[in] VARIANT AbsThreshold, [in] VARIANT VarThreshold )

Prepare a variation model for comparison with an image.


PrepareDirectVariationModel prepares a variation model for the image comparison with
CompareVariationModel or CompareExtVariationModel. The variation model must have been
created with Mode=’direct’ with CreateVariationModel. In contrast to PrepareVariationModel,
the ideal image of the object and the corresponding variation image are not computed with
TrainVariationModel, but are specified directly in RefImage and VarImage. This is useful if the
variation model should be created from a single image, as described with CreateVariationModel.
The variation image should typically be created with edge operators like SobelAmp, EdgesImage, or
GrayRangeRect.
PrepareDirectVariationModel converts the ideal image RefImage and the variation image VarImage
into two threshold images and stores them in the variation model. These threshold images are used in
CompareVariationModel or CompareExtVariationModel to perform the comparison of the current
image to the variation model.
Two thresholds are used to compute the threshold images. The parameter AbsThreshold determines the mini-
mum amount of gray levels by which the image of the current object must differ from the image of the ideal object.
The parameter VarThreshold determines a factor relative to the variation image for the minimum difference of
the current image and the ideal image. AbsThreshold and VarThreshold each can contain one or two values.
If two values are specified, different thresholds can be determined for too bright and too dark pixels. In this mode,
the first value refers to too bright pixels, while the second value refers to too dark pixels. If one value is specified,
this value refers to both the too bright and too dark pixels. Let i(x, y) be the ideal image RefImage, v(x, y) the
variation image VarImage, au = AbsThreshold[0], al = AbsThreshold[1], bu = VarThreshold[0],
and bl = VarThreshold[1] (or au = AbsThreshold, al = AbsThreshold, bu = VarThreshold, and
bl = VarThreshold, respectively). Then the two threshold images tu,l are computed as follows:

tu (x, y) = i(x, y) + max{au , bu v(x, y)} tl (x, y) = i(x, y) − max{al , bl v(x, y)} .

If the current image c(x, y) is compared to the variation model using CompareVariationModel, the output
region contains all points that differ substantially from the model, i.e., that fulfill the following condition:

c(x, y) > tu (x, y) ∨ c(x, y) < tl (x, y) .

In CompareExtVariationModel, extended comparison modes are available, which return only too bright
errors, only too dark errors, or bright and dark errors as separate regions.
After the threshold images have been created they can be read out with
GetThreshImagesVariationModel.
It should be noted that RefImage and VarImage are not stored as the ideal and variation images in the model
to save memory in the model.
Parameter

. RefImage (input iconic) . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte, int2, uint2 )


Reference image of the object.
. VarImage (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, int2, uint2 )
Variation image of the object.
. ModelID (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . variation_model ; HVariationModelX / VARIANT
ID of the variation model.
. AbsThreshold (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( real, integer )
Absolute minimum threshold for the differences between the image and the variation model.
Default Value : 10
Suggested values : AbsThreshold ∈ {0, 5, 10, 15, 20, 30, 40, 50}
Restriction : (AbsT hreshold ≥ 0)

HALCON/COM Reference Manual, 2008-5-13


15.12. IMAGE-COMPARISON 1247

. VarThreshold (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( real, integer )


Threshold for the differences based on the variation of the variation model.
Default Value : 2
Suggested values : VarThreshold ∈ {1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5}
Restriction : (V arT hreshold ≥ 0)
Example

read_image (Image, ’model’)


sobel_amp (Image, VarImage, ’sum_abs’, 3)
get_image_pointer1 (Image, Pointer, Type, Width, Height)
create_variation_model (Width, Height, Type, ’direct’, ModelID)
prepare_direct_variation_model (Image, VarImage, ModelID, 20, 1)
write_variation_model (ModelID, ’model.var’)
clear_variation_model (ModelID)

Result
PrepareDirectVariationModel returns TRUE if all parameters are correct.
Parallelization Information
PrepareDirectVariationModel is processed completely exclusively without parallelization.
Possible Predecessors
SobelAmp, EdgesImage, GrayRangeRect
Possible Successors
CompareVariationModel, CompareExtVariationModel,
GetThreshImagesVariationModel, WriteVariationModel
See also
CreateVariationModel
Alternatives
PrepareVariationModel
Module
Matching

void HVariationModelX.PrepareVariationModel
([in] VARIANT AbsThreshold, [in] VARIANT VarThreshold )
void HOperatorSetX.PrepareVariationModel ([in] VARIANT ModelID,
[in] VARIANT AbsThreshold, [in] VARIANT VarThreshold )

Prepare a variation model for comparison with an image.


PrepareVariationModel prepares a variation model for the image comparison with
CompareVariationModel or CompareExtVariationModel. This is done by converting the ideal
image and the variation image that have been trained with TrainVariationModel into two threshold images
and storing them in the variation model. These threshold images are used in CompareVariationModel or
CompareExtVariationModel to speed up the comparison of the current image to the variation model.
Two thresholds are used to compute the threshold images. The parameter AbsThreshold determines the min-
imum amount of gray levels by which the image of the current object must differ from the image of the ideal
object. The parameter VarThreshold determines a factor relative to the variation image for the minimum dif-
ference of the current image and the ideal image. AbsThreshold and VarThreshold each can contain one
or two values. If two values are specified, different thresholds can be determined for too bright and too dark pix-
els. In this mode, the first value refers to too bright pixels, while the second value refers to too dark pixels. If
one value is specified, this value refers to both the too bright and too dark pixels. Let i(x, y) be the ideal image,
v(x, y) the variation image, au = AbsThreshold[0], al = AbsThreshold[1], bu = VarThreshold[0],
and bl = VarThreshold[1] (or au = AbsThreshold, al = AbsThreshold, bu = VarThreshold, and
bl = VarThreshold, respectively). Then the two threshold images tu,l are computed as follows:
tu (x, y) = i(x, y) + max{au , bu v(x, y)} tl (x, y) = i(x, y) − max{al , bl v(x, y)} .

HALCON 8.0.2
1248 CHAPTER 15. TOOLS

If the current image c(x, y) is compared to the variation model using CompareVariationModel, the output
region contains all points that differ substantially from the model, i.e., that fulfill the following condition:

c(x, y) > tu (x, y) ∨ c(x, y) < tl (x, y) .

In CompareExtVariationModel, extended comparison modes are available, which return only too bright
errors, only too dark errors, or bright and dark errors as separate regions.
After the threshold images have been created they can be read out with
GetThreshImagesVariationModel. Furthermore, the training data can be deleted with
ClearTrainDataVariationModel to save memory.
Parameter
. ModelID (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . variation_model ; HVariationModelX / VARIANT
ID of the variation model.
. AbsThreshold (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( real, integer )
Absolute minimum threshold for the differences between the image and the variation model.
Default Value : 10
Suggested values : AbsThreshold ∈ {0, 5, 10, 15, 20, 30, 40, 50}
Restriction : (AbsT hreshold ≥ 0)
. VarThreshold (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( real, integer )
Threshold for the differences based on the variation of the variation model.
Default Value : 2
Suggested values : VarThreshold ∈ {1, 1.5, 2, 2.5, 3, 3.5, 4, 4.5, 5}
Restriction : (V arT hreshold ≥ 0)
Result
PrepareVariationModel returns TRUE if all parameters are correct.
Parallelization Information
PrepareVariationModel is processed completely exclusively without parallelization.
Possible Predecessors
TrainVariationModel
Possible Successors
CompareVariationModel, CompareExtVariationModel,
GetThreshImagesVariationModel, ClearTrainDataVariationModel,
WriteVariationModel
See also
CreateVariationModel
Alternatives
PrepareDirectVariationModel
Module
Matching

void HVariationModelX.ReadVariationModel ([in] String FileName )


void HOperatorSetX.ReadVariationModel ([in] VARIANT FileName,
[out] VARIANT ModelID )

Read a variation model from a file.


The operator ReadVariationModel reads a variation model, which has been written with
WriteVariationModel, from the file FileName.
Parameter
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.read ; String / VARIANT
File name.
. ModelID (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . variation_model ; HVariationModelX / VARIANT
ID of the variation model.

HALCON/COM Reference Manual, 2008-5-13


15.12. IMAGE-COMPARISON 1249

Result
If the file name is valid, the operator ReadVariationModel returns TRUE. If necessary an exception handling
is raised.
Parallelization Information
ReadVariationModel is reentrant and processed without parallelization.
Possible Successors
CompareVariationModel, CompareExtVariationModel
See also
WriteVariationModel
Module
Matching

void HImageX.TrainVariationModel ([in] HVariationModelX ModelID )


void HVariationModelX.TrainVariationModel ([in] HImageX Images )
void HOperatorSetX.TrainVariationModel ([in] IHObjectX Images,
[in] VARIANT ModelID )

Train a variation model.


TrainVariationModel trains the variation model that is passed in ModelID with one or more images, which
are passed in Images.
As described for CreateVariationModel, a variation model that has been created using the mode ’standard’
can be trained iteratively, i.e., as soon as images of good objects become available, they can be trained with
TrainVariationModel. The ideal image of the object is computed as the mean of all previous training
images and the images that are passed in Images. The corresponding variation image is computed as the standard
deviation of the training images and the images that are passed in Images.
If the variation model has been created using the mode ’robust’, the model cannot be trained iteratively, i.e., all
training images must be accumulated using ConcatObj and be trained with TrainVariationModel in a
single call. If any images have been trained previously, the training information of the previous call is discarded.
The image of the ideal object is computed as the median of all training images passed in Images. The corre-
sponding variation image is computed as a suitably scaled median absolute deviation of the training images and
the median image.
Attention
At most 65535 training images can be trained.
Parameter
. Images (input iconic) . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte, int2, uint2 )
Images of the object to be trained.
. ModelID (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . variation_model ; HVariationModelX / VARIANT
ID of the variation model.
Example

open_framegrabber (’File’, 1, 1, 0, 0, 0, 0, ’default’, -1,


’default’, -1, ’default’, ’model.seq’, ’default’,
-1, -1, FGHandle)
grab_image (Image, FGHandle)
get_image_pointer1 (Image, Pointer, Type, Width, Height)
disp_obj (Image, WindowHandle)
draw_region (Region, WindowHandle)
reduce_domain (Image, Region, ImageReduced)
area_center (Region, Area, RowRef, ColumnRef)
create_shape_model (ImageReduced, 4, 0, rad(360), rad(1), ’none’,
’use_polarity’, 40, 10, TemplateID)
create_variation_model (Width, Height, Type, ’standard’, ModelID)

HALCON 8.0.2
1250 CHAPTER 15. TOOLS

for K := 1 to 100 by 1
grab_image (Image, FGHandle)
find_shape_model (Image, TemplateID, 0, rad(360), 0.5, 1, 0.5,
’true’, 4, 0.9, Row, Column, Angle, Score)
if (|Score| = 1)
vector_angle_to_rigid (Row, Column, Angle, RowRef,
ColumnRef, 0, HomMat2D)
affine_trans_image (Image, ImageTrans, HomMat2D, ’constant’,
’false’)
train_variation_model (ImageTrans, ModelID)
endif
endfor
prepare_variation_model (ModelID, 10, 4)
write_region (Region, ’model.reg’)
write_shape_model (TemplateID, ’model.shm’)
write_variation_model (ModelID, ’model.var’)
clear_shape_model (TemplateID)
clear_variation_model (ModelID)
close_framegrabber (FGHandle)

Result
TrainVariationModel returns TRUE if all parameters are correct.
Parallelization Information
TrainVariationModel is processed completely exclusively without parallelization.
Possible Predecessors
CreateVariationModel, FindShapeModel, AffineTransImage, ConcatObj
Possible Successors
PrepareVariationModel
See also
PrepareVariationModel, CompareVariationModel, CompareExtVariationModel,
ClearVariationModel
Module
Matching

void HVariationModelX.WriteVariationModel ([in] String FileName )


void HOperatorSetX.WriteVariationModel ([in] VARIANT ModelID,
[in] VARIANT FileName )

Write a variation model to a file.


WriteVariationModel writes a variation model to the file FileName. The model can be read with
ReadVariationModel.
Parameter
. ModelID (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . variation_model ; HVariationModelX / VARIANT
ID of the variation model.
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.write ; String / VARIANT
File name.
Result
If the file name is valid (write permission), the operator WriteVariationModel returns TRUE. If necessary
an exception handling is raised.
Parallelization Information
WriteVariationModel is reentrant and processed without parallelization.
Possible Predecessors
TrainVariationModel

HALCON/COM Reference Manual, 2008-5-13


15.13. KALMAN-FILTER 1251

See also
ReadVariationModel
Module
Matching

15.13 Kalman-Filter
[out] VARIANT PredictionOut HMiscX.FilterKalman ([in] VARIANT Dimension,
[in] VARIANT Model, [in] VARIANT Measurement, [in] VARIANT PredictionIn,
[out] VARIANT Estimate )
void HOperatorSetX.FilterKalman ([in] VARIANT Dimension,
[in] VARIANT Model, [in] VARIANT Measurement, [in] VARIANT PredictionIn,
[out] VARIANT PredictionOut, [out] VARIANT Estimate )

Estimate the current state of a system with the help of the Kalman filtering.
The operator FilterKalman returns an estimate of the current state (or also a prediction of a future state)
of a discrete, stochastically disturbed, linear system. In practice, Kalman filters are used successfully in image
processing in the analysis of image sequences (background identification, lane tracking with the help of line tracing
or region analysis, etc.). A short introduction concerning the theory of the Kalman filters will be followed by a
detailed description of the routine FilterKalman itself.
KALMAN FILTER: A discrete, stochastically disturbed, linear system is characterized by the following markers:

• State x(t): Describes the current state of the system (speeds, temperatures,...).
• Parameter u(t): Inputs from outside into the system.
• Measurement y(t): Measurements gained by observing the system. They indicate the state of the system (or
at least parts of it).
• An output function describing the dependence of the measurements on the state.
• A transition function indicating how the state changes with regard to time, the current value and the parame-
ters.

The output function and the transition function are linear. Their application can therefore be written as a multipli-
cation with a matrix.
The transition function is described with the help of the transition matrix A(t) and the parameter matrix , the initial
function is described by the measurement matrix C(t). Hereby C(t) characterizes the dependency of the new state
on the old, G(t) indicates the dependency on the parameters. In practice it is rarely possible (or at least too time
consuming) to describe a real system and its behaviour in a complete and exact way. Normally only a relatively
small number of variables will be used to simulate the behaviour of the system. This leads to an error, the so called
system error (also called system disturbance) v(t).
The output function, too, is usually not exact. Each measurement is faulty. The measurement errors will be called
w(t). Therefore the following system equations arise:
x(t + 1) = A(t)x(t) + G(t)u(t) + v(t)
y(t) = c(t)x(t) + w(t)
The system error v(t) and the measurement error w(t) are not known. As far as systems are concerned which
are interpreted with the help of the Kalman filter, these two errors are considered as Gaussian distributed random
vectors (therefore the expression "‘stochastically disturbed systems"’). Therefore the system can be calculated, if
the corresponding expected values for v(t) and w(t) as well as the covariance matrices are known.
The estimation of the state of the system is carried out in the same way as in the Gaussian-Markov-estimation.
However, the Kalman filter is a recursive algorithm which is based only on the current measurements y(t) and the
latest state x(t). The latter implicitly also includes the knowlegde about earlier measurements.
A suitable estimate value x_0, which is interpreted as the expected value of a random variable for x(0), must be
indicated for the initial value x(0). This variable should have an expected error value of 0 and the covariance
matrix P _0 which also has to be indicated. At a certain time t the expected values of both disturbances v(t) and
w(t) should be 0 and their covariances should be Q(t) and R(t). x(t), v(t) and w(t) will usually be assumed to be

HALCON 8.0.2
1252 CHAPTER 15. TOOLS

not correlated (any kind of noise-process can be modelled - however the development of the necessary matrices by
the user will be considerably more demanding). The following conditions must be met by the searched estimate
values xt :

• The estimate values xt are linearly dependent on the actual value x(t) and on the measurement sequence
y(0), y(1), · · · , y(t).
• xt being hereby considered to meet its expectations, i.e. Ext = Ex(t).
• The grade criterion for xt is the criterion of minimal variance, i.e. the variance of the estimation error defined
as x(t) − xt , being as small as possible.

After the initialization


x̂(0) = x0 , P̂ (0) = P0
at each point in time t the Kalman filter executes the following calculation steps:

P̂ (t)C 0 (t)
(K − III) K(t) = C(t)P̂ (t)C 0 (t)+R(t)
(K − IV ) xt = x̂(t) + K(t)(y(t) − C(t)x̂(t))
(K − V ) P̃ (t) = P̂ (t) − K(t)C(t)P̂ (t)
(K − I) x̂(t + 1) = A(t)xt + G(t)u(t)
(K − II) P̂ (t + 1) = A(t)P̃ (t)A0 (t) + Q(t)

Hereby P̃ (t) is the covariance matrix of the estimation error, x̂(t) is the extrapolation value respective the predic-
tion value of the state, P̂ (t) are the covariances of the prediction error x̂ − x, K is the amplifier matrix (the so
called Kalman gain), and X 0 is the transposed of a matrix X.
Please note that the prediction of the future state is also possible with the equation (K-I). Somtimes this is very
useful in image processing in order to determine "‘regions of interest"’ in the next image.
As mentioned above, it is much more demanding to model any kind of noise processes. If for example the system
noise and the measurement noise are correlated with the corresponding covariance matrix L, the equations for the
Kalman gain and the error covariance matrix have to be modified:

P̂ (t)C 0 (t)+L(t)
(K − III) K(t) = C(t)P̂ (t)+C(t)l(t)+L0 C 0 (t)+R(t)
(K − V ) P̃ (t) = (P̂ (t) − K(t)C(t)P̂ (t))P̂ (t) − K(t)L(t)

This means that the user himself has to establish the linear system equations from (K-I) up to (K-V) with respect to
the actual problem. The user must therefore develop a mathematical model upon which the solution to the problem
can be based. Statistical characteristics describing the inaccuracies of the system as well as the measurement
errors, which are to be expected, thereby have to be estimated if they cannot be calculated exactly. Therefore the
following individual steps are necessary:

1. Developing a mathematical model


2. Selecting characteristic state variables
3. Establishing the equations describing the changes of these state variables and their linearization (matrices A
and G)
4. Establishing the equations describing the dependency of the measurement values of the system on the state
variables and their linearization (matrix C)
5. Developing or estimating of statistical dependencies between the system disturbances (matrix Q)
6. Developing or estimating of statistical dependencies between the measurement errors (matrix R)
7. Initialization of the initial state

As mentioned above, the initialization of the system (point 7) hereby necessitates to indicate an estimate x0 of the
state of the system at the time 0 and the corresponding covariance matrix P0 . If the exact initial state is not known,
it is recommendable to set the components of the vector x0 to the average values of the corresponding range, and
to set high values for P0 (about the size of the squares of the range). After a few iterations (when the number of the
accumulated measurement values in total has exceeded the number of the system values), the values which have
been determined in this way are also useable.

HALCON/COM Reference Manual, 2008-5-13


15.13. KALMAN-FILTER 1253

If on the other hand the initial state is known exactly, all entries for P0 have to be set to 0, because P0 describes
the covariances of the error between the estimated value x0 and the actual value x(0).
THE FILTER ROUTINE:
A Kalman filter is dependent on a range of data which can be organized in four groups:

Model parameter: transition matrix A, control matrix G including the parameter u and the measurement matrix
C
Model stochastic: system-error covariance matrix Q, system-error - measurement-error covariance matrix L, and
measurement-error covariance matrix R
Measurement vector: y
History of the system: extrapolation vector x̂ and extrapolation-error covariance matrix P̂

Thereby many systems can work without input "‘from outside"’, i.e. without G and u. Further, system errors and
measurement errors are normally not correlated (L is dropped).
Actually the data necessary for the routine will be set by the following parameters:

Dimension: This parameter includes the dimensions of the status vector, the measurement vector and the con-
troller vector. Dimension thereby is a vector [n,m,p], whereby n indicates the number of the state variables,
m the number of the measurement values and p the number of the controller members. For a system without
determining control (i.e. without influence "‘from outside"’) therefore [n,m,0] has to be passed.
Model: This parameter includes the lined up matrices (vectors) A,C,Q,G,u and (if necessary) L having been stored
in row-major order. Model therefore is a vector of the length n × n + n × m + n × n + n × p + p[+n × m].
The last summand is dropped, in case the system errors and measurement errors are not correlated, i.e. there
is no value for L.
Measurement: This parameter includes the matrix R which has been stored in row-major order, and the mea-
surement vector y lined up. Measurement therefore is a vector of the dimension m × m + m.
PredictionIn / PredictionOut: These two parameters include the matrix P̂ (the extrapolation-error co-
variance matrix) which has been stored in row-major order and the extrapolation vector x̂ lined up. This
means, they are vectors of the length n × n + n. PredictionIn therefore is an input parameter, which
must contain P̂ (t) and x̂(t) at the current time t. With PredictionOut the routine returns the correspond-
ing predictions P̂ (t + 1) and x̂(t + 1).
Estimate: With this parameter the routine returns the matrix P̃ (the estimation-error covariance matrix) which
has been stored in row-major order and the estimated state x̃ lined up. Estimate therefore is a vector of
the length n × n + n.

Please note that the covariance matrices (Q, R, P̂ , P̃ ) must of course be symmetric.
Attention

Parameter

. Dimension (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )


The dimensions of the state vector, the measurement and the controller vector.
Default Value : [3,1,0]
Typical range of values : 0 ≤ Dimension ≤ 0
. Model (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
The lined up matrices A, C, Q, possibly G and u, and if necessary L which have been stored in row-major
order.
Default Value : [1.0,1.0,0.5,0.0,1.0,1.0,0.0,0.0,1.0,1.0,0.0,0.0,54.3,37.9,48.0,37.9,34.3,42.5,48.0,42.5,43.7]
Typical range of values : 0.0 ≤ Model ≤ 0.0
. Measurement (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
The matrix R stored in row-major order and the measurement vector y lined up.
Default Value : [1.2,1.0]
Typical range of values : 0.0 ≤ Measurement ≤ 0.0

HALCON 8.0.2
1254 CHAPTER 15. TOOLS

. PredictionIn (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )


The matrix P̂ (the extrapolation-error covariances) stored in row-major order and the extrapolation vector x̂
lined up.
Default Value : [0.0,0.0,0.0,0.0,180.5,0.0,0.0,0.0,100.0,0.0,100.0,0.0]
Typical range of values : 0.0 ≤ PredictionIn ≤ 0.0
. PredictionOut (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
The matrix P∗ (the extrapolation-error covariances)stored in row-major order and the extrapolation vector x̂
lined up.
. Estimate (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
The matrix P̃ (the estimation-error covariances) stored in row-major order and the estimated state x̃ lined up.
Example

// Typical procedure:
// 1. To initialize the variables, which describe the model, e.g. with
read_kalman(’kalman.init’,Dim,Mod,Meas,Pred)
// Generation of the first measurements (typical of the first image of an
// image series) with an appropriate problem-specific routine (there is a
// fictitious routine extract_features in example):
extract_features(Image1,Meas,Meas1)
// first Kalman-Filtering:
filter_kalman(Dim,Mod,Meas1,Pred,Pred1,Est1)
// To use the estimate value (if need be the prediction too)
// with a problem-specific routine (here use_est):
use_est(Est1)
// To get the next measurements (e.g. from the next image):
extract_next_features(Image2,Meas1,Meas2)
// if need be Update of the model parameter (a constant model)
// second Kalman-Filtering:
filter_kalman(Dim,Mod,Meas2,Pred1,Pred2,Est2)
use_est(Est2)
extract_next_features(Image3,Meas2,Meas3).
// etc.

Result
If the parameter values are correct, the operator FilterKalman returns the value TRUE. Otherwise an exception
handling will be raised.
Parallelization Information
FilterKalman is reentrant and processed without parallelization.
Possible Predecessors
ReadKalman, SensorKalman
Possible Successors
UpdateKalman
See also
ReadKalman, UpdateKalman, SensorKalman
References
W.Hartinger: "‘Entwurf eines anwendungsunabh"angigen Kalman-Filters mit Untersuchungen im Bereich der
Bildfolgenanalyse"’; Diplomarbeit; Technische Universit"at M"unchen, Institut f"ur Informatik, Lehrstuhl Prof.
Radig; 1991.
R.E.Kalman: "‘A New Approach to Linear Filtering and Prediction Problems"’; Transactions ASME, Ser.D: Jour-
nal of Basic Engineering; Vol. 82, S.34-45; 1960.
R.E.Kalman, P.l.Falb, M.A.Arbib: "‘Topics in Mathematical System Theory"’; McGraw-Hill Book Company, New
York; 1969.
K-P. Karmann, A.von Brandt: "‘Moving Object Recognition Using an Adaptive Background Memory"’; Time-
Varying Image Processing and Moving Object Recognition 2 (ed.: V. Cappellini), Proc. of the 3rd Interantional
Workshop, Florence, Italy, May, 29th - 31st, 1989; Elsevier, Amsterdam; 1990.

HALCON/COM Reference Manual, 2008-5-13


15.13. KALMAN-FILTER 1255

Module
Foundation

[out] VARIANT Dimension HMiscX.ReadKalman ([in] String FileName,


[out] VARIANT Model, [out] VARIANT Measurement, [out] VARIANT Prediction )
void HOperatorSetX.ReadKalman ([in] VARIANT FileName,
[out] VARIANT Dimension, [out] VARIANT Model, [out] VARIANT Measurement,
[out] VARIANT Prediction )

Read the description file of a Kalman filter.


The operator ReadKalman reads the description file FileName of a Kalman filter. Kalman filters return an
estimate of the current state (or even the prediction of a future state) of a discrete, stochastically disturbed, linear
system. They are successfully used in image processing, especially in the analysis of image sequences. A Kalman
filtering is based on a mathematical model of the system to be examined which at any point in time has the
following characteristics:

Model parameter: transition matrix A, control matrix G including the controller output u and the measurement
matrix C
Model stochastic: system-error covariance matrix Q, system-error - measurement-error covariance matrix L and
measurement-error covariance matrix R
Estimate of the initial state of the system: state x0 and corresponding covariance matrix P0

Many systems do not need entries "‘from outside"’, and therefore G and u can be dropped. Further, system errors
and measurement errors are normally not correlated (L is dropped). The characteristics mentioned above can be
stored in an ASCII-file and then can be read with the help of the operator ReadKalman. This ASCII-file must
have the following structure:
Dimension row
+ content row
+ matrix A
+ atrix C
+ matrix Q
[ + matrix G + vector u ]
[ + matrix L ]
+ matrix R
[ + matrix P0 ]
[ + vector x0 ]

The dimension row thereby is always of the following form:


n = <integer> m = <integer> p = <integer>
whereby n indicates the number of the state variables, m the number of the measurement values and p the number
of the controller members (see also Dimension). The maximal dimension will hereby be limited by a system
constant (= 30 for the time being).
The content row has the following form:
A ∗ C ∗ Q ∗ G ∗ u ∗ L ∗ R ∗ P ∗ x∗
and describes the following content of the file. Instead of ’∗’, ’+’ (= parameter is available) respectively ’-’ (=
parameter is missing) have to be set. Please note that only the parameters marked by [...] in the above list may be
left out in the description file. If the initial state estimate a0 is missing (i.e. ’x-’), the components of the vector will
supposed to be 0.0. If the covariance matrix P0 of the initial state estimate is missing (i.e. ’P-’), the error will be
supposed to be tremendous. In this case the matrix elements will be set to 10000.0. This value seems to be very
high, however, it is only sufficient if the range of components of the state vector x is smaller to the tenth power.
(r × s) matrices will be stored per row in the following form:

HALCON 8.0.2
1256 CHAPTER 15. TOOLS

< Kommentar, d.h. string >


< a11 > < a12 > · · · < a1s >
.. .. ..
. . .
< ar1 > < ar2 > ··· < ars >

(the spaces and line feed characters can be chosen at will),


vectors will be stored correspondingly in the following form:

< comment, i.e.string >


< a1 > · · · < ak >

The following parameter values are returned by the operator ReadKalman:

Dimension: This parameter includes the dimensions of the status vector, the measurement vector and the con-
troller vector. Dimension thereby is a vector [n,m,p], whereby n indicates the number of the state variables,
m the number of the measurement values and p the number of the controller members. For a system without
determining control (i.e. without influence "‘from outside"’) therefore Dimension = [n,m,0].
Model: This parameter includes the lined up matrices (vectors) A, C, Q, G, u and (if necessary) L having been
stored in row-major order. Model therefore is a vector of the length n×n+n×m+n×n+n×p+p[+n×m].
The last summand is dropped, in case the system errors and measurement errors are not correlated, i.e. there
is no value for L.
Measurement: This parameter includes the matrix R which has been stored in row-major order.
Measurement therefore is vector of the dimension m × m.
Prediction: This parameter includes the matrix P0 (the error covariance matrix of the initial state estimate)
and the initial state estimate x0 lined up. This means, it is a vector of the length n × n + n.

Attention

Parameter

. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.read ; String / VARIANT


Description file for a Kalman filter.
Default Value : ’kalman.init’
. Dimension (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
The dimensions of the state vector, the measurement vector and the controller vector.
. Model (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
The lined up matrices A, C, Q, possibly G and u, and if necessary L stored in row-major order.
. Measurement (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
The matrix R stored in row-major order.
. Prediction (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
The matrix P0 (error covariance matrix of the initial state estimate) stored in row-major order and the initial
state estimate x0 lined up.
Example

%An example of the description-file:


%
%n=3 m=1 p=0
%A+C+Q+G-u-L-R+P+x+
%transition matrix A:
%1 1 0.5
%0 1 1
%0 0 1
%measurement matrix C:
%1 0 0

HALCON/COM Reference Manual, 2008-5-13


15.13. KALMAN-FILTER 1257

%system-error covariance matrix Q:


%54.3 37.9 48.0
%37.9 34.3 42.5
%48.0 42.5 43.7
%measurement-error covariance matrix R:
%1.2
%estimation-error covariance matrix (for the initial estimate) P0:
%0 0 0
%0 180.5 0
%0 0 100
%initial estimate x0:
%0 100 0
%
%the result of read_kalman with the upper descriptionfile
%as inputparameter:
%
%Dimension = [3,1,0]
%Model = [1.0,1.0,0.5,0.0,1.0,1.0,0.0,0.0,1.0,1.0,0.0,0.0,
% 54.3,37.9,48.0,37.9,34.3,42.5,48.0,42.5,43.7]
%Measurement = [1.2]
%Prediction = [0.0,0.0,0.0,0.0,180.5,0.0,0.0,0.0,100.0,0.0,100.0,
% 0.0].

Result
If the description file is readable and correct, the operator ReadKalman returns the value TRUE. Otherwise an
exception handling will be raised.
Parallelization Information
ReadKalman is reentrant and processed without parallelization.
Possible Successors
FilterKalman
See also
UpdateKalman, FilterKalman, SensorKalman
Module
Foundation

[out] VARIANT MeasurementOut HMiscX.SensorKalman ([in] long Dimension,


[in] VARIANT MeasurementIn )
void HOperatorSetX.SensorKalman ([in] VARIANT Dimension,
[in] VARIANT MeasurementIn, [out] VARIANT MeasurementOut )

Interactive input of measurement values for a Kalman filtering.


The operator SensorKalman supports the interactive input of measurement values for a Kalman filtering.
Kalman filters return an estimate of the current state (or even the prediction of a future state) of a discrete, stochas-
tically disturbed, linear system. They are successfully used in image processing, especially in the analysis of image
sequences.
Each filtering is hereby based on certain measurement values. How these values are extracted from images or
sensor data depends strongly on the individual application and therefore must be entirely up to the user. However,
the operator SensorKalman allows an interactive input of (fictitious) measurement values y and the correspond-
ing measurement-error covariance matrix R. Especially the testing of Kalman filters during the development can
hereby be facilitated.
The parameters MeasurementIn and MeasurementOut include the matrix R which has been stored in
row-major order and the measurement vector y lined up, i.e. they are vectors of the length Dimension ×
Dimension + Dimension
Attention

HALCON 8.0.2
1258 CHAPTER 15. TOOLS

Parameter
. Dimension (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of measurement values.
Default Value : 1
Typical range of values : 0 ≤ Dimension ≤ 0
. MeasurementIn (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
The matrix R stored in row-major order and the measurement vector y lined up.
Default Value : [1.2,1.0]
Typical range of values : 0.0 ≤ MeasurementIn ≤ 0.0
. MeasurementOut (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
The matrix R stored in row-major order and the measurement vector y lined up.
Result
If the parameters are correct, the operator SensorKalman returns the value TRUE. Otherwise an exception
handling is raised.
Parallelization Information
SensorKalman is reentrant and processed without parallelization.
Possible Successors
FilterKalman
See also
FilterKalman, ReadKalman, UpdateKalman
Module
Foundation

[out] VARIANT DimensionOut HMiscX.UpdateKalman ([in] String FileName,


[in] VARIANT DimensionIn, [in] VARIANT ModelIn, [in] VARIANT MeasurementIn,
[out] VARIANT ModelOut, [out] VARIANT MeasurementOut )
void HOperatorSetX.UpdateKalman ([in] VARIANT FileName,
[in] VARIANT DimensionIn, [in] VARIANT ModelIn, [in] VARIANT MeasurementIn,
[out] VARIANT DimensionOut, [out] VARIANT ModelOut,
[out] VARIANT MeasurementOut )

Read an update file of a Kalman filter.


The operator UpdateKalman reads the update file FileName of a Kalman filter. Kalman filters return an
estimate of the current state (or even the prediction of a future state) of a discrete, stochastically disturbed, linear
system.
A Kalman filtering is based on a mathematical model of the system to be examined which at any point in time has
the following characteristics:

Model parameter: transition matrix A, control matrix G including the controller output u and the measurement
matrix C
Model stochastic: system-error covariance matrix Q, system-error - measurement-error covariance matrix L and
measurement-error covariance matrix R
Measurement vector: y
History of the system: extrapolation vector x̂ and extrapolation-error covariance matrix P̂

Many systems do not need entries "‘from outside"’ and therefore G and u can be dropped. Further, system errors
and measurement errors are normally not correlated (L is dropped). Some of the characteristics mentioned above
may change dynamically (from one iteration to the next). The operator UpdateKalman serves to modify parts
of the system according to an update file (ASCII) with the following structure (see also ReadKalman):
Dimension row
+ content row
+ matrix A
+ matrix C

HALCON/COM Reference Manual, 2008-5-13


15.13. KALMAN-FILTER 1259

+ matrix Q
+ matrix G + vector u
+ matrix L
+ matrix R

The dimension row thereby has the following form:


n = <integer> m = <integer> p = <integer>
whereby n indicates the number of the state variables, m the number of the measurement values and p the number
of the controller members (see also DimensionIn / DimensionOut). The maximal dimension will hereby be
limited by a system constant (= 30 for the time being). As in this case changes should take effect at a valid model,
the dimensions n and m are invariant (and will only be indicated for purposes of control).
The content row has the following form:
A ∗ C ∗ Q ∗ G ∗ u ∗ L ∗ R∗
and describes the further content of the file. Instead of ’∗’, ’+’ (= parameter is available) respectively ’-’ (=
parameter is missing) has to be set. In contrast to description files for ReadKalman, the system description
needs not be complete in this case. Only those parts of the system which are changed must be indicated. The
indication of estimated values is unnecessary, as these values must stem from the latest filtering according to the
structure of the filter.
(r × s) matrices will be stored in row-major order in the following form:

< comment, i.e. string >


< a11 > < a12 > · · · < a1s >
.. .. ..
. . .
< ar1 > < ar2 > ··· < ars >

(the spaces/line feed characters can be chosen at will),


vectors will be stored correspondingly in the following form:

< commentar, i.e. string >


< a1 > · · · < ak >

The following parameter values of the operator ReadKalman will be changed:

DimensionIn / DimensionOut: These parameters include the dimensions of the state vector, measurement
vector and controller vector and therefore are vectors [n,m,p], whereby n indicates the number of the state
variables, m the number of the measurement values and p the number of the controller members. n and m are
invariant for a given system, i.e. they must not differ from corresponding input values of the update file. For
a system without without influence "‘from outside"’ p = 0.
ModelIn / ModelOut: These parameters include the lined up matrices (vectors) A, C, Q, G, u and if necessary
L which have been stored in row-major order. ModelIn / ModelOut therefore are vectors of the length
n × n + n × m + n × n + n × p + p[+n × m]. The last summand is dropped if system errors and measurement
errors are not correlated, i.e. no value has been set for L.
MeasurementIn / MeasurementOut: These parameters include the matrix R stored in row-major order, and
therefore are vectors of the dimension m × m.

Attention

Parameter
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.read ; String / VARIANT
Update file for a Kalman filter.
Default Value : ’kalman.updt’
. DimensionIn (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
The dimensions of the state vector, measurement vector and controller vector.
Default Value : [3,1,0]
Typical range of values : 0 ≤ DimensionIn ≤ 0

HALCON 8.0.2
1260 CHAPTER 15. TOOLS

. ModelIn (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )


The lined up matrices A,C,Q, possibly G and u, and if necessary L which all have been stored in row-major
order.
Default Value : [1.0,1.0,0.5,0.0,1.0,1.0,0.0,0.0,1.0,1.0,0.0,0.0,54.3,37.9,48.0,37.9,34.3,42.5,48.0,42.5,43.7]
Typical range of values : 0.0 ≤ ModelIn ≤ 0.0
. MeasurementIn (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
The matrix R stored in row-major order.
Default Value : [1,2]
Typical range of values : 0.0 ≤ MeasurementIn ≤ 0.0
. DimensionOut (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
The dimensions of the state vector, measurement vector and controller vector.
. ModelOut (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
The lined up matrices A,C,Q, possibly G and u, and if necessary L which all have been stored in row-major
order.
. MeasurementOut (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
The matrix R stored in row-major order.
Example

%The following values are describing the system


%
%DimensionIn = [3,1,0]
%ModelIn = [1.0,1.0,0.5,0.0,1.0,1.0,0.0,0.0,1.0,1.0,0.0,0.0,
% 54.3,37.9,48.0,37.9,34.3,42.5,48.0,42.5,43.7]
%MeasurementIn = [1,2]
%
%An example of the Updatefile:
%
%n=3 m=1 p=0
%A+C-Q-G-u-L-R-
%transitions at time t=15:
%2 1 1
%0 2 2
%0 0 2
%
%the results of update_kalman:
%
%DimensionOut = [3,1,0]
%ModelOut = [2.0,1.0,1.0,0.0,2.0,2.0,0.0,0.0,2.0,1.0,0.0,0.0,
% 54.3,37.9,48.0,37.9,34.3,42.5,48.0,42.5,43.7]
%MeasurementOut = [1.2]

Result
If the update file is readable and correct, the operator UpdateKalman returns the value TRUE. Otherwise an
exception handling is raised.
Parallelization Information
UpdateKalman is reentrant and processed without parallelization.
Possible Successors
FilterKalman
See also
ReadKalman, FilterKalman, SensorKalman
Module
Foundation

HALCON/COM Reference Manual, 2008-5-13


15.14. MEASURE 1261

15.14 Measure
void HMiscX.CloseAllMeasures ( )
void HOperatorSetX.CloseAllMeasures ( )

Delete all measure objects.


CloseAllMeasures deletes all measure objects that have been created using GenMeasureRectangle2 or
GenMeasureArc. The memory used for the measure objects is freed.
Attention
CloseAllMeasures exists solely for the purpose of implementing the “reset program” functionality in HDe-
velop. CloseAllMeasures must not be used in any application.
Result
CloseAllMeasures always returns TRUE.
Parallelization Information
CloseAllMeasures is reentrant and processed without parallelization.
Possible Predecessors
GenMeasureRectangle2, GenMeasureArc, MeasurePos, MeasurePairs
Alternatives
CloseMeasure
Module
1D Metrology

void HOperatorSetX.CloseMeasure ([in] VARIANT MeasureHandle )

Delete a measure object.


CloseMeasure deletes the measure object given by MeasureHandle. The memory used for the measure
object is freed.
Parameter

. MeasureHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . measure_id ; HMeasureX / VARIANT


Measure object handle.
Result
If the parameter values are correct the operator CloseMeasure returns the value TRUE. Otherwise an exception
handling is raised.
Parallelization Information
CloseMeasure is reentrant and processed without parallelization.
Possible Predecessors
GenMeasureRectangle2, GenMeasureArc, MeasurePos, MeasurePairs
See also
CloseAllMeasures
Module
1D Metrology

HALCON 8.0.2
1262 CHAPTER 15. TOOLS

[out] VARIANT RowEdgeFirst HImageX.FuzzyMeasurePairing


([in] long MeasureHandle, [in] double Sigma, [in] double AmpThresh,
[in] double FuzzyThresh, [in] String Transition, [in] String Pairing,
[in] long NumPairs, [out] VARIANT ColumnEdgeFirst,
[out] VARIANT AmplitudeFirst, [out] VARIANT RowEdgeSecond,
[out] VARIANT ColumnEdgeSecond, [out] VARIANT AmplitudeSecond,
[out] VARIANT RowPairCenter, [out] VARIANT ColumnPairCenter,
[out] VARIANT FuzzyScore, [out] VARIANT IntraDistance )
[out] VARIANT RowEdgeFirst HMeasureX.FuzzyMeasurePairing
([in] HImageX Image, [in] double Sigma, [in] double AmpThresh,
[in] double FuzzyThresh, [in] String Transition, [in] String Pairing,
[in] long NumPairs, [out] VARIANT ColumnEdgeFirst,
[out] VARIANT AmplitudeFirst, [out] VARIANT RowEdgeSecond,
[out] VARIANT ColumnEdgeSecond, [out] VARIANT AmplitudeSecond,
[out] VARIANT RowPairCenter, [out] VARIANT ColumnPairCenter,
[out] VARIANT FuzzyScore, [out] VARIANT IntraDistance )
void HOperatorSetX.FuzzyMeasurePairing ([in] IHObjectX Image,
[in] VARIANT MeasureHandle, [in] VARIANT Sigma, [in] VARIANT AmpThresh,
[in] VARIANT FuzzyThresh, [in] VARIANT Transition, [in] VARIANT Pairing,
[in] VARIANT NumPairs, [out] VARIANT RowEdgeFirst,
[out] VARIANT ColumnEdgeFirst, [out] VARIANT AmplitudeFirst,
[out] VARIANT RowEdgeSecond, [out] VARIANT ColumnEdgeSecond,
[out] VARIANT AmplitudeSecond, [out] VARIANT RowPairCenter,
[out] VARIANT ColumnPairCenter, [out] VARIANT FuzzyScore,
[out] VARIANT IntraDistance )

Extract straight edge pairs perpendicular to a rectangle or an annular arc.


FuzzyMeasurePairing serves to extract straight edge pairs that lie perpendicular to the major axis of a
rectangle or an annular arc. In addition to MeasurePos it uses fuzzy member functions to evaluate and select
the edge pairs.
The extraction algorithm is identical to FuzzyMeasurePos. In addition, the edges are grouped to pairs: If
Transition = ’positive’, the edge points with a dark-to-light transition in the direction of the major axis of the
rectangle or the annular arc are returned in RowEdgeFirst and ColumnEdgeFirst. In this case, the cor-
responding edges with a light-to-dark transition are returned in RowEdgeSecond and ColumnEdgeSecond.
If Transition = ’negative’, the behavior is exactly opposite. If Transition = ’all’, the first detected edge
defines the transition for RowEdgeFirst and ColumnEdgeFirst.
Having extracted subpixel edge locations, the edges are paired. The features of a possible edge pair are evaluated
by a fuzzy function, set by SetFuzzyMeasure. Which edge pairs are selected can be determined with the
parameter FuzzyThresh, which constitutes a threshold on the weight over all fuzzy sets, i.e., the geometric
mean of the weights of the defined fuzzy membership functions. As an extension to FuzzyMeasurePairs,
the pairing algorithm can be restricted by Pairing. Currently only ’no_restriction’ is available, which returns all
possible edge pairs, allowing interleaving and inclusion of pairs. Finally, the best scored NumPairs edge pairs
are returned, whereas 0 indicates to return all possible found edge combinations.
The selected edges are returned as single points, which lie on the major axis of the rectangle or annular arc. The
corresponding edge amplitudes are returned in AmplitudeFirst and AmplitudeSecond, the fuzzy scores in
FuzzyScore. In addition, the distance between each edge pair is returned in IntraDistance, corresponding
to the distance between EdgeFirst[i] and EdgeSecond[i].
Attention
FuzzyMeasurePairing only returns meaningful results if the assumptions that the edges are straight and
perpendicular to the major axis of the rectangle or annular arc are fulfilled. Thus, it should not be used to extract
edges from curved objects, for example. Furthermore, the user should ensure that the rectangle or annular arc is
as close to perpendicular as possible to the edges in the image. Additionally, Sigma must not become larger than
approx. 0.5 * Length1 (for Length1 see GenMeasureRectangle2).
It should be kept in mind that FuzzyMeasurePairing ignores the domain of Image for efficiency reasons.
If certain regions in the image should be excluded from the measurement a new measure object with appropriately
modified parameters should be generated.

HALCON/COM Reference Manual, 2008-5-13


15.14. MEASURE 1263

Parameter
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, uint2 )
Input image.
. MeasureHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . measure_id ; long / HMeasureX / VARIANT
Measure object handle.
. Sigma (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Sigma of Gaussian smoothing.
Default Value : 1.0
Suggested values : Sigma ∈ {0.4, 0.6, 0.8, 1.0, 1.5, 2.0, 3.0, 4.0, 5.0, 7.0, 10.0}
Typical range of values : 0.4 ≤ Sigma ≤ 0.4(lin)
Minimum Increment : 0.01
Recommended Increment : 0.1
Restriction : (Sigma ≥ 0.4)
. AmpThresh (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Minimum edge amplitude.
Default Value : 30.0
Suggested values : AmpThresh ∈ {5.0, 10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 90.0, 110.0}
Typical range of values : 1 ≤ AmpThresh ≤ 1(lin)
Minimum Increment : 0.5
Recommended Increment : 2
. FuzzyThresh (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Minimum fuzzy value.
Default Value : 0.5
Suggested values : FuzzyThresh ∈ {0.1, 0.3, 0.5, 0.7, 0.9}
Typical range of values : 0.0 ≤ FuzzyThresh ≤ 0.0(lin)
Recommended Increment : 0.1
. Transition (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Select the first gray value transition of the edge pairs.
Default Value : ’all’
List of values : Transition ∈ {’all’, ’positive’, ’negative’}
. Pairing (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Constraint of pairing.
Default Value : ’no_restriction’
List of values : Pairing ∈ {’no_restriction’}
. NumPairs (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; long / VARIANT
Number of edge pairs.
Default Value : 10
Suggested values : NumPairs ∈ {0, 1, 10, 20, 50}
Recommended Increment : 1
. RowEdgeFirst (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; VARIANT ( real )
Row coordinate of the first edge.
. ColumnEdgeFirst (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; VARIANT ( real )
Column coordinate of the first edge.
. AmplitudeFirst (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Edge amplitude of the first edge (with sign).
. RowEdgeSecond (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; VARIANT ( real )
Row coordinate of the second edge.
. ColumnEdgeSecond (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; VARIANT ( real )
Column coordinate of the second edge.
. AmplitudeSecond (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Edge amplitude of the second edge (with sign).
. RowPairCenter (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; VARIANT ( real )
Row coordinate of the center of the edge pair.
. ColumnPairCenter (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; VARIANT ( real )
Column coordinate of the center of the edge pair.
. FuzzyScore (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Fuzzy evaluation of the edge pair.

HALCON 8.0.2
1264 CHAPTER 15. TOOLS

. IntraDistance (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )


Distance between the edges of the edge pair.
Result
If the parameter values are correct the operator FuzzyMeasurePairing returns the value TRUE. Otherwise
an exception handling is raised.
Parallelization Information
FuzzyMeasurePairing is reentrant and processed without parallelization.
Possible Predecessors
GenMeasureRectangle2, GenMeasureArc, SetFuzzyMeasure
Possible Successors
CloseMeasure
See also
FuzzyMeasurePos, MeasurePos
Alternatives
EdgesSubPix, FuzzyMeasurePairs, MeasurePairs
Module
1D Metrology

[out] VARIANT RowEdgeFirst HImageX.FuzzyMeasurePairs


([in] long MeasureHandle, [in] double Sigma, [in] double AmpThresh,
[in] double FuzzyThresh, [in] String Transition,
[out] VARIANT ColumnEdgeFirst, [out] VARIANT AmplitudeFirst,
[out] VARIANT RowEdgeSecond, [out] VARIANT ColumnEdgeSecond,
[out] VARIANT AmplitudeSecond, [out] VARIANT RowEdgeCenter,
[out] VARIANT ColumnEdgeCenter, [out] VARIANT FuzzyScore,
[out] VARIANT IntraDistance, [out] VARIANT InterDistance )
[out] VARIANT RowEdgeFirst HMeasureX.FuzzyMeasurePairs
([in] HImageX Image, [in] double Sigma, [in] double AmpThresh,
[in] double FuzzyThresh, [in] String Transition,
[out] VARIANT ColumnEdgeFirst, [out] VARIANT AmplitudeFirst,
[out] VARIANT RowEdgeSecond, [out] VARIANT ColumnEdgeSecond,
[out] VARIANT AmplitudeSecond, [out] VARIANT RowEdgeCenter,
[out] VARIANT ColumnEdgeCenter, [out] VARIANT FuzzyScore,
[out] VARIANT IntraDistance, [out] VARIANT InterDistance )
void HOperatorSetX.FuzzyMeasurePairs ([in] IHObjectX Image,
[in] VARIANT MeasureHandle, [in] VARIANT Sigma, [in] VARIANT AmpThresh,
[in] VARIANT FuzzyThresh, [in] VARIANT Transition,
[out] VARIANT RowEdgeFirst, [out] VARIANT ColumnEdgeFirst,
[out] VARIANT AmplitudeFirst, [out] VARIANT RowEdgeSecond,
[out] VARIANT ColumnEdgeSecond, [out] VARIANT AmplitudeSecond,
[out] VARIANT RowEdgeCenter, [out] VARIANT ColumnEdgeCenter,
[out] VARIANT FuzzyScore, [out] VARIANT IntraDistance,
[out] VARIANT InterDistance )

Extract straight edge pairs perpendicular to a rectangle or an annular arc.


FuzzyMeasurePairs serves to extract straight edge pairs which lie perpendicular to the major axis of a rect-
angle or an annular arc. In addition to MeasurePairs it uses fuzzy member functions to evaluate and select the
edge pairs.
The extraction algorithm is identical to FuzzyMeasurePos. In addition, the edges are grouped to pairs: If
Transition = ’positive’, the edge points with a dark-to-light transition in the direction of the major axis of
the rectangle or annular arc are returned in RowEdgeFirst and ColumnEdgeFirst. In this case, the cor-
responding edges with a light-to-dark transition are returned in RowEdgeSecond and ColumnEdgeSecond.
If Transition = ’negative’, the behavior is exactly opposite. If Transition = ’all’, the first detected edge
defines the transition for RowEdgeFirst and ColumnEdgeFirst. I.e., dependent on the positioning of the

HALCON/COM Reference Manual, 2008-5-13


15.14. MEASURE 1265

measure object, edge pairs with a light-dark-light transition or edge pairs with a dark-light-dark transition are
returned. This is suited, e.g., to measure objects with different brightness relative to the background.
Having extracted subpixel edge locations, the edges are paired. The pairing algorithm groups the edges such that
interleavings and inclusions of pairs are prohibited. The features of an edge pair are evaluated by a fuzzy function,
which can be set by SetFuzzyMeasure or SetFuzzyMeasureNormPair. Which edge pairs are selected
can be determined with the parameter FuzzyThresh, which constitutes a threshold on the weight over all fuzzy
sets, i.e., the geometric mean of the weights of the defined fuzzy member functions.
The selected edges are returned as single points, which lie on the major axis of the rectangle or annular arc. The
corresponding edge amplitudes are returned in AmplitudeFirst and AmplitudeSecond, the fuzzy scores
in FuzzyScore. In addition, the distance between each edge pair is returned in IntraDistance and the
distance between consecutive edge pairs is returned in InterDistance. Here, IntraDistance[i] corresponds to
the distance between EdgeFirst[i] and EdgeSecond[i], while InterDistance[i] corresponds to the distance between
EdgeSecond[i] and EdgeFirst[i+1], i.e., the tuple InterDistance contains one element less than the tuples of
the edge pairs.
Attention
FuzzyMeasurePairs only returns meaningful results if the assumptions that the edges are straight and perpen-
dicular to the major axis of the rectangle or annular arc are fulfilled. Thus, it should not be used to extract edges
from curved objects, for example. Furthermore, the user should ensure that the rectangle or a annular arc is as
close to perpendicular as possible to the edges in the image. Additionally, Sigma must not become larger than
approx. 0.5 * Length1 (for Length1 see GenMeasureRectangle2).
It should be kept in mind that FuzzyMeasurePairs ignores the domain of Image for efficiency reasons. If
certain regions in the image should be excluded from the measurement a new measure object with appropriately
modified parameters should be generated.
Parameter
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, uint2 )
Input image.
. MeasureHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . measure_id ; long / HMeasureX / VARIANT
Measure object handle.
. Sigma (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Sigma of Gaussian smoothing.
Default Value : 1.0
Suggested values : Sigma ∈ {0.4, 0.6, 0.8, 1.0, 1.5, 2.0, 3.0, 4.0, 5.0, 7.0, 10.0}
Typical range of values : 0.4 ≤ Sigma ≤ 0.4(lin)
Minimum Increment : 0.01
Recommended Increment : 0.1
Restriction : (Sigma ≥ 0.4)
. AmpThresh (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Minimum edge amplitude.
Default Value : 30.0
Suggested values : AmpThresh ∈ {5.0, 10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 90.0, 110.0}
Typical range of values : 1 ≤ AmpThresh ≤ 1(lin)
Minimum Increment : 0.5
Recommended Increment : 2
. FuzzyThresh (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Minimum fuzzy value.
Default Value : 0.5
Suggested values : FuzzyThresh ∈ {0.1, 0.3, 0.5, 0.7, 0.9}
Typical range of values : 0.0 ≤ FuzzyThresh ≤ 0.0(lin)
Recommended Increment : 0.1
. Transition (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Select the first gray value transition of the edge pairs.
Default Value : ’all’
List of values : Transition ∈ {’all’, ’positive’, ’negative’}
. RowEdgeFirst (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; VARIANT ( real )
Row coordinate of the first edge point.
. ColumnEdgeFirst (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; VARIANT ( real )
Column coordinate of the first edge point.

HALCON 8.0.2
1266 CHAPTER 15. TOOLS

. AmplitudeFirst (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )


Edge amplitude of the first edge (with sign).
. RowEdgeSecond (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; VARIANT ( real )
Row coordinate of the second edge point.
. ColumnEdgeSecond (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; VARIANT ( real )
Column coordinate of the second edge point.
. AmplitudeSecond (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Edge amplitude of the second edge (with sign).
. RowEdgeCenter (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; VARIANT ( real )
Row coordinate of the center of the edge pair.
. ColumnEdgeCenter (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; VARIANT ( real )
Column coordinate of the center of the edge pair.
. FuzzyScore (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Fuzzy evaluation of the edge pair.
. IntraDistance (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Distance between edges of an edge pair.
. InterDistance (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Distance between consecutive edge pairs.
Result
If the parameter values are correct the operator FuzzyMeasurePairs returns the value TRUE. Otherwise an
exception handling is raised.
Parallelization Information
FuzzyMeasurePairs is reentrant and processed without parallelization.
Possible Predecessors
GenMeasureRectangle2, GenMeasureArc, SetFuzzyMeasure
Possible Successors
CloseMeasure
See also
FuzzyMeasurePos, MeasurePos
Alternatives
EdgesSubPix, FuzzyMeasurePairing, MeasurePairs
Module
1D Metrology

[out] VARIANT RowEdge HImageX.FuzzyMeasurePos ([in] long MeasureHandle,


[in] double Sigma, [in] double AmpThresh, [in] double FuzzyThresh,
[in] String Transition, [out] VARIANT ColumnEdge, [out] VARIANT Amplitude,
[out] VARIANT FuzzyScore, [out] VARIANT Distance )
[out] VARIANT RowEdge HMeasureX.FuzzyMeasurePos ([in] HImageX Image,
[in] double Sigma, [in] double AmpThresh, [in] double FuzzyThresh,
[in] String Transition, [out] VARIANT ColumnEdge, [out] VARIANT Amplitude,
[out] VARIANT FuzzyScore, [out] VARIANT Distance )
void HOperatorSetX.FuzzyMeasurePos ([in] IHObjectX Image,
[in] VARIANT MeasureHandle, [in] VARIANT Sigma, [in] VARIANT AmpThresh,
[in] VARIANT FuzzyThresh, [in] VARIANT Transition, [out] VARIANT RowEdge,
[out] VARIANT ColumnEdge, [out] VARIANT Amplitude, [out] VARIANT FuzzyScore,
[out] VARIANT Distance )

Extract straight edges perpendicular to a rectangle or an annular arc.


FuzzyMeasurePos extracts straight edges which lie perpendicular to the major axis of a rectangle or an annular
arc. In addition to MeasurePos it uses fuzzy member functions to evaluate and select the edges.
The algorithm works by averaging the gray values in “slices” perpendicular to the major axis of the rectangle or
annular arc in order to obtain a one-dimensional edge profile. The sampling is done at subpixel positions in the

HALCON/COM Reference Manual, 2008-5-13


15.14. MEASURE 1267

image Image at integer row and column distances (in the coordinate frame of the rectangle) from the center of
the rectangle. Since this involves some calculations which can be used repeatedly in several mesurements, the op-
erator GenMeasureRectangle2 is used to perform these calculations only once, thus increasing the speed of
FuzzyMeasurePos significantly. Since there is a trade-off between accuracy and speed in the subpixel calcula-
tions of the gray values, and thus in the accuracy of the extracted edge positions, different interpolation schemes
can be selected in GenMeasureRectangle2. (The interpolation only influences rectangles not aligned with
the image axesand annular arcs.) The measure object generated with GenMeasureRectangle2 is passed in
MeasureHandle.
After the one-dimensional edge profile has been calculated, subpixel edge locations are computed by convolving
the profile with the derivatives of a Gaussian smoothing kernel of standard deviation Sigma. Salient edges can be
selected with the parameter AmpThresh, which constitutes a threshold on the amplitude, i.e., the absolute value of
the first derivative of the edge. Additionally, it is possible to select only positive edges, i.e., edges which constitute
a dark-to-light transition in the direction of the major axis of the rectangle (Transition = ’positive’), only
negative edges, i.e., light-to-dark transitions (Transition = ’negative’), or both types of edges (Transition
= ’all’). Finally, it is possible to select which edge points are returned.
Having extracted subpixel edge locations, features of these edges are evaluated by a corresponding fuzzy function,
which can be set by SetFuzzyMeasure. Which edges are selected can be determined with the parameter
FuzzyThresh, which constitutes a threshold on the weight over all fuzzy sets, i.e., the geometric mean of the
weights of the defined sets.
The selected edges are returned as single points, which lie on the major axis of the rectangle or annular arc, in
(RowEdge,ColumnEdge). The corresponding edge amplitudes are returned in Amplitude, the fuzzy scores
in FuzzyScore. In addition, the distance between consecutive edge points is returned in Distance. Here,
Distance[i] corresponds to the distance between Edge[i] and Edge[i+1], i.e., the tuple Distance contains one
element less than the tuples RowEdge and ColumnEdge.
Attention
FuzzyMeasurePos only returns meaningful results if the assumptions that the edges are straight and perpen-
dicular to the major axis of the rectangle are fulfilled. Thus, it should not be used to extract edges from curved
objects, for example. Furthermore, the user should ensure that the rectangle is as close to perpendicular as possible
to the edges in the image. Additionally, Sigma must not become larger than approx. 0.5 * Length1 (for Length1
see GenMeasureRectangle2).
It should be kept in mind that FuzzyMeasurePos ignores the domain of Image for efficiency reasons. If
certain regions in the image should be excluded from the measurement a new measure object with appropriately
modified parameters should be generated.
Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, uint2 )


Input image.
. MeasureHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . measure_id ; long / HMeasureX / VARIANT
Measure object handle.
. Sigma (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Sigma of Gaussian smoothing.
Default Value : 1.0
Suggested values : Sigma ∈ {0.4, 0.6, 0.8, 1.0, 1.5, 2.0, 3.0, 4.0, 5.0, 7.0, 10.0}
Typical range of values : 0.4 ≤ Sigma ≤ 0.4(lin)
Minimum Increment : 0.01
Recommended Increment : 0.1
Restriction : (Sigma ≥ 0.4)
. AmpThresh (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Minimum edge amplitude.
Default Value : 30.0
Suggested values : AmpThresh ∈ {5.0, 10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 90.0, 110.0}
Typical range of values : 1 ≤ AmpThresh ≤ 1(lin)
Minimum Increment : 2
Recommended Increment : 0.5

HALCON 8.0.2
1268 CHAPTER 15. TOOLS

. FuzzyThresh (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT


Minimum fuzzy value.
Default Value : 0.5
Suggested values : FuzzyThresh ∈ {0.1, 0.3, 0.5, 0.6, 0.7, 0.9}
Typical range of values : 0.0 ≤ FuzzyThresh ≤ 0.0(lin)
Recommended Increment : 0.1
. Transition (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Select light/dark or dark/light edges.
Default Value : ’all’
List of values : Transition ∈ {’all’, ’positive’, ’negative’}
. RowEdge (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; VARIANT ( real )
Row coordinate of the edge point.
. ColumnEdge (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; VARIANT ( real )
Column coordinate of the edge point.
. Amplitude (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Edge amplitude of the edge (with sign).
. FuzzyScore (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Fuzzy evaluation of the edges.
. Distance (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Distance between consecutive edges.
Result
If the parameter values are correct the operator FuzzyMeasurePos returns the value TRUE. Otherwise an
exception handling is raised.
Parallelization Information
FuzzyMeasurePos is reentrant and processed without parallelization.
Possible Predecessors
GenMeasureRectangle2, GenMeasureArc, SetFuzzyMeasure
Possible Successors
CloseMeasure
See also
FuzzyMeasurePairing, FuzzyMeasurePairs, MeasurePairs
Alternatives
EdgesSubPix, MeasurePos
Module
1D Metrology

void HMeasureX.GenMeasureArc ([in] VARIANT CenterRow,


[in] VARIANT CenterCol, [in] VARIANT Radius, [in] VARIANT AngleStart,
[in] VARIANT AngleExtent, [in] VARIANT AnnulusRadius, [in] long Width,
[in] long Height, [in] String Interpolation )
void HOperatorSetX.GenMeasureArc ([in] VARIANT CenterRow,
[in] VARIANT CenterCol, [in] VARIANT Radius, [in] VARIANT AngleStart,
[in] VARIANT AngleExtent, [in] VARIANT AnnulusRadius, [in] VARIANT Width,
[in] VARIANT Height, [in] VARIANT Interpolation,
[out] VARIANT MeasureHandle )

Prepare the extraction of straight edges perpendicular to an annular arc.


GenMeasureArc prepares the extraction of straight edges which lie perpendicular to an annular arc. Here,
annular arc denotes a circular arc with an associated width. The center of the arc is passed in the parameters
CenterRow and CenterCol, its radius in Radius, the starting angle in AngleStart, and its angular extent
relative to the starting angle in AngleExtent. If AngleExtent > 0, an arc with counterclockwise orientation
is generated, otherwise an arc with clockwise orientation. The radius of the annular arc, i.e., half its width, is
determined by AnnulusRadius.

HALCON/COM Reference Manual, 2008-5-13


15.14. MEASURE 1269

The edge extraction algorithm is described in the documentation of the operator MeasurePos. As discussed
there, different types of interpolation can be used for the calculation of the one-dimensional gray value profile. For
Interpolation = ’nearest_neighbor’, the gray values in the measurement are obtained from the gray values of
the closest pixel, i.e., by constant interpolation. For Interpolation = ’bilinear’, bilinear interpolation is used,
while for Interpolation = ’bicubic’, bicubic interpolation is used.
To perform the actual measurement at optimal speed, all computations that can be used for multiple measurements
are already performed in the operator GenMeasureArc. For this, an optimized data structure, a so-called
measure object, is constructed and returned in MeasureHandle. The size of the images in which measurements
will be performed must be specified in the parameters Width and Height.
The system parameter ’int_zooming’ (see SetSystem) affects the accuracy and speed of the calculations used to
construct the measure object. If ’int_zooming’ is set to ’true’, the internal calculations are performed using fixed
point arithmetic, leading to much shorter execution times. However, the geometric accuracy is slightly lower in
this mode. If ’int_zooming’ is set to ’false’, the internal calculations are performed using floating point arithmetic,
leading to the maximum geometric accuracy, but also to significantly increased execution times.
Attention
Note that when using bilinear or bicubic interpolation, not only the measurement rectangle but additionally the
margin around the rectangle must fit into the image. The width of the margin (in all four directions) must be at
least one pixel for bilinear interpolation and two pixels for bicubic interpolation. For projection lines that do not
fulfill this condition, no gray value is computed. Thus, no edge can be extracted at these positions.
Parameter

. CenterRow (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; VARIANT ( integer, real )


Row coordinate of the center of the arc.
Default Value : 100.0
Suggested values : CenterRow ∈ {10.0, 20.0, 50.0, 100.0, 200.0, 300.0, 400.0, 500.0}
Typical range of values : 0.0 ≤ CenterRow ≤ 0.0(lin)
Minimum Increment : 1.0
Recommended Increment : 10.0
. CenterCol (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; VARIANT ( integer, real )
Column coordinate of the center of the arc.
Default Value : 100.0
Suggested values : CenterCol ∈ {10.0, 20.0, 50.0, 100.0, 200.0, 300.0, 400.0, 500.0}
Typical range of values : 0.0 ≤ CenterCol ≤ 0.0(lin)
Minimum Increment : 1.0
Recommended Increment : 10.0
. Radius (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Radius of the arc.
Default Value : 50.0
Suggested values : Radius ∈ {10.0, 20.0, 50.0, 100.0, 200.0, 300.0, 400.0, 500.0}
Typical range of values : 0.0 ≤ Radius ≤ 0.0(lin)
Minimum Increment : 1.0
Recommended Increment : 10.0
. AngleStart (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; VARIANT ( integer, real )
Start angle of the arc in radians.
Default Value : 0.0
Suggested values : AngleStart ∈ {-3.14159, -2.35619, -1.57080, -0.78540, 0.0, 0.78540, 1.57080,
2.35619, 3.14159}
Typical range of values : -3.14159 ≤ AngleStart ≤ -3.14159(lin)
Minimum Increment : 0.03142
Recommended Increment : 0.31416
. AngleExtent (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.rad ; VARIANT ( integer, real )
Angular extent of the arc in radians.
Default Value : 6.28318
Suggested values : AngleExtent ∈ {-6.28318, -5.49779, -4.71239, -3.92699, -3.14159, -2.35619,

HALCON 8.0.2
1270 CHAPTER 15. TOOLS

-1.57080, -0.78540, 0.78540, 1.57080, 2.35619, 3.14159, 3.92699, 4.71239, 5.49779, 6.28318}
Typical range of values : -6.28318 ≤ AngleExtent ≤ -6.28318(lin)
Minimum Increment : 0.03142
Recommended Increment : 0.31416
Restriction : (AngleExtent 6= 0.0)
. AnnulusRadius (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Radius (half width) of the annulus.
Default Value : 10.0
Suggested values : AnnulusRadius ∈ {10.0, 20.0, 50.0, 100.0, 200.0, 300.0, 400.0, 500.0}
Typical range of values : 0.0 ≤ AnnulusRadius ≤ 0.0(lin)
Minimum Increment : 1.0
Recommended Increment : 10.0
Restriction : (AnnulusRadius ≤ Radius)
. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; long / VARIANT
Width of the image to be processed subsequently.
Default Value : 512
Suggested values : Width ∈ {128, 160, 192, 256, 320, 384, 512, 640, 768}
Typical range of values : 0 ≤ Width ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 16
. Height (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; long / VARIANT
Height of the image to be processed subsequently.
Default Value : 512
Suggested values : Height ∈ {120, 128, 144, 240, 256, 288, 480, 512, 576}
Typical range of values : 0 ≤ Height ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 16
. Interpolation (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Type of interpolation to be used.
Default Value : ’nearest_neighbor’
List of values : Interpolation ∈ {’nearest_neighbor’, ’bilinear’, ’bicubic’}
. MeasureHandle (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . measure_id ; HMeasureX / VARIANT
Measure object handle.
Result
If the parameter values are correct, the operator GenMeasureArc returns the value TRUE. Otherwise an excep-
tion handling is raised.
Parallelization Information
GenMeasureArc is reentrant and processed without parallelization.
Possible Predecessors
DrawCircle
Possible Successors
MeasurePos, MeasurePairs, FuzzyMeasurePos, FuzzyMeasurePairs,
FuzzyMeasurePairing
See also
GenMeasureRectangle2
Alternatives
EdgesSubPix
Module
1D Metrology

HALCON/COM Reference Manual, 2008-5-13


15.14. MEASURE 1271

void HMeasureX.GenMeasureRectangle2 ([in] VARIANT Row,


[in] VARIANT Column, [in] VARIANT Phi, [in] VARIANT Length1,
[in] VARIANT Length2, [in] long Width, [in] long Height,
[in] String Interpolation )
void HOperatorSetX.GenMeasureRectangle2 ([in] VARIANT Row,
[in] VARIANT Column, [in] VARIANT Phi, [in] VARIANT Length1,
[in] VARIANT Length2, [in] VARIANT Width, [in] VARIANT Height,
[in] VARIANT Interpolation, [out] VARIANT MeasureHandle )

Prepare the extraction of straight edges perpendicular to a rectangle.


GenMeasureRectangle2 prepares the extraction of straight edges which lie perpendicular to the major axis
of a rectangle. The center of the rectangle is passed in the parameters Row and Column, the direction of the major
axis of the rectangle in Phi, and the length of the two axes, i.e., half the diameter of the rectangle, in Length1
and Length2.
The edge extraction algorithm is described in the documentation of the operator MeasurePos. As discussed
there, different types of interpolation can be used for the calculation of the one-dimensional gray value profile. For
Interpolation = ’nearest_neighbor’, the gray values in the measurement are obtained from the gray values of
the closest pixel, i.e., by constant interpolation. For Interpolation = ’bilinear’, bilinear interpolation is used,
while for Interpolation = ’bicubic’, bicubic interpolation is used.
To perform the actual measurement at optimal speed, all computations that can be used for multiple measurements
are already performed in the operator GenMeasureRectangle2. For this, an optimized data structure, a
so-called measure object, is constructed and returned in MeasureHandle. The size of the images in which
measurements will be performed must be specified in the parameters Width and Height.
The system parameter ’int_zooming’ (see SetSystem) affects the accuracy and speed of the calculations used to
construct the measure object. If ’int_zooming’ is set to ’true’, the internal calculations are performed using fixed
point arithmetic, leading to much shorter execution times. However, the geometric accuracy is slightly lower in
this mode. If ’int_zooming’ is set to ’false’, the internal calculations are performed using floating point arithmetic,
leading to the maximum geometric accuracy, but also to significantly increased execution times.
Attention
Note that when using bilinear or bicubic interpolation, not only the measurement rectangle but additionally the
margin around the rectangle must fit into the image. The width of the margin (in all four directions) must be at
least one pixel for bilinear interpolation and two pixels for bicubic interpolation. For projection lines that do not
fulfill this condition, no gray value is computed. Thus, no edge can be extracted at these positions.
Parameter
. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle2.center.y ; VARIANT ( integer, real )
Row coordinate of the center of the rectangle.
Default Value : 50.0
Suggested values : Row ∈ {10.0, 20.0, 50.0, 100.0, 200.0, 300.0, 400.0, 500.0}
Typical range of values : 0.0 ≤ Row ≤ 0.0(lin)
Minimum Increment : 1.0
Recommended Increment : 10.0
. Column (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle2.center.x ; VARIANT ( integer, real )
Column coordinate of the center of the rectangle.
Default Value : 100.0
Suggested values : Column ∈ {10.0, 20.0, 50.0, 100.0, 200.0, 300.0, 400.0, 500.0}
Typical range of values : 0.0 ≤ Column ≤ 0.0(lin)
Minimum Increment : 1.0
Recommended Increment : 10.0
. Phi (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle2.angle.rad ; VARIANT ( integer, real )
Angle of longitudinal axis of the rectangle to horizontal (radians).
Default Value : 0.0
Suggested values : Phi ∈ {-1.178097, -0.785398, -0.392699, 0.0, 0.392699, 0.785398, 1.178097}
Typical range of values : -1.178097 ≤ Phi ≤ -1.178097(lin)
Minimum Increment : 0.001
Recommended Increment : 0.1
Restriction : ((−(pi) < P hi) ∧ (P hi ≤ pi))

HALCON 8.0.2
1272 CHAPTER 15. TOOLS

. Length1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle2.hwidth ; VARIANT ( integer, real )


Half width of the rectangle.
Default Value : 200.0
Suggested values : Length1 ∈ {3.0, 5.0, 10.0, 15.0, 20.0, 50.0, 100.0, 200.0, 300.0, 500.0}
Typical range of values : 0.0 ≤ Length1 ≤ 0.0(lin)
Minimum Increment : 1.0
Recommended Increment : 10.0
. Length2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . rectangle2.hheight ; VARIANT ( integer, real )
Half height of the rectangle.
Default Value : 100.0
Suggested values : Length2 ∈ {1.0, 2.0, 3.0, 5.0, 10.0, 15.0, 20.0, 50.0, 100.0, 200.0}
Typical range of values : 0.0 ≤ Length2 ≤ 0.0(lin)
Minimum Increment : 1.0
Recommended Increment : 10.0
Restriction : (Length2 ≤ Length1)
. Width (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.x ; long / VARIANT
Width of the image to be processed subsequently.
Default Value : 512
Suggested values : Width ∈ {128, 160, 192, 256, 320, 384, 512, 640, 768}
Typical range of values : 0 ≤ Width ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 16
. Height (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . extent.y ; long / VARIANT
Height of the image to be processed subsequently.
Default Value : 512
Suggested values : Height ∈ {120, 128, 144, 240, 256, 288, 480, 512, 576}
Typical range of values : 0 ≤ Height ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 16
. Interpolation (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Type of interpolation to be used.
Default Value : ’nearest_neighbor’
List of values : Interpolation ∈ {’nearest_neighbor’, ’bilinear’, ’bicubic’}
. MeasureHandle (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . measure_id ; HMeasureX / VARIANT
Measure object handle.
Result
If the parameter values are correct the operator GenMeasureRectangle2 returns the value TRUE. Otherwise
an exception handling is raised.
Parallelization Information
GenMeasureRectangle2 is reentrant and processed without parallelization.
Possible Predecessors
DrawRectangle2
Possible Successors
MeasurePos, MeasurePairs, FuzzyMeasurePos, FuzzyMeasurePairs,
FuzzyMeasurePairing, MeasureThresh
See also
GenMeasureArc
Alternatives
EdgesSubPix
Module
1D Metrology

HALCON/COM Reference Manual, 2008-5-13


15.14. MEASURE 1273

[out] VARIANT RowEdgeFirst HImageX.MeasurePairs


([in] long MeasureHandle, [in] double Sigma, [in] double Threshold,
[in] String Transition, [in] String Select, [out] VARIANT ColumnEdgeFirst,
[out] VARIANT AmplitudeFirst, [out] VARIANT RowEdgeSecond,
[out] VARIANT ColumnEdgeSecond, [out] VARIANT AmplitudeSecond,
[out] VARIANT IntraDistance, [out] VARIANT InterDistance )
[out] VARIANT RowEdgeFirst HMeasureX.MeasurePairs ([in] HImageX Image,
[in] double Sigma, [in] double Threshold, [in] String Transition,
[in] String Select, [out] VARIANT ColumnEdgeFirst,
[out] VARIANT AmplitudeFirst, [out] VARIANT RowEdgeSecond,
[out] VARIANT ColumnEdgeSecond, [out] VARIANT AmplitudeSecond,
[out] VARIANT IntraDistance, [out] VARIANT InterDistance )
void HOperatorSetX.MeasurePairs ([in] IHObjectX Image,
[in] VARIANT MeasureHandle, [in] VARIANT Sigma, [in] VARIANT Threshold,
[in] VARIANT Transition, [in] VARIANT Select, [out] VARIANT RowEdgeFirst,
[out] VARIANT ColumnEdgeFirst, [out] VARIANT AmplitudeFirst,
[out] VARIANT RowEdgeSecond, [out] VARIANT ColumnEdgeSecond,
[out] VARIANT AmplitudeSecond, [out] VARIANT IntraDistance,
[out] VARIANT InterDistance )

Extract straight edge pairs perpendicular to a rectangle or annular arc.


MeasurePairs serves to extract straight edge pairs which lie perpendicular to the major axis of a rectangle or
annular arc.
The extraction algorithm is identical to MeasurePos. In addition the edges are grouped to pairs: If
Transition = ’positive’, the edge points with a dark-to-light transition in the direction of the major axis of
the rectangle are returned in RowEdgeFirst and ColumnEdgeFirst. In this case, the corresponding edges
with a light-to-dark transition are returned in RowEdgeSecond and ColumnEdgeSecond. If Transition =
’negative’, the behavior is exactly opposite. If Transition = ’all’, the first detected edge defines the transition
for RowEdgeFirst and ColumnEdgeFirst. I.e., dependent on the positioning of the measure object, edge
pairs with a light-dark-light transition or edge pairs with a dark-light-dark transition are returned. This is suited,
e.g., to measure objects with different brightness relative to the background.
If more than one consecutive edge with the same transition is found, the first one is used as a pair element. This
behavior may cause problems in applications in which the threshold Threshold cannot be selected high enough
to suppress consecutive edges of the same transition. For these applications, a second pairing mode exists that only
selects the respective strongest edges of a sequence of consecutive rising and falling edges. This mode is selected
by appending ’_strongest’ to any of the above modes for Transition, e.g., ’negative_strongest’. Finally, it is
possible to select which edge pairs are returned. If Select is set to ’all’, all edge pairs are returned. If it is set to
’first’, only the first of the extracted edge pairs is returned, while it is set to ’last’, only the last one is returned.
The extracted edges are returned as single points which lie on the major axis of the rectangle. The corresponding
edge amplitudes are returned in AmplitudeFirst and AmplitudeSecond. In addition, the distance between
each edge pair is returned in IntraDistance and the distance between consecutive edge pairs is returned
in InterDistance. Here, IntraDistance[i] corresponds to the distance between EdgeFirst[i] and EdgeSec-
ond[i], while InterDistance[i] corresponds to the distance between EdgeSecond[i] and EdgeFirst[i+1], i.e., the
tuple InterDistance contains one element less than the tuples of the edge pairs.
Attention
MeasurePairs only returns meaningful results if the assumptions that the edges are straight and perpendicular
to the major axis of the rectangle are fulfilled. Thus, it should not be used to extract edges from curved objects,
for example. Furthermore, the user should ensure that the rectangle is as close to perpendicular as possible to the
edges in the image. Additionally, Sigma must not become larger than approx. 0.5 * Length1 (for Length1 see
GenMeasureRectangle2).
It should be kept in mind that MeasurePairs ignores the domain of Image for efficiency reasons. If certain
regions in the image should be excluded from the measurement a new measure object with appropriately modified
parameters should be generated.

HALCON 8.0.2
1274 CHAPTER 15. TOOLS

Parameter
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, uint2 )
Input image.
. MeasureHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . measure_id ; long / HMeasureX / VARIANT
Measure object handle.
. Sigma (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Sigma of gaussian smoothing.
Default Value : 1.0
Suggested values : Sigma ∈ {0.4, 0.6, 0.8, 1.0, 1.5, 2.0, 3.0, 4.0, 5.0, 7.0, 10.0}
Typical range of values : 0.4 ≤ Sigma ≤ 0.4(lin)
Minimum Increment : 0.01
Recommended Increment : 0.1
Restriction : (Sigma ≥ 0.4)
. Threshold (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Minimum edge amplitude.
Default Value : 30.0
Suggested values : Threshold ∈ {5.0, 10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 90.0, 110.0}
Typical range of values : 1 ≤ Threshold ≤ 1(lin)
Minimum Increment : 0.5
Recommended Increment : 2
. Transition (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Type of gray value transition that determines how edges are grouped to edge pairs.
Default Value : ’all’
List of values : Transition ∈ {’all’, ’positive’, ’negative’, ’all_strongest’, ’positive_strongest’,
’negative_strongest’}
. Select (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Selection of edge pairs.
Default Value : ’all’
List of values : Select ∈ {’all’, ’first’, ’last’}
. RowEdgeFirst (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; VARIANT ( real )
Row coordinate of the center of the first edge.
. ColumnEdgeFirst (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; VARIANT ( real )
Column coordinate of the center of the first edge.
. AmplitudeFirst (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Edge amplitude of the first edge (with sign).
. RowEdgeSecond (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; VARIANT ( real )
Row coordinate of the center of the second edge.
. ColumnEdgeSecond (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; VARIANT ( real )
Column coordinate of the center of the second edge.
. AmplitudeSecond (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Edge amplitude of the second edge (with sign).
. IntraDistance (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Distance between edges of an edge pair.
. InterDistance (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Distance between consecutive edge pairs.
Result
If the parameter values are correct the operator MeasurePairs returns the value TRUE. Otherwise an exception
handling is raised.
Parallelization Information
MeasurePairs is reentrant and processed without parallelization.
Possible Predecessors
GenMeasureRectangle2
Possible Successors
CloseMeasure
See also
MeasurePos, FuzzyMeasurePos

HALCON/COM Reference Manual, 2008-5-13


15.14. MEASURE 1275

Alternatives
EdgesSubPix, FuzzyMeasurePairs, FuzzyMeasurePairing
Module
1D Metrology

[out] VARIANT RowEdge HImageX.MeasurePos ([in] long MeasureHandle,


[in] double Sigma, [in] double Threshold, [in] String Transition,
[in] String Select, [out] VARIANT ColumnEdge, [out] VARIANT Amplitude,
[out] VARIANT Distance )
[out] VARIANT RowEdge HMeasureX.MeasurePos ([in] HImageX Image,
[in] double Sigma, [in] double Threshold, [in] String Transition,
[in] String Select, [out] VARIANT ColumnEdge, [out] VARIANT Amplitude,
[out] VARIANT Distance )
void HOperatorSetX.MeasurePos ([in] IHObjectX Image,
[in] VARIANT MeasureHandle, [in] VARIANT Sigma, [in] VARIANT Threshold,
[in] VARIANT Transition, [in] VARIANT Select, [out] VARIANT RowEdge,
[out] VARIANT ColumnEdge, [out] VARIANT Amplitude, [out] VARIANT Distance )

Extract straight edges perpendicular to a rectangle or annular arc.


MeasurePos extracts straight edges which lie perpendicular to the major axis of a rectangle or annular arc.
The algorithm works by averaging the gray values in “slices” perpendicular to the major axis of the rectangle or
annular arc in order to obtain a one-dimensional edge profile. The sampling is done at subpixel positions in the
image Image at integer row and column distances (in the coordinate frame of the rectangle) from the center of
the rectangle. Since this involves some calculations which can be used repeatedly in several mesurements, the
operator GenMeasureRectangle2 or GenMeasureArc is used to perform these calculations only once,
thus increasing the speed of MeasurePos significantly. Since there is a trade-off between accuracy and speed
in the subpixel calculations of the gray values, and thus in the accuracy of the extracted edge positions, different
interpolation schemes can be selected in GenMeasureRectangle2. (The interpolation only influences rectan-
gles not aligned with the image axes.) The measure object generated with GenMeasureRectangle2 is passed
in MeasureHandle.
After the one-dimensional edge profile has been calculated, subpixel edge locations are computed by convolving
the profile with the derivatives of a Gaussian smoothing kernel of standard deviation Sigma. Salient edges can
be selected with the parameter Threshold, which constitutes a threshold on the amplitude, i.e., the absolute
value of the first derivative of the edge. Additionally, it is possible to select only positive edges, i.e., edges which
constitute a dark-to-light transition in the direction of the major axis of the rectangle or the arc (Transition =
’positive’), only negative edges, i.e., light-to-dark transitions (Transition = ’negative’), or both types of edges
(Transition = ’all’). Finally, it is possible to select which edge points are returned. If Select is set to ’all’,
all edge points are returned. If it is set to ’first’, only the first of the extracted edge points is returned, while it is set
to ’last’, only the last one is returned.
The extracted edges are returned as single points which lie on the major axis of the rectangle or arc in
(RowEdge,ColumnEdge). The corresponding edge amplitudes are returned in Amplitude. In addition, the
distance between consecutive edge points is returned in Distance. Here, Distance[i] corresponds to the distance
between Edge[i] and Edge[i+1], i.e., the tuple Distance contains one element less than the tuples RowEdge and
ColumnEdge.
Attention
MeasurePos only returns meaningful results if the assumptions that the edges are straight and perpendicular to
the major axis of the rectangle or arc are fulfilled. Thus, it should not be used to extract edges from curved objects,
for example. Furthermore, the user should ensure that the rectangle or arc is as close to perpendicular as possible
to the edges in the image. Additionally, Sigma must not become larger than approx. 0.5 * Length1 (for Length1
see GenMeasureRectangle2).
It should be kept in mind that MeasurePos ignores the domain of Image for efficiency reasons. If certain
regions in the image should be excluded from the measurement a new measure object with appropriately modified
parameters should be generated.

HALCON 8.0.2
1276 CHAPTER 15. TOOLS

Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, uint2 )


Input image.
. MeasureHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . measure_id ; long / HMeasureX / VARIANT
Measure object handle.
. Sigma (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Sigma of gaussian smoothing.
Default Value : 1.0
Suggested values : Sigma ∈ {0.4, 0.6, 0.8, 1.0, 1.5, 2.0, 3.0, 4.0, 5.0, 7.0, 10.0}
Typical range of values : 0.4 ≤ Sigma ≤ 0.4(lin)
Minimum Increment : 0.01
Recommended Increment : 0.1
Restriction : (Sigma ≥ 0.4)
. Threshold (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Minimum edge amplitude.
Default Value : 30.0
Suggested values : Threshold ∈ {5.0, 10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 90.0, 110.0}
Typical range of values : 1 ≤ Threshold ≤ 1(lin)
Minimum Increment : 2
Recommended Increment : 0.5
. Transition (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Light/dark or dark/light edge.
Default Value : ’all’
List of values : Transition ∈ {’all’, ’positive’, ’negative’}
. Select (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Selection of end points.
Default Value : ’all’
List of values : Select ∈ {’all’, ’first’, ’last’}
. RowEdge (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; VARIANT ( real )
Row coordinate of the center of the edge.
. ColumnEdge (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; VARIANT ( real )
Column coordinate of the center of the edge.
. Amplitude (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Edge amplitude of the edge (with sign).
. Distance (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Distance between consecutive edges.
Result
If the parameter values are correct the operator MeasurePos returns the value TRUE. Otherwise an exception
handling is raised.
Parallelization Information
MeasurePos is reentrant and processed without parallelization.
Possible Predecessors
GenMeasureRectangle2
Possible Successors
CloseMeasure
See also
MeasurePairs, FuzzyMeasurePairs, FuzzyMeasurePairing
Alternatives
EdgesSubPix, FuzzyMeasurePos
Module
1D Metrology

HALCON/COM Reference Manual, 2008-5-13


15.14. MEASURE 1277

[out] VARIANT GrayValues HImageX.MeasureProjection


([in] long MeasureHandle )
[out] VARIANT GrayValues HMeasureX.MeasureProjection
([in] HImageX Image )
void HOperatorSetX.MeasureProjection ([in] IHObjectX Image,
[in] VARIANT MeasureHandle, [out] VARIANT GrayValues )

Extract a gray value profile perpendicular to a rectangle or annular arc.


MeasureProjection extracts a one-dimensional gray value profile perpendicular to a rectangle or annular arc.
This is done by averaging the gray values in “slices” perpendicular to the major axis of the rectangle or arc. The
sampling is done at subpixel positions in the image Image at integer row and column distances (in the coordinate
frame of the rectangle) from the center of the rectangle. Since this involves some calculations which can be used
repeatedly in several projections, the operator GenMeasureRectangle2 is used to perform these calculations
only once, thus increasing the speed of MeasureProjection significantly. Since there is a trade-off between
accuracy and speed in the subpixel calculations of the gray values, different interpolation schemes can be selected
in GenMeasureRectangle2 (the interpolation only influences rectangles not aligned with the image axes).
The measure object generated with GenMeasureRectangle2 is passed in MeasureHandle.
Attention
It should be kept in mind that MeasureProjection ignores the domain of Image for efficiency reasons. If
certain regions in the image should be excluded from the measurement a new measure object with appropriately
modified parameters should be generated.
Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, uint2 )


Input image.
. MeasureHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . measure_id ; long / HMeasureX / VARIANT
Measure object handle.
. GrayValues (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real )
Gray value profile.
Result
If the parameter values are correct the operator MeasureProjection returns the value TRUE. Otherwise an
exception handling is raised.
Parallelization Information
MeasureProjection is reentrant and processed without parallelization.
Possible Predecessors
GenMeasureRectangle2
Possible Successors
CloseMeasure
Alternatives
GrayProjections
Module
1D Metrology

HALCON 8.0.2
1278 CHAPTER 15. TOOLS

[out] VARIANT RowThresh HImageX.MeasureThresh ([in] long MeasureHandle,


[in] double Sigma, [in] double Threshold, [in] String Select,
[out] VARIANT ColumnThresh, [out] VARIANT Distance )
[out] VARIANT RowThresh HMeasureX.MeasureThresh ([in] HImageX Image,
[in] double Sigma, [in] double Threshold, [in] String Select,
[out] VARIANT ColumnThresh, [out] VARIANT Distance )
void HOperatorSetX.MeasureThresh ([in] IHObjectX Image,
[in] VARIANT MeasureHandle, [in] VARIANT Sigma, [in] VARIANT Threshold,
[in] VARIANT Select, [out] VARIANT RowThresh, [out] VARIANT ColumnThresh,
[out] VARIANT Distance )

Extracting points with a particular grey value along a rectangle or an annular arc.
MeasureThresh extracts points for which the gray value within an one-dimensional gray value profile is equal
to the specified threshold Threshold. The gray value profile is projected onto the major axis of the measure
rectangle which is passed with the parameter MeasureHandle, so the threshold points calculated within the
gray value profile correspond to certain image coordinates on the rectangle’s major axis. These coordinates are
returned as the operator results in RowThresh and ColumnThresh.
If the gray value profile intersects the threshold line for several times, the parameter Select determines which
values to return. Possible settings are ’first’, ’last’, ’first_last’ (first and last) or ’all’. For the last two cases
Distance returns the distances between the calculated points.
The gray value profile is created by averaging the gray values along all line segments, which are defined by the
measure rectangle as follows:

1. The segments are perpendicular to the major axis of the rectangle,


2. they have an integer distance to the center of the rectangle,
3. the rectangle bounds the segments.

For every line segment, the average of the gray values of all points with an integer distance to the major axis is
calculated. Due to translation and rotation of the measure rectangle with respect to the image coordinates the input
image Image is in general sampled at subpixel positions.
Since this involves some calculations which can be used repeatedly in several projections, the operator
GenMeasureRectangle2 is used to perform these calculations only once in advance. Here, the measure
object MeasureHandle is generated and different interpolation schemes can be selected.
Attention
MeasureThresh only returns meaningful results if the assumptions that the edges are straight and perpendicular
to the major axis of the rectangle are fulfilled. Thus, it should not be used to extract edges from curved objects,
for example. Furthermore, the user should ensure that the rectangle is as close to perpendicular as possible to the
edges in the image. Additionally, Sigma must not become larger than approx. 0.5 * Length1 (for Length1 see
GenMeasureRectangle2).
It should be kept in mind that MeasureThresh ignores the domain of Image for efficiency reasons. If certain
regions in the image should be excluded from the measurement a new measure object with appropriately modified
parameters should be generated.
Parameter
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, uint2 )
Input image.
. MeasureHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . measure_id ; long / HMeasureX / VARIANT
Measure object handle.
. Sigma (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Sigma of gaussian smoothing.
Default Value : 1.0
Suggested values : Sigma ∈ {0.0, 0.4, 0.6, 0.8, 1.0, 1.5, 2.0, 3.0, 4.0, 5.0, 7.0, 10.0}
Typical range of values : 0.4 ≤ Sigma ≤ 0.4(lin)
Minimum Increment : 0.01
Recommended Increment : 0.1
Restriction : (Sigma ≥ 0.0)

HALCON/COM Reference Manual, 2008-5-13


15.14. MEASURE 1279

. Threshold (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT


Threshold.
Default Value : 128.0
Typical range of values : 0 ≤ Threshold ≤ 0(lin)
Minimum Increment : 1
Recommended Increment : 0.5
. Select (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Selection of points.
Default Value : ’all’
List of values : Select ∈ {’all’, ’first’, ’last’, ’first_last’}
. RowThresh (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; VARIANT ( real )
Row coordinates of points with threshold value.
. ColumnThresh (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; VARIANT ( real )
Column coordinates of points with threshold value.
. Distance (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Distance between consecutive points.
Result
If the parameter values are correct the operator MeasureThresh returns the value TRUE. Otherwise, an excep-
tion handling is raised.
Parallelization Information
MeasureThresh is reentrant and processed without parallelization.
Possible Predecessors
GenMeasureRectangle2
Possible Successors
CloseMeasure
Alternatives
MeasurePos, EdgesSubPix, MeasurePairs
Module
1D Metrology

void HMeasureX.ResetFuzzyMeasure ([in] String SetType )


void HOperatorSetX.ResetFuzzyMeasure ([in] VARIANT MeasureHandle,
[in] VARIANT SetType )

Reset a fuzzy member function.


ResetFuzzyMeasure discards a fuzzy member function of the fuzzy set SetType. This member function
should have been set by SetFuzzyMeasure before.
Parameter
. MeasureHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . measure_id ; HMeasureX / VARIANT
Measure object handle.
. SetType (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Selection of the fuzzy set.
Default Value : ’contrast’
List of values : SetType ∈ {’position’, ’position_pair’, ’size’, ’gray’, ’contrast’}
Parallelization Information
ResetFuzzyMeasure is reentrant and processed without parallelization.
Possible Predecessors
SetFuzzyMeasure
Possible Successors
FuzzyMeasurePos, FuzzyMeasurePairs
See also
SetFuzzyMeasure, SetFuzzyMeasureNormPair

HALCON 8.0.2
1280 CHAPTER 15. TOOLS

Module
1D Metrology

void HMeasureX.SetFuzzyMeasure ([in] String SetType,


[in] HFunction1dX Function )
void HOperatorSetX.SetFuzzyMeasure ([in] VARIANT MeasureHandle,
[in] VARIANT SetType, [in] VARIANT Function )

Specify a fuzzy member function.


SetFuzzyMeasure specifies a fuzzy member function passed in Function. The specified fuzzy functions
enable FuzzyMeasurePos and FuzzyMeasurePairs / FuzzyMeasurePairing to evaluate and select
the detected edge candidates. For this purpose, weighting characteristics for different edge features can be defined
by one function each. Such a specified feature is called fuzzy set. Specifying no function for a fuzzy set means not
to use this feature for the final edge evaluation. Setting a second fuzzy function to a set means to discard the first
defined function and replace it by the second one. A previously defined fuzzy member function can be discarded
completely by ResetFuzzyMeasure.
Functions for five different fuzzy set types selected by the SetType parameter can be defined, the sub types of a
set beeing mutual exclusive:

• ’contrast’ will use the fuzzy function to evaluate the amplitudes of the edge candidates. When extracting
edge pairs, the fuzzy evaluation is obtained by the geometric average of the fuzzy contrast scores of both
edges.
• The fuzzy function of ’position’ evaluates the distance of each edge candidate to the reference point of the
measure object, generated by GenMeasureArc or GenMeasureRectangle2. The reference point is
located at the beginning whereas ’position_center’ or ’position_end’ sets the reference point to the middle
or the end of the one-dimensional gray value profile instead. If the fuzzy position evaluation depends on the
position of the object along the profile, ’position_first_edge’ / ’position_last_edge’ sets the referece point at
the position of the first/last extracted edge. When extracting edge pairs the position of a pair is referenced by
the geometric average of the fuzzy position scores of both edges.
• Similar to ’position’, ’position_pair’ evaluates the distance of each edge pair to the reference point of
the measure object. The position of a pair is defined by the center point between both edges. The ob-
ject’s reference can be set by ’position_pair_center’, ’position_pair_end’ and ’position_first_pair’, ’po-
sition_last_pair’, respectively. Contrary to ’position’, this set is only used by FuzzyMeasurePairs/
FuzzyMeasurePairing.
• ’size’ denotes a fuzzy set that evaluates the normed distance of the two edges of a pair in pixels. This
set is only used by FuzzyMeasurePairs/ FuzzyMeasurePairing. Specifying an upper bound
for the size by terminating the member function with a corresponding fuzzy value of 0.0 will speed up
FuzzyMeasurePairs / FuzzyMeasurePairing because not all possible pairs need to be considered.
• ’gray’ sets a fuzzy function to weight the mean projected gray value between two edges of a pair. This set is
only used by FuzzyMeasurePairs / FuzzyMeasurePairing.

A fuzzy member function is defined as a piecewise linear function by at least two pairs of values, sorted in an
ascending order by their x value. The x values represent the edge feature and must lie within the parameter space
of the set type, i.e., in case of ’contrast’ and ’gray’ feature and, e.g., byte images within the range 0.0 ≤ x ≤ 255.0.
In case of ’size’ x has to satisfy 0.0 ≤ x whereas in case of ’position’ x can be any real number. The y values of the
fuzzy function represent the weight of the corresponding feature value and have to satisfy the range of 0.0 ≤ y ≤
1.0. Outside of the function’s interval, defined by the smallest and the greatest x value, the y values of the interval
borders are continued constantly. Such Fuzzy member functions can be generated by CreateFunct1DPairs.
If more than one set is defined, FuzzyMeasurePos / FuzzyMeasurePairs / FuzzyMeasurePairing
yield the overall fuzzy weighting by the geometric middle of the weights of each set.
Parameter

. MeasureHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . measure_id ; HMeasureX / VARIANT


Measure object handle.

HALCON/COM Reference Manual, 2008-5-13


15.14. MEASURE 1281

. SetType (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT


Selection of the fuzzy set.
Default Value : ’contrast’
List of values : SetType ∈ {’position’, ’position_center’, ’position_end’, ’position_first_edge’,
’position_last_edge’, ’position_pair_center’, ’position_pair_end’, ’position_first_pair’, ’position_last_pair’,
’size’, ’gray’, ’contrast’}
. Function (input control) . . . . . . . . . . . . . . . . . . . . function_1d ; HFunction1dX / VARIANT ( real, integer )
Fuzzy member function.
Example

/* how to use a fuzzy function */


...
gen_measure_rectangle2 (50, 100, 0, 200, 100, 512, 512, ’nearest_neighbor’,
MeasureHandle)
/* create a generalized fuzzy function to evaluate edge pairs
* (30% uncertainty). */
create_funct_1d_pairs ([0.7,1.0,1.3], [0.0,1.0,0.0], SizeFunction)
/* and transform it to expected size of 13.45 pixels */
transform_funct_1d (SizeFunction, [1.0,0.0,13.45,0.0], TransformedFunction)
set_fuzzy_measure (MeasureHandle, ’size’, SizeFunction)

fuzzy_measure_pairs (Image, MeasureHandle, 1, 30, 0.5, ’all’, RowEdgeFirst,


ColumnEdgeFirst, AmplitudeFirst, RowEdgeSecond,
ColumnEdgeSecond, AmplitudeSecond, RowEdgeCenter,
ColumnEdgeCenter, FuzzyScore, IntraDistance,
InterDistance)

Parallelization Information
SetFuzzyMeasure is reentrant and processed without parallelization.
Possible Predecessors
GenMeasureArc, GenMeasureRectangle2, CreateFunct1DPairs, TransformFunct1D
Possible Successors
FuzzyMeasurePos, FuzzyMeasurePairs
See also
ResetFuzzyMeasure
Alternatives
SetFuzzyMeasureNormPair
Module
1D Metrology

void HMeasureX.SetFuzzyMeasureNormPair ([in] VARIANT PairSize,


[in] String SetType, [in] HFunction1dX Function )
void HOperatorSetX.SetFuzzyMeasureNormPair
([in] VARIANT MeasureHandle, [in] VARIANT PairSize, [in] VARIANT SetType,
[in] VARIANT Function )

Specify a normalized fuzzy member function for edge pairs.


SetFuzzyMeasureNormPair specifies a normalized fuzzy member function passed in Function. The spec-
ified fuzzy functions enables FuzzyMeasurePos, FuzzyMeasurePairs and FuzzyMeasurePairing
to evaluate and select the detected candidates of edges and edge pairs. For this purpose, weighting characteristics
for different edge features can be defined by one function each. Such a specified feature is called fuzzy set. Speci-
fying no function for a fuzzy set means not to use this feature for the final edge evaluation. Setting a second fuzzy
function to a fuzzy set means to discard the first defined function and replace it by the second one. In difference

HALCON 8.0.2
1282 CHAPTER 15. TOOLS

to SetFuzzyMeasure, the abscissa x of these member functions must be defined relative to the desired size s
of the edge pairs (passed in PairSize). This enables a generalized usage of the defined functions. A previously
defined normalized fuzzy member function can be discarded completely by ResetFuzzyMeasure.
Functions for three different fuzzy set types selected by the SetType parameter can be defined, the sub types of
a set beeing mutual exclusive:
• ’size’ denotes a fuzzy set that valuates the normalized distance of two edges of a pair in pixels:
d
(x ≥ 0) .
x=
s
Specifying an upper bound x_max for the size by terminating the member function with a corresponding
fuzzy value of 0.0 will speed up FuzzyMeasurePairs / FuzzyMeasurePairing because not all
possible pairs must be considered. Additionally, this fuzzy set can also be specified as a normalized size
difference by ’size_diff’
s−d
x= (x ≤ 1)
s
and a absolute normalized size difference by ’size_abs_diff’
|s − d|
x= (0 ≤ x ≤ 1) .
s
• The fuzzy function of ’position’ evaluates the signed distance p of each edge candidate to the reference point
of the measure object, generated by GenMeasureArc or GenMeasureRectangle2:
p
x= .
s
The reference point is located at the beginning whereas ’position_center’ or ’position_end’ sets the reference
point to the middle or the end of the one-dimensional gray value profile, instead. If the fuzzy position
valuation depends on the position of the object along the profile ’position_first_edge’ / ’position_last_edge’
sets the referece point at the position of the first/last extracted edge. When extracting edge pairs, the position
of a pair is referenced by the geometric average of the fuzzy position scores of both edges.
• Similar to ’position’, ’position_pair’ evaluates the signed distance of each edge pair to the reference point
of the measure object. The position of a pair is defined by the center point between both edges. The
object’s reference can be set by ’position_pair_center’, ’position_pair_end’ and ’position_first_pair’, ’po-
sition_last_pair’, respectively. Contrary to ’position’, this set is only used by FuzzyMeasurePairs/
FuzzyMeasurePairing.
A normalized fuzzy member function is defined as a piecewise linear function by at least two pairs of values,
sorted in an ascending order by their x value. The y values of the fuzzy function represent the weight of the
corresponding feature value and must satisfy the range of 0.0 ≤ y ≤ 1.0. Outside of the function’s interval, defined
by the smallest and the greatest x value, the y values of the interval borders are continued constantly. Such Fuzzy
member functions can be generated by CreateFunct1DPairs.
If more than one set is defined, FuzzyMeasurePos / FuzzyMeasurePairs / FuzzyMeasurePairing
yield the overall fuzzy weighting by the geometric mean of the weights of each set.
Parameter
. MeasureHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . measure_id ; HMeasureX / VARIANT
Measure object handle.
. PairSize (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Favored width of edge pairs.
Default Value : 10.0
List of values : PairSize ∈ {4.0, 6.0, 8.0, 10.0, 15.0, 20.0, 30.0}
Minimum Increment : 0.1
Recommended Increment : 1.0
. SetType (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Selection of the fuzzy set.
Default Value : ’size_abs_diff’
List of values : SetType ∈ {’size’, ’size_diff’, ’size_abs_diff’, ’position’, ’position_center’, ’position_end’,
’position_first_edge’, ’position_last_edge’, ’position_pair_center’, ’position_pair_end’, ’position_first_pair’,
’position_last_pair’}
. Function (input control) . . . . . . . . . . . . . . . . . . . . function_1d ; HFunction1dX / VARIANT ( real, integer )
Fuzzy member function.

HALCON/COM Reference Manual, 2008-5-13


15.14. MEASURE 1283

Example

/* how to use a fuzzy function */


...
gen_measure_rectangle2 (50, 100, 0, 200, 100, 512, 512, ’nearest_neighbor’,
MeasureHandle)
/* create a generalized fuzzy function to evaluate edge pairs
* (30% uncertainty). */
create_funct_1d_pairs ([0.7,1.0,1.3], [0.0,1.0,0.0], SizeFunction)
/* and set it for an expected pair size of 13.45 pixels */
set_fuzzy_measure_norm_pair (MeasureHandle, 13.45, ’size’, SizeFunction)

fuzzy_measure_pairs (Image, MeasureHandle, 1, 30, 0.5, ’all’, RowEdgeFirst,


ColumnEdgeFirst, AmplitudeFirst, RowEdgeSecond,
ColumnEdgeSecond, AmplitudeSecond, RowEdgeCenter,
ColumnEdgeCenter, FuzzyScore, IntraDistance,
InterDistance)

Parallelization Information
SetFuzzyMeasureNormPair is reentrant and processed without parallelization.
Possible Predecessors
GenMeasureArc, GenMeasureRectangle2, CreateFunct1DPairs
Possible Successors
FuzzyMeasurePairs, FuzzyMeasurePairing
See also
ResetFuzzyMeasure
Alternatives
TransformFunct1D, SetFuzzyMeasure
Module
1D Metrology

void HMeasureX.TranslateMeasure ([in] VARIANT Row,


[in] VARIANT Column )
void HOperatorSetX.TranslateMeasure ([in] VARIANT MeasureHandle,
[in] VARIANT Row, [in] VARIANT Column )

Translate a measure object.


TranslateMeasure translates the reference point of the measure object given by MeasureHandle to the
point (Row,Column). If the measure object and the translated measure object lie completely within the image, the
measure object is shifted to the new reference point in an efficient manner. Otherwise, the measure object is gen-
erated anew with GenMeasureRectangle2 or GenMeasureArc using the parameters that were specified
when the measure object was created and the new reference point.
Parameter

. MeasureHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . measure_id ; HMeasureX / VARIANT


Measure object handle.
. Row (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.y ; VARIANT ( integer, real )
Row coordinate of the new reference point.
Default Value : 50.0
Suggested values : Row ∈ {10.0, 20.0, 50.0, 100.0, 200.0, 300.0, 400.0, 500.0}
Typical range of values : 0.0 ≤ Row ≤ 0.0(lin)
Minimum Increment : 1.0
Recommended Increment : 10.0

HALCON 8.0.2
1284 CHAPTER 15. TOOLS

. Column (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . point.x ; VARIANT ( integer, real )


Column coordinate of the new reference point.
Default Value : 100.0
Suggested values : Column ∈ {10.0, 20.0, 50.0, 100.0, 200.0, 300.0, 400.0, 500.0}
Typical range of values : 0.0 ≤ Column ≤ 0.0(lin)
Minimum Increment : 1.0
Recommended Increment : 10.0
Result
If the parameter values are correct the operator TranslateMeasure returns the value TRUE. Otherwise an
exception handling is raised.
Parallelization Information
TranslateMeasure is reentrant and processed without parallelization.
Possible Predecessors
GenMeasureRectangle2, GenMeasureArc
Possible Successors
MeasurePos, MeasurePairs, FuzzyMeasurePos, FuzzyMeasurePairs,
FuzzyMeasurePairing, MeasureThresh
See also
CloseMeasure
Alternatives
GenMeasureRectangle2, GenMeasureArc
Module
1D Metrology

15.15 OCV
void HMiscX.CloseAllOcvs ( )
void HOperatorSetX.CloseAllOcvs ( )

Clear all OCV tools.


CloseAllOcvs closes all OCV tools which have been opened using CreateOcvProj or ReadOcv. All
handles are invalid after this call.
Attention
CloseAllOcvs exists solely for the purpose of implementing the “reset program” functionality in HDevelop.
CloseAllOcvs must not be used in any application.
Result
CloseAllOcvs returns always TRUE.
Parallelization Information
CloseAllOcvs is processed completely exclusively without parallelization.
Possible Predecessors
ReadOcv, CreateOcvProj
Alternatives
CloseOcv
Module
OCR/OCV

void HOperatorSetX.CloseOcv ([in] VARIANT OCVHandle )

Clear an OCV tool.


CloseOcv closes an open OCV tool and frees the memory. The OCV tool has been created using
CreateOcvProj or ReadOcv. The handle is after this call no longer valid.

HALCON/COM Reference Manual, 2008-5-13


15.15. OCV 1285

Parameter

. OCVHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ocv ; HOcvX / VARIANT


Handle of the OCV tool which has to be freed.
Result
CloseOcv returns TRUE, if the handle is valid. Otherwise, an exception handling is raised.
Parallelization Information
CloseOcv is processed completely exclusively without parallelization.
Possible Predecessors
ReadOcv, CreateOcvProj
See also
CloseOcr
Module
OCR/OCV

void HOcvX.CreateOcvProj ([in] VARIANT PatternNames )


void HOperatorSetX.CreateOcvProj ([in] VARIANT PatternNames,
[out] VARIANT OCVHandle )

Create a new OCV tool based on gray value projections.


CreateOcvProj creates a new OCV tool. This tool will be used to train good-patterns for the optical character
verification. The training is done using the operator TraindOcvProj. Thus TraindOcvProj is normally
called after CreateOcvProj.
The pattern comparison is based on the gray projections: For every traing pattern the horizontal and vertical gray
projections are calculated by summing up the gray values along the rows and columns inside the region of the
pattern. This operation is applied to the training patterns and the test patterns. For the training patterns the result
is stored inside the OCV tool to save runtime while comparing patterns. The OCV is done by comparing the
corresponding projections. The Quality is the similarity of the projections.
Input for CreateOcvProj are the names of the patterns (PatternNames) which have to be trained. The
number and the names can be chosen arbitrary. In most case only one pattern will be trained, thus only one name
has to be specified. The names will be used when doing the OCV ( DoOcvSimple). It is possible to specify more
names than actually used. These might be trained later.
To close the OCV tool, i.e. to free the memory, the operator CloseOcv is called.
Parameter

. PatternNames (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )


List of names for patterns to be trained.
Default Value : ’a’
. OCVHandle (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ocv ; HOcvX / VARIANT
Handle of the created OCV tool.
Result
CreateOcvProj returns TRUE, if the parameters are correct. Otherwise, an exception handling is raised.
Parallelization Information
CreateOcvProj is processed completely exclusively without parallelization.
Possible Successors
TraindOcvProj, WriteOcv, CloseOcv
See also
CreateOcrClassBox
Alternatives
ReadOcv
Module
OCR/OCV

HALCON 8.0.2
1286 CHAPTER 15. TOOLS

[out] VARIANT Quality HImageX.DoOcvSimple ([in] HOcvX OCVHandle,


[in] VARIANT PatternName, [in] String AdaptPos, [in] String AdaptSize,
[in] String AdaptAngle, [in] String AdaptGray, [in] double Threshold )
[out] VARIANT Quality HOcvX.DoOcvSimple ([in] HImageX Pattern,
[in] VARIANT PatternName, [in] String AdaptPos, [in] String AdaptSize,
[in] String AdaptAngle, [in] String AdaptGray, [in] double Threshold )
void HOperatorSetX.DoOcvSimple ([in] IHObjectX Pattern,
[in] VARIANT OCVHandle, [in] VARIANT PatternName, [in] VARIANT AdaptPos,
[in] VARIANT AdaptSize, [in] VARIANT AdaptAngle, [in] VARIANT AdaptGray,
[in] VARIANT Threshold, [out] VARIANT Quality )

Verification of a pattern using an OCV tool.


DoOcvSimple evaluates the pattern in (Pattern). Before the evaluation the good-pattern has be trained by
using the operator TraindOcvProj. Both patterns should have roughly the same (relative) extent and shape. To
specify which of the trained patterns is used as reference its name is specified in PatternName. The next four
parameters influence the automatic adaption: AdaptPos and AdaptSize refer to the geometry of the pattern.
AdaptPos specifies whether a shift of the position will be adapted automatically. AdaptSize is used to adapt
to changes in the size of the pattern. AdaptAngle is not yet implemented. The parameter AdaptGray controls
the adaption to changes of the grayvalues. This comprises additive and multiplicative changes of the intensity.
The parameter Threshold specifies the minimum difference of the gray values to be treated as an error. In this
case the percentage of wrong pixels is returned. If the value is below 0 the sum of all errors normalized with
respect to the size is returned.
The result of the operator is the Quality of the pattern with a value between 0 and 1. The value 1 corresponds to
a pattern with no faults. The value 0 corresponds to a very big fault.
Parameter
. Pattern (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte )
Characters to be verified.
. OCVHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ocv ; HOcvX / VARIANT
Handle of the OCV tool.
. PatternName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Name of the character.
Default Value : ’a’
. AdaptPos (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Adaption to vertical and horizontal translation.
Default Value : ’true’
List of values : AdaptPos ∈ {’true’, ’false’}
. AdaptSize (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Adaption to vertical and horizontal scaling of the size.
Default Value : ’true’
List of values : AdaptSize ∈ {’true’, ’false’}
. AdaptAngle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Adaption to changes of the orientation (not yet implemented).
Default Value : ’false’
List of values : AdaptAngle ∈ {’false’}
. AdaptGray (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Adaption to additive and scaling gray value changes.
Default Value : ’true’
List of values : AdaptGray ∈ {’true’, ’false’}
. Threshold (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; double / VARIANT
Minimum difference between objects.
Default Value : 10
Suggested values : Threshold ∈ {-1, 0, 1, 5, 10, 15, 20, 30, 40, 50, 60, 80, 100, 150}
. Quality (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Evaluation of the character.
Typical range of values : 0.0 ≤ Quality ≤ 0.0

HALCON/COM Reference Manual, 2008-5-13


15.15. OCV 1287

Result
DoOcvSimple returns TRUE, if the handle and the characters are correct. Otherwise, an exception handling is
raised.
Parallelization Information
DoOcvSimple is reentrant and processed without parallelization.
Possible Predecessors
TraindOcrClassBox, TrainfOcrClassBox, ReadOcv, Threshold, Connection, SelectShape
Possible Successors
CloseOcv
See also
CreateOcvProj
Module
OCR/OCV

void HOcvX.ReadOcv ([in] String FileName )


void HOperatorSetX.ReadOcv ([in] VARIANT FileName,
[out] VARIANT OCVHandle )

Reading an OCV tool from file.


ReadOcv reads an OCV tool from file. The tool will contain the same information that it contained when saving
it with WriteOcv. After reading the tool the training can be completed for those patterns which have not been
trained so far. Otherwise a pattern comparison can be applied directly by calling DoOcvSimple.
As extension ’.ocv’ is used. If this extension is not given with the file name it will be added automatically.
Parameter
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.read ; String / VARIANT
Name of the file which has to be read.
Default Value : ’test_ocv’
. OCVHandle (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ocv ; HOcvX / VARIANT
Handle of read OCV tool.
Result
ReadOcv returns TRUE, if the file is correct. Otherwise, an exception handling is raised.
Parallelization Information
ReadOcv is processed completely exclusively without parallelization.
Possible Predecessors
WriteOcv
Possible Successors
DoOcvSimple, CloseOcv
See also
ReadOcr
Module
OCR/OCV

void HImageX.TraindOcvProj ([in] HOcvX OCVHandle, [in] VARIANT Name,


[in] String Mode )
void HOcvX.TraindOcvProj ([in] HImageX Pattern, [in] VARIANT Name,
[in] String Mode )
void HOperatorSetX.TraindOcvProj ([in] IHObjectX Pattern,
[in] VARIANT OCVHandle, [in] VARIANT Name, [in] VARIANT Mode )

Training of an OCV tool.

HALCON 8.0.2
1288 CHAPTER 15. TOOLS

TraindOcvProj trains patterns for an OCV tool that has been created using the operators CreateOcvProj
or ReadOcv. For this training one or multiple patterns are offered the system. Such a pattern consists of an image
with a reduced domain (ROI) for the area of the pattern. Note that the pattern should not only contain foreground
pixels (e.g. dark pixels of a character) but also background pixels. This can be implemented e.g. by the smallest
surrounding rectangle of the pattern. Without this context an evaluation of the pattern is not possible.
If more than one pattern has to be trained this can be achieved by multiple calls (one for each pattern) or by calling
TraindOcvProj once with all patterns and a tuple of the corresponding names. The result will be in both cases
the same. However using multiple calls will normally result in a longer execution time than using one call with all
patterns.
Parameter

. Pattern (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte )


Pattern to be trained.
. OCVHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ocv ; HOcvX / VARIANT
Handle of the OCV tool to be trained.
. Name (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Name(s) of the object(s) to analyse.
Default Value : ’a’
. Mode (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Mode for training (only one mode implemented).
Default Value : ’single’
List of values : Mode ∈ {’single’}
Result
TraindOcvProj returns TRUE, if the handle and the training pattern(s) are correct. Otherwise, an exception
handling is raised.
Parallelization Information
TraindOcvProj is processed completely exclusively without parallelization.
Possible Predecessors
WriteOcrTrainf, CreateOcvProj, ReadOcv, Threshold, Connection, SelectShape
Possible Successors
CloseOcv
See also
TraindOcrClassBox
Module
OCR/OCV

void HOcvX.WriteOcv ([in] String FileName )


void HOperatorSetX.WriteOcv ([in] VARIANT OCVHandle,
[in] VARIANT FileName )

Saving an OCV tool to file.


WriteOcv writes an OCV tool to file. This can be used to save the result of a training ( TraindOcvProj). The
whole information contained in the OCV tool is stored in the file. The file can be reloaded afterwards using the
operator ReadOcv.
As file extension ’.ocv’ is used. If this extension is not given with the file name, it will be added automatically.
Parameter

. OCVHandle (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ocv ; HOcvX / VARIANT


Handle of the OCV tool to be written.
. FileName (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . filename.write ; String / VARIANT
Name of the file where the tool has to be saved.
Default Value : ’test_ocv’

HALCON/COM Reference Manual, 2008-5-13


15.16. SHAPE-FROM 1289

Result
WriteOcv returns TRUE, if the data is correct and the file can be written. Otherwise, an exception handling is
raised.
Parallelization Information
WriteOcv is reentrant and processed without parallelization.
Possible Predecessors
TraindOcvProj
Possible Successors
CloseOcv
See also
WriteOcr
Module
OCR/OCV

15.16 Shape-from

[out] HImageX Depth HImageX.DepthFromFocus ([out] HImageX Confidence,


[in] VARIANT Filter, [in] VARIANT Selection )
void HOperatorSetX.DepthFromFocus ([in] IHObjectX MultiFocusImage,
[out] HUntypedObjectX Depth, [out] HUntypedObjectX Confidence,
[in] VARIANT Filter, [in] VARIANT Selection )

Extract depth using mutiple focus levels.


The operator DepthFromFocus extracts the depth using a focus sequence. The images of the focus sequence
have to passed as a multi channel image (MultiFocusImage). The depth for each pixel will be returned in
Depth as the channel number. The parameter Confidence returns a confidence value for each depth estimation:
The larger this value, the higher the confidence of the depth estimation is.
DepthFromFocus selects the pixels with the best focus of all focus levels. The method used to extract these
pixels is specified by the parameters Filter and Selection:

’highpass’ The value of the focus is estimated by a highpass filter.


’bandpass’ The value of the focus is estimated by a bandpass filter.
’next_maximum’ To decide which focus level has be selected, the pixel in the neighborhood with the best confi-
dence is used to determine this value.
’local’ The decision for a focus level is based only on the locally calculated focus values.

Parameter

. MultiFocusImage (input iconic) . . . . . . . . . . multichannel-image-array ; HImageX / IHObjectX ( byte )


Multichannel gray image consisting of multiple focus levels.
. Depth (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte )
Depth image.
. Confidence (output iconic) . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte )
Confidence of depth estimation.
. Filter (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Filter used to find sharp pixels.
Default Value : ’highpass’
List of values : Filter ∈ {’highpass’, ’bandpass’}
. Selection (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Method used to find sharp pixels.
Default Value : ’next_maximum’
List of values : Selection ∈ {’next_maximum’, ’local’}

HALCON 8.0.2
1290 CHAPTER 15. TOOLS

Parallelization Information
DepthFromFocus is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
Compose2, Compose3, Compose4, AddChannels, ReadImage, ReadSequence
Possible Successors
SelectGrayvaluesFromChannels, MeanImage, BinomialFilter, GaussImage, Threshold
See also
CountChannels
Module
3D Metrology

HImageX.EstimateAlAm ([out] VARIANT Ambient )


[out] VARIANT Albedo
void HOperatorSetX.EstimateAlAm ([in] IHObjectX Image,
[out] VARIANT Albedo, [out] VARIANT Ambient )

Estimate the albedo of a surface and the amount of ambient light.


EstimateAlAm estimates the Albedo of a surface, i.e. the percentage of light reflected by the surface, and the
amount of ambient light Ambient by using the maximum and minimum gray values of the image.
Attention
It is assumed that the image contains at least one point for which the reflection function assumes its minimum, e.g.,
points in shadows. Furthermore, it is assumed that the image contains at least one point for which the reflection
function assumes its maximum. If this is not the case, wrong values will be estimated.
Parameter
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte )
Image for which albedo and ambient are to be estimated.
. Albedo (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Amount of light reflected by the surface.
. Ambient (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Amount of ambient light.
Result
EstimateAlAm always returns the value TRUE.
Parallelization Information
EstimateAlAm is reentrant and automatically parallelized (on tuple level).
Possible Successors
SfsModLr, SfsOrigLr, SfsPentland, PhotStereo, ShadeHeightField
Module
3D Metrology

HImageX.EstimateSlAlLr ([out] VARIANT Albedo )


[out] VARIANT Slant
void HOperatorSetX.EstimateSlAlLr ([in] IHObjectX Image,
[out] VARIANT Slant, [out] VARIANT Albedo )

Estimate the slant of a light source and the albedo of a surface.


EstimateSlAlLr estimates the Slant of a light source, i.e., the angle between the light source and the positive
z-axis, and the albedo of the surface in the input image Image, i.e. the percentage of light reflected by the surface,
using the algorithm of Lee and Rosenfeld.
Attention
The Albedo is assumed constant for the entire surface depicted in the image.

HALCON/COM Reference Manual, 2008-5-13


15.16. SHAPE-FROM 1291

Parameter
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte )
Image for which slant and albedo are to be estimated.
. Slant (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.deg(-array) ; VARIANT ( real )
Angle between the light sources and the positive z-axis (in degrees).
. Albedo (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Amount of light reflected by the surface.
Result
EstimateSlAlLr always returns the value TRUE.
Parallelization Information
EstimateSlAlLr is reentrant and automatically parallelized (on tuple level).
Possible Successors
SfsModLr, SfsOrigLr, SfsPentland, PhotStereo, ShadeHeightField
Module
3D Metrology

HImageX.EstimateSlAlZc ([out] VARIANT Albedo )


[out] VARIANT Slant
void HOperatorSetX.EstimateSlAlZc ([in] IHObjectX Image,
[out] VARIANT Slant, [out] VARIANT Albedo )

Estimate the slant of a light source and the albedo of a surface.


EstimateSlAlZc estimates the Slant of a light source, i.e. the angle between the light source and the positive
z-axis, and the albedo of the surface in the input image Image, i.e. the percentage of light reflected by the surface,
using the algorithm of Zheng and Chellappa.
Attention
The Albedo is assumed constant for the entire surface depicted in the image.
Parameter
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte )
Image for which slant and albedo are to be estimated.
. Slant (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.deg(-array) ; VARIANT ( real )
Angle of the light sources and the positive z-axis (in degrees).
. Albedo (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Amount of light reflected by the surface.
Result
EstimateSlAlZc always returns the value TRUE.
Parallelization Information
EstimateSlAlZc is reentrant and automatically parallelized (on tuple level).
Possible Successors
SfsModLr, SfsOrigLr, SfsPentland, PhotStereo, ShadeHeightField
Module
3D Metrology

HImageX.EstimateTiltLr ( )
[out] VARIANT Tilt
void HOperatorSetX.EstimateTiltLr ([in] IHObjectX Image,
[out] VARIANT Tilt )

Estimate the tilt of a light source.


EstimateTiltLr estimates the tilt of a light source, i.e. the angle between the light source and the x-axis after
projection into the xy-plane, from the image Image using the algorithm of Lee and Rosenfeld.

HALCON 8.0.2
1292 CHAPTER 15. TOOLS

Parameter
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte )
Image for which the tilt is to be estimated.
. Tilt (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.deg(-array) ; VARIANT ( real )
Angle between the light source and the x-axis after projection into the xy-plane (in degrees).
Result
EstimateTiltLr always returns the value TRUE.
Parallelization Information
EstimateTiltLr is reentrant and automatically parallelized (on tuple level).
Possible Successors
SfsModLr, SfsOrigLr, SfsPentland, PhotStereo, ShadeHeightField
Module
3D Metrology

[out] VARIANT Tilt HImageX.EstimateTiltZc ( )


void HOperatorSetX.EstimateTiltZc ([in] IHObjectX Image,
[out] VARIANT Tilt )

Estimate the tilt of a light source.


EstimateTiltZc estimates the tilt of a light source, i.e. the angle between the light source and the x-axis after
projection into the xy-plane, from the image Image using the algorithm of Zheng and Chellappa.
Parameter
. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte )
Image for which the tilt is to be estimated.
. Tilt (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.deg(-array) ; VARIANT ( real )
Angle between the light source and the x-axis after projection into the xy-plane (in degrees).
Result
EstimateTiltZc always returns the value TRUE.
Parallelization Information
EstimateTiltZc is reentrant and automatically parallelized (on tuple level).
Possible Successors
SfsModLr, SfsOrigLr, SfsPentland, PhotStereo, ShadeHeightField
Module
3D Metrology

[out] HImageX Height HImageX.PhotStereo ([in] VARIANT Slants,


[in] VARIANT Tilts )
void HOperatorSetX.PhotStereo ([in] IHObjectX Images,
[out] HUntypedObjectX Height, [in] VARIANT Slants, [in] VARIANT Tilts )

Reconstruct a surface from at least three gray value images.


PhotStereo reconstructs a surface (i.e., the relative height of each image point) using the algorithm of Woodham
from at least three gray value images given by the multi-channel image Images. The light sources corresponding
to the individual images are given by the parameters Slants and Tilts and are assumed to lie infinitely far
away.
Attention
PhotStereo assumes that the heights are to be extracted on a lattice with step width 1. If this is not the case, the
calculated heights must be multiplied by the step width after the call to PhotStereo. A Cartesian coordinate
system with the origin in the lower left corner of the image is used internally. All given images must be byte-
images. At least three images must be given in a multi-channel image. Slants and Tilts must contain exactly

HALCON/COM Reference Manual, 2008-5-13


15.16. SHAPE-FROM 1293

as many light sources as the number of channels in Images. At least three of the light source directions must be
linearly independent.
Parameter
. Images (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . (multichannel-)image ; HImageX / IHObjectX ( byte )
Shaded input image with at least three channels.
. Height (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / HUntypedObjectX ( real )
Reconstructed height field.
. Slants (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.deg ; VARIANT ( real, integer )
Angle between the light sources and the positive z-axis (in degrees).
Default Value : 45.0
Suggested values : Slants ∈ {1.0, 5.0, 10.0, 20.0, 40.0, 60.0, 90.0}
Typical range of values : 0.0 ≤ Slants ≤ 0.0(lin)
Minimum Increment : 0.01
Recommended Increment : 10.0
. Tilts (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.deg ; VARIANT ( real, integer )
Angle between the light source and the x-axis after projection into the xy-plane (in degrees).
Default Value : 45.0
Suggested values : Tilts ∈ {1.0, 5.0, 10.0, 20.0, 40.0, 60.0, 90.0}
Typical range of values : 0.0 ≤ Tilts ≤ 0.0(lin)
Minimum Increment : 0.01
Recommended Increment : 10.0
Result
If all parameters are correct PhotStereo returns the value TRUE. Otherwise, an exception is raised.
Parallelization Information
PhotStereo is reentrant and processed without parallelization.
Possible Predecessors
EstimateSlAlLr, EstimateSlAlZc, EstimateTiltLr, EstimateTiltZc
Possible Successors
ShadeHeightField
Module
3D Metrology

[out] HImageX Selected HImageX.SelectGrayvaluesFromChannels


([in] HImageX IndexImage )
void HOperatorSetX.SelectGrayvaluesFromChannels
([in] IHObjectX MultichannelImage, [in] IHObjectX IndexImage,
[out] HUntypedObjectX Selected )

Selection of gray values of a multi-channel image using an index image.


The operator SelectGrayvaluesFromChannels selects gray values from the different channels of
MultichannelImage. The channel number for each pixel is determined from the corresponding pixel value
in IndexImage. If MultichannelImage and IndexImage contain the same number of images, the corre-
sponding images are processed pairwise. Otherwise, IndexImage must contain only one single image. In this
case, the gray value selection is performed for each image of MultichannelImage according to IndexImage
.
Parameter
. MultichannelImage (input iconic) . . . . . . . . multichannel-image-array ; HImageX / IHObjectX ( byte )
Multi-channel gray value image.
. IndexImage (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte )
Image, where pixel values are interpreted as channel index.
Number of elements : ((IndexImage = M ultichannelImage) ∨ (IndexImage = 1))
. Selected (output iconic) . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte )
Resulting image.

HALCON 8.0.2
1294 CHAPTER 15. TOOLS

Parallelization Information
SelectGrayvaluesFromChannels is reentrant and automatically parallelized (on tuple level, domain
level).
Possible Predecessors
DepthFromFocus, MeanImage
Possible Successors
DispImage
See also
CountChannels
Module
Foundation

[out] HImageX Height HImageX.SfsModLr ([in] VARIANT Slant,


[in] VARIANT Tilt, [in] VARIANT Albedo, [in] VARIANT Ambient )
void HOperatorSetX.SfsModLr ([in] IHObjectX Image,
[out] HUntypedObjectX Height, [in] VARIANT Slant, [in] VARIANT Tilt,
[in] VARIANT Albedo, [in] VARIANT Ambient )

Reconstruct a surface from a gray value image.


SfsModLr reconstructs a surface (i.e. the relative height of each image point) using the modified algorithm of
Lee and Rosenfeld. The surface is reconstructed from the input image Image, and the light source given by the
parameters Slant, Tilt, Albedo and Ambient, and is assumed to lie infinitely far away in the direction given
by Slant and Tilt. The parameter Albedo determines the albedo of the surface, i.e. the percentage of light
reflected in all directions. Ambient determines the amount of ambient light falling onto the surface. It can be set
to values greater than zero if, for example, the white balance of the camera was badly adjusted at the moment the
image was taken.
Attention
SfsModLr assumes that the heights are to be extracted on a lattice with step width 1. If this is not the case, the
calculated heights must be multiplied with the step width after the call to SfsModLr. A Cartesian coordinate
system with the origin in the lower left corner of the image is used internally. SfsModLr can only handle
byte-images.
Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte )


Shaded input image.
. Height (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX ( real )
Reconstructed height field.
. Slant (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.deg ; VARIANT ( real, integer )
Angle between the light source and the positive z-axis (in degrees).
Default Value : 45.0
Suggested values : Slant ∈ {1.0, 5.0, 10.0, 20.0, 40.0, 60.0, 90.0}
Typical range of values : 0.0 ≤ Slant ≤ 0.0(lin)
Minimum Increment : 0.01
Recommended Increment : 10.0
. Tilt (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.deg ; VARIANT ( real, integer )
Angle between the light source and the x-axis after projection into the xy-plane (in degrees).
Default Value : 45.0
Suggested values : Tilt ∈ {1.0, 5.0, 10.0, 20.0, 40.0, 60.0, 90.0}
Typical range of values : 0.0 ≤ Tilt ≤ 0.0(lin)
Minimum Increment : 0.01
Recommended Increment : 10.0

HALCON/COM Reference Manual, 2008-5-13


15.16. SHAPE-FROM 1295

. Albedo (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )


Amount of light reflected by the surface.
Default Value : 1.0
Suggested values : Albedo ∈ {0.1, 0.5, 1.0, 5.0}
Typical range of values : 0.0 ≤ Albedo ≤ 0.0(lin)
Minimum Increment : 0.01
Recommended Increment : 0.1
Restriction : (Albedo ≥ 0.0)
. Ambient (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Amount of ambient light.
Default Value : 0.0
Suggested values : Ambient ∈ {0.1, 0.5, 1.0}
Typical range of values : 0.0 ≤ Ambient ≤ 0.0(lin)
Minimum Increment : 0.01
Recommended Increment : 0.1
Restriction : (Ambient ≥ 0.0)
Result
If all parameters are correct SfsModLr returns the value TRUE. Otherwise, an exception is raised.
Parallelization Information
SfsModLr is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
EstimateAlAm, EstimateSlAlLr, EstimateSlAlZc, EstimateTiltLr, EstimateTiltZc
Possible Successors
ShadeHeightField
Module
3D Metrology

[out] HImageX Height HImageX.SfsOrigLr ([in] VARIANT Slant,


[in] VARIANT Tilt, [in] VARIANT Albedo, [in] VARIANT Ambient )
void HOperatorSetX.SfsOrigLr ([in] IHObjectX Image,
[out] HUntypedObjectX Height, [in] VARIANT Slant, [in] VARIANT Tilt,
[in] VARIANT Albedo, [in] VARIANT Ambient )

Reconstruct a surface from a gray value image.


SfsOrigLr reconstructs a surface (i.e. the relative height of each image point) using the original algorithm of
Lee and Rosenfeld. The surface is reconstructed from the input image Image. The light source is to be given by
the parameters Slant, Tilt, Albedo and Ambient, and is assumed to lie infinitely far away in the direction
given by Slant and Tilt. The parameter Albedo determines the albedo of the surface, i.e. the percentage of
light reflected in all directions. Ambient determines the amount of ambient light falling onto the surface. It can
be set to values greater than zero if, for example, the white balance of the camera was badly adjusted at the moment
the image was taken.
Attention
SfsOrigLr assumes that the heights are to be extracted on a lattice with step width 1. If this is not the case, the
calculated heights must be multiplied with the step width after the call to SfsOrigLr. A Cartesian coordinate
system with the origin in the lower left corner of the image is used internally. SfsOrigLr can only handle
byte-images.
Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte )


Shaded input image.
. Height (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX ( real )
Reconstructed height field.

HALCON 8.0.2
1296 CHAPTER 15. TOOLS

. Slant (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.deg ; VARIANT ( real, integer )


Angle between the light source and the positive z-axis (in degrees).
Default Value : 45.0
Suggested values : Slant ∈ {1.0, 5.0, 10.0, 20.0, 40.0, 60.0, 90.0}
Typical range of values : 0.0 ≤ Slant ≤ 0.0(lin)
Minimum Increment : 0.01
Recommended Increment : 10.0
. Tilt (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.deg ; VARIANT ( real, integer )
Angle between the light source and the x-axis after projection into the xy-plane (in degrees).
Default Value : 45.0
Suggested values : Tilt ∈ {1.0, 5.0, 10.0, 20.0, 40.0, 60.0, 90.0}
Typical range of values : 0.0 ≤ Tilt ≤ 0.0(lin)
Minimum Increment : 0.01
Recommended Increment : 10.0
. Albedo (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Amount of light reflected by the surface.
Default Value : 1.0
Suggested values : Albedo ∈ {0.1, 0.5, 1.0, 5.0}
Typical range of values : 0.0 ≤ Albedo ≤ 0.0(lin)
Minimum Increment : 0.01
Recommended Increment : 0.1
Restriction : (Albedo ≥ 0.0)
. Ambient (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Amount of ambient light.
Default Value : 0.0
Suggested values : Ambient ∈ {0.1, 0.5, 1.0}
Typical range of values : 0.0 ≤ Ambient ≤ 0.0(lin)
Minimum Increment : 0.01
Recommended Increment : 0.1
Restriction : (Ambient ≥ 0.0)
Result
If all parameters are correct SfsOrigLr returns the value TRUE. Otherwise, an exception is raised.
Parallelization Information
SfsOrigLr is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
EstimateAlAm, EstimateSlAlLr, EstimateSlAlZc, EstimateTiltLr, EstimateTiltZc
Possible Successors
ShadeHeightField
Module
3D Metrology

[out] HImageX Height HImageX.SfsPentland ([in] VARIANT Slant,


[in] VARIANT Tilt, [in] VARIANT Albedo, [in] VARIANT Ambient )
void HOperatorSetX.SfsPentland ([in] IHObjectX Image,
[out] HUntypedObjectX Height, [in] VARIANT Slant, [in] VARIANT Tilt,
[in] VARIANT Albedo, [in] VARIANT Ambient )

Reconstruct a surface from a gray value image.


SfsPentland reconstructs a surface (i.e. the relative height of each image point) using the algorithm of Pentland.
The surface is reconstructed from the input image Image. The light source must be given by the parameters
Slant, Tilt, Albedo and Ambient, and is assumed to lie infinitely far away in the direction given by Slant
and Tilt. The parameter Albedo determines the albedo of the surface, i.e. the percentage of light reflected in
all directions. Ambient determines the amount of ambient light falling onto the surface. It can be set to values
greater than zero if, for example, the white balance of the camera was badly adjusted at the moment the image was
taken.

HALCON/COM Reference Manual, 2008-5-13


15.16. SHAPE-FROM 1297

Attention
SfsPentland assumes that the heights are to be extracted on a lattice with step width 1. If this is not the case, the
calculated heights must be multiplied with the step width after the call to SfsPentland. A Cartesian coordinate
system with the origin in the lower left corner of the image is used internally. SfsPentland can only handle
byte-images.
Parameter

. Image (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte )


Shaded input image.
. Height (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX ( real )
Reconstructed height field.
. Slant (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.deg ; VARIANT ( real, integer )
Angle between the light source and the positive z-axis (in degrees).
Default Value : 45.0
Suggested values : Slant ∈ {1.0, 5.0, 10.0, 20.0, 40.0, 60.0, 90.0}
Typical range of values : 0.0 ≤ Slant ≤ 0.0(lin)
Minimum Increment : 1.0
Recommended Increment : 10.0
. Tilt (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.deg ; VARIANT ( real, integer )
Angle between the light source and the x-axis after projection into the xy-plane (in degrees).
Default Value : 45.0
Suggested values : Tilt ∈ {1.0, 5.0, 10.0, 20.0, 40.0, 60.0, 90.0}
Typical range of values : 0.0 ≤ Tilt ≤ 0.0(lin)
Minimum Increment : 1.0
Recommended Increment : 10.0
. Albedo (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Amount of light reflected by the surface.
Default Value : 1.0
Suggested values : Albedo ∈ {0.1, 0.5, 1.0, 5.0}
Typical range of values : 0.0 ≤ Albedo ≤ 0.0(lin)
Minimum Increment : 0.01
Recommended Increment : 0.1
Restriction : (Albedo ≥ 0.0)
. Ambient (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Amount of ambient light.
Default Value : 0.0
Suggested values : Ambient ∈ {0.1, 0.5, 1.0}
Typical range of values : 0.0 ≤ Ambient ≤ 0.0(lin)
Minimum Increment : 0.01
Recommended Increment : 0.1
Restriction : (Ambient ≥ 0.0)
Result
If all parameters are correct SfsPentland returns the value TRUE. Otherwise, an exception is raised.
Parallelization Information
SfsPentland is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
EstimateAlAm, EstimateSlAlLr, EstimateSlAlZc, EstimateTiltLr, EstimateTiltZc
Possible Successors
ShadeHeightField
Module
3D Metrology

HALCON 8.0.2
1298 CHAPTER 15. TOOLS

[out] HImageX ImageShade HImageX.ShadeHeightField ([in] VARIANT Slant,


[in] VARIANT Tilt, [in] VARIANT Albedo, [in] VARIANT Ambient,
[in] String Shadows )
void HOperatorSetX.ShadeHeightField ([in] IHObjectX ImageHeight,
[out] HUntypedObjectX ImageShade, [in] VARIANT Slant, [in] VARIANT Tilt,
[in] VARIANT Albedo, [in] VARIANT Ambient, [in] VARIANT Shadows )

Shade a height field.


ShadeHeightField computes a shaded image from the height field ImageHeight as if the image were
illuminated by an infinitely far away light source. It is assumed that the surface described by the height field has
Lambertian reflection properties determined by Albedo and Ambient. The parameter Shadows determines
whether shadows are to be calculated.
Attention
ShadeHeightField assumes that the heights are given on a lattice with step width 1. If this is not the case, the
heights must be divided by the step width before the call to ShadeHeightField. Otherwise, the derivatives
used internally to compute the orientation of the surface will be estimated to steep or too flat. Example: The height
field is given on 100*100 points on the square [0,1]*[0,1]. Then the heights must be divided by 1/100 first. A
Cartesian coordinate system with the origin in the lower left corner of the image is used internally.
Parameter

. ImageHeight (input iconic) . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / IHObjectX ( byte, int4, real )


Height field to be shaded.
. ImageShade (output iconic) . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX ( byte )
Shaded image.
. Slant (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.deg ; VARIANT ( real, integer )
Angle between the light source and the positive z-axis (in degrees).
Default Value : 0.0
Suggested values : Slant ∈ {1.0, 5.0, 10.0, 20.0, 40.0, 60.0, 90.0}
Typical range of values : 0.0 ≤ Slant ≤ 0.0(lin)
Minimum Increment : 0.01
Recommended Increment : 10.0
. Tilt (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . angle.deg ; VARIANT ( real, integer )
Angle between the light source and the x-axis after projection into the xy-plane (in degrees).
Default Value : 0.0
Suggested values : Tilt ∈ {1.0, 5.0, 10.0, 20.0, 40.0, 60.0, 90.0}
Typical range of values : 0.0 ≤ Tilt ≤ 0.0(lin)
Minimum Increment : 0.01
Recommended Increment : 10.0
. Albedo (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Amount of light reflected by the surface.
Default Value : 1.0
Suggested values : Albedo ∈ {0.1, 0.5, 1.0, 5.0}
Typical range of values : 0.0 ≤ Albedo ≤ 0.0(lin)
Minimum Increment : 0.01
Recommended Increment : 0.1
Restriction : (Albedo ≥ 0.0)
. Ambient (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Amount of ambient light.
Default Value : 0.0
Suggested values : Ambient ∈ {0.1, 0.5, 1.0}
Typical range of values : 0.0 ≤ Ambient ≤ 0.0(lin)
Minimum Increment : 0.01
Recommended Increment : 0.1
Restriction : (Ambient ≥ 0.0)

HALCON/COM Reference Manual, 2008-5-13


15.17. STEREO 1299

. Shadows (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT


Should shadows be calculated?
Default Value : ’false’
Suggested values : Shadows ∈ {’true’, ’false’}
Result
If all parameters are correct ShadeHeightField returns the value TRUE. Otherwise, an exception is raised.
Parallelization Information
ShadeHeightField is reentrant and automatically parallelized (on tuple level).
Possible Predecessors
SfsModLr, SfsOrigLr, SfsPentland, PhotStereo
Module
Foundation

15.17 Stereo
[out] VARIANT CamParam1 HPoseX.BinocularCalibration ([in] VARIANT NX,
[in] VARIANT NY, [in] VARIANT NZ, [in] VARIANT NRow1, [in] VARIANT NCol1,
[in] VARIANT NRow2, [in] VARIANT NCol2, [in] VARIANT StartCamParam1,
[in] VARIANT StartCamParam2, [in] VARIANT NStartPose1,
[in] VARIANT NStartPose2, [in] VARIANT EstimateParams,
[out] VARIANT CamParam2, [out] VARIANT NFinalPose1,
[out] VARIANT NFinalPose2, [out] VARIANT RelPose, [out] VARIANT Errors )
void HOperatorSetX.BinocularCalibration ([in] VARIANT NX,
[in] VARIANT NY, [in] VARIANT NZ, [in] VARIANT NRow1, [in] VARIANT NCol1,
[in] VARIANT NRow2, [in] VARIANT NCol2, [in] VARIANT StartCamParam1,
[in] VARIANT StartCamParam2, [in] VARIANT NStartPose1,
[in] VARIANT NStartPose2, [in] VARIANT EstimateParams,
[out] VARIANT CamParam1, [out] VARIANT CamParam2, [out] VARIANT NFinalPose1,
[out] VARIANT NFinalPose2, [out] VARIANT RelPose, [out] VARIANT Errors )

Determine all camera parameters of a binocular stereo system.


In general, binocular calibration means the exact determination of the parameters that model the 3D reconstruction
of a 3D point from the corresponding images of this point in a binocular stereo system. This reconstruction
is specified by the internal parameters CamParam1 of camera 1 and CamParam2 of camera 2 describing the
underlying projective camera model, and the external parameters RelPose describing the relative pose of camera
system 2 in relation to camera system 1.
Thus, known 3D model points (with coordinates NX, NY, NZ) are projected in the image planes of both cameras
(camera 1 and camera 2) and the sum of the squared distances between these projections and the corresponding
measured image points (with coordinates NRow1, NCol1 for camera 1 and NRow2, NCol2 for camera 2) is mini-
mized. It should be noted that all these model points must be visible in both images. The projection uses the initial
values StartCamParam1 and StartCamParam2 of the internal parameters of camera 1 and camera 2 which
can be obtained from the camera data sheets. In addition, the initial guesses NStartPose1 and NStartPose2
of the poses of the 3D calibration model in relation to the camera coordinate systems (CCS) of camera 1 and
camera 2 are needed as well. These 3D transformation poses can be determined by the FindMarksAndPose
operator. Since this calibration algorithm simultaneously handles correspondences between measured image and
known model points from different image pairs, poses (NStartPose1,NStartPose2), and measured points
(NRow1,NCol1,NRow2, NCol2) must be passed concatenated in a corresponding order.
The input parameter EstimateParams is used to select the parameters to be estimated. Usually this pa-
rameter is set to ’all’, i.e., all external camera parameters (translation and rotation) and all internal camera pa-
rameters are determined. Otherwise, EstimateParams contains a tuple of strings indicating the combina-
tion of parameters to estimate. For instance, if the interior camera parameters already have been determined
(e.g., by previous calls to CameraCalibration) it is often desired to only determine relative the pose of
the two cameras to each other (RelPose). In this case, EstimateParams can be set to ’pose_rel’. This
has the same effect as EstimateParams = [’pose1’,’pose2’]. The internal parameters can be subsumed by
the parameter values ’cam_param1’ and ’cam_param2’, as well. In addition, parameters can be excluded from

HALCON 8.0.2
1300 CHAPTER 15. TOOLS

estimation by using the prefix ~. For example, the values [’pose1’, ’~transx1’] have the same effect as [’al-
pha1’,’beta1’,’gamma1’,’transy1’,’transz1’]. Whereas [’all’,’~focus1’] determines all internal and external param-
eters except the focus of camera 1, for instance. The prefix ~ can be used with all parameter values except ’all’.
The underlying camera model is explained in the description of the CameraCalibration operator. It is
specified by the parameters [focus1, kappa1, sx1, sy1, cx1, cy1, image_width1, image_height1] of camera 1
returned in CamParam1 and [focus2, kappa2, sx2, sy2, cx2, cy2, image_width2, image_height2] of camera 2
returned in CamParam2 (with focus > 0). The external parameters [alpha_rel, beta_rel, gamma_rel, transx_rel,
transy_rel, transz_rel] are returned in RelPose and specify the 3D transformation of points of CCS 2 into CCS
1. Note that according to the description of poses at CreatePose one parameter is appended to the pose tuple
at the last position to define the representation type of this pose.
According to CameraCalibration the 3D transformation poses of the calibration model to the respective CCS
are returned in NFinalPose1 and NFinalPose2. These transformations are related to RelPose according
to the following equation (neglecting differences due to the balancing effects of the multi image calibration):
HomMat3D_NFinalPose2 = INV(HomMat3D_RelPose) * HomMat3D_NFinalPose1,
whereas HomMat3D_* denotes a homogeneous transformation matrix of the respective poses and INV() inverts a
homogeneous matrix.
The computed average errors returned in Errors give an impression of the accuracy of the calibration. Using
the determined camera parameters they denote the average of the euklidean distance of the projection of the mark
centers of the model to their image.
Attention

Parameter

. NX (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )


Ordered Tuple with all X-coordinates of the calibration marks (in meters).
. NY (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Ordered Tuple with all Y-coordinates of the calibration marks (in meters).
. NZ (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
Ordered Tuple with all Z-coordinates of the calibration marks (in meters).
. NRow1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT
Ordered Tuple with all row-coordinates of the extracted calibration marks of camera 1 (in pixels).
. NCol1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT
Ordered Tuple with all column-coordinates of the extracted calibration marks of camera 1 (in pixels).
. NRow2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT
Ordered Tuple with all row-coordinates of the extracted calibration marks of camera 2 (in pixels).
. NCol2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT
Ordered Tuple with all column-coordinates of the extracted calibration marks of camera 2 (in pixels).
. StartCamParam1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( integer, real )
Initial values for the internal projective parameters of the projective camera 1.
. StartCamParam2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( integer, real )
Initial values for the internal projective parameters of teh projective camera 2.
. NStartPose1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pose ; VARIANT ( real, integer )
Ordered tuple with all initial values for the poses of the calibration model in relation to camera 1.
. NStartPose2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pose ; VARIANT ( real, integer )
Ordered tuple with all initial values for the poses of the calibration model in relation to camera 2.
. EstimateParams (input control) . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string, integer )
Camera parameters to be estimated.
Default Value : ’all’
List of values : EstimateParams ∈ {’all’, ’pose_rel’, ’pose1’, ’pose2’, ’cam_param1’, ’cam_param2’,
’alpha1’, ’beta1’, ’gamma1’, ’transx1’, ’transy1’, ’transz1’, ’alpha2’, ’beta2’, ’gamma2’, ’transx2’, ’transy2’,
’transz2’, ’focus1’, ’kappa1’, ’cx1’, ’cy1’, ’sx1’, ’sy1’, ’focus2’, ’kappa2’, ’cx2’, ’cy2’, ’sx2’, ’sy2’}
. CamParam1 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Internal Parameters of the projective camera 1.
. CamParam2 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Internal parameters of the projective camera 2.

HALCON/COM Reference Manual, 2008-5-13


15.17. STEREO 1301

. NFinalPose1 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pose ; VARIANT ( real, integer )


Ordered tuple with all poses of the calibration model in relation to camera 1.
. NFinalPose2 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pose ; VARIANT ( real, integer )
Ordered tuple with all poses of the calibration model in relation to camera 2.
. RelPose (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pose ; VARIANT ( real, integer )
Pose of camera 2 in relation to camera 1.
. Errors (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT
Average error distances in pixels.
Example

// open image source


close_all_framegrabbers ()
open_framegrabber (’File’, 1, 1, 0, 0, 0, 0, ’default’, -1, ’default’, -1,
’default’, ’images_l.seq’, ’default’, 0, -1, FGHandle1)
open_framegrabber (’File’, 1, 1, 0, 0, 0, 0, ’default’, -1, ’default’, -1,
’default’, ’images_r.seq’, ’default’, 1, -1, FGHandle2)

// initialize the start parameters


create_caltab (0.03, ’caltab_30.descr’, ’caltab_30.ps’)
caltab_points (’caltab_30.descr’, X, Y, Z)
StartCamParam1 := [0.0125, 0, 7.4e-6, 7.4e-6,Width/2.0,Height/2.0,Width,Height]
StartCamParam2 := StartCamParam1
Rows1 := []
Cols1 := []
StartPoses1 := []
Rows2 := []
Cols2 := []
StartPoses2 := []

// find calibration marks and startposes


for i := 0 to 11 by 1
grab_image_async (Image1, FGHandle1, -1)
grab_image_async (Image2, FGHandle2, -1)
find_caltab (Image1, Caltab1, ’caltab_30.descr’, 3, 120, 5)
find_caltab (Image2, Caltab2, ’caltab_30.descr’, 3, 120, 5)
find_marks_and_pose (Image1, Caltab1, ’caltab_30.descr’, StartCamParam1,
128, 10, 20, 0.7, 5, 100, RCoord1, CCoord1,
StartPose1)
Rows1 := [Rows1,RCoord1]
Cols1 := [Cols1,CCoord1]
StartPoses1 := [StartPoses1,StartPose1]
find_marks_and_pose (Image2, Caltab2, ’caltab_30.descr’, StartCamParam2,
128, 10, 20, 0.7, 5, 100, RCoord2, CCoord2,
StartPose2)
Rows2 := [Rows2,RCoord2]
Cols2 := [Cols2,CCoord2]
StartPoses2 := [StartPoses2,StartPose2]
endfor

// calibrate the stereo rig


binocular_calibration (X, Y, Z, Rows1, Cols1, Rows2, Cols2, StartCamParam1,
StartCamParam2, StartPoses1, StartPoses2, ’all’,
CamParam1, CamParam2, NFinalPose1, NFinalPose2,
RelPose, Errors)
// archive the results
write_cam_par (CamParam1, ’cam_left-125.dat’)
write_cam_par (CamParam2, ’cam_right-125.dat’)
write_pose (RelPose, ’rel_pose.dat’)

HALCON 8.0.2
1302 CHAPTER 15. TOOLS

// ... rectify the stereo images


gen_binocular_rectification_map (Map1, Map2, CamParam1, CamParam2, RelPose,
’geometric’, ’bilinear’, CamParamRect1, CamParamRect2, Cam1PoseRect1,
Cam2PoseRect2, RelPoseRect)
map_image (Image1, Map1, ImageMapped1)
map_image (Image2, Map2, ImageMapped2)

Result
BinocularCalibration returns TRUE if all parameter values are correct and the desired parameters have
been determined by the minimization algorithm. If necessary, an exception handling is raised.
Parallelization Information
BinocularCalibration is reentrant and processed without parallelization.
Possible Predecessors
FindMarksAndPose, CaltabPoints, ReadCamPar
Possible Successors
WritePose, WriteCamPar, PoseToHomMat3d, DispCaltab, GenBinocularRectificationMap
See also
FindCaltab, SimCaltab, ReadCamPar, CreatePose, ConvertPoseType, ReadPose,
HomMat3dToPose, CreateCaltab, BinocularDisparity, BinocularDistance
Module
3D Metrology

[out] HImageX Disparity HImageX.BinocularDisparity


([in] HImageX Image2, [out] HImageX Score, [in] String Method,
[in] long MaskWidth, [in] long MaskHeight, [in] VARIANT TextureThresh,
[in] long MinDisparity, [in] long MaxDisparity, [in] long NumLevels,
[in] VARIANT ScoreThresh, [in] VARIANT Filter, [in] String SubDisparity )
void HOperatorSetX.BinocularDisparity ([in] IHObjectX Image1,
[in] IHObjectX Image2, [out] HUntypedObjectX Disparity,
[out] HUntypedObjectX Score, [in] VARIANT Method, [in] VARIANT MaskWidth,
[in] VARIANT MaskHeight, [in] VARIANT TextureThresh,
[in] VARIANT MinDisparity, [in] VARIANT MaxDisparity, [in] VARIANT NumLevels,
[in] VARIANT ScoreThresh, [in] VARIANT Filter, [in] VARIANT SubDisparity )

Compute the disparities of a rectified image pair.


BinocularDisparity computes pixel-wise correspondences between two epipolar images using correlation
techniques. Different from BinocularDistance the results are not transformed into distance values.
The algorithm requires a reference image Image1 and a search image Image2 which must be rectified,
i.e., corresponding epipolar lines are parallel and lie on identical image rows ( r1 = r2 ). In case this
assumption is violated the images can be rectified by using the operators BinocularCalibration,
GenBinocularRectificationMap, and MapImage. Hence, given a pixel in the reference image Image1
the homologous pixel in Image2 is selected by searching along the corresponding row in Image2 and match-
ing a local neighborhood within a rectangular window of size MaskWidth and MaskHeight. The pixel cor-
respondences are returned in the single-channel Disparity image d(r1 , c1 ) which specifies for each pixel
(r1,c1) of the reference image Image1 a suitable matching pixel (r2,c2) of Image2 according to the equation
c2 = c1 + d(r1 , c1 ). A quality measure for each disparity value is returned in Score, containing the best result of
the matching function S of a reference pixel. For the matching, the gray values of the original unprocessed images
are used.
The used matching function is defined by the parameter Method allocating three different kinds of correlation:
r+m c+n
1
| g1 (r0 , c0 ) − g2 (r0 , c0 + d) |,
P P
• ’sad’: Summed Absolute Differences S(r, c, d) = N
r 0 =r−m c0 =c−n
with 0 ≤ S(r, c, d) ≤ 255.

HALCON/COM Reference Manual, 2008-5-13


15.17. STEREO 1303

r+m c+n
1
(g1 (r0 , c0 ) − g2 (r0 , c0 + d))2 ,
P P
• ’ssd’: Summed Squared Differences S(r, c, d) = N
r 0 =r−m c0 =c−n
with 0 ≤ S(r, c, d) ≤ 65025.
r+m
P c+n
P
(g1 (r 0 ,c0 )−g¯1 (r,c))(g2 (r 0 ,c0 +d)−g¯2 (r,c))
r 0 =r−m c0 =c−n
• ’nnc’: Normalized Cross Correlation S(r, c, d) = s ,
r+m
P c+n+d
P
(g1 (r 0 ,c0 )−g¯1 (r,c))2 (g2 (r 0 ,c0 +d)−g¯2 (r,c+d))2
r 0 =r−m c0 =c−n

with −1.0 ≤ S(r, c, d) ≤ 1.0.

with
r1, c1, r2, c2: row and column coordinates of the corresponding pixels of the two input images,
g1, g2: gray values of the unprocessed input images,
N = (2m + 1)(2n + 1): size of correlation window
r+m c+n
ḡ(r, c) = N1 g(r0 , c0 ): mean value within the correlation window of width 2m+1 and height 2n+1.
P P
r 0 =r−m c0 =c−n

It should be noted, that the quality of correlation for rising S is falling in methods ’sad’ and ’ssd’ (the best quality
value is 0) but rising in method ’ncc’ (the best quality value is 1.0).
The size of the correlation window, referenced by 2m + 1 and 2n + 1, has to be odd numbered and is passed in
MaskWidth and MaskHeight. The search space is confined by the minimum and maximum disparity value
MinDisparity and MaxDisparity. Due to pixel values not defined beyond the image border the resulting
domain of Disparity and Score is not set along the image border within a margin of height (MaskHeight-
1)/2 at the top and bottom border and of width (MaskWidth-1)/2 at the left and right border. For the same reason,
the maximum disparity range is reduced at the left and right image border.
Since matching turns out to be highly unreliable when dealing with poorly textured areas, the minimum statistical
spread of gray values within the correlation window can be defined in TextureThresh. This threshold is applied
on both input images Image1 and Image2. In addition, ScoreThresh guarantees the matching quality and
defines the maximum (’sad’,’ssd’) or, respectively, minimum (’ncc’) score value of the correlation function. Setting
Filter to ’left_right_check’, moreover, increases the robustness of the returned matches, as the result relies on a
concurrent direct and reverse match, whereas ’none’ switches it off.
The number of pyramid levels used to improve the time response of BinocularDisparity is determined by
NumLevels. Following a coarse-to-fine scheme disparity images of higher levels are computed and segmented
into rectangular subimages of similar disparity to reduce the disparity range on the next lower pyramid level.
TextureThresh and ScoreThresh are applied on every level and the returned domain of the Disparity
and Score images arises from the intersection of the resulting domains of every single level. Generally, pyramid
structures are the more advantageous the more the disparity image can be segmented into regions of homogeneous
disparities and the bigger the disparity range is specified. As a drawback, coarse pyramid levels might loose
important texture information which can result in deficient disparity values.
Finally, the value ’interpolation’ for parameter SubDisparity performs subpixel refinement of disparities. It is
switched off by setting the parameter to ’none’.
Parameter

. Image1 (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . (multichannel-)image ; HImageX / IHObjectX ( byte )


Epipolar image of camera 1.
. Image2 (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . (multichannel-)image ; HImageX / IHObjectX ( byte )
Epipolar image of camera 2.
. Disparity (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / HUntypedObjectX ( real )
Disparity map.
. Score (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / HUntypedObjectX ( real )
Evaluation of the disparity values.
. Method (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Matching function.
Default Value : ’ncc’
List of values : Method ∈ {’sad’, ’ssd’, ’ncc’}

HALCON 8.0.2
1304 CHAPTER 15. TOOLS

. MaskWidth (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT


Width of the correlation window.
Default Value : 11
Suggested values : MaskWidth ∈ {5, 7, 9, 11, 21}
Restriction : (M askW idth ∧ odd)
. MaskHeight (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Height of the correlation window.
Default Value : 11
Suggested values : MaskHeight ∈ {5, 7, 9, 11, 21}
Restriction : (M askHeight ∧ odd)
. TextureThresh (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real, integer )
Variance threshold of textured image regions.
Default Value : 0.0
Suggested values : TextureThresh ∈ {0.0, 10.0, 30.0}
Restriction : (0.0 ≤ T extureT hresh)
. MinDisparity (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Minimum of the expected disparities.
Default Value : -30.0
. MaxDisparity (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Maximum of the expected disparities.
Default Value : 30.0
. NumLevels (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of pyramid levels.
Default Value : 1
Suggested values : NumLevels ∈ {1, 2, 3, 4}
Restriction : (1 ≤ N umLevels)
. ScoreThresh (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real, integer )
Threshold of the correlation function.
Default Value : 0.5
Suggested values : ScoreThresh ∈ {-1.0, 0.0, 0.3, 0.5, 0.7}
. Filter (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Downstream filters.
Default Value : ’none’
List of values : Filter ∈ {’none’, ’left_right_check’}
. SubDisparity (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Subpixel interpolation of disparities.
Default Value : ’none’
List of values : SubDisparity ∈ {’none’, ’interpolation’}
Example

// ...
// read the internal and external stereo parameters
read_cam_par (’cam_left.dat’, CamParam1)
read_cam_par (’cam_right.dat’, CamParam2)
read_pose (’relpos.dat’, RelPose)

// compute the mapping for epipolar images


gen_binocular_rectification_map (Map1, Map2, CamParam1, CamParam2, RelPose,
’geometric’, ’bilinear’, CamParamRect1,CamParamRect2, Cam1PoseRect1,
Cam2PoseRect2,RelPoseRect)

// compute the disparities in online images


while 1
grab_image_async (Image1, FGHandle1, -1)
map_image (Image1, Map1, ImageMapped1)

grab_image_async (Image2, FGHandle2, -1)

HALCON/COM Reference Manual, 2008-5-13


15.17. STEREO 1305

map_image (Image2, Map2, ImageMapped2)

binocular_disparity(ImageMapped1, ImageMapped2, Disparity, Score, ’sad’,


11, 11, 20, -40, 20, 2, 25, ’left_right_check’,’interpolation’)
endfor

Result
BinocularDisparity returns TRUE if all parameter values are correct. If necessary, an exception handling
is raised.
Parallelization Information
BinocularDisparity is reentrant and automatically parallelized (on domain level).
Possible Predecessors
MapImage
Possible Successors
Threshold, DisparityToDistance
See also
MapImage, GenBinocularRectificationMap, BinocularCalibration
Alternatives
BinocularDistance
Module
3D Metrology

[out] HImageX Distance HImageX.BinocularDistance ([in] HImageX Image2,


[out] HImageX Score, [in] VARIANT CamParamRect1, [in] VARIANT CamParamRect2,
[in] VARIANT RelPoseRect, [in] String Method, [in] long MaskWidth,
[in] long MaskHeight, [in] VARIANT TextureThresh, [in] VARIANT MinDisparity,
[in] VARIANT MaxDisparity, [in] long NumLevels, [in] VARIANT ScoreThresh,
[in] VARIANT Filter, [in] VARIANT SubDistance )
[out] HImageX Distance HPoseX.BinocularDistance ([in] HImageX Image1,
[in] HImageX Image2, [out] HImageX Score, [in] VARIANT CamParamRect1,
[in] VARIANT CamParamRect2, [in] VARIANT RelPoseRect, [in] String Method,
[in] long MaskWidth, [in] long MaskHeight, [in] VARIANT TextureThresh,
[in] VARIANT MinDisparity, [in] VARIANT MaxDisparity, [in] long NumLevels,
[in] VARIANT ScoreThresh, [in] VARIANT Filter, [in] VARIANT SubDistance )
void HOperatorSetX.BinocularDistance ([in] IHObjectX Image1,
[in] IHObjectX Image2, [out] HUntypedObjectX Distance,
[out] HUntypedObjectX Score, [in] VARIANT CamParamRect1,
[in] VARIANT CamParamRect2, [in] VARIANT RelPoseRect, [in] VARIANT Method,
[in] VARIANT MaskWidth, [in] VARIANT MaskHeight, [in] VARIANT TextureThresh,
[in] VARIANT MinDisparity, [in] VARIANT MaxDisparity, [in] VARIANT NumLevels,
[in] VARIANT ScoreThresh, [in] VARIANT Filter, [in] VARIANT SubDistance )

Compute the distance values for a rectified stereo image pair.


BinocularDistance computes pixel-wise correspondences between two images of a rectified stereo rig using
correlation techniques. Different from BinocularDistance this operator transforms these pixel correlations
into distances of the corresponding 3D world points to the stereo camera system.
The algorithm requires a reference image Image1 and a search image Image2 which must be rectified,
i.e., corresponding epipolar lines are parallel and lie on identical image rows ( r1 = r2 ). In case this
assumption is violated the images can be rectified by using the operators BinocularCalibration,
GenBinocularRectificationMap and MapImage. Hence, given a pixel in the reference image Image1
the homologous pixel in Image2 is selected by searching along the corresponding row in Image2 and matching
a local neighborhood within a rectangular window of size MaskWidth and MaskHeight. For each defined

HALCON 8.0.2
1306 CHAPTER 15. TOOLS

reference pixel the pixel correspondences are transformed into distances of the world points defined by the in-
tersection of the lines of sight of a corresponding pixel pair to the z = 0 plane of the rectified stereo system.
These distances are returned in the single channel image Distance. For this transformation the rectified inter-
nal camera parameters CamParamRect1 of the projective camera 1 and CamParamRect2 of the projective
camera 2, and the the external parameters RelPoseRect have to be defined. Latter characterizes the relative
pose of both cameras to each other and specifies a point transformation from the rectified camera system 2 to the
rectified camera system 1. These parameters can be obtained from the operator BinocularCalibration
and GenBinocularRectificationMap. After all, a quality measure for each distance value is returned in
Score, containing the best result of the matching function S of a reference pixel. For the matching, the gray
values of the original unprocessed images are used.
The used matching function is defined by the parameter Method allocating three different kinds of correlation:
r+m c+n
1
| g1 (r0 , c0 ) − g2 (r0 , c0 + d) |,
P P
• ’sad’: Summed Absolute Differences S(r, c, d) = N
r 0 =r−m c0 =c−n
with 0 ≤ S(r, c, d) ≤ 255.
r+m c+n
1
(g1 (r0 , c0 ) − g2 (r0 , c0 + d))2 ,
P P
• ’ssd’: Summed Squared Differences S(r, c, d) = N
r 0 =r−m c0 =c−n
with 0 ≤ S(r, c, d) ≤ 65025.
r+m
P c+n
P
(g1 (r 0 ,c0 )−g¯1 (r,c))(g2 (r 0 ,c0 +d)−g¯2 (r,c+d))
r 0 =r−m c0 =c−n
• ’nnc’: Normalized Cross Correlation S(r, c, d) = s ,
r+m
P c+n
P
(g1 (r 0 ,c0 )−g¯1 (r,c))2 (g2 (r 0 ,c0 +d)−g¯2 (r,c+d))2
r 0 =r−m c0 =c−n

with −1.0 ≤ S(r, c, d) ≤ 1.0.

with
r1, c1, r2, c2: row and column coordinates of the corresponding pixels of the two input images,
g1, g2: gray values of the unprocessed input images,
N = (2m + 1)(2n + 1): size of correlation window
r+m c+n
ḡ(r, c) = N1 g(r0 , c0 ): mean value within the correlation window of width 2m+1 and height 2n+1.
P P
r 0 =r−m c0 =c−n

It should be noted that the quality of correlation for rising S is falling in methods ’sad’ and ’ssd’ (the best quality
value is 0) but rising in method ’ncc’ (the best quality value is 1.0).
The size of the correlation window has to be odd numbered and is passed in MaskWidth and MaskHeight. The
search space is confined by the minimum and maximum disparity value MinDisparity and MaxDisparity.
Due to pixel values not defined beyond the image border the resulting domain of Distance and Score is
generally not set along the image border within a margin of height MaskHeight/2 at the top and bottom border
and of width MaskWidth/2 at the left and right border. For the same reason, the maximum disparity range is
reduced at the left and right image border.
Since matching turns out to be highly unreliable when dealing with poorly textured areas, the minimum variance
within the correlation window can be defined in TextureThresh. This threshold is applied on both input
images Image1 and Image2. In addition, ScoreThresh guarantees the matching quality and defines the
maximum (’sad’,’ssd’) or, respectively, minimum (’ncc’) score value of the correlation function. Setting Filter
to ’left_right_check’, moreover, increases the robustness of the returned matches, as the result relies on a concurrent
direct and reverse match, whereas ’none’ switches it off.
The number of pyramid levels used to improve the time response of BinocularDistance is determined by
NumLevels. Following a coarse-to-fine scheme disparity images of higher levels are computed and segmentated
into rectangular subimages to reduce the disparity range on the next lower pyramid level. TextureThresh and
ScoreThresh are applied on every level and the returned domain of the Distance and Score images arises
from the intersection of the resulting domains of every single level. Generally, pyramid structures are the more
advantageous the more the distance image can be segmented into regions of homogeneous distance values and the
bigger the disparity range must be specified. As a drawback, coarse pyramid levels might loose important texture
information which can result in deficient distance values.
Finally, the value ’interpolation’ for parameter SubDistance increases the refinement and accuracy of the dis-
tance values. It is switched off by setting the parameter to ’none’.

HALCON/COM Reference Manual, 2008-5-13


15.17. STEREO 1307

Parameter

. Image1 (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . (multichannel-)image ; HImageX / IHObjectX ( byte )


Epipolar image of camera 1.
. Image2 (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . (multichannel-)image ; HImageX / IHObjectX ( byte )
Epipolar image of camera 2.
. Distance (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / HUntypedObjectX ( real )
Distance image.
. Score (output iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / HUntypedObjectX ( real )
Evaluation of a distance value.
. CamParamRect1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Rectified internal camera parameters of the projective camera 1.
Number of elements : 8
. CamParamRect2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Rectified internal camera parameters of the projective camera 2.
Number of elements : 8
. RelPoseRect (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pose ; VARIANT ( integer, real )
Point transformation from rectified camera 2 to rectified camera 1.
Number of elements : 7
. Method (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Matching function.
Default Value : ’ncc’
List of values : Method ∈ {’sad’, ’ssd’, ’ncc’}
. MaskWidth (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Width of the correlation window.
Default Value : 11
Suggested values : MaskWidth ∈ {5, 7, 9, 11, 21}
Restriction : (M askW idth ∧ odd)
. MaskHeight (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Height of the correlation window.
Default Value : 11
Suggested values : MaskHeight ∈ {5, 7, 9, 11, 21}
Restriction : (M askHeight ∧ odd)
. TextureThresh (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real, integer )
Variance threshold of textured image regions.
Default Value : 0.0
Suggested values : TextureThresh ∈ {-1.0, 0.0, 0.3, 0.5, 0.7}
Restriction : (0.0 ≤ T extureT hresh)
. MinDisparity (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real, integer )
Minimum of the expected disparities.
Default Value : 0.0
. MaxDisparity (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real, integer )
Maximum of the expected disparities.
Default Value : 30.0
. NumLevels (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Number of pyramid levels.
Default Value : 1
List of values : NumLevels ∈ {1, 2, 3, 4}
Restriction : (1 ≤ N umLevels)
. ScoreThresh (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real, integer )
Threshold of the correlation function.
Default Value : 0.0
List of values : ScoreThresh ∈ {-1.0, 0.0, 0.3, 0.5, 0.7}
. Filter (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )
Downstream filters.
Default Value : ’none’
List of values : Filter ∈ {’none’, ’left_right_check’}

HALCON 8.0.2
1308 CHAPTER 15. TOOLS

. SubDistance (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string(-array) ; VARIANT ( string )


Distance interpolation.
Default Value : ’none’
List of values : SubDistance ∈ {’none’, ’interpolation’}
Example

// ...
// read the internal and external stereo parameters
read_cam_par (’cam_left.dat’, CamParam1)
read_cam_par (’cam_right.dat’, CamParam2)
read_pose (’relpose.dat’, RelPose)

// compute the mapping for epipolar images


gen_binocular_rectification_map (Map1, Map2, CamParam1, CamParam2, RelPose,
’geometric’, ’bilinear’, CamParamRect1,
CamParamRect2, Cam1PoseRect1, Cam2PoseRect2,
RelPoseRect)

// compute the distance values on online images


while 1
grab_image_async (Image1, FGHandle1, -1)
map_image (Image1, Map1, ImageMapped1)

grab_image_async (Image2, FGHandle2, -1)


map_image (Image2, Map2, ImageMapped2)

binocular_distance(ImageMapped1, ImageMapped2, Distance, Score, ’sad’,


11, 11, 20, -40, 20, 2, 25, ’left_right_check’,
’interpolation’)
endwhile

Result
BinocularDisparity returns TRUE if all parameter values are correct. If necessary, an exception handling
is raised.
Parallelization Information
BinocularDistance is reentrant and automatically parallelized (on domain level).
Possible Predecessors
MapImage
Possible Successors
Threshold
See also
MapImage, GenBinocularRectificationMap, BinocularCalibration,
DistanceToDisparity, DisparityToDistance
Alternatives
BinocularDisparity
Module
3D Metrology

HALCON/COM Reference Manual, 2008-5-13


15.17. STEREO 1309

[out] VARIANT Distance HPoseX.DisparityToDistance


([in] VARIANT CamParamRect1, [in] VARIANT CamParamRect2,
[in] VARIANT RelPoseRect, [in] VARIANT Disparity )
void HOperatorSetX.DisparityToDistance ([in] VARIANT CamParamRect1,
[in] VARIANT CamParamRect2, [in] VARIANT RelPoseRect, [in] VARIANT Disparity,
[out] VARIANT Distance )

Transform a disparity value into a distance value in a rectified binocular stereo system.
DisparityToDistance transforms a disparity value into a distance of an object point to the binocular
stereo system. The cameras of this system must be rectified and are defined by the rectified internal parame-
ters CamParamRect1 of the projective camera 1 and CamParamRect2 of the projective camera 2, and the
external parameters RelPoseRect. Latter specifies the relative pose of both cameras to each other by defin-
ing a point transformation from rectified camera system 2 to rectified camera system 1. These parameters can
be obtained from the operator BinocularCalibration and GenBinocularRectificationMap. The
disparity value Disparity is defined by the column difference of the image coordinates of two corresponding
points on an epipolar line according to the equation d = c2 − c1 (see also BinocularDisparity). This value
characterises a set of 3D object points of an equal distance to a plane beeing parallel to the rectified image plane of
the stereo system. The distance to the subset plane z = 0 which is parallel to the rectified image plane and contains
the optical centers of both cameras is returned in Distance.
Parameter

. CamParamRect1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )


Rectified internal camera parameters of the projective camera 1.
Number of elements : 8
. CamParamRect2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Rectified internal camera parameters of the projective camera 2.
Number of elements : 8
. RelPoseRect (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pose ; VARIANT ( integer, real )
Point transformation from rectified camera 2 to rectified camera 1.
Number of elements : 7
. Disparity (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( integer, real )
Disparity between the images of the world point.
. Distance (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Distance of a world point to the rectified camera system.
Result
DisparityToDistance returns TRUE if all parameter values are correct. If necessary, an exception handling
is raised.
Parallelization Information
DisparityToDistance is reentrant and processed without parallelization.
Possible Predecessors
BinocularCalibration, GenBinocularRectificationMap, MapImage,
BinocularDisparity
See also
DistanceToDisparity, DisparityToPoint3D
Alternatives
BinocularDistance
Module
3D Metrology

HALCON 8.0.2
1310 CHAPTER 15. TOOLS

[out] VARIANT X HPoseX.DisparityToPoint3D ([in] VARIANT CamParamRect1,


[in] VARIANT CamParamRect2, [in] VARIANT RelPoseRect, [in] VARIANT Row1,
[in] VARIANT Col1, [in] VARIANT Disparity, [out] VARIANT Y, [out] VARIANT Z )
void HOperatorSetX.DisparityToPoint3D ([in] VARIANT CamParamRect1,
[in] VARIANT CamParamRect2, [in] VARIANT RelPoseRect, [in] VARIANT Row1,
[in] VARIANT Col1, [in] VARIANT Disparity, [out] VARIANT X, [out] VARIANT Y,
[out] VARIANT Z )

Transform an image point and its disparity into a 3D point in a rectified stereo system.
Given an image point of the rectified camera 1, specified by its image coordinates (Row1,Col1), and its disparity
in a rectified binocular stereo system, DisparityToPoint3D computes the corresponding three dimensional
object point. Whereby the disparity value Disparity defines the column difference of the image coordinates
of two corresponding features on an epipolar line according to the equation d = c2 − c1 . The rectified binocular
camera system is specified by its internal camera parameters CamParamRect1 of the projective camera 1 and
CamParamRect2 of the projective camera 2, and the external parameters RelPoseRect defining the pose of
the rectified camera 2 in relation to the rectified camera 1. These camera parameters can be obtained from the
operators BinocularCalibration and GenBinocularRectificationMap. The 3D point is returned
in Cartesian coordinates (X,Y,Z) of the rectified camera system 1.
Parameter

. CamParamRect1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )


Rectified internal camera parameters of the projective camera 1.
Number of elements : 8
. CamParamRect2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Rectified internal camera parameters of the projective camera 2.
Number of elements : 8
. RelPoseRect (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pose ; VARIANT ( integer, real )
Pose of the rectified camera 2 in relation to the rectified camera 1.
Number of elements : 7
. Row1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( integer, real )
Row coordinate of a point in the rectified image 1.
. Col1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( integer, real )
Column coordinate of a point in the rectified image 1.
. Disparity (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( integer, real )
Disparity of the images of the world point.
. X (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
X coordinate of the 3D point.
. Y (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Y coordinate of the 3D point.
. Z (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Z coordinate of the 3D point.
Result
DisparityToPoint3D returns TRUE if all parameter values are correct. If necessary, an exception handling
is raised.
Parallelization Information
DisparityToPoint3D is reentrant and processed without parallelization.
Possible Predecessors
BinocularCalibration, GenBinocularRectificationMap
Possible Successors
BinocularDisparity, BinocularDistance
See also
IntersectLinesOfSight
Module
3D Metrology

HALCON/COM Reference Manual, 2008-5-13


15.17. STEREO 1311

[out] VARIANT Disparity HPoseX.DistanceToDisparity


([in] VARIANT CamParamRect1, [in] VARIANT CamParamRect2,
[in] VARIANT RelPoseRect, [in] VARIANT Distance )
void HOperatorSetX.DistanceToDisparity ([in] VARIANT CamParamRect1,
[in] VARIANT CamParamRect2, [in] VARIANT RelPoseRect, [in] VARIANT Distance,
[out] VARIANT Disparity )

Transfrom a distance value into a disparity in a rectified stereo system.


DistanceToDisparity transforms a distance of a 3D point to the binocular stereo system into a dispar-
ity value. The cameras of this system must be rectified and are defined by the rectified internal parameters
CamParamRect1 of the projective camera 1 and CamParamRect2 of the projective camera 2 and the external
parameters RelPoseRect. latter specifies the relative pose of both camera systems to each other by defining a
point transformation from the rectified camera system 2 to the rectified camera system 1. These parameters can
be obtained from the operator BinocularCalibration and GenBinocularRectificationMap. The
distance value is passed in Distance and the resulting disparity value Disparity is defined by the column
difference of the image coordinates of two corresponding features on an epipolar line according to the equation
d = c2 − c1 .
Parameter

. CamParamRect1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )


rectified internal camera parameters of the projective camera 1.
Number of elements : 8
. CamParamRect2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
rectified internal camera parameters of the projective camera 2.
Number of elements : 8
. RelPoseRect (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pose ; VARIANT ( integer, real )
Point transformation from rectified camera 2 to rectified camera 1.
Number of elements : 7
. Distance (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Distance of a world point to camera 1.
Restriction : (0 < Distance)
. Disparity (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( integer, real )
Disparity between the images of the point.
Result
DistanceToDisparity returns TRUE if all parameter values are correct. If necessary, an exception handling
is raised.
Parallelization Information
DistanceToDisparity is reentrant and processed without parallelization.
Possible Predecessors
BinocularCalibration, GenBinocularRectificationMap
Possible Successors
BinocularDisparity
Module
3D Metrology

[out] HHomMat2dX FMatrix HHomMat2dX.EssentialToFundamentalMatrix


([in] VARIANT CovEMat, [in] HHomMat2dX CamMat1, [in] HHomMat2dX CamMat2,
[out] VARIANT CovFMat )
void HOperatorSetX.EssentialToFundamentalMatrix
([in] VARIANT EMatrix, [in] VARIANT CovEMat, [in] VARIANT CamMat1,
[in] VARIANT CamMat2, [out] VARIANT FMatrix, [out] VARIANT CovFMat )

Compute the fundamental matrix from an essential matrix.

HALCON 8.0.2
1312 CHAPTER 15. TOOLS

The fundamental matrix is the entity describing the epipolar constraint in image coordinates (C,R) and the essential
matrix is its counterpart for 3D direction vectors (X,Y,1):
 T    T  
C2 C1 X2 X1
 R2  · FMatrix ·  R1  = 0 and  Y2  · EMatrix ·  Y1  = 0 .
1 1 1 1

Image coordinates result from 3D direction vectors by multiplication with the camera matrix CamM at:
   
col X
 row  = CamM at ·  Y  .
1 1

Therefore, the fundamental matrix FMatrix is calculated from the essential matrix EMatrix and the camera
matrices CamMat1, CamMat2 by the following formula:

FMatrix = CamMat2−T · EMatrix · CamMat1−1 .

The transformation of the essential matrix to the fundamental matrix goes along with the propagation of the co-
variance matrices CovEMat to CovFMat. If CovEMat is empty CovFMat will be empty too.
The conversion operator EssentialToFundamentalMatrix is used especially for a subsequent visualiza-
tion of the epipolar line structure via the fundamental matrix, which depicts the underlying stereo geometry.
Parameter

. EMatrix (input control) . . . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real, integer )


Essential matrix.
. CovEMat (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
9 × 9 covariance matrix of the essential matrix.
Default Value : []
. CamMat1 (input control) . . . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real, integer )
Camera matrix of the 1. camera.
. CamMat2 (input control) . . . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real, integer )
Camera matrix of the 2. camera.
. FMatrix (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )
Computed fundamental matrix.
. CovFMat (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT
9 × 9 covariance matrix of the fundamental matrix.
Parallelization Information
EssentialToFundamentalMatrix is reentrant and processed without parallelization.
Possible Predecessors
VectorToEssentialMatrix
Alternatives
RelPoseToFundamentalMatrix
References

Module
3D Metrology

HALCON/COM Reference Manual, 2008-5-13


15.17. STEREO 1313

void HImageX.GenBinocularProjRectification ([out] HImageX Map2,


[in] HHomMat2dX FMatrix, [in] VARIANT CovFMat, [in] long Width1,
[in] long Height1, [in] long Width2, [in] long Height2,
[in] VARIANT SubSampling, [in] String Mapping, [out] VARIANT CovFMatRect,
[out] HHomMat2dX H1, [out] HHomMat2dX H2 )
[out] HImageX Map1 HHomMat2dX.GenBinocularProjRectification
([out] HImageX Map2, [in] VARIANT CovFMat, [in] long Width1,
[in] long Height1, [in] long Width2, [in] long Height2,
[in] VARIANT SubSampling, [in] String Mapping, [out] VARIANT CovFMatRect,
[out] HHomMat2dX H1, [out] HHomMat2dX H2 )
void HOperatorSetX.GenBinocularProjRectification
([out] HUntypedObjectX Map1, [out] HUntypedObjectX Map2,
[in] VARIANT FMatrix, [in] VARIANT CovFMat, [in] VARIANT Width1,
[in] VARIANT Height1, [in] VARIANT Width2, [in] VARIANT Height2,
[in] VARIANT SubSampling, [in] VARIANT Mapping, [out] VARIANT CovFMatRect,
[out] VARIANT H1, [out] VARIANT H2 )

Compute the projective rectification of weakly calibrated binocular stereo images.


A binocular stereo setup is called weakly calibrated if the fundamental matrix, which describes the projective
relation between the two images, is known. Rectification is the process of finding a suitable set of transformations,
that transform both images such that all corresponding epipolar lines become collinear and parallel to the horizontal
axes. The rectified images can be thought of as aquired by a stereo configuration where the left and right image
plane are identical and the difference between both image centres is a horizontal translation. Note that rectification
can only be performed if both of the epipoles are located outside the images.
Typically, the fundamental matrix is calculated beforehand with MatchFundamentalMatrixRansac and
FMatrix is the basis for the computation of the two homographies H1 and H2, which describe the rectifications
for the left image and the right image respectively. Since a projective rectification is an underdetermined problem,
additional constraints are defined: the algorithm chooses the set of homographies that minimizes the projective
distortion induced by the homographies in both images. For the computation of this cost function the dimensions
of the images must be provided in Width1, Height1, Width2, Height2. After rectification the fundamental
matrix is always of the canonical form
 
0 0 0
 0 0 −1  .
0 1 0

In the case of a known covariance matrix CovFMat of the fundamental matrix FMatrix, the covariance matrix
CovFMatRect of the above rectified fundamental matrix is calculated. This can help for an improved stereo
matching process because the covariance matrix defines in terms of probabilities the image domain where to find
a corresponding match.
Similar to the operator GenBinocularRectificationMap the output images Map1 and Map2 describe
the transformation, also called mapping, of the original images to the rectified ones. The parameter Mapping
specifies whether bilinear interpolation (’bilinear_map’) should be applied between the pixels in the input image
or whether the gray value of the nearest neighboring pixel should be taken (’nn_map’). The size and resolution
of the maps and of the transformed images can be adjusted by the parameter SubSampling, which applies a
sub-sampling factor to the original images. For example, a factor of two will halve the image sizes. If just the two
homographies are required Mapping can be set to ’no_map’ and no maps will be returned. For speed reasons,
this option should be used if for a specific stereo configuration the images must be rectified only once. If the stereo
setup is fixed, the maps should be generated only once and both images should be rectified with MapImage; this
will result in the smallest computational cost for on-line rectification.
When using the maps, the transformed images are of the same size as their maps. Each pixel in the map contains
the description of how the new pixel at this position is generated. The images Map1 and Map2 are single channel
images if Mapping is set to ’nn_map’ and five channel images if it is set to ’bilinear_map’. In the first channel,
which is of type int4, the pixels contain the linear coordinates of their reference pixels in the original image. With
Mapping equal to ’no_map’ this reference pixel is the nearest neighbor to the back-transformed pixel coordinates
of the map. In the case of bilinear interpolation the reference pixel is the next upper left pixel relative to the back-

HALCON 8.0.2
1314 CHAPTER 15. TOOLS

transformed coordinates. The following scheme shows the ordering of the pixels in the original image next to the
back-transformed pixel coordinates, where the reference pixel takes the number 2.

2 3
4 5

The channels 2 to 5, which are of type uint2, contain the weights of the relevant pixels for the bilinear interpolation.
Based on the rectified images, the disparity be computed using BinocularDisparity. In contrast to stereo
with fully calibrated cameras, using the operator GenBinocularRectificationMap and its successors,
metric depth information can not be derived for weakly calibrated cameras. The disparity map gives just a qualita-
tive depth ordering of the scene.
Parameter

. Map1 (output iconic) . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX ( int4, uint2 )


Image coding the rectification of the 1. image.
. Map2 (output iconic) . . . . . . . . . . . . . . . . . . . . . . . image(-array) ; HImageX / HUntypedObjectX ( int4, uint2 )
Image coding the rectification of the 2. image.
. FMatrix (input control) . . . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real, integer )
Fundamental matrix.
. CovFMat (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
9 × 9 covariance matrix of the fundamental matrix.
Default Value : []
. Width1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Width of the 1. image.
Default Value : 512
List of values : Width1 ∈ {128, 256, 512, 1024}
Restriction : (W idth1 > 0)
. Height1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Height of the 1. image.
Default Value : 512
List of values : Height1 ∈ {128, 256, 512, 1024}
Restriction : (Height1 > 0)
. Width2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Width of the 2. image.
Default Value : 512
List of values : Width2 ∈ {128, 256, 512, 1024}
Restriction : (W idth2 > 0)
. Height2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Height of the 2. image.
Default Value : 512
List of values : Height2 ∈ {128, 256, 512, 1024}
Restriction : (Height2 > 0)
. SubSampling (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Subsampling factor.
Default Value : 1
List of values : SubSampling ∈ {1, 2, 3, 1.5}
. Mapping (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Type of mapping.
Default Value : ’no_map’
List of values : Mapping ∈ {’no_map’, ’nn_map’, ’bilinear_map’}
. CovFMatRect (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real )
9 × 9 covariance matrix of the rectified fundamental matrix.
. H1 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )
Projective transformation of the 1. image.
. H2 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )
Projective transformation of the 2. image.

HALCON/COM Reference Manual, 2008-5-13


15.17. STEREO 1315

Parallelization Information
GenBinocularProjRectification is reentrant and processed without parallelization.
Possible Predecessors
MatchFundamentalMatrixRansac, VectorToFundamentalMatrix
Possible Successors
MapImage, ProjectiveTransImage, BinocularDisparity
Alternatives
GenBinocularRectificationMap
References
J. Gluckmann and S.K. Nayar: “Rectifying transformations that minimize resampling effects”; IEEE Conference
on Computer Vision and Pattern Recognition (CVPR) 2001, vol I, pages 111-117.
Module
3D Metrology

void HImageX.GenBinocularRectificationMap ([out] HImageX Map2,


[in] VARIANT CamParam1, [in] VARIANT CamParam2, [in] VARIANT RelPose,
[in] double SubSampling, [in] String Method, [in] String Interpolation,
[out] VARIANT CamParamRect1, [out] VARIANT CamParamRect2,
[out] VARIANT CamPoseRect1, [out] VARIANT CamPoseRect2,
[out] VARIANT RelPoseRect )
[out] HImageX Map1 HPoseX.GenBinocularRectificationMap
([out] HImageX Map2, [in] VARIANT CamParam1, [in] VARIANT CamParam2,
[in] VARIANT RelPose, [in] double SubSampling, [in] String Method,
[in] String Interpolation, [out] VARIANT CamParamRect1,
[out] VARIANT CamParamRect2, [out] VARIANT CamPoseRect1,
[out] VARIANT CamPoseRect2, [out] VARIANT RelPoseRect )
void HOperatorSetX.GenBinocularRectificationMap
([out] HUntypedObjectX Map1, [out] HUntypedObjectX Map2,
[in] VARIANT CamParam1, [in] VARIANT CamParam2, [in] VARIANT RelPose,
[in] VARIANT SubSampling, [in] VARIANT Method, [in] VARIANT Interpolation,
[out] VARIANT CamParamRect1, [out] VARIANT CamParamRect2,
[out] VARIANT CamPoseRect1, [out] VARIANT CamPoseRect2,
[out] VARIANT RelPoseRect )

Generate transformation maps that describe the mapping of the images of a binocular camera pair to a common
rectified image plane.
Given a pair of stereo images, rectification determines a transformation of each image plane in a way that pairs of
conjugate epipolar lines become collinear and parallel to the horizontal image axes. The rectified epipolar images
can be thought of as acquired by a new stereo rig, obtained by rotating the original cameras. The camera centers of
this virtual rig are maintained whereas the image planes coincide, which means that the focal lengths are set equal,
and the optical axes parallel.
To achieve the transformation map for epipolar images GenBinocularRectificationMap requires the
internal camera parameters CamParam1 of the projective camera 1 and CamParam2 of the projective camera 2,
as well as the relative pose RelPose defining a point transformation from camera 2 to camera 1. These parameters
can be obtained, e.g., from the operator BinocularCalibration.
The projection onto a common plane has many degrees of freedom which are implicitly restricted by selecting a
certain method in Method (currently only one method available):

• ’geometric’ specifies the orientation of the common image plane by the cross product of the base line and the
line of intersection of the original image planes. The new focal length are determined in such a way as the
old prinzipal points have the same distance to the new common image plane.

Similar to GenImageToWorldPlaneMap the parameter Interpolation specifies whether bilinear inter-


polation (’bilinear’) should be applied between the pixels in the input image or the gray value of the nearest

HALCON 8.0.2
1316 CHAPTER 15. TOOLS

neighboring pixel should be taken (’none’). The size and resolution of the maps and of the transformed images can
be adjusted by the SubSampling parameter which applies a sub-sampling factor to the original images.
The mapping functions for the images of camera 1 and camera 2 are returned in the images Map1 and Map2.
If Interpolation is set to ’none’, both maps consist of one single-channel image which contains the linear
coordinate of the pixel of the respective input image that is the nearest neighbor of the transformed coordinate.
In case of bilinear interpolation, each map contains one five-channel image. The first channel contains for each
pixel of the respective map the linear coordinate of the pixel in the respective input image that is in the upper left
position with respect to the transformed coordinate. The remaining four channels of each map contain the weights
of the four neighboring pixels of the transformed coordinates which are used for the bilinear interpolation. The
mapping of the channel numbers to the neighboring pixels is as follows:

2 3
4 5

In addition, GenBinocularRectificationMap returns the modified internal and external camera parame-
ters of the rectified stereo rig. CamParamRect1 and CamParamRect2 contain the modified internal parameters
of camera 1 and camera 2, respectively. The rotation of the rectified camera in relation to the original camera is
specified by CamPoseRect1 and CamPoseRect2, respectively. Finally, RelPoseRect returns the modified
relative pose of the rectified camera system 2 in relation to the rectified camera system 1 defining a translation in x
only. Generally, the transformations are defined in a way that the rectified camera 1 is left of the rectified camera
2. This means that the optical center of camera 2 has a positive x coordinate of the rectified coordinate system of
camera 1.
Parameter
. Map1 (output iconic) . . . . . . . . . . . . . . . . (multichannel-)image ; HImageX / HUntypedObjectX ( int4, uint2 )
Image containing the mapping data of camera 1.
. Map2 (output iconic) . . . . . . . . . . . . . . . . (multichannel-)image ; HImageX / HUntypedObjectX ( int4, uint2 )
Image containing the mapping data of camera 2.
. CamParam1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Internal parameters of the projective camera 1.
Number of elements : 8
. CamParam2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Internal parameters of the projective camera 2.
Number of elements : 8
. RelPose (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pose ; VARIANT ( integer, real )
Point transformation from camera 2 to camera 1.
Number of elements : 7
. SubSampling (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Factor of sub sampling.
Default Value : 1.0
Suggested values : SubSampling ∈ {0.5, 0.66, 1.0, 1.5, 2.0, 3.0, 4.0}
. Method (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Type of rectification.
Default Value : ’geometric’
List of values : Method ∈ {’geometric’}
. Interpolation (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Type of interpolation.
Default Value : ’bilinear’
List of values : Interpolation ∈ {’none’, ’bilinear’}
. CamParamRect1 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Rectified internal parameters of the projective camera 1.
Number of elements : 8
. CamParamRect2 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Rectified internal parameters of the projective camera 2.
Number of elements : 8
. CamPoseRect1 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pose ; VARIANT ( integer, real )
Point transformation from the rectified camera 1 to the original camera 1.
Number of elements : 7

HALCON/COM Reference Manual, 2008-5-13


15.17. STEREO 1317

. CamPoseRect2 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pose ; VARIANT ( integer, real )


Point transformation from the rectified camera 1 to the original camera 1.
Number of elements : 7
. RelPoseRect (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pose ; VARIANT ( integer, real )
Point transformation from the rectified camera 2 to the rectified camera 1.
Number of elements : 7
Example

// ...
// read the internal and external stereo parameters
read_cam_par (’cam_left.dat’, CamParam1)
read_cam_par (’cam_right.dat’, CamParam2)
read_pose (’relpos.dat’, RelPose)

// the stereo images


gen_binocular_rectification_map (Map1, Map2, CamParam1, CamParam2, RelPose,
’geometric’, ’bilinear’, CamParRect1,
CamParamRect2, Cam1PoseRect1, Cam2PoseRect2,
RelPoseRect)

while 1
grab_image_async (Image1, FGHandle1, -1)
map_image (Image1, Map1, ImageMapped1)

grab_image_async (Image2, FGHandle2, -1)


map_image (Image2, Map2, ImageMapped2)

binocular_disparity(ImageMapped1, ImageMapped2, Disparity, Score, ’sad’,


11, 11, 20, -40, 20, 2, 25, ’left_right_check’,
’interpolation’)
endwhile

Result
GenBinocularRectificationMap returns TRUE if all parameter values are correct. If necessary, an ex-
ception handling is raised.
Parallelization Information
GenBinocularRectificationMap is reentrant and processed without parallelization.
Possible Predecessors
BinocularCalibration
Possible Successors
MapImage
See also
MapImage, GenImageToWorldPlaneMap, ContourToWorldPlaneXld,
ImagePointsToWorldPlane
Alternatives
GenImageToWorldPlaneMap
Module
3D Metrology

void HOperatorSetX.IntersectLinesOfSight ([in] VARIANT CamParam1,


[in] VARIANT CamParam2, [in] VARIANT RelPose, [in] VARIANT Row1,
[in] VARIANT Col1, [in] VARIANT Row2, [in] VARIANT Col2, [out] VARIANT X,
[out] VARIANT Y, [out] VARIANT Z, [out] VARIANT Dist )

Get a 3D point from the intersection of two lines of sight within a binocular camera system.

HALCON 8.0.2
1318 CHAPTER 15. TOOLS

Given two lines of sight from different cameras, specified by their image points (Row1,Col1) of camera 1 and
(Row2,Col2) of camera 2, IntersectLinesOfSight computes the 3D point of intersection of these lines.
The binocular camera system is specified by its internal camera parameters CamParam1 of the projective cam-
era 1 and CamParam2 of the projective camera 2, and the external parameters RelPose defining the pose of
the cameras by a point transformation from camera 2 to camera 1. These camera parameters can be obtained,
e.g., from the operator BinocularCalibration, if the coordinates of the image points (Row1,Col1) and
(Row2,Col2) refer to the respective original image coordinate system. In case of rectified image coordinates (
e.g., obtained from epipolar images), the rectified camera parameters must be passed, as they are returned by the
operator GenBinocularRectificationMap. The ’point of intersection’ is defined by the point with the
shortest distance to both lines of sight. This point is returned in Cartesian coordinates (X,Y,Z) of camera system 1
and its distance to the lines of sight is passed in Dist.
Parameter

. CamParam1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )


Internal parameters of the projective camera 1.
Number of elements : 8
. CamParam2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Internal parameters of the projective camera 2.
Number of elements : 8
. RelPose (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pose ; VARIANT ( integer, real )
Point transformation from camera 2 to camera 1.
Number of elements : 7
. Row1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( integer, real )
Row coordinate of a point in image 1.
. Col1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( integer, real )
Column coordinate of a point in image 1.
. Row2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( integer, real )
Row coordinate of the corresponding point in image 2.
. Col2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( integer, real )
Column coordinate of the corresponding point in image 2.
. X (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
X coordinate of the 3D point.
. Y (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Y coordinate of the 3D point.
. Z (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Z coordinate of the 3D point.
. Dist (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT ( real )
Distance of the 3D point to the lines of sight.
Result
IntersectLinesOfSight returns TRUE if all parameter values are correct. If necessary, an exception han-
dling is raised.
Parallelization Information
IntersectLinesOfSight is reentrant and processed without parallelization.
Possible Predecessors
BinocularCalibration
See also
DisparityToPoint3D
Module
3D Metrology

HALCON/COM Reference Manual, 2008-5-13


15.17. STEREO 1319

[out] HHomMat2dX EMatrix HImageX.MatchEssentialMatrixRansac


([in] HImageX Image2, [in] VARIANT Rows1, [in] VARIANT Cols1,
[in] VARIANT Rows2, [in] VARIANT Cols2, [in] HHomMat2dX CamMat1,
[in] HHomMat2dX CamMat2, [in] String GrayMatchMethod, [in] long MaskSize,
[in] long RowMove, [in] long ColMove, [in] long RowTolerance,
[in] long ColTolerance, [in] VARIANT Rotation, [in] VARIANT MatchThreshold,
[in] String EstimationMethod, [in] VARIANT DistanceThreshold,
[in] long RandSeed, [out] VARIANT CovEMat, [out] VARIANT Error,
[out] VARIANT Points1, [out] VARIANT Points2 )
[out] HHomMat2dX EMatrix HHomMat2dX.MatchEssentialMatrixRansac
([in] HImageX Image1, [in] HImageX Image2, [in] VARIANT Rows1,
[in] VARIANT Cols1, [in] VARIANT Rows2, [in] VARIANT Cols2,
[in] HHomMat2dX CamMat2, [in] String GrayMatchMethod, [in] long MaskSize,
[in] long RowMove, [in] long ColMove, [in] long RowTolerance,
[in] long ColTolerance, [in] VARIANT Rotation, [in] VARIANT MatchThreshold,
[in] String EstimationMethod, [in] VARIANT DistanceThreshold,
[in] long RandSeed, [out] VARIANT CovEMat, [out] VARIANT Error,
[out] VARIANT Points1, [out] VARIANT Points2 )
void HOperatorSetX.MatchEssentialMatrixRansac
([in] IHObjectX Image1, [in] IHObjectX Image2, [in] VARIANT Rows1,
[in] VARIANT Cols1, [in] VARIANT Rows2, [in] VARIANT Cols2,
[in] VARIANT CamMat1, [in] VARIANT CamMat2, [in] VARIANT GrayMatchMethod,
[in] VARIANT MaskSize, [in] VARIANT RowMove, [in] VARIANT ColMove,
[in] VARIANT RowTolerance, [in] VARIANT ColTolerance, [in] VARIANT Rotation,
[in] VARIANT MatchThreshold, [in] VARIANT EstimationMethod,
[in] VARIANT DistanceThreshold, [in] VARIANT RandSeed, [out] VARIANT EMatrix,
[out] VARIANT CovEMat, [out] VARIANT Error, [out] VARIANT Points1,
[out] VARIANT Points2 )

Compute the essential matrix for a pair of stereo images by automatically finding correspondences between image
points.
Given a set of coordinates of characteristic points (Rows1, Cols1) and (Rows2, Cols2) in the stereo images
Image1 and Image2 along with known internal camera parameters, specified by the camera matrices CamMat1
and CamMat2, MatchEssentialMatrixRansac automatically determines the geometry of the stereo setup
and finds the correspondences between the characteristic points. The geometry of the stereo setup is represented
by the essential matrix EMatrix and all corresponding points have to fulfill the epipolar constraint.
The operator MatchEssentialMatrixRansac is designed to deal with a linear camera model. The internal
camera parameters are passed by the arguments CamMat1 and CamMat2, which are 3 × 3 upper triangular
matrices desribing an affine transformation. The relation between a vector (X,Y,1), representing the direction from
the camera to the viewed 3D space point and its (projective) 2D image coordinates (col,row,1) is:
     
col X f /sx s cx
 row  = CamM at ·  Y  where CamM at =  0 f /sy cy  .
1 1 0 0 1

Note the column/row ordering in the point coordinates which has to be compliant with the x/y notation of the
camera coordinate system. The focal length is denoted by f , sx , sy are scaling factors, s describes a skew factor
and (cx , cy ) indicates the principal point. Mainly, these are the elements known from the camera parameters as
used for example in CameraCalibration. Alternatively, the elements of the camera matrix can be described
in a different way, see e.g. StationaryCameraSelfCalibration. Multiplied by the inverse of the camera
matrices the direction vectors in 3D space are obtained from the (projective) image coordinates. For known camera
matrices the epipolar constraint is given by:
 T  
X2 X1
 Y2  · EM atrix ·  Y1  = 0 .
1 1

HALCON 8.0.2
1320 CHAPTER 15. TOOLS

The matching process is based on characteristic points, which can be extracted with point operators like
PointsFoerstner or PointsHarris. The matching itself is carried out in two steps: first, gray value
correlations of mask windows around the input points in the first and the second image are determined and an ini-
tial matching between them is generated using the similarity of the windows in both images. Then, the RANSAC
algorithm is applied to find the essential matrix that maximizes the number of correspondences under the epipolar
constraint.
The size of the mask windows is MaskSize × MaskSize. Three metrics for the correlation can be selected.
If GrayMatchMethod has the value ’ssd’, the sum of the squared gray value differences is used, ’sad’ means
the sum of absolute differences, and ’ncc’ is the normalized cross correlation. This metric is minimized (’ssd’,
’sad’) or maximized (’ncc’) over all possible point pairs. A thus found matching is only accepted if the value of
the metric is below the value of MatchThreshold (’ssd’, ’sad’) or above that value (’ncc’).
To increase the speed of the algorithm, the search area for the matchings can be limited. Only points within a
window of 2 · RowTolerance × 2 · ColTolerance points are considered. The offset of the center of the
search window in the second image with respect to the position of the current point in the first image is given by
RowMove and ColMove.
If the second camera is rotated around the optical axis with respect to the first camera the parameter Rotation
may contain an estimate for the rotation angle or an angle interval in radians. A good guess will increase the quality
of the gray value matching. If the actual rotation differs too much from the specified estimate the matching will
typically fail. In this case, an angle interval should be specified, and Rotation is a tuple with two elements. The
larger the given interval the slower the operator is since the RANSAC algorithm is run over all angle increments
within the interval.
After the initial matching is completed a randomized search algorithm (RANSAC) is used to determine the essen-
tial matrix EMatrix. It tries to find the essential matrix that is consistent with a maximum number of correspon-
dences. For a point to be accepted, the distance to its corresponding epipolar line must not exceed the threshold
DistanceThreshold.
The parameter EstimationMethod decides whether the relative orientation between the cameras is of a special
type and which algorithm is to be applied for its computation. If EstimationMethod is either ’normalized_dlt’
or ’gold_standard’ the relative orientation is arbitrary. Choosing ’trans_normalized_dlt’ or ’trans_gold_standard’
means that the relative motion between the cameras is a pure translation. The typical application for this special
motion case is the scenario of a single fixed camera looking onto a moving conveyor belt. In order to get a unique
solution in the correspondence problem the minimum required number of corresponding points is six in the general
case and three in the special, translational case.
The essential matrix is computed by a linear algorithm if ’normalized_dlt’ or ’trans_normalized_dlt’ is chosen.
With ’gold_standard’ or ’trans_gold_standard’ the algorithm gives a statistically optimal result, and returns the
covariance of the essential matrix CovEMat as well. Here, ’normalized_dlt’ and ’gold_standard’ stand for direct-
linear-transformation and gold-standard-algorithm respectively. Note, that in general the found correspondences
differ depending on the deployed estimation method.
The value Error indicates the overall quality of the estimation procedure and is the mean euclidian distance in
pixels between the points and their corresponding epipolar lines.
Point pairs consistent with the mentioned constraints are considered to be in correspondences. Points1 contains
the indices of the matched input points from the first image and Points2 contains the indices of the corresponding
points in the second image.
For the operator MatchEssentialMatrixRansac a special configuration of scene points and cameras exists:
if all 3D points lie in a single plane and additionally are all closer to one of the two cameras then the solution in
the essential matrix is not unique but twofold. As a consequence both solutions are computed and returned by the
operator. This means that the output parameters EMatrix, CovEMat and Error are of double length and the
values of the second solution are simply concatenated behind the values of the first one.
The parameter RandSeed can be used to control the randomized nature of the RANSAC algorithm, and hence
to obtain reproducible results. If RandSeed is set to a positive number the operator yields the same result on
every call with the same parameters because the internally used random number generator is initialized with the
RandSeed. If RandSeed = 0 the random number generator is initialized with the current time. In this case the
results may not be reproducible.

HALCON/COM Reference Manual, 2008-5-13


15.17. STEREO 1321

Parameter

. Image1 (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, uint2 )


Input image 1.
. Image2 (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, uint2 )
Input image 2.
. Rows1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Row coordinates of characteristic points in image 1.
Restriction : (Rows1 ∨ (length ≥ 3))
. Cols1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Column coordinates of characteristic points in image 1.
Restriction : (Rows1 = length)
. Rows2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Row coordinates of characteristic points in image 2.
Restriction : (Rows2 ∨ (length ≥ 3))
. Cols2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Column coordinates of characteristic points in image 2.
Restriction : (Rows2 = length)
. CamMat1 (input control) . . . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real, integer )
Camera matrix of the 1st camera.
. CamMat2 (input control) . . . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real, integer )
Camera matrix of the 2nd camera.
. GrayMatchMethod (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Gray value comparison metric.
Default Value : ’ssd’
List of values : GrayMatchMethod ∈ {’ssd’, ’sad’, ’ncc’}
. MaskSize (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Size of gray value masks.
Default Value : 10
Typical range of values : 3 ≤ MaskSize ≤ 3
Restriction : (M askSize ≥ 1)
. RowMove (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Average row coordinate shift of corresponding points.
Default Value : 0
Typical range of values : 0 ≤ RowMove ≤ 0
. ColMove (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Average column coordinate shift of corresponding points.
Default Value : 0
Typical range of values : 0 ≤ ColMove ≤ 0
. RowTolerance (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Half height of matching search window.
Default Value : 200
Typical range of values : 50 ≤ RowTolerance ≤ 50
Restriction : (RowT olerance ≥ 1)
. ColTolerance (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Half width of matching search window.
Default Value : 200
Typical range of values : 50 ≤ ColTolerance ≤ 50
Restriction : (ColT olerance ≥ 1)
. Rotation (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( real, integer )
Estimate of the relative orientation of the right image with respect to the left image.
Default Value : 0.0
Suggested values : Rotation ∈ {0.0, 0.1, -0.1, 0.7854, 1.571, 3.142}
. MatchThreshold (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Threshold for gray value matching.
Default Value : 10
Suggested values : MatchThreshold ∈ {10, 20, 50, 100, 0.9, 0.7}

HALCON 8.0.2
1322 CHAPTER 15. TOOLS

. EstimationMethod (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT


Algorithm for the computation of the essential matrix and for special camera orientations.
Default Value : ’normalized_dlt’
List of values : EstimationMethod ∈ {’normalized_dlt’, ’gold_standard’, ’trans_normalized_dlt’,
’trans_gold_standard’}
. DistanceThreshold (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Maximal deviation of a point from its epipolar line.
Default Value : 1
Typical range of values : 0.5 ≤ DistanceThreshold ≤ 0.5
Restriction : (DistanceT hreshold > 0)
. RandSeed (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Seed for the random number generator.
Default Value : 0
. EMatrix (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )
Computed essential matrix.
. CovEMat (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT
9 × 9 covariance matrix of the essential matrix.
. Error (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT
Root-Mean-Square of the epipolar distance error.
. Points1 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Indices of matched input points in image 1.
. Points2 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Indices of matched input points in image 2.
Parallelization Information
MatchEssentialMatrixRansac is reentrant and processed without parallelization.
Possible Predecessors
PointsFoerstner, PointsHarris
Possible Successors
VectorToEssentialMatrix
See also
MatchFundamentalMatrixRansac, MatchRelPoseRansac,
StationaryCameraSelfCalibration
References
Richard Hartley, Andrew Zisserman: “Multiple View Geometry in Computer Vision”; Cambridge University Press,
Cambridge; 2003.
Olivier Faugeras, Quang-Tuan Luong: “The Geometry of Multiple Images: The Laws That Govern the Formation
of Multiple Images of a Scene and Some of Their Applications”; MIT Press, Cambridge, MA; 2001.
Module
3D Metrology

HALCON/COM Reference Manual, 2008-5-13


15.17. STEREO 1323

[out] HHomMat2dX FMatrix HImageX.MatchFundamentalMatrixRansac


([in] HImageX Image2, [in] VARIANT Rows1, [in] VARIANT Cols1,
[in] VARIANT Rows2, [in] VARIANT Cols2, [in] String GrayMatchMethod,
[in] long MaskSize, [in] long RowMove, [in] long ColMove,
[in] long RowTolerance, [in] long ColTolerance, [in] VARIANT Rotation,
[in] VARIANT MatchThreshold, [in] String EstimationMethod,
[in] VARIANT DistanceThreshold, [in] long RandSeed, [out] VARIANT CovFMat,
[out] double Error, [out] VARIANT Points1, [out] VARIANT Points2 )
void HHomMat2dX.MatchFundamentalMatrixRansac ([in] HImageX Image1,
[in] HImageX Image2, [in] VARIANT Rows1, [in] VARIANT Cols1,
[in] VARIANT Rows2, [in] VARIANT Cols2, [in] String GrayMatchMethod,
[in] long MaskSize, [in] long RowMove, [in] long ColMove,
[in] long RowTolerance, [in] long ColTolerance, [in] VARIANT Rotation,
[in] VARIANT MatchThreshold, [in] String EstimationMethod,
[in] VARIANT DistanceThreshold, [in] long RandSeed, [out] VARIANT CovFMat,
[out] double Error, [out] VARIANT Points1, [out] VARIANT Points2 )
void HOperatorSetX.MatchFundamentalMatrixRansac
([in] IHObjectX Image1, [in] IHObjectX Image2, [in] VARIANT Rows1,
[in] VARIANT Cols1, [in] VARIANT Rows2, [in] VARIANT Cols2,
[in] VARIANT GrayMatchMethod, [in] VARIANT MaskSize, [in] VARIANT RowMove,
[in] VARIANT ColMove, [in] VARIANT RowTolerance, [in] VARIANT ColTolerance,
[in] VARIANT Rotation, [in] VARIANT MatchThreshold,
[in] VARIANT EstimationMethod, [in] VARIANT DistanceThreshold,
[in] VARIANT RandSeed, [out] VARIANT FMatrix, [out] VARIANT CovFMat,
[out] VARIANT Error, [out] VARIANT Points1, [out] VARIANT Points2 )

Compute the fundamental matrix for a pair of stereo images by automatically finding correspondences between
image points.
Given a set of coordinates of characteristic points (Rows1, Cols1) and (Rows2, Cols2) in the stereo images
Image1 and Image2, MatchFundamentalMatrixRansac automatically finds the correspondences be-
tween the characteristic points and determines the geometry of the stereo setup. For unknown cameras the geom-
etry of the stereo setup is represented by the fundamental matrix FMatrix and all corresponding points have to
fulfill the epipolar constraint, namely:
 T  
Cols2 Cols1
 Rows2  · FMatrix ·  Rows1  = 0 .
1 1

Note the column/row ordering in the point coordinates: because the fundamental matrix encodes the projective
relation between two stereo images embedded in 3D space, the x/y notation has to be compliant with the camera
coordinate system. So, (x,y) coordinates correspond to (column,row) pairs.
The matching process is based on characteristic points, which can be extracted with point operators like
PointsFoerstner or PointsHarris. The matching itself is carried out in two steps: first, gray value
correlations of mask windows around the input points in the first and the second image are determined and an ini-
tial matching between them is generated using the similarity of the windows in both images. Then, the RANSAC
algorithm is applied to find the fundamental matrix that maximizes the number of correspondences under the
epipolar constraint.
The size of the mask windows is MaskSize × MaskSize. Three metrics for the correlation can be selected.
If GrayMatchMethod has the value ’ssd’, the sum of the squared gray value differences is used, ’sad’ means
the sum of absolute differences, and ’ncc’ is the normalized cross correlation. This metric is minimized (’ssd’,
’sad’) or maximized (’ncc’) over all possible point pairs. A thus found matching is only accepted if the value of
the metric is below the value of MatchThreshold (’ssd’, ’sad’) or above that value (’ncc’).
To increase the speed of the algorithm the search area for the matchings can be limited. Only points within a
window of 2 · RowTolerance × 2 · ColTolerance points are considered. The offset of the center of the
search window in the second image with respect to the position of the current point in the first image is given by
RowMove and ColMove.

HALCON 8.0.2
1324 CHAPTER 15. TOOLS

If the second camera is rotated around the optical axis with respect to the first camera the parameter Rotation
may contain an estimate for the rotation angle or an angle interval in radians. A good guess will increase the quality
of the gray value matching. If the actual rotation differs too much from the specified estimate the matching will
typically fail. In this case, an angle interval should be specified and Rotation is a tuple with two elements. The
larger the given interval the slower the operator is since the RANSAC algorithm is run over all angle increments
within the interval.
After the initial matching is completed a randomized search algorithm (RANSAC) is used to determine the fun-
damental matrix FMatrix. It tries to find the matrix that is consistent with a maximum number of correspon-
dences. For a point to be accepted, the distance to its corresponding epipolar line must not exceed the threshold
DistanceThreshold.
The parameter EstimationMethod decides whether the relative orientation between the cameras is of a special
type and which algorithm is to be applied for its computation. If EstimationMethod is either ’normalized_dlt’
or ’gold_standard’ the relative orientation is arbitrary. If left and right camera are identical and the relative orien-
tation between them is a pure translation then choose EstimationMethod equal to ’trans_normalized_dlt’ or
’trans_gold_standard’. The typical application for this special motion case is the scenario of a single fixed camera
looking onto a moving conveyor belt. In order to get a unique solution in the correspondence problem the min-
imum required number of corresponding points is eight in the general case and three in the special, translational
case.
The fundamental matrix is computed by a linear algorithm if ’normalized_dlt’ or ’trans_normalized_dlt’ is chosen.
With ’gold_standard’ or ’trans_gold_standard’ the algorithm gives a statistically optimal result, and returns as
well the covariance of the fundamental matrix CovFMat. Here, ’normalized_dlt’ and ’gold_standard’ stand for
direct-linear-transformation and gold-standard-algorithm respectively.
The value Error indicates the overall quality of the estimation procedure and is the mean euclidian distance in
pixels between the points and their corresponding epipolar lines.
Point pairs consistent with the mentioned constraints are considered to be in correspondences. Points1 contains
the indices of the matched input points from the first image and Points2 contains the indices of the corresponding
points in the second image.
The parameter RandSeed can be used to control the randomized nature of the RANSAC algorithm, and hence
to obtain reproducible results. If RandSeed is set to a positive number the operator yields the same result on
every call with the same parameters because the internally used random number generator is initialized with the
RandSeed. If RandSeed = 0 the random number generator is initialized with the current time. In this case the
results may not be reproducible.
Parameter

. Image1 (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, uint2 )


Input image 1.
. Image2 (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, uint2 )
Input image 2.
. Rows1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Row coordinates of characteristic points in image 1.
Restriction : (Rows1 ∨ (length ≥ 3))
. Cols1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Column coordinates of characteristic points in image 1.
Restriction : (Rows1 = length)
. Rows2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Row coordinates of characteristic points in image 2.
Restriction : (Rows2 ∨ (length ≥ 3))
. Cols2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Column coordinates of characteristic points in image 2.
Restriction : (Rows2 = length)
. GrayMatchMethod (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Gray value comparison metric.
Default Value : ’ssd’
List of values : GrayMatchMethod ∈ {’ssd’, ’sad’, ’ncc’}

HALCON/COM Reference Manual, 2008-5-13


15.17. STEREO 1325

. MaskSize (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT


Size of gray value masks.
Default Value : 10
Typical range of values : 3 ≤ MaskSize ≤ 3
Restriction : (M askSize ≥ 1)
. RowMove (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Average row coordinate shift of corresponding points.
Default Value : 0
Typical range of values : 0 ≤ RowMove ≤ 0
. ColMove (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Average column coordinate shift of corresponding points.
Default Value : 0
Typical range of values : 0 ≤ ColMove ≤ 0
. RowTolerance (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Half height of matching search window.
Default Value : 200
Typical range of values : 50 ≤ RowTolerance ≤ 50
Restriction : (RowT olerance ≥ 1)
. ColTolerance (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Half width of matching search window.
Default Value : 200
Typical range of values : 50 ≤ ColTolerance ≤ 50
Restriction : (ColT olerance ≥ 1)
. Rotation (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( real, integer )
Estimate of the relative orientation of the right image with respect to the left image.
Default Value : 0.0
Suggested values : Rotation ∈ {0.0, 0.1, -0.1, 0.7854, 1.571, 3.142}
. MatchThreshold (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Threshold for gray value matching.
Default Value : 10
Suggested values : MatchThreshold ∈ {10, 20, 50, 100, 0.9, 0.7}
. EstimationMethod (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Algorithm for the computation of the fundamental matrix and for special camera orientations.
Default Value : ’normalized_dlt’
List of values : EstimationMethod ∈ {’normalized_dlt’, ’gold_standard’, ’trans_normalized_dlt’,
’trans_gold_standard’}
. DistanceThreshold (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Maximal deviation of a point from its epipolar line.
Default Value : 1
Typical range of values : 0.5 ≤ DistanceThreshold ≤ 0.5
Restriction : (DistanceT hreshold > 0)
. RandSeed (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Seed for the random number generator.
Default Value : 0
. FMatrix (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )
Computed fundamental matrix.
. CovFMat (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT
9 × 9 covariance matrix of the fundamental matrix.
. Error (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; double / VARIANT
Root-Mean-Square of the epipolar distance error.
. Points1 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Indices of matched input points in image 1.
. Points2 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Indices of matched input points in image 2.
Parallelization Information
MatchFundamentalMatrixRansac is reentrant and processed without parallelization.

HALCON 8.0.2
1326 CHAPTER 15. TOOLS

Possible Predecessors
PointsFoerstner, PointsHarris
Possible Successors
VectorToFundamentalMatrix, GenBinocularProjRectification
See also
MatchEssentialMatrixRansac, MatchRelPoseRansac, ProjMatchPointsRansac
References
Richard Hartley, Andrew Zisserman: “Multiple View Geometry in Computer Vision”; Cambridge University Press,
Cambridge; 2003.
Olivier Faugeras, Quang-Tuan Luong: “The Geometry of Multiple Images: The Laws That Govern the Formation
of Multiple Images of a Scene and Some of Their Applications”; MIT Press, Cambridge, MA; 2001.
Module
3D Metrology

[out] VARIANT RelPose HImageX.MatchRelPoseRansac ([in] HImageX Image2,


[in] VARIANT Rows1, [in] VARIANT Cols1, [in] VARIANT Rows2,
[in] VARIANT Cols2, [in] VARIANT CamPar1, [in] VARIANT CamPar2,
[in] String GrayMatchMethod, [in] long MaskSize, [in] long RowMove,
[in] long ColMove, [in] long RowTolerance, [in] long ColTolerance,
[in] VARIANT Rotation, [in] VARIANT MatchThreshold,
[in] String EstimationMethod, [in] VARIANT DistanceThreshold,
[in] long RandSeed, [out] VARIANT CovRelPose, [out] VARIANT Error,
[out] VARIANT Points1, [out] VARIANT Points2 )
[out] VARIANT RelPose HPoseX.MatchRelPoseRansac ([in] HImageX Image1,
[in] HImageX Image2, [in] VARIANT Rows1, [in] VARIANT Cols1,
[in] VARIANT Rows2, [in] VARIANT Cols2, [in] VARIANT CamPar1,
[in] VARIANT CamPar2, [in] String GrayMatchMethod, [in] long MaskSize,
[in] long RowMove, [in] long ColMove, [in] long RowTolerance,
[in] long ColTolerance, [in] VARIANT Rotation, [in] VARIANT MatchThreshold,
[in] String EstimationMethod, [in] VARIANT DistanceThreshold,
[in] long RandSeed, [out] VARIANT CovRelPose, [out] VARIANT Error,
[out] VARIANT Points1, [out] VARIANT Points2 )
void HOperatorSetX.MatchRelPoseRansac ([in] IHObjectX Image1,
[in] IHObjectX Image2, [in] VARIANT Rows1, [in] VARIANT Cols1,
[in] VARIANT Rows2, [in] VARIANT Cols2, [in] VARIANT CamPar1,
[in] VARIANT CamPar2, [in] VARIANT GrayMatchMethod, [in] VARIANT MaskSize,
[in] VARIANT RowMove, [in] VARIANT ColMove, [in] VARIANT RowTolerance,
[in] VARIANT ColTolerance, [in] VARIANT Rotation,
[in] VARIANT MatchThreshold, [in] VARIANT EstimationMethod,
[in] VARIANT DistanceThreshold, [in] VARIANT RandSeed, [out] VARIANT RelPose,
[out] VARIANT CovRelPose, [out] VARIANT Error, [out] VARIANT Points1,
[out] VARIANT Points2 )

Compute the relative orientation between two cameras by automatically finding correspondences between image
points.
Given a set of coordinates of characteristic points (Rows1, Cols1) and (Rows2, Cols2) in the stereo
images Image1 and Image2 along with known internal camera parameters CamPar1 and CamPar2,
MatchRelPoseRansac automatically determines the geometry of the stereo setup and finds the correspon-
dences between the characteristic points. The geometry of the stereo setup is represented by the relative pose
RelPose and all corresponding points have to fulfill the epipolar constraint. RelPose indicates the rela-
tive pose of camera 1 with respect to camera 2 (See CreatePose for more information about poses and
their representations.). This is in accordance with the explicit calibration of a stereo setup using the operator
BinocularCalibration. Now, let R, t be the rotation and translation of the relative pose. Then, the essential
matrix E is defined as E = ([t]× R)T , where [t]× denotes the 3 × 3 skew-symmetric matrix realising the cross
product with the vector t. The pose can be determined from the epipolar constraint:

HALCON/COM Reference Manual, 2008-5-13


15.17. STEREO 1327

 T    
X2 X1 0 −tz ty
 Y2  · ([t]× R)T ·  Y1  = 0 where [t]× =  tz 0 −tx  .
1 1 −ty tx 0

Note, that the essential matrix is a projective entity and thus is defined up to a scaling factor. From this follows that
the translation vector of the relative pose can only be determined up to scale too. In fact, the computed translation
vector will always be normalized to unit length. As a consequence, a subsequent threedimensional reconstruction
of the scene, using for instance VectorToRelPose, can be carried out only up to a single global scaling factor.
The operator MatchRelPoseRansac is designed to deal with a camera model, that includes lens distortions.
This is in contrast to the operator MatchEssentialMatrixRansac, which encompasses only straight line
preserving cameras. The camera parameters are passed in CamPar1 and CamPar2. The 3D direction vectors
(X1 , Y1 , 1) and (X2 , Y2 , 1) are calculated from the point coordinates (Rows1,Cols1) and (Rows2,Cols2) by
inverting the process of projection (see CameraCalibration).
The matching process is based on characteristic points, which can be extracted with point operators like
PointsFoerstner or PointsHarris. The matching itself is carried out in two steps: first, gray value
correlations of mask windows around the input points in the first and the second image are determined and an ini-
tial matching between them is generated using the similarity of the windows in both images. Then, the RANSAC
algorithm is applied to find the relative pose that maximizes the number of correspondences under the epipolar
constraint.
The size of the mask windows is MaskSize × MaskSize. Three metrics for the correlation can be selected.
If GrayMatchMethod has the value ’ssd’, the sum of the squared gray value differences is used, ’sad’ means
the sum of absolute differences, and ’ncc’ is the normalized cross correlation. This metric is minimized (’ssd’,
’sad’) or maximized (’ncc’) over all possible point pairs. A thus found matching is only accepted if the value of
the metric is below the value of MatchThreshold (’ssd’, ’sad’) or above that value (’ncc’).
To increase the speed of the algorithm, the search area for the matchings can be limited. Only points within a
window of 2 · RowTolerance × 2 · ColTolerance points are considered. The offset of the center of the
search window in the second image with respect to the position of the current point in the first image is given by
RowMove and ColMove.
If the second camera is rotated around the optical axis with respect to the first camera the parameter Rotation
may contain an estimate for the rotation angle or an angle interval in radians. A good guess will increase the quality
of the gray value matching. If the actual rotation differs too much from the specified estimate the matching will
typically fail. In this case, an angle interval should be specified, and Rotation is a tuple with two elements. The
larger the given interval the slower the operator is since the RANSAC algorithm is run over all angle increments
within the interval.
After the initial matching is completed a randomized search algorithm (RANSAC) is used to determine the rel-
ative pose RelPose. It tries to find the relative pose that is consistent with a maximum number of correspon-
dences. For a point to be accepted, the distance to its corresponding epipolar line must not exceed the threshold
DistanceThreshold.
The parameter EstimationMethod decides whether the relative orientation between the cameras is of a special
type and which algorithm is to be applied for its computation. If EstimationMethod is either ’normalized_dlt’
or ’gold_standard’ the relative orientation is arbitrary. Choosing ’trans_normalized_dlt’ or ’trans_gold_standard’
means that the relative motion between the cameras is a pure translation. The typical application for this special
motion case is the scenario of a single fixed camera looking onto a moving conveyor belt. In order to get a unique
solution in the correspondence problem the minimum required number of corresponding points is six in the general
case and three in the special, translational case.
The relative pose is computed by a linear algorithm if ’normalized_dlt’ or ’trans_normalized_dlt’ is chosen. With
’gold_standard’ or ’trans_gold_standard’ the algorithm gives a statistically optimal result, and returns as well the
covariance of the relative pose CovRelPose. Here, ’normalized_dlt’ and ’gold_standard’ stand for direct-linear-
transformation and gold-standard-algorithm respectively. Note, that in general the found correspondences differ
depending on the deployed estimation method.
The value Error indicates the overall quality of the estimation procedure and is the mean euclidian distance in
pixels between the points and their corresponding epipolar lines.
Point pairs consistent with the mentioned constraints are considered to be in correspondences. Points1 contains
the indices of the matched input points from the first image and Points2 contains the indices of the corresponding
points in the second image.

HALCON 8.0.2
1328 CHAPTER 15. TOOLS

For the operator MatchRelPoseRansac a special configuration of scene points and cameras exists: if all 3D
points lie in a single plane and additionally are all closer to one of the two cameras then the solution in the essential
matrix is not unique but twofold. As a consequence both solutions are computed and returned by the operator. This
means that the output parameters RelPose, CovRelPose and Error are of double length and the values of the
second solution are simply concatenated behind the values of the first one.
The parameter RandSeed can be used to control the randomized nature of the RANSAC algorithm, and hence
to obtain reproducible results. If RandSeed is set to a positive number the operator yields the same result on
every call with the same parameters because the internally used random number generator is initialized with the
RandSeed. If RandSeed = 0 the random number generator is initialized with the current time. In this case the
results may not be reproducible.
Parameter

. Image1 (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, uint2 )


Input image 1.
. Image2 (input iconic) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . image ; HImageX / IHObjectX ( byte, uint2 )
Input image 2.
. Rows1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Row coordinates of characteristic points in image 1.
Restriction : (Rows1 ∨ (length ≥ 3))
. Cols1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Column coordinates of characteristic points in image 1.
Restriction : (Rows1 = length)
. Rows2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Row coordinates of characteristic points in image 2.
Restriction : (Rows2 ∨ (length ≥ 3))
. Cols2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Column coordinates of characteristic points in image 2.
Restriction : (Rows2 = length)
. CamPar1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Parameters of the 1st camera.
. CamPar2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Parameters of the 2nd camera.
. GrayMatchMethod (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Gray value comparison metric.
Default Value : ’ssd’
List of values : GrayMatchMethod ∈ {’ssd’, ’sad’, ’ncc’}
. MaskSize (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Size of gray value masks.
Default Value : 10
Typical range of values : 3 ≤ MaskSize ≤ 3
Restriction : (M askSize ≥ 1)
. RowMove (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Average row coordinate shift of corresponding points.
Default Value : 0
Typical range of values : 0 ≤ RowMove ≤ 0
. ColMove (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Average column coordinate shift of corresponding points.
Default Value : 0
Typical range of values : 0 ≤ ColMove ≤ 0
. RowTolerance (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Half height of matching search window.
Default Value : 200
Typical range of values : 50 ≤ RowTolerance ≤ 50
Restriction : (RowT olerance ≥ 1)

HALCON/COM Reference Manual, 2008-5-13


15.17. STEREO 1329

. ColTolerance (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT


Half width of matching search window.
Default Value : 200
Typical range of values : 50 ≤ ColTolerance ≤ 50
Restriction : (ColT olerance ≥ 1)
. Rotation (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( real, integer )
Estimate of the relative orientation of the right image with respect to the left image.
Default Value : 0.0
Suggested values : Rotation ∈ {0.0, 0.1, -0.1, 0.7854, 1.571, 3.142}
. MatchThreshold (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( integer, real )
Threshold for gray value matching.
Default Value : 10
Suggested values : MatchThreshold ∈ {10, 20, 50, 100, 0.9, 0.7}
. EstimationMethod (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . string ; String / VARIANT
Algorithm for the computation of the relative pose and for special pose types.
Default Value : ’normalized_dlt’
List of values : EstimationMethod ∈ {’normalized_dlt’, ’gold_standard’, ’trans_normalized_dlt’,
’trans_gold_standard’}
. DistanceThreshold (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Maximal deviation of a point from its epipolar line.
Default Value : 1
Typical range of values : 0.5 ≤ DistanceThreshold ≤ 0.5
Restriction : (DistanceT hreshold > 0)
. RandSeed (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; long / VARIANT
Seed for the random number generator.
Default Value : 0
. RelPose (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pose ; VARIANT ( integer, real )
Computed relative orientation of the cameras (3D pose).
. CovRelPose (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT
6 × 6 covariance matrix of the relative orientation.
. Error (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT
Root-Mean-Square of the epipolar distance error.
. Points1 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Indices of matched input points in image 1.
. Points2 (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . integer ; VARIANT ( integer )
Indices of matched input points in image 2.
Parallelization Information
MatchRelPoseRansac is reentrant and processed without parallelization.
Possible Predecessors
PointsFoerstner, PointsHarris
Possible Successors
VectorToRelPose, GenBinocularRectificationMap
See also
BinocularCalibration, MatchFundamentalMatrixRansac,
MatchEssentialMatrixRansac, CreatePose
References
Richard Hartley, Andrew Zisserman: “Multiple View Geometry in Computer Vision”; Cambridge University Press,
Cambridge; 2003.
Olivier Faugeras, Quang-Tuan Luong: “The Geometry of Multiple Images: The Laws That Govern the Formation
of Multiple Images of a Scene and Some of Their Applications”; MIT Press, Cambridge, MA; 2001.
Module
3D Metrology

HALCON 8.0.2
1330 CHAPTER 15. TOOLS

[out] VARIANT X HHomMat2dX.Reconst3dFromFundamentalMatrix


([in] VARIANT Rows1, [in] VARIANT Cols1, [in] VARIANT Rows2,
[in] VARIANT Cols2, [in] VARIANT CovRR1, [in] VARIANT CovRC1,
[in] VARIANT CovCC1, [in] VARIANT CovRR2, [in] VARIANT CovRC2,
[in] VARIANT CovCC2, [in] VARIANT CovFMat, [out] VARIANT Y, [out] VARIANT Z,
[out] VARIANT W, [out] VARIANT CovXYZW )
void HOperatorSetX.Reconst3dFromFundamentalMatrix
([in] VARIANT Rows1, [in] VARIANT Cols1, [in] VARIANT Rows2,
[in] VARIANT Cols2, [in] VARIANT CovRR1, [in] VARIANT CovRC1,
[in] VARIANT CovCC1, [in] VARIANT CovRR2, [in] VARIANT CovRC2,
[in] VARIANT CovCC2, [in] VARIANT FMatrix, [in] VARIANT CovFMat,
[out] VARIANT X, [out] VARIANT Y, [out] VARIANT Z, [out] VARIANT W,
[out] VARIANT CovXYZW )

Compute the projective 3d reconstruction of points based on the fundamental matrix.


A pair of stereo images is called weakly calibrated if the fundamental matrix, which defines the geometric relation
between the two images, is known. Given such a fundamental matrix FMatrix and a set of corresponding points
(Rows1,Cols1) and (Rows2,Cols2) the operator Reconst3dFromFundamentalMatrix determines the
three-dimensional space points projecting onto these image points. This 3D reconstruction is purely projective
and the projective coordinates are returned by the four-vector (X,Y,Z,W). This type of reconstruction is also known
as projective triangulation. If additionally the covariances CovRR1, CovRC1, CovCC1 and CovRR2, CovRC2,
CovCC2 of the image points are given the covariances of the reconstructed points CovXYZW are computed too.
Let n be the number of points. Then the concatenated covariances are stored in a 16 × n tuple. The computation
of the covariances is more precise if the covariance of the fundamental matrix CovFMat is provided.
The operator Reconst3dFromFundamentalMatrix is typically used after
MatchFundamentalMatrixRansac to perform 3d reconstruction. This will save computational cost
compared with the deployment of VectorToFundamentalMatrix.
Reconst3dFromFundamentalMatrix is the projective equivalent to the euclidian reconstruction operator
IntersectLinesOfSight.
Parameter
. Rows1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( real, integer )
Input points in image 1 (row coordinate).
. Cols1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( real, integer )
Input points in image 1 (column coordinate).
. Rows2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( real, integer )
Input points in image 2 (row coordinate).
. Cols2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( real, integer )
Input points in image 2 (column coordinate).
. CovRR1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( real, integer )
Row coordinate variance of the points in image 1.
Default Value : []
. CovRC1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( real, integer )
Covariance of the points in image 1.
Default Value : []
. CovCC1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( real, integer )
Column coordinate variance of the points in image 1.
Default Value : []
. CovRR2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( real, integer )
Row coordinate variance of the points in image 2.
Default Value : []
. CovRC2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( real, integer )
Covariance of the points in image 2.
Default Value : []
. CovCC2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number(-array) ; VARIANT ( real, integer )
Column coordinate variance of the points in image 2.
Default Value : []

HALCON/COM Reference Manual, 2008-5-13


15.17. STEREO 1331

. FMatrix (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )


Fundamental matrix.
. CovFMat (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT ( real )
9 × 9 covariance matrix of the fundamental matrix.
Default Value : []
. X (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT
X coordinates of the reconstructed points in projective 3D space.
. Y (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT
Y coordinates of the reconstructed points in projective 3D space.
. Z (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT
Z coordinates of the reconstructed points in projective 3D space.
. W (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT
W coordinates of the reconstructed points in projective 3D space.
. CovXYZW (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real(-array) ; VARIANT
Covariance matrices of the reconstructed points.
Parallelization Information
Reconst3dFromFundamentalMatrix is reentrant and processed without parallelization.
Possible Predecessors
MatchFundamentalMatrixRansac
Alternatives
VectorToFundamentalMatrix, IntersectLinesOfSight
References
Richard Hartley, Andrew Zisserman: “Multiple View Geometry in Computer Vision”; Cambridge University Press,
Cambridge; 2000.
Module
3D Metrology

void HHomMat2dX.RelPoseToFundamentalMatrix ([in] VARIANT RelPose,


[in] VARIANT CovRelPose, [in] VARIANT CamPar1, [in] VARIANT CamPar2,
[out] VARIANT CovFMat )
[out] HHomMat2dX FMatrix HPoseX.RelPoseToFundamentalMatrix
([in] VARIANT RelPose, [in] VARIANT CovRelPose, [in] VARIANT CamPar1,
[in] VARIANT CamPar2, [out] VARIANT CovFMat )
void HOperatorSetX.RelPoseToFundamentalMatrix
([in] VARIANT RelPose, [in] VARIANT CovRelPose, [in] VARIANT CamPar1,
[in] VARIANT CamPar2, [out] VARIANT FMatrix, [out] VARIANT CovFMat )

Compute the fundamental matrix from the relative orientation of two cameras.
Cameras including lens distortions can be modeled by the following set of parameters: the focal length f , two
scaling factors sx , sy , the coordinates of the principal point (cx , cy ) and the distortion coefficient κ. For a more
detailed description see the operator CameraCalibration. Only cameras with a distortion coefficient equal to
zero project straight lines in the world onto straight lines in the image. Then, image projection is a linear mapping
and the camera, i.e. the set of internal parameters, can be described by the camera matrix CamM at:
 
f /sx 0 cx
CamM at =  0 f /sy cy  .
0 0 1

Going from a nonlinear model to a linear model is an approximation of the real underlying camera. For a variety of
camera lenses, especially lenses with long focal length, the error induced by this approximation can be neglected.
Following the formula E = ([t]× R)T , the essential matrix E is derived from the translation t and the rotation
R of the relative pose RelPose (see also operator VectorToRelPose). In the linearized framework the
fundamental matrix can be calculated from the relative pose and the camera matrices according to the formula
presented under EssentialToFundamentalMatrix:

HALCON 8.0.2
1332 CHAPTER 15. TOOLS

FMatrix = CamM at2−T · ([t]× R)T · CamM at1−1 .

The transformation from a relative pose to a fundamental matrix goes along with the propagation of the covariance
matrices CovRelPose to CovFMat. If CovRelPose is empty CovFMat will be empty too.
The conversion operator RelPoseToFundamentalMatrix is used especially for a subsequent visualization
of the epipolar line structure via the fundamental matrix, which depicts the underlying stereo geometry.
Parameter

. RelPose (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . pose ; VARIANT ( real, integer )


Relative orientation of the cameras (3D pose).
. CovRelPose (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
6 × 6 covariance matrix of relative pose.
Default Value : []
. CamPar1 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Parameters of the 1. camera.
. CamPar2 (input control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . number ; VARIANT ( real, integer )
Parameters of the 2. camera.
. FMatrix (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . hom_mat2d ; HHomMat2dX / VARIANT ( real )
Computed fundamental matrix.
. CovFMat (output control) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . real ; VARIANT
9 × 9 covariance matrix of the fundamental matrix.
Parallelization Information
RelPoseToFundamentalMatrix is reentrant and processed without parallelization.
Possible Predecessors
VectorToRelPose
See also
CameraCalibration
Alternatives
EssentialToFundamentalMatrix
References

Module
3D Metrology

[out] HHomMat2dX EMatrix HHomMat2dX.VectorToEssentialMatrix


([in] VARIANT Rows1, [in] VARIANT Cols1, [in] VARIANT Rows2,
[in] VARIANT Cols2, [in] VARIANT CovRR1, [in] VARIANT CovRC1,
[in] VARIANT CovCC1, [in] VARIANT CovRR2, [in] VARIANT CovRC2,
[in] VARIANT CovCC2, [in] HHomMat2dX CamMat2, [in] String Method,
[out] VARIANT CovEMat, [out] VARIANT Error, [out] VARIANT X, [out] VARIANT Y,
[out] VARIANT Z, [out] VARIANT CovXYZ )
void HOperatorSetX.VectorToEssentialMatrix ([in] VARIANT Rows1,
[in] VARIANT Cols1, [in] VARIANT Rows2, [in] VARIANT Cols2,
[in] VARIANT CovRR1, [in] VARIANT CovRC1, [in] VARIANT CovCC1,
[in] VARIANT CovRR2, [in] VARIANT CovRC2, [in] VARIANT CovCC2,
[in] VARIANT CamMat1, [in] VARIANT CamMat2, [in] VARIANT Method,
[out] VARIANT EMatrix, [out] VARIANT CovEMat, [out] VARIANT Error,
[out] VARIANT X, [out] VARIANT Y, [out] VARIANT Z, [out] VARIANT CovXYZ )

Compute the essential matrix given image point correspondences and known camera matrices and reconstruct 3D
points.

HALCON/COM Reference Manual, 2008-5-13


15.17. STEREO 1333

For a stereo configuration with known camera matrices the geometric relation between the two images is defined by
the essential matrix. The operator VectorToEssentialMatrix determines the essential matrix EMatrix
from in general at least six given point correspondences, that fulfill the epipolar constraint:
 T  
X2 X1
 Y2  · EM atrix ·  Y1  = 0
1 1

The operator V

Você também pode gostar