VisionLab Help File

Binary image

Binary images are instantiations of class OrdImage<Pixel>, see Image hierarchy

Binary images can have only two possible pixel values:
- 0 = BackGround
- 1 = Object

The result of displaying a binary image depends on thedisplayLUT used, see: Displaying of greyscale images (LUTs).

If binary images are displayed using de displayLUT Binary:
- BackGround = white
- Object = black

If binary images are displayed using de displayLUT Stretch:
- BackGround = black
- Object = white

Back to Contents

Displaying of greyscale images (LUTs).

Greyscale images are displayed on the screen using a Look Up Table (LUT).

The screen can maximal display 256 levels of greyscale values. Before a greyscale image can be displayed it has to be transformed into a byte format. This transformation is controlled by LUTs.

The following LUTs are available for
IntImages:

- Stretch: used for displaying with maximal contrast.
After determining the minimum and maximum values in the image,all pixel values are stretched (or condensed) to the range [0..255].

- Clip: used for displaying the 'true' pixel values.
All pixel values exceeding [0.255] are clipped. Is mostly used when setting up the camera.

- Binary: used for displaying images with binary values, see Binary image
Threshold operations produce binary images.
Pixel value 0 = white, pixel value 1 = Black.

- Labeled: used for displaying images with labels.
Label blobs operation produce images with labels, see Label blobs
Background (pixel value 0) is displayed as white.
Each blob is displayed with a color.

The following LUTs are available for FloatImages:

- FloatLinear: After determining the minimum and maximum values in the image,all pixel values are stretched (or condensed) in a linear fashion to the range [0..255].
- FloatLog: After determining the minimum and maximum values in the image,all pixel values are stretched (or condensed) in a logarithm fashion to the range [0..255].If image contains negative values the image is displayed as a total black image. (You can not take the logarithm of negative values)

For complex images the power spectrum is displayed as a FloatImage.

Back to Contents

Contributions

Logo design by Klaas Dijkstra.

Interfaces to framegrabbers/cameras:
- FireWire: Andrej Girgenson and Jaap van de Loosdrecht
- DirectXCam: Andrej Girgenson and Wouter Storteboom
- FirePackage: Alex Beemsterboer and Klaas Dijkstra
- Gen<I>Cam/GenTL, XIMEA, Festo SBOXs, Matrix Vision Blue Cougar: Klaas Dijkstra
- Native IDS: Tjalling Lankreijer, Rene Ferwerda, Wouter Keuning and Martin Dijkstra
- Kinect: Johan van Althuis and Jesse Otten
- MFCam: Rene Ferwerda
- Video4Linux2: Martin Dijkstra
- Html help: Klaas Dijkstra

Camera calibration:
- algorithm: Jaap van de Loosdrecht and Dick Bruin
- 1st implementation: Marcel Hoekstra and Michel Leijenaar
- 2nd implementation: Jaap van de Loosdrecht

Algorithms and tools:
- DeInterlace: Gerben Wiersma and Michiel Leemker
- SnapOnSoftTrigger: Gerben Wiersma and Michiel Leemker
- PolarStretch: Jan Wybren de Jong
- Idea for Threshold Tool: Robbert Broersma and Martine Dubling
- OpticalCorrection, Warp, FishEye, VectorDistance and ExactDistance: Dick Bruin
- WeightedCOG, SwapAxis, PlugIn sytem, FindFirstTransitions, FindFirstEdges, MapAxis, Widgets: Klaas Dijkstra
- 2nd version PlugIn sytem: Martin Dijkstra
- Blob matcher: Dick Bruin and Jaap van de Loosdrecht
- OpenCL toolbox: Jaap van de Loosdrecht and Herman Schubert
- Robotic Operation System (ROS) server: Martin Dijkstra
- Watershed: Klaas Dijkstra and Jaap van de Loosdrecht

The help file is generated using a tool developed by Dick Bruin.

I also want to thank the many colleagues and students from the NHL University of Applied Sciencewho gave feedback and/or ideas and thus helped to improve the system.


Back to Contents

Multi core support

At the moment multi core version of the algorithms in VisionLab are under development.

In the system menu operators can be found that influence the performance for Multi Core Processing (MCP).
On large images MCP can give a significant performance benifit. Due to the overhead involved with MCP the use of MCP on small images can lead to a performance lost compared to running on one core. If VisionLab MCP is run in the auto multi core mode it VisionLab will decide automatically to run in MCP or single core. This is called automatic operator parallelization for multi core processing. An important parameter in making this decision is the MultiCoreThreshold value.With the CalibrateAutoMultiCore VisionLab can calibrate the MultiCoreThreshold value.

- CalibrateAutoMultiCore <nrThreads> <gain>
This operator calculates the optimal MultiCoreThreshold value.
nrThreads: the number of threads that the user wants to use
gain: how much profit MCP must give compared to running with one thread, example: 1.1 means 10% profit
Note: when calibrating it is important that the specified number of cores are available and not busy with other work.

- GetAffinityMask
This operator returns the process affinity mask as hexadecimal code.

- GetAutoMultiCore
This operator returns true if VisionLab is running in auto multi core mode.

- GetMultiCoreThreshold
This operator returns the MultiCoreThreshold value.

- GetNestedParallel
This operator returns a boolean whether nested parallel regions are allowed or not

- GetNrCores
This operator returns the number of cores in the computer

- GetNrTrhreads
This operator returns the number of threads to be used in MCP

- SetAffinityMask <mask>
This operator sets the processor affinity mask (hexadecimal code) and return a mask with the processors that could be selected.

- SetAutoMultiCore <bool>
This operator sets the auto multi core mode to true or false

- SetMultiCoreThreshold <value>
This operator sets the MultiCoreThreshold

- GetNestedParallel <true|false>
This sets whether nested parallel regions are allowed or not

- SetNrTrhreads
This operator sets the number of threads to be used in MCP

It is to be expected that in the near future more algorithmes will be enabled for MCP.


Back to Contents

OpenCL

Prelimenary version of OpenCL interface commands.

OpenCL is an open standard for parallel programming of heterogeneous systems.
See www.khronos.org for more information and manuals.

With CL_Init a platform and device type can be chosen.
The other commands have the same names and parameters as specified in the Khronos OpenCL documentation.

OpenCL

OpenCL

opencl_jl.h

Script commands for OpenCL host interface.

Note: in this interface a list is string starting with '(' and terminated with ')', all items in the list are separated with a ','. Examples: with four ids: (1,3,5,6) and empty list: ().

CL_Init <platformVendor> <deviceType>
Creates an OpenCL object and initializes all resources needed for computation on the specified platform vendor and device.
platformVendor: name of the platform vendor.
deviceType: name of the device type

CL_Free
Deletes the OpenCL Object and clears the buffer.

CL_AddKernel <programId> <kernelName>
Creates a kernel object for a program with specified name.
programId: programId with a successfully built executable.
kernelName: function name in the program declared with the kernel qualifier.

CL_Build <programId> <(&$)options>
Build a program executable from the program source or binary for all the devices or a specific device(s) in the OpenCL context associated with program.
programId: programId
(&$)options: reference to a string that describes the build options to be used for building the program executable. Can be empty.

CL_CreateBuffer <contextId> <bufferRWType> <argType> <[imageName|size]>
Creates a buffer object for a context of a specific type and size.
Function result is the bufferId.
contextId: valid contextId used to create the buffer object.
bufferRWType: defines how the buffer will be used, possible values: ReadOnly, WriteOnly or ReadWrite.
argType: type of argument, possible values: CL_Buffer, CL_Char, CL_CharArray, CL_Double, CL_DoubleArray, CL_Float, CL_FloatArray, CL_ImageBuffer, CL_Image2D, CL_Int, CL_IntArray, CL_LocalBuffer, CL_Long, CL_LongArray, CL_UChar, CL_UCharArray, CL_UInt, CL_UIntArray, CL_ULong, CL_ULongArray, CL_UShort, CL_UShortArray, CL_Short or CL_ShortArray.
[imageName|size]: optional paramter, only used for specifying imageName or size for buffer (in bytes) or array (in number elements).

CL_CreateContext <platformId> <deviceList>
Creates a context object for your platform.
Function result is the contextId.
platformId: platformId.
deviceList: list with unique deviceIds.

CL_CreateEvent
Create an event object.
Function result is the eventId.

CL_CreateImage2D <contextId> <bufferRWType> <imageType> <height> <width>
Create an image object with specified dimensions and type.
Function result is the bufferId.
contextId: a valid contextId on which the image object is to be created.
bufferRWType: defines how the buffer will be used, possible values: ReadOnly, WriteOnly or ReadWrite.
imageType: possible values are CL_ByteImage, CL_FloatImage, CL_Int16Image, CL_Int32Image or CL_RGB888Image.
height: the height of the image in pixels. Must be greater than or equal to 1.
width: the width of the image in pixels. Must be greater than or equal to 1.

CL_CreateProgram <contextId> <(&$)program>
Create a program object for a context, and loads the source code specified into the program object.
Function result is the programId.
contextId: valid contextId.
(&$)program: reference to variable with the source code.

CL_CreateProgramWithBinary <contextId> <filename>
Create a program object for a context, and loads the binary images into the program object.
Function result is the programId.
contextId: valid contextId.
filename: filename of the binary.

CL_CreateQueue <contextId> <deviceId> <QOutOfOrder> <QProfiling>
Create a command-queue on a specific device.
Function result is the queueId.
contextId: valid context Id.
deviceId: deviceId associated with context.
QOutOfOrder: out of order property, possible values: OutOfOrderEnabled or OutOfOrderDisabled.
QProfiling: profiling property, possible values: ProfilingEnabled, ProfilingDisabled

CL_Finish <queueId>
Block until all previously queued OpenCL runtime commands in the queue are issued to the associated device and have completed.
queueId: valid queueId.

CL_Flush <queueId>
Issue all previously queued OpenCL commands in the queue to the device associated with the queue.
queueId: valid queueId.

CL_GetDeviceInfo <platformId> <deviceId> <deviceInfo>
Function result is information about an OpenCL device.
platformId: valid platformId.
deviceId: valid device Id.
deviceInfo: specifies the device info that must be returned.

CL_GetDevices <platformId> <(&$)deviceTab>
Get an array with the names of the devices. Index in array is deviceId.
Function result is the number of devices.
platformId: valid platformId.
(&$)deviceTab: reference to an array variable for the device names.

CL_GetKernelWorkGroupInfo <platformId> <deviceId> <kernelName> <deviceInfo>
Function result is information about the kernel object that may be specific to a device.
platformId: valid platformId.
deviceId: valid deviceId.
kernelName: kernelId being queried.
deviceInfo: device info that is requested.

CL_GetPlatformInfo <platformId> <platformInfo>
Function result is the requested platform info.
platformId: valid platformId.
platformInfo: platform info you want returned.

CL_GetPlatforms <(&$)platformTab>
Get an array with the names of the platforms. Index in array is platformId.
Function result is the number of platforms.
(&$)platformTab: reference to an array variable for the platform names.

CL_PinImage <queueId> <contextId> <imageName>
Pin buffer of an image with imageName and create buffer on GPU. After pinning memory transfer between CPU and GPU will be faster.
Function result is the bufferId.
queueId: valid queueId.
imageId: valid imageId.
imageName: name of the image to pin.

CL_UnpinImage <queueId> <bufferId> <imageName>
Unpin the buffer of an image. Note: a pinned image MUST be unpinned before it is deleted from memory!
queueId: valid queueId.
bufferId: valid bufferId.
imageName: name of the image you want the image written to.

CL_ReadBuffer <queueId> <bufId> <(&$)var|image> <waitlist> <eventId> <wait>
Enqueue a command to read from a buffer object to host memory, and write it to a variable.
queueId: valid queueId.
bufId: valid bufferId.
(&$)var|Image: the variable or image that is to be read from the buffer.
waitList: list of events that need to complete before this command can be executed.
eventId: list with zero or one event, event triggerd when operation is completed.
wait: indicates if the operation is blocking or non-blocking.

CL_ReadImage2D <queueId> <imageId> <imageName> <waitlist> <eventId> <wait>
Enqueue a command to read from a 2D or 3D image object to host memory, and write it to an image.
queueId: valid queueId.
imageId: valid imageId.
imageName: name of the image that is to be read from the buffer.
waitList: list of events that need to complete before this command can be executed.
eventId: list with zero or one event, event triggerd when operation is completed.
wait: indicates if the operation is blocking or non-blocking.

CL_Run <queueId> <kernelName> <offset> <global> <local> <waitlist> <eventId> <wait>
Enqueue a command to execute a kernel on a device.
queueId: valid queueId.
kernelName: valid kernel name.
offset: list with the offsets used to calculate the global work id.
global: list with the global work sizes.
local: list with the local work sizes.
waitList: list of events that need to complete before this command can be executed.
eventId: list with zero or one event, event triggerd when operation is completed.
wait: indicates if the operation is blocking or non-blocking.

CL_SaveBinary <programId> <filename>
Save the program to binary files.
programId: valid programId.
filename: filename used to save the binary.

CL_SetArg <kernelName> <index> <argType> <value|bufId>
Set the argument value for a specific argument of a kernel.
kernelName: kernel name.
index: argument index.
argType: the argument type, possible values: Buffer, Char, Double, Float, ImageBuffer, Image2D, Int, LocalBuffer, Long, UChar, UInt, UShort or Short.
value|bufId: value or buffer to be set to the argument.

CL_SupportAtomCounters <platformId> <deviceId>
Checks if device supports atom counters.
Return value is true if device supports atom counters
platformId: valid platformId.
deviceId: valid deviceId.

CL_SupportDoubles <platformId> <deviceId>
Checks if device supports doubles.
Return value is true if device supports doubles.
platformId: valid platformId.
deviceId: valid deviceId.

CL_SupportExtension <platformId> <deviceId> <extension>
Checks if device supports the spectified extension
Return value is true if device supports the spectified extension.
platformId: valid platformId.
deviceId: valid deviceId.
extension: string with specified extension

CL_WaitForEvent <eventId> <Blocking | SpinLock>
Wait on the host thread for command identified by event to complete.
eventId: valid eventId.

CL_WaitForEvents <waitlist> <Blocking | SpinLock>
Wait on the host thread for commands identified by waitlist to complete.
waitList: list of events that must be completed before being able to continue.

CL_WriteBuffer <queueId> <bufId> <value|image> <waitlist> <eventId> <wait>
Enqueue a command to write to a buffer object from host memory.
queueId: valid queueId.
bufId: valid bufferId.
value|image: value or image to be written to the buffer.
waitList: list of events that need to complete before this command can be executed.
eventId: list with zero or one event, event triggerd when operation is completed.
wait: indicates if the operation is blocking or non-blocking.

Usage: CL_WriteImage2D <queueId> <imageId> <imageName> <waitlist> <eventId> <wait>
Enqueue a command to write to a 2D or 3D image object from host memory.
queueId: valid queueId.
imageId: valid imageId.
imageName: name of the image to be written to the buffer.
waitList: list of events that need to complete before this command can be executed.
eventId: list with zero or one event, event triggerd when operation is completed.
wait: indicates if the operation is blocking or non-blocking.


Back to Contents

OpenCL

// OpenCL test
// Jaap van de Loosdrecht, VdLMV
// 20 Dec 2012

#pragma OPENCL EXTENSION cl_khr_byte_addressable_store: enable
#ifdef __AMD__
#pragma OPENCL EXTENSION cl_amd_printf: enable
#endif

kernel void TestDefines (global int *a) {
*a = 0;
#ifdef __CPU__
*a = 1;
#endif
#ifdef __GPU__
*a = 2;
#endif
#ifdef __Accelerator__
*a += 3;
#endif
#ifdef __DefaultDevice__
*a += 4;
#endif
#ifdef __AllDevices__
*a = 5;
#endif
#ifdef __AMD__
*a += 10;
#endif
#ifdef __NVIDIA__
*a += 20;
#endif
#ifdef __INTEL__
*a += 30;
#endif
#ifdef __AllPlatforms__
*a += 100;
#endif
#if defined(__AMD__) && defined(__CPU__)
printf("Test of printf: %d\n", *a);
#endif
}

kernel void TestInts (const int a, global int *b, global int *c) {
*c = a + *b;
}

kernel void TestUInts (const uint a, global uint *b, global uint *c) {
*c = a + *b;
}

kernel void TestInt4 (const int size, global int4 *b, global int *c) {
for (int i = 0; i < size/4; i++) {
c[i*4+0] = b[i].x;
c[i*4+1] = b[i].y;
c[i*4+2] = b[i].z;
c[i*4+3] = b[i].w;
}
}

kernel void TestUInt4 (const uint size, global uint4 *b, global uint *c) {
for (int i = 0; i < size/4; i++) {
c[i*4+0] = b[i].x;
c[i*4+1] = b[i].y;
c[i*4+2] = b[i].z;
c[i*4+3] = b[i].w;
}
}

kernel void TestShorts (global short *a, global short *b, global short *c) {
*c = *a + *b;
}

kernel void TestLongs (global long *a, global long *b, global long *c) {
*c = *a + *b;
}

kernel void TestUChars (const uchar a, global uchar *b, global uchar *c) {
*c = a + *b;
}

kernel void TestFloats (const float a, const float b, global float *c) {
*c = a + b;
}

kernel void TestIntArray (const int size, global int *b, global int *c) {
for (int i = 0; i < size; i++) {
c[i] = b[i];
}
}

kernel void TestUIntArray (const uint size, global uint *b, global uint *c) {
for (int i = 0; i < size; i++) {
c[i] = b[i];
}
}

kernel void TestShortArray (const int size, global short *b, global short *c) {
for (int i = 0; i < size; i++) {
c[i] = b[i];
}
}

kernel void TestLongArray (const int size, global long *b, global long *c) {
for (int i = 0; i < size; i++) {
c[i] = b[i];
}
}

kernel void TestFloatArray (const int size, global float *b, global float *c) {
for (int i = 0; i < size; i++) {
c[i] = b[i];
}
}


#ifdef cl_khr_fp64
#pragma OPENCL EXTENSION cl_khr_fp64: enable
#else
#ifdef cl_amd_fp64
#pragma OPENCL EXTENSION cl_amd_fp64: enable
#define cl_khr_fp64
#endif
#endif
//#if defined(cl_amd_fp64) || defined(cl_khr_fp64)
#ifdef cl_khr_fp64
kernel void TestDoubles (const double a, const double b, global double* c) {
*c = a + b;
}
kernel void TestDoubleArray (const int size, global double *b, global double *c) {
for (int i = 0; i < size; i++) {
c[i] = b[i];
}
}

#endif

kernel void TestInt16Image (global short* c, global short* a, global short* b) {
unsigned int n = get_global_id(0);
c[n] = a[n] + b[n];
}

kernel void TestGlobalIds (global int *tab) {
tab[get_global_id(0)] = get_global_id(0);
}


kernel void TestLocal (global int *val, local int *loc) {
if (get_global_id(0) == 0) *loc = 10;
barrier (CLK_LOCAL_MEM_FENCE);
if (get_global_id(0) == 1) *loc += 100;
barrier (CLK_LOCAL_MEM_FENCE);
if (get_global_id(0) == 0) *val = *loc;
}

kernel void TestLocal3 (global int *val) {
local int loc;
if (get_global_id(0) == 0) loc = 10;
barrier (CLK_LOCAL_MEM_FENCE);
if (get_global_id(0) == 1) loc += 100;
barrier (CLK_LOCAL_MEM_FENCE);
if (get_global_id(0) == 0) *val = loc;
}


#ifdef __IMAGE_SUPPORT__

constant sampler_t imgSampler = CLK_NORMALIZED_COORDS_FALSE | CLK_ADDRESS_NONE;

kernel void TestImageCol8(read_only image2d_t imageIn, write_only image2d_t imageOut)
{
int2 coord = (int2)(get_global_id(0), get_global_id(1));
uint4 pixel;
pixel = read_imageui(imageIn,imgSampler,coord);
write_imageui(imageOut,coord,pixel);
}

kernel void TestImageCol16(read_only image2d_t imageIn, write_only image2d_t imageOut)
{
int2 coord = (int2)(get_global_id(0), get_global_id(1));
int4 pixel;
pixel = read_imagei(imageIn,imgSampler,coord);
write_imagei(imageOut,coord,pixel);
}

kernel void TestImageB(read_only image2d_t imageIn, write_only image2d_t imageOut)
{
int2 coord = (int2)(get_global_id(0), get_global_id(1));
uint4 pixel;
pixel = read_imageui(imageIn,imgSampler,coord);
write_imageui(imageOut,coord,pixel);
}

kernel void TestImageI16(read_only image2d_t imageIn, write_only image2d_t imageOut)
{
int2 coord = (int2)(get_global_id(0), get_global_id(1));
int4 pixel;
pixel = read_imagei(imageIn,imgSampler,coord);
//pixel = (int4)(0,0,0,0);
write_imagei(imageOut,coord,pixel);
}

kernel void TestImageI32(read_only image2d_t imageIn, write_only image2d_t imageOut)
{
int2 coord = (int2)(get_global_id(0), get_global_id(1));
int4 pixel;
pixel = read_imagei(imageIn,imgSampler,coord);
//pixel = (int4)(0,0,0,0);
write_imagei(imageOut,coord,pixel);
}

kernel void TestImageF(read_only image2d_t imageIn, write_only image2d_t imageOut)
{
int2 coord = (int2)(get_global_id(0), get_global_id(1));
float4 pixel;
pixel = read_imagef(imageIn,imgSampler,coord);
write_imagef(imageOut,coord,pixel);
}

#endif // __IMAGE_SUPPORT__





Back to Contents

OpenCL

$dir = LPWD
CWD $dir
$src = VarFromFile example_cl.cl
CL_Init NVIDIA GPU
$nrP = CL_GetPlatforms &$tabP
$platformId = 0
$nrD = CL_GetDevices $platformId &$tabD
$deviceId = 0
$doubles = CL_SupportDoubles $platformId $deviceId
$contextId = CL_CreateContext $platformId ($deviceId)
$qId = CL_CreateQueue $contextId $deviceId OutOfOrderEnabled ProfilingEnabled
$options = ""
$programId = CL_CreateProgram $contextId &$src
CL_Build $programId &$options
CL_SaveBinary $programId kernel.clo
$programId = CL_CreateProgramWithBinary $contextId kernel.clo
CL_Build $programId &$options

CL_AddKernel $programId TestDefines
$bufDefines = CL_CreateBuffer $contextId WriteOnly Int
$a = -1
CL_SetArg TestDefines 0 Buffer $bufDefines
CL_Run $qId TestDefines () (1) () () () Wait
CL_ReadBuffer $qId $bufDefines &$a () () Wait
$exp = 21
//TestEqualVar &$a &$exp

CL_AddKernel $programId TestInts
$bufIb = CL_CreateBuffer $contextId ReadOnly Int
$bufIc = CL_CreateBuffer $contextId WriteOnly Int
$a = 1
$b = 2
$c = 9
CL_WriteBuffer $qId $bufIb $b () () Wait
CL_SetArg TestInts 0 Int $a
CL_SetArg TestInts 1 Buffer $bufIb
CL_SetArg TestInts 2 Buffer $bufIc
CL_Run $qId TestInts () (1) () () () Wait
CL_ReadBuffer $qId $bufIc &$c () () Wait
$exp = 3
TestEqualVar &$c &$exp

CL_AddKernel $programId TestUInts
$bufUIb = CL_CreateBuffer $contextId ReadOnly UInt
$bufUIc = CL_CreateBuffer $contextId WriteOnly UInt
$a = 1
$b = 2
$c = 9
CL_WriteBuffer $qId $bufUIb $b () () Wait
CL_SetArg TestUInts 0 UInt $a
CL_SetArg TestUInts 1 Buffer $bufUIb
CL_SetArg TestUInts 2 Buffer $bufUIc
CL_Run $qId TestUInts () (1) () () () Wait
CL_ReadBuffer $qId $bufUIc &$c () () Wait
$exp = 3
TestEqualVar &$c &$exp

$size = 16
CL_AddKernel $programId TestInt4
$bufI4b = CL_CreateBuffer $contextId ReadOnly IntArray $size
$bufI4c = CL_CreateBuffer $contextId WriteOnly IntArray $size
for $i = 0 to ($size - 1) do
$b[$i] = 2
$c[$i] = 9
endfor
CL_SetArg TestInt4 0 Int $size
CL_SetArg TestInt4 1 Buffer $bufI4b
CL_SetArg TestInt4 2 Buffer $bufI4c
CL_WriteBuffer $qId $bufI4b &$b () () Wait
CL_Run $qId TestInt4 () (1) () () () Wait
CL_ReadBuffer $qId $bufI4c &$c () () Wait
TestEqualVar &$c &$b

$size = 16
CL_AddKernel $programId TestUInt4
$bufUI4b = CL_CreateBuffer $contextId ReadOnly UIntArray $size
$bufUI4c = CL_CreateBuffer $contextId WriteOnly UIntArray $size
for $i = 0 to ($size - 1) do
$b[$i] = 2
$c[$i] = 9
endfor
CL_SetArg TestUInt4 0 UInt $size
CL_SetArg TestUInt4 1 Buffer $bufUI4b
CL_SetArg TestUInt4 2 Buffer $bufUI4c
CL_WriteBuffer $qId $bufUI4b &$b () () Wait
CL_Run $qId TestUInt4 () (1) () () () Wait
CL_ReadBuffer $qId $bufUI4c &$c () () Wait
TestEqualVar &$c &$b

CL_AddKernel $programId TestShorts
$bufSa = CL_CreateBuffer $contextId ReadOnly Short
$bufSb = CL_CreateBuffer $contextId ReadOnly Short
$bufSc = CL_CreateBuffer $contextId WriteOnly Short
$a = 1
$b = 2
$c = 9
CL_SetArg TestShorts 0 Buffer $bufSa
CL_SetArg TestShorts 1 Buffer $bufSb
CL_SetArg TestShorts 2 Buffer $bufSc
CL_WriteBuffer $qId $bufSa $a () () Wait
CL_WriteBuffer $qId $bufSb $b () () Wait
CL_Run $qId TestShorts () (1) () () () Wait
CL_ReadBuffer $qId $bufSc &$c () () Wait
$exp = 3
TestEqualVar &$c &$exp

CL_AddKernel $programId TestUChars
$bufCb = CL_CreateBuffer $contextId ReadOnly UChar
$bufCc = CL_CreateBuffer $contextId WriteOnly UChar
$a = 1
$b = 2
$c = 9
CL_WriteBuffer $qId $bufCb $b () () Wait
CL_SetArg TestUChars 0 UChar $a
CL_SetArg TestUChars 1 Buffer $bufCb
CL_SetArg TestUChars 2 Buffer $bufCc
CL_Run $qId TestUChars () (1) () () () Wait
CL_ReadBuffer $qId $bufCc &$c () () Wait
$exp = 3
TestEqualVar &$c &$exp

CL_AddKernel $programId TestLongs
$bufLa = CL_CreateBuffer $contextId ReadOnly Long
$bufLb = CL_CreateBuffer $contextId ReadOnly Long
$bufLc = CL_CreateBuffer $contextId WriteOnly Long
$a = 1
$b = 2
$c = 9
CL_SetArg TestLongs 0 Buffer $bufLa
CL_SetArg TestLongs 1 Buffer $bufLb
CL_SetArg TestLongs 2 Buffer $bufLc
CL_WriteBuffer $qId $bufLa $a () () Wait
CL_WriteBuffer $qId $bufLb $b () () Wait
CL_Run $qId TestLongs () (1) () () () Wait
CL_ReadBuffer $qId $bufLc &$c () () Wait
$exp = 3
TestEqualVar &$c &$exp

CL_AddKernel $programId TestFloats
$bufF = CL_CreateBuffer $contextId WriteOnly Float
$a = 1
$b = 2
$c = 9
CL_SetArg TestFloats 0 Float $a
CL_SetArg TestFloats 1 Float $b
CL_SetArg TestFloats 2 Buffer $bufF
CL_Run $qId TestFloats () (1) () () () Wait
CL_ReadBuffer $qId $bufF &$c () () Wait
$exp = 3
TestEqualVar &$c &$exp

if $doubles then
CL_AddKernel $programId TestDoubles
$bufD = CL_CreateBuffer $contextId WriteOnly Double
$a = 1
$b = 2
$c = 9
CL_SetArg TestDoubles 0 Double $a
CL_SetArg TestDoubles 1 Double $b
CL_SetArg TestDoubles 2 Buffer $bufD
CL_Run $qId TestDoubles () (1) () () () Wait
CL_ReadBuffer $qId $bufD &$c () () Wait
$exp = 3
TestEqualVar &$c &$exp
endif

$size = 10
RemoveVar &$b
RemoveVar &$c
CL_AddKernel $programId TestIntArray
$bufIb = CL_CreateBuffer $contextId ReadOnly IntArray $size
$bufIc = CL_CreateBuffer $contextId WriteOnly IntArray $size
for $i = 0 to ($size - 1) do
$b[$i] = 2
$c[$i] = 9
endfor
CL_SetArg TestIntArray 0 Int $size
CL_SetArg TestIntArray 1 Buffer $bufIb
CL_SetArg TestIntArray 2 Buffer $bufIc
CL_WriteBuffer $qId $bufIb &$b () () Wait
CL_Run $qId TestIntArray () (1) () () () Wait
CL_ReadBuffer $qId $bufIc &$c () () Wait
TestEqualVar &$c &$b

$size = 10
CL_AddKernel $programId TestUIntArray
$bufUI4b = CL_CreateBuffer $contextId ReadOnly UIntArray $size
$bufUI4c = CL_CreateBuffer $contextId WriteOnly UIntArray $size
for $i = 0 to ($size - 1) do
$b[$i] = 2
$c[$i] = 9
endfor
CL_SetArg TestUIntArray 0 UInt $size
CL_SetArg TestUIntArray 1 Buffer $bufUI4b
CL_SetArg TestUIntArray 2 Buffer $bufUI4c
CL_WriteBuffer $qId $bufUI4b &$b () () Wait
CL_Run $qId TestUIntArray () (1) () () () Wait
CL_ReadBuffer $qId $bufUI4c &$c () () Wait
TestEqualVar &$c &$b

$size = 10
RemoveVar &$b
RemoveVar &$c
CL_AddKernel $programId TestLongArray
$bufLb = CL_CreateBuffer $contextId ReadOnly LongArray $size
$bufLc = CL_CreateBuffer $contextId WriteOnly LongArray $size
for $i = 0 to ($size - 1) do
$b[$i] = 2
$c[$i] = 9
endfor
CL_SetArg TestLongArray 0 Int $size
CL_SetArg TestLongArray 1 Buffer $bufLb
CL_SetArg TestLongArray 2 Buffer $bufLc
CL_WriteBuffer $qId $bufLb &$b () () Wait
CL_Run $qId TestLongArray () (1) () () () Wait
CL_ReadBuffer $qId $bufLc &$c () () Wait
TestEqualVar &$c &$b

$size = 10
RemoveVar &$b
RemoveVar &$c
CL_AddKernel $programId TestShortArray
$bufSb = CL_CreateBuffer $contextId ReadOnly ShortArray $size
$bufSc = CL_CreateBuffer $contextId WriteOnly ShortArray $size
for $i = 0 to ($size - 1) do
$b[$i] = 2
$c[$i] = 9
endfor
CL_SetArg TestShortArray 0 Int $size
CL_SetArg TestShortArray 1 Buffer $bufSb
CL_SetArg TestShortArray 2 Buffer $bufSc
CL_WriteBuffer $qId $bufSb &$b () () Wait
CL_Run $qId TestShortArray () (1) () () () Wait
CL_ReadBuffer $qId $bufSc &$c () () Wait
TestEqualVar &$c &$b

$size = 10
RemoveVar &$b
RemoveVar &$c
CL_AddKernel $programId TestFloatArray
$bufFb = CL_CreateBuffer $contextId ReadOnly FloatArray $size
$bufFc = CL_CreateBuffer $contextId WriteOnly FloatArray $size
for $i = 0 to ($size - 1) do
$b[$i] = 2
$c[$i] = 9
endfor
CL_SetArg TestFloatArray 0 Int $size
CL_SetArg TestFloatArray 1 Buffer $bufFb
CL_SetArg TestFloatArray 2 Buffer $bufFc
CL_WriteBuffer $qId $bufFb &$b () () Wait
CL_Run $qId TestFloatArray () (1) () () () Wait
CL_ReadBuffer $qId $bufFc &$c () () Wait
TestEqualVar &$c &$b

if $doubles then
RemoveVar &$b
RemoveVar &$c
CL_AddKernel $programId TestDoubleArray
$bufDb = CL_CreateBuffer $contextId ReadOnly DoubleArray $size
$bufDc = CL_CreateBuffer $contextId WriteOnly DoubleArray $size
for $i = 0 to ($size - 1) do
$b[$i] = 2
$c[$i] = 9
endfor
CL_SetArg TestDoubleArray 0 Int $size
CL_SetArg TestDoubleArray 1 Buffer $bufDb
CL_SetArg TestDoubleArray 2 Buffer $bufDc
CL_WriteBuffer $qId $bufDb &$b () () Wait
CL_Run $qId TestDoubleArray () (1) () () () Wait
CL_ReadBuffer $qId $bufDc &$c () () Wait
TestEqualVar &$c &$b
endif

$size = 100
$nrPixels = $size * $size
$bufSize = 2 * $nrPixels
Create imageA Int16Image $size $size
Create imageB Int16Image $size $size
Create imageC Int16Image $size $size
Create imageD Int16Image $size $size
SetAllPixels imageA 1
SetAllPixels imageB 2
SetAllPixels imageC 9
SetAllPixels imageD 3
CL_AddKernel $programId TestInt16Image
$bufA = CL_CreateBuffer $contextId ReadOnly ImageBuffer imageA
$bufB = CL_CreateBuffer $contextId ReadOnly ImageBuffer imageB
$bufC = CL_CreateBuffer $contextId WriteOnly ImageBuffer imageC
$pBufA = CL_PinImage $qId $contextId imageA ReadOnly
$pBufB = cl_PinImage $qId $contextId imageB ReadOnly
$pBufC = cl_PinImage $qId $contextId imageC WriteOnly
CL_SetArg TestInt16Image 0 ImageBuffer $bufC
CL_SetArg TestInt16Image 1 ImageBuffer $bufA
CL_SetArg TestInt16Image 2 ImageBuffer $bufB
CL_WriteBuffer $qId $bufA imageA () () Wait
CL_WriteBuffer $qId $bufB imageB () () Wait
CL_Run $qId TestInt16Image () ($nrPixels) () () () Wait
CL_ReadBuffer $qId $bufC imageC () () Wait
TestEqual imageC imageD
CL_UnPinImage $qId $pBufA imageA
CL_UnPinImage $qId $pBufB imageB
CL_UnPinImage $qId $pBufC imageC
TestEqual imageC imageD

$size = 10
RemoveVar &$ids
RemoveVar &$exp
CL_AddKernel $programId TestGlobalIds
$bufGIds = CL_CreateBuffer $contextId WriteOnly IntArray $size
for $i = 0 to ($size - 1) do
$ids[$i] = -1
$exp[$i] = $i
endfor
CL_SetArg TestGlobalIds 0 Buffer $bufGIds
CL_Run $qId TestGlobalIds () ($size) () () () Wait
CL_ReadBuffer $qId $bufGIds &$ids () () Wait
TestEqualVar &$exp &$ids

CL_AddKernel $programId TestLocal
$bufL = CL_CreateBuffer $contextId WriteOnly Int
CL_SetArg TestLocal 0 Buffer $bufL
CL_SetArg TestLocal 1 LocalBuffer 4
CL_Run $qId TestLocal () (2) (2) () () Wait
CL_ReadBuffer $qId $bufL &$l () () Wait
$exp = 110
TestEqualVar &$l &$exp

CL_AddKernel $programId TestLocal3
$bufL = CL_CreateBuffer $contextId WriteOnly Int
CL_SetArg TestLocal3 0 Buffer $bufL
CL_Run $qId TestLocal3 () (2) (2) () () Wait
CL_ReadBuffer $qId $bufL &$l () () Wait
$exp = 110
TestEqualVar &$l &$exp

$event = CL_CreateEvent
$bufL = CL_CreateBuffer $contextId WriteOnly Int
CL_SetArg TestLocal 0 Buffer $bufL
CL_SetArg TestLocal 1 LocalBuffer 4
// next line can NOT be removed
CL_Run $qId TestLocal () (2) (2) () ($event) NoWait
CL_Run $qId TestLocal () (2) (2) ($event) () NoWait
CL_Flush $qId
CL_Finish $qId
CL_ReadBuffer $qId $bufL &$l () () Wait
$exp = 110
TestEqualVar &$l &$exp

$images = CL_GetDeviceInfo $platformId $deviceId IMAGE_SUPPORT
if !($images) then
break
return
endif

$size = 256
Create imageA RGB888Image $size $size
Create imageB RGB888Image $size $size
SetAllPixels imageA (1,1,1)
SetAllPixels imageB (8,8,8)
$imA = CL_CreateImage2D $contextId ReadOnly RGB888Image $size $size
$imB = CL_CreateImage2D $contextId WriteOnly RGB888Image $size $size
CL_AddKernel $programId TestImageCol8
CL_SetArg TestImageCol8 0 Image2D $imA
CL_SetArg TestImageCol8 1 Image2D $imB
CL_WriteImage2D $qId $imA imageA () () Wait
CL_Run $qId TestImageCol8 () (256,256) (16,16) () () Wait
CL_ReadImage2D $qId $imB imageB () () Wait
TestEqual imageA imageB

$size = 256
Create imageA ByteImage $size $size
Create imageB ByteImage $size $size
RampPattern imageA 128 128 255
SetAllPixels imageB 5
$imAb = CL_CreateImage2D $contextId ReadOnly ByteImage $size $size
$imBb = CL_CreateImage2D $contextId WriteOnly ByteImage $size $size
CL_AddKernel $programId TestImageB
CL_SetArg TestImageB 0 Image2D $imAb
CL_SetArg TestImageB 1 Image2D $imBb
CL_WriteImage2D $qId $imAb imageA () () Wait
CL_Run $qId TestImageB () (256,256) (16,16) () () Wait
CL_ReadImage2D $qId $imBb imageB () () Wait
TestEqual imageA imageB

$size = 256
Create imageA Int32Image $size $size
Create imageB Int32Image $size $size
RampPattern imageA 128 128 255
SetAllPixels imageB 5
$imAi32 = CL_CreateImage2D $contextId ReadOnly Int32Image $size $size
$imBi32 = CL_CreateImage2D $contextId WriteOnly Int32Image $size $size
CL_AddKernel $programId TestImageI32
CL_SetArg TestImageI32 0 Image2D $imAi32
CL_SetArg TestImageI32 1 Image2D $imBi32
CL_WriteImage2D $qId $imAi32 imageA () () Wait
CL_Run $qId TestImageI32 () (256,256) (16,16) () () Wait
CL_ReadImage2D $qId $imBi32 imageB () () Wait
TestEqual imageA imageB

$size = 256
Create imageA Int16Image $size $size
Create imageB Int16Image $size $size
RampPattern imageA 128 128 255
SetAllPixels imageA 0
SetAllPixels imageB 5
$imAi16 = CL_CreateImage2D $contextId ReadOnly Int16Image $size $size
$imBi16 = CL_CreateImage2D $contextId WriteOnly Int16Image $size $size
CL_AddKernel $programId TestImageI16
CL_SetArg TestImageI16 0 Image2D $imAi16
CL_SetArg TestImageI16 1 Image2D $imBi16
CL_WriteImage2D $qId $imAi16 imageA () () Wait
CL_Run $qId TestImageI16 () (256,256) (16,16) () () Wait
CL_ReadImage2D $qId $imBi16 imageB () () Wait
TestEqual imageA imageB

$size = 256
Create imageA FloatImage $size $size
Create imageB FloatImage $size $size
RampPattern imageA 128 128 255
SetAllPixels imageB 5
$imAf = CL_CreateImage2D $contextId ReadOnly FloatImage $size $size
$imBf = CL_CreateImage2D $contextId WriteOnly FloatImage $size $size
CL_AddKernel $programId TestImageF
CL_SetArg TestImageF 0 Image2D $imAf
CL_SetArg TestImageF 1 Image2D $imBf
CL_WriteImage2D $qId $imAf imageA () () Wait
CL_Run $qId TestImageF () (256,256) (16,16) () () Wait
CL_ReadImage2D $qId $imBf imageB () () Wait
TestEqual imageA imageB




Back to Contents

opencl_jl.h

/* File : OpenCL_JL.h
* Project : visionlib V3.0
* Author : Jaap van de Loosdrecht, Herman Schubert
* Van de Loosdrecht Machine Vision BV
* www.vdlmv.nl
* Date : 1-6-2012
*
* Copyright (c) 1993-2017, Van de Loosdrecht Machine Vision BV,
* all rights reserved.
*/

#ifndef JL_OPENCL
#define JL_OPENCL

#include "compiler.h"
#pragma warning( disable : 4100 4245 4510 4512 4610 4290)
#define __CL_ENABLE_EXCEPTIONS
#include <CL/cl.hpp>
#include <vector>
#include <string>
#include <map>
#include "image.h"
#include "word.h"

namespace JL_OpenCL {

class Error: public std::exception {
public:
Error (const std::string& msg);
Error (const std::string& opName, const std::string& msg);
virtual const char *what() const throw();
virtual ~Error() throw() {}
protected:
std::string msg;
};

// to do: NVIDA must be NVIDIA
enum PlatformVendor {AMD, NVIDIA, INTEL, AllPlatforms, NrOfPlatformVendors};
enum DeviceType {DefaultDevice, CPU, GPU, Accelerator, AllDevices, NrOfDeviceTypes};
enum QOutOfOrder {OutOfOrderEnabled, OutOfOrderDisabled};
enum QProfiling {ProfilingEnabled, ProfilingDisabled};
enum WaitType {NoWait, Wait};
enum BlockType {Blocking, SpinLock};
enum BufferRWType {ReadOnly, WriteOnly, ReadWrite, NrOfBufferRWTypes};
enum ImageType {CL_ByteImage, CL_FloatImage, CL_Int16Image, CL_Int32Image, CL_RGB888Image, NrOfImageTypes};
enum PlatformInfo {PLATFORM_PROFILE, PLATFORM_VERSION, PLATFORM_NAME, PLATFORM_VENDOR,
PLATFORM_EXTENSIONS, NrOfPlatformInfos};
enum DeviceInfo { // note: problem with macro DEVICE_TYPE, so DEVICE_Type is used
DEVICE_Type, DEVICE_VENDOR_ID, DEVICE_MAX_COMPUTE_UNITS, DEVICE_MAX_WORK_ITEM_DIMENSIONS,
DEVICE_MAX_WORK_GROUP_SIZE, DEVICE_MAX_WORK_ITEM_SIZES, DEVICE_PREFERRED_VECTOR_WIDTH_CHAR,
DEVICE_PREFERRED_VECTOR_WIDTH_SHORT, DEVICE_PREFERRED_VECTOR_WIDTH_INT, DEVICE_PREFERRED_VECTOR_WIDTH_LONG,
DEVICE_PREFERRED_VECTOR_WIDTH_FLOAT, DEVICE_PREFERRED_VECTOR_WIDTH_DOUBLE, DEVICE_MAX_CLOCK_FREQUENCY,
DEVICE_ADDRESS_BITS, DEVICE_MAX_READ_IMAGE_ARGS, DEVICE_MAX_WRITE_IMAGE_ARGS, DEVICE_MAX_MEM_ALLOC_SIZE,
DEVICE_IMAGE2D_MAX_WIDTH, DEVICE_IMAGE2D_MAX_HEIGHT, DEVICE_IMAGE3D_MAX_WIDTH, DEVICE_IMAGE3D_MAX_HEIGHT,
DEVICE_IMAGE3D_MAX_DEPTH, DEVICE_IMAGE_SUPPORT, DEVICE_MAX_PARAMETER_SIZE, DEVICE_MAX_SAMPLERS,
DEVICE_MEM_BASE_ADDR_ALIGN, DEVICE_MIN_DATA_TYPE_ALIGN_SIZE, DEVICE_SINGLE_FP_CONFIG, DEVICE_GLOBAL_MEM_CACHE_TYPE,
DEVICE_GLOBAL_MEM_CACHELINE_SIZE, DEVICE_GLOBAL_MEM_CACHE_SIZE, DEVICE_GLOBAL_MEM_SIZE,
DEVICE_MAX_CONSTANT_BUFFER_SIZE, DEVICE_MAX_CONSTANT_ARGS, DEVICE_LOCAL_MEM_TYPE, DEVICE_LOCAL_MEM_SIZE,
DEVICE_ERROR_CORRECTION_SUPPORT, DEVICE_PROFILING_TIMER_RESOLUTION, DEVICE_ENDIAN_LITTLE, DEVICE_AVAILABLE,
DEVICE_COMPILER_AVAILABLE, DEVICE_EXECUTION_CAPABILITIES, DEVICE_QUEUE_PROPERTIES, DEVICE_NAME, DEVICE_VENDOR,
DRIVER_VERSION, DEVICE_PROFILE, DEVICE_VERSION, DEVICE_EXTENSIONS, DEVICE_PLATFORM, DEVICE_DOUBLE_FP_CONFIG,
DEVICE_HALF_FP_CONFIG, DEVICE_PREFERRED_VECTOR_WIDTH_HALF, DEVICE_HOST_UNIFIED_MEMORY,
DEVICE_NATIVE_VECTOR_WIDTH_CHAR, DEVICE_NATIVE_VECTOR_WIDTH_SHORT, DEVICE_NATIVE_VECTOR_WIDTH_INT,
DEVICE_NATIVE_VECTOR_WIDTH_LONG, DEVICE_NATIVE_VECTOR_WIDTH_FLOAT, DEVICE_NATIVE_VECTOR_WIDTH_DOUBLE,
DEVICE_NATIVE_VECTOR_WIDTH_HALF, DEVICE_OPENCL_C_VERSION,
NrOfDeviceInfos};
enum KernelWorkGroupInfo {
KERNEL_WORK_GROUP_SIZE, KERNEL_COMPILE_WORK_GROUP_SIZE, KERNEL_LOCAL_MEM_SIZE,
KERNEL_PREFERRED_WORK_GROUP_SIZE_MULTIPLE, KERNEL_PRIVATE_MEM_SIZE,
NrOfKernelWorkGroupInfos};
enum AmdBufferType {AMD_LOCAL, AMD_UNCACHED, AMD_CACHABLE};

struct ContextRec {
ContextRec (const cl::Context &c, const int pId) {
context = c; platformId = pId;
}
cl::Context context;
int platformId; // NOTE: is JL platformId used in deviceTab, not OpenCL platformId!!
}; // ContextRec

extern cl::NDRange StrToNDRange(const string &str);
extern std::vector<int> WaitEventList (const int nr, ...);

class OpenCL_JL {
public:
OpenCL_JL ();
OpenCL_JL::~OpenCL_JL (); // to do: OpenCL_JL:: not neccessary
void Init (const PlatformVendor pv, const DeviceType dt);

void AddKernel (const int programId, const std::string &name);
void Build (const int programId, const std::string &options);
std::string BuildInfo (const int programId);
int CreateBuffer (const int contextId, const int size, const BufferRWType rw);
int CreateHostBufferFromPtr (const int contextId, IN void* buffer, const int size, const BufferRWType rw);
int CreateHostBuffer (const int contextId, const int queueId, OUT void** buffer, const int size, const BufferRWType rw);
//int CreateAmdBuffer (const int contextId, const int queueId, OUT void** buffer, const int size,
// const AmdBufferType bufferType);
void UnmapHostBuffer(IN void* buffer, const int queueId, const int bufferId);
int CreateContext (const int platformId, const std::vector<int> &deviceTab);
int CreateEvent ();
int CreateImage2D (const int contextId, const ImageType imageType,
const int height, const int width, const BufferRWType rw);
int CreateProgram (const int contextId, const std::string &src);
int CreateProgramWithBinary (const int contextId, const std::string &fileName);
int CreateQueue (const int contextId, const int deviceId, const QOutOfOrder qOrder, const QProfiling qProf);
void DeleteAll ();
void DeleteBuffers ();
void DeleteContexts ();
void DeleteDevices ();
void DeleteEvents ();
void DeleteKernels ();
void DeleteImage2Ds ();
void DeletePlatforms ();
void DeletePrograms ();
void DeleteQueues ();

void Finish (const int queueId);
void Flush (const int queueId);
std::string GetDeviceInfo (const int platformId, const int deviceId, const DeviceInfo info);
std::string GetKernelWorkGroupInfo (const int platformId, const int deviceId,
const std::string &kernelName, const KernelWorkGroupInfo info);
std::string GetPlatformInfo (const int platformId, const PlatformInfo info);
int NrDevices (const int platformId);
int NrPlatforms ();
void ReadBuffer (const int queueId, const int bufId, const int size, void *buf,
const std::vector<int> waitList, const int eventId = -1, const WaitType wait = Wait);
void ReadImage2D (const int queueId, const int imageId, JL_VisionLib_V3::Image &image,
const std::vector<int> waitList, const int eventId = -1, const WaitType wait = Wait);
void Run (const int queueId, const std::string &kernelName, const cl::NDRange& offset,
const cl::NDRange& global, const cl::NDRange& local,
const std::vector<int> waitList, const int eventId = -1, const WaitType wait = Wait);
void SaveBinary (const int programId, const std::string &fileName);
template <class Value> void SetArg (const string &kernelName, const int index, const Value value);
void SetArgBuf (const std::string &kernelName, const int index, const int bufId);
void SetArgImage2D (const std::string &kernelName, const int index, const int imageId);
void SetArgLocalBuf (const std::string &kernelName, const int index, const int size);
bool SupportAtomCounters(const int platformId, const int deviceId);
bool SupportDoubles(const int platformId, const int deviceId);
bool SupportExtension(const int platformId, const int deviceId, const std::string &ext);
void WaitForEvent (const int eventId, const BlockType bt = Blocking);
void WaitForEvents (const std::vector<int> waitList, const BlockType bt = Blocking);
void WriteBuffer (const int queueId, const int bufId, const int size, void *buf,
const std::vector<int> waitList, const int eventId = -1, const WaitType wait = Wait);
void WriteImage2D (const int queueId, const int imageId, JL_VisionLib_V3::Image &image,
const std::vector<int> waitList, const int eventId = -1, const WaitType wait = Wait);
static std::string ErrorCodeToStr (const int err);
protected:
struct Image2DRec {
Image2DRec (ImageType it, int h, int w, BufferRWType rwt, cl::Image2D &buf) {
imageType = it; height = h; width = w; rw = rwt; buffer = buf;
}
ImageType imageType;
int height;
int width;
BufferRWType rw;
cl::Image2D buffer;
}; // Image2DRec
enum InfoType {IT_uint, IT_bool, IT_string, IT_ulong, IT_size_t, IT_size_tArray, IT_enum, IT_NotSupported};
struct InfoElm {
InfoElm (const int c = 0, const InfoType t = IT_NotSupported) { code = c; type = t; }
int code;
InfoType type;
};
typedef std::vector<cl::Platform> PlatformTab;
typedef std::vector<std::vector<cl::Device> >DeviceTab; // [platformId][deviceId]
typedef std::vector<ContextRec> ContextTab;
typedef std::vector<cl::CommandQueue> QueueTab;
typedef std::vector<cl::Program > ProgramTab;
typedef std::map<std::string, cl::Kernel> KernelTab;
typedef std::vector<cl::Buffer> BufferTab;
typedef std::vector<Image2DRec> Image2DTab;
typedef std::vector<cl::Event> EventTab;

typedef vector<std::string> PlatformVendorTab;
typedef vector<int> DeviceTypeTab;
typedef vector<int> BufferRWTypeTab;
typedef vector<cl::ImageFormat> ImageFormatTab;
typedef vector<int> PlatformInfoTab;
typedef vector<InfoElm> DeviceInfoTab;
typedef vector<InfoElm> KernelWorkGroupInfoTab;
typedef vector<std::string> ErrorCodeTab;
bool initialized;
PlatformVendor platformVendor;
DeviceType deviceType;
PlatformTab platformTab;
DeviceTab deviceTab;
ContextTab contextTab;
QueueTab queueTab;
ProgramTab programTab;
KernelTab kernelTab;
BufferTab bufferTab;
Image2DTab image2DTab;
EventTab eventTab;
PlatformVendorTab platformVendorTab;
DeviceTypeTab deviceTypeTab;
BufferRWTypeTab bufferRWTypeTab;
ImageFormatTab imageFormatTab;
PlatformInfoTab platformInfoTab;
KernelWorkGroupInfoTab kernelWorkGroupInfoTab;
DeviceInfoTab deviceInfoTab;
static ErrorCodeTab errorCodeTab;
void InitConvTabs ();
void InitErrorCodeTab ();
void InitPlatformInfoTab ();
void InitKernelWorkGroupInfoTab ();
void InitDeviceInfoTab ();
void CheckPlatformId (const std::string &opName, const int platformId);
void CheckDeviceId (const std::string &opName, const int platformId, const int deviceId);
void CheckContextId (const std::string &opName, const int contextId);
void CheckImage2DId (const std::string &opName, const int imageId);
void CheckProgramId (const std::string &opName, const int programId);
void CheckKernelName (const std::string &opName, const std::string &kernelName);
void CheckBufferId (const std::string &opName, const int bufferId);
void CheckQueueId (const std::string &opName, const int queueId);
std::vector<cl::Event> OpenCL_JL::ConvWaitList (const std::vector<int> &wl);
cl::Event* OpenCL_JL::ConvEvent(const int eventId);
private:
void TestInitialized (const std::string opName);
}; // OpenCL_JL

EnumStrIODeclaration(PlatformVendor)
EnumStrIODeclaration(DeviceType)
EnumStrIODeclaration(QOutOfOrder)
EnumStrIODeclaration(QProfiling)
EnumStrIODeclaration(WaitType)
EnumStrIODeclaration(BlockType)
EnumStrIODeclaration(BufferRWType)
EnumStrIODeclaration(ImageType)
EnumStrIODeclaration(DeviceInfo)
EnumStrIODeclaration(KernelWorkGroupInfo)
EnumStrIODeclaration(PlatformInfo)
EnumStrIODeclaration(AmdBufferType)

} // namespace JL_OpenCL

#endif // JL_OPENCL






Back to Contents

Attributes

With this operator the attributes of the image can be viewed and some of the attributes can be changed.

Name: the name of the image. (editable)
In order to make image names unique, a '%' and an extra number is appended to the image name. So the real name of the image used internally is <name>%id.

Type:
image type

Size: height and width of the image.

LUT: Look up table used for displaying. See LUTs.

Reduce: factor by which the image is reduced in size before being displayed.

Print scale: enlarge factor used when an image is printed.

For IntXXXImage only: type of connectivity.

History: In the history window the history of applied operators duringthe session is displayed.

This can be selected also by double clicking on the image window.

Back to Contents

Edit

Class: NumImage, see NumImage.

Menu: Operator | Analyse

With this operator the individual pixel values can be examined and, if wanted, changed.

By single clicking with the mouse pointer in either the editwindow or the image window a cross relation between the two windows can be established.

Back to Contents

Histogram and Histogram ROI (Statistics)

Class: IntImage, see IntImage.

Menu: Operator | Analyse

With this operator a histogram of the distribution of the pixel values is displayed. The pixel values are displayed horizontal andthe frequencies are displayed vertical.

Also the average value for the pixels in the image is displayed.

With the use of the combobox type the view on the histogram can be changed:
- HistogramFrequency
- HistogramPartialSum
- HistogramIOD (= Integrated Optical Density)


The following statistical information is calculated:
- Min
- Max
- NrElms
- Sum
- Mean
- Median
- Modal
- Standard deviation
- IsoData (2 means value)

The Histogram ROI operator performs the same operation as Histogram with theexception that the histogram is only calculated for the selected pixels in the roi.

The Histogram Statistics and Histogram ROI Statistics operators only return the statistical information without the histogram. The first number in the result string is the number of statistics calculated.

HistogramToArray and HistogramROIArray are the commands to be used in order to get the resultsin an array. The function result is the MinValue of the histogram. Array[0] contains the frequencyfor the MinValue.
Histogram0ToArray is an optimized version of HistogramToArray. It asumes that the lowest pixel value in the image is not lowerthan 0 and the highest pixel value lower than the value of the hisSize parameter.

Back to Contents

Pixels

Class: OrdImage, see OrdImage.

Menu: Operator | Analyse

With this operator horizontal and vertical lines of pixel values can be examined.

By single clicking with the mouse pointer in either the analysewindow or the image window a cross relation between the two windows can be established.

Back to Contents

Threshold tool

Class: IntImage, RGB888Image and HSV888Image see OrdImage.

Menu: Operator | Analyse

With this tool you can threshold interactively an image by selecting the object pixels with the mouse cursor.

auto update: with this option every change in the threshold low and high bordervalues is reflected in the thresholded image.

invert: background pixels are selected.

wrap around red: used only for HSV images. selection is based around the red pixels.


Back to Contents

Average pixel

AveragePixel image

Class: OrdImage, see
OrdImage.

Menu: Operator | Analyse
The averagepixel operator calculates the average pixel value of the image.

Back to Contents

Count pixel(s)

CountPixel image value
CountPixels image low high

Class for CountPixel NumImage, see
NumImage.

Class for CountPixels OrdImage, see OrdImage.

Menu: Operator | Analyse

This operator calculates how many pixels there are with the specified value (range) inthe image.

Back to Contents

Is equal, Is the same

IsEqual imageName1 imageName2
IsTheSame imageName1 imageName2 difference

IsEqual: Class: NumImage
IsTheSame: Class: OrdImage, see
NumImage.

Menu: Operator | Point

With the operator IsEqual the active image and the image selected as second are compared for equalness. The result of the operator is a string:'equal' or 'not equal'.

With the operator IsTheSame the active image and the image selected as second are compared for sameness. The images are the same if the differ in each pixel less the specified difference. The result of the operator is a string:'the same' or 'not the same'.

See also: how to select the second image for a dyadic operator.

Back to Contents

In Focus Value

InFocusValue image lowestfreqnr
Class: OrdImage, see
NumImage.

Menu: Operator | Analyse

This operator calculates a value for how good the image is in focus (='sharpness').The higher the returned value the more high freqencies are present in the image.

The parameter lowestfreqnr gives the lowest frequency nr in the FFT which is usedin the calculation.

Back to Contents

LowestButZeroPixel, MaxPixel, MinPixel, MinmMaxPixel, MaxLabel, MinLabel, MinmMaxLabel

LowestButZeroPixel imageName
MaxLabel imageName
MinLabel imageName
MinMaxLabel imageName
MaxPixel imageName
MinPixel imageName
MinMaxPixel imageName

Class: OrdImage, see
OrdImage.

Menu: Operator | Analyse

LowestButZeroPixel:
With this operator the minimum (with the exception of zero) pixel value of an image is calculated.

MaxLabel, MinLabel, MinmMaxLabel:
With these operators the minimum and/or maximum label value of a labeled image is calculated.

MaxPixel, MinPixel, MinmMaxPixel:
With these operators the minimum and/or maximum pixel value of an image is calculated..

Note: MaxLabel and MaxPixel are the same operators. The difference between MinLabeland MinPixel is that MinLabel return the minimum pixel value which is greater then zero (background).

Back to Contents

Standard Deviation

StandardDeviation image

Class: OrdImage, see
OrdImage.

Menu: Operator | Analyse

This operator calculates the standard deviation of the pixelvalues in the image.

Used formula: SQRT((SUM(p**2) - ((SUM(p)**2)/N) / (N-1))
Where p is the pixelvalue and N the number of pixels in the image.
The summation is done over all pixels in the image.

Back to Contents

Sum int pixels and Sum float pixels

SumIntPixels image

Class: IntImage, see
IntImage.

SumFloatPixels image

Class: OrdImage, see OrdImage.

Menu: Operator | Analyse

This operator sums all pixelvalues in the image.

Back to Contents

XYCoordTabFromImage

XYCoordTabFromNum image pixelvalue
Class: NumImage, see
numImage.

XYCoordTabFromOrd image low high
Class: OrdImage, see OrdImage.

Menu: Operator | Analyse

Note: name of both operators in C++ library is XYCoordTabFromImage.

These operators initialise a XYCoordTab with the coordinates of theselected pixels in the image. For xycoordtabfromnum all pixels with pixelvalueare selected. For xycoordtabfromord if low <= high all pixels in the range[low..high] and if low > high all pixels < low and all pixels > high.


Back to Contents

Image Logger

This tool is intended to log images with additional string information.

During an experiment images with string information are stored in RAM memory. This will give only a slow delay in execution. After the experiment is finished, the images and strings can be stored to files for subsequent analysis.

Operators:

InitImageLogger imageType loggerType maxNrFrames height width maxStrSize disgard
CloseImageLogger
ImageLoggerAdd imageName loggerMode string
ImageLoggerClear
ImageLoggerSaveToFile fileNameBase
ImageLoggerGetNth nth imageName

The InitImageLogger operator initialise the image logger. RAM memory for maxNrFrames of image of imageType andmaxNrFrames of strings of size maxStrSize is reserved.
The loggerType parameter can be LinearImageLogger or CircularImageLogger. When the log of LinearImageLogger isfull new added images and strings are ignored. When the log of a CircularImageLogger is full the oldest image and string are deleted and the new image an string are added.
The disgard parameter specifies how many ImageLoggerAdd commands are ignored before an image and string are storedin RAM memory.

The CloseImageLogger operator releases all allocated memory.

The ImageLoggerAdd operator adds an image and string to the log. The parameter loggerMode can have the values DisgardNImageLogger or ForceImageLogger. In DisgardNImageLogger mode disgard images are ignored before an imageis stored in the log. In ForceImageLogger mode the image and string is always stored.

The ImageLoggerClear operator clears all logged images and strings.

The ImageLoggerSaveToFile operator save all image to file. The parameter fileNameBase is used to generate uniquefile names. The Nth image is saved as fileNameBase_N.jl. The strings are saved in a file with name fileNameBase.txt.The format of fileNameBase.txt is one line for each image: <fileName> <string>.

The ImageLoggerGetNth operator retrieves the nth image in the log and makes a copy into image with imageName.The function result is the string associated string with the Nth image.


Back to Contents

Identify Barcode

IdentifyBarCode image barcodeType nrChars lineDistance scanDir check

Class: IntImage, see
IntImage.

Menu: Operator | Analyse

This operator identifies a barcode in a binary image. The barcode lines must be approximatly vertical.

NOTE: in order to perform properly, the smallest bar must be at least 3 pixels wide.

Parameters:

BarcodeTypes: Bookland CODE_39 CODE_128 EAN_8 EAN_13 Industrial_2of5 Interleaved_2of5 Standard_2of5 UPC_A UPC_E USD_3
nrChars: number of characters in barcode, only used for variable length barcodes
lineDistance: distance between the scanlines. Value = 1 for most accurate results, values > 1 give higher speed
scanDir: NormalScanDir, ReversedScanDir or BothScanDirs
check: Check or NoCheck. Whether or not result is checked, like for checksum if applicable.


Back to Contents

Class Image Set (CIS)

A CIS is used in training or evaluation of classifiers.

Menu: File | Create CIS, for creating interactively a CIS
Menu: File | Open, for opening an existing CIS (file extenstion *.CIS)
Menu: Operator | Class image set for script commands

A CIS is a collection of images with their associated classes.The imagetype and size are defined when the CIS is created.If both height and width are set to 0 (zero), size checking is suppressed.The info field gives a text description of the CIS. This info field is defined whenthe CIS is created and the text should be between quotes<"> and <"> if the text field contains spaces.

A CIS has a class table and for each class an image table.Each image in an image table has its unique image index number.The Min Max Pixel value box gives the minimum and maximum pixel value of all pixelsof all images in the CIS.

With the Add class button a new empty class can be added to the class table. The system will generate an unique id for this class.
With the Remove class the current selected class table and its image table can be removedfrom the CIS.

An image, which has been selected as 2nd image, can be added to image table of a class by selecting a class in the class and pressing the Add image button.
With the Remove image button the current selected image in the CIS can be removed from the selected image table.
With the Extract image button a copy can be maked of the current selected image in the CIS.

Scripts commands for CIS:


- CIS_AddClass <cisName> <className>
Add class to cis.
Function result is string with classId.

- CIS_AddImage <cisName> <imageName> <className>
Add image to cis.
Function result is string with imageId.

- CIS_ClassId <cisName> <className>
Function result is string with classId.

- CIS_ClassName <cisName> <classId>

Function result is string with class name.

- CIS_Create <cisName> <imageType> <info> <height> <width>
Create an cis for specified image type with images of height x width.

- CIS_Delete <cisName>
Delete specified cis.

- CIS_GetClassTab <cisName>
Function result is string with class table.

- CIS_GetInfo <cisName>
Function result is string with info field.

- CIS_GetImage <cisName> <imageName> <className> <imageIndex>
Specified image in cis is copied to image with image name.

- CIS_GetImageHeight <cisName>
Function result is string with height of images in cis.

- CIS_GetImageWidth <cisName>
Function result is string with width of images in cis.

- CIS_GetMaxPixel <cisName>
Function result is string with max pixel value of all images in cis.

- CIS_GetMinPixel <cisName>

Function result is string with min pixel value of all images in cis.

- CIS_MaxClassId <cisName>
FUnction result is a string the largest classId in cis.

- CIS_NrOfImages <cisName> <className>
FUnction result is a string the nr of images in cis.

- CIS_ReadFromFile <cisName> <filename>
Read cis from file.

- CIS_RemoveClass <cisName> <className>
Remove class from cis.

- CIS_RemoveImage <cisName> <className> <imageIndex>
Remove specified image from cis.

- CIS_Rename <old cisName> <new cisName>
Rename cis from old name to new name.

- CIS_WriteToFile <cisName> <filename>
Write cis to file.


Back to Contents

Class Feature Set (CFS)

A CFS is used in training or evaluation of classifiers.

Menu: File | Create CFS, for creating interactively a CIFS
Menu: File | Open, for opening an existing CFS (file extenstion *.CFS)
Menu: Operator | Class feature set for script commands

A CFS is a collection of images with their associated classes.

A CFS has a class table and for each class an image table.Each image in an image table has its unique image index number.The Min Max Pixel value box gives the minimum and maximum pixel value of all pixelsof all images in the CFS.

With the Add class button a new empty class can be added to the class table. The system will generate an unique id for this class.
With the Remove class the current selected class table and its image table can be removedfrom the CFS.

An image, which has been selected as 2nd image, can be added to image table of a class by selecting a class in the class and pressing the Add image button.
With the Remove image button the current selected image in the CFS can be removed from the selected image table.
With the Extract image button a copy can be maked of the current selected image in the CFS.

Scripts commands for CFS:


- CFS_AddClass <cfsName> <className>
Add class to cfs.
Function result is string with classId.

- CFS_AddFeature <cfsName> <featureName>
Add feature to cfs.
Function result is string with featureId.

- CFS_AddImage <cfsName> <imageName> <className>
Add image with imageName to cfs for class className.

- CFS_CalcFeatures <cfsName> <internalScriptName>
Execute internal script with internalScriptName to calculate all features for all images in cfs.

- CFS_ClassId <cfsName> <className>
Function result is string with classId for class with className in cfs.

- CFS_ClassName <cfsName> <classId>
Function result is string with class name for classId in cfs.

- CFS_Create <cfsName> <imageType> <info>
Create a cfs for specified image type and add text in info parameter to info field of cfs.

- CFS_Delete <cfsName>
Delete specified cfs.

- CFS_GetFeatureNameTab <cfsName>
Function result is string with all feature names.

- CFS_GetInfo <cfsName>
Function result is info field of cfs.

- CFS_GetImage <cfsName> <imageName> <className> <imageIndex>
Specified image in cfs is copied to image with image name.

- CFS_GetMinMaxTab <cfsName>
Function result is string with MinMaxTable of cfs.

- CFS_GetNrFeatures <cfsName>
Function result is string with nr of features in cfs.

- CFS_GetNrSelectedFeatures <cfsName>
Function result is string with nr of selected features of cfs.

- CFS_GetFeaturesImage <cfsName> <className> <imageIndex>
Function result is string with all features of selected image in cfs.

- CFS_GetScriptName <cfsName>
Function result is string with internal script name of cfs used to calculated the features.

- CFS_GetSelectedFeaturesImage <cfsName> <className> <imageIndex>
Function result is string with the selected features of selected image in cfs.

- CFS_GetSelectTab <cfsName>
Function result is a string with represents the selected feautures.
The string consists of '0' and '1' seperated by spaces.
'0' means feature not selected, '1' means feature is selected.
The '0' and '1' are in the order of increasing classId.

- CFS_GetClassTab <cfsName>
Function result is a string with the class table.

- CFS_MaxClassId <cfsName>
FUnction result is a string the largest classId in cfs.

- CFS_NrOfImages <cfsName> <className>
Function result is a string with the number of images of className in cfs.

- CFS_ReadFromFile <cfsName> <filename>
Read cfs from file.

- CFS_RemoveClass <cfsName> <className>
Remove class className from cfs, all images for className are deleted from cfs.

- CFS_RemoveFeature <cfsName> <featureName>
Remove feature with featureName from cfs.

- CFS_RemoveImage <cfsName> <className> <imageIndex>
Remove specified image from cfs.

- CFS_Rename <old cfsName> <new cfsName>
Rename cfs from old name to new name.

- CFS_SelectFeature <cfsName> <featureName> <0|1>
Include ('1') or remove ('0') specified feature to selected set of features of cfs.

- CFS_SetMinMaxTab <cfsName> <minmaxinputtab>
Set minMaxTab of cfs.

- CFS_SetFeaturesImage <cfsName> <className> <imageIndex> <features>
Set features of specified image in cfs.

- CFS_SetScriptName <cfsName> <scriptname>
Set name of internal script used to calculate the features for all images in cfs.

- CFS_SetSelectTab <cfsName> <selected>
Set selected features of cfs.
The selected string consists of '0' and '1' seperated by spaces.
'0' means feature not selected, '1' means feature is selected.
The '0' and '1' are in the order of increasing classId.

- CFS_WriteToFile <cfsName> <filename>
Write cfs to file.


Back to Contents

BackPropagation Network (BPN)

BPN can be used to train a system in order to classify object. A BPN must first be trained using examplesbefore it can be used.

Scripts commands for BPN:


- BPN_Classify <bpnName> <inputs>
Classify with specified inputs, function result is string with classId and confidenceseperated with a space.
bpnName: name of bpn variable.
inputs: string with all inputs separated by space.

- BPN_ClassifyFeatures <bpnName> <image> <iscript>
Classify image with feature classifier.
Features are calculated with internal script, %p1 is image.
Function result is string with classId and confidence seperated with a space.
bpnName: name of bpn variable.
image: name of image to classify
iscript: name of internal script.

- BPN_ClassifySelectedFeatures <bpnName> <image> <iscript> <selected>
Classify image with feature classifier.
Features are calculated with internal script, %p1 is image.
Function result is string with classId and confidence seperated with a space.
bpnName: name of bpn variable.
image: name of image to classify
iscript: name of internal script
selected: selection of features with “01” string.

- BPN_ClassifyFeaturesOutputTab <bpnName> <image> <iscript> <&$array>
Classify image with feature classifier.
Features are calculated with internal script, %p1 is image.
Function result is the confidence.
bpnName: name of bpn variable.
image: name of image to classify
iscript: name of internal script.
&$array: an array with tupples (<classId>,<output>) sorted on highest output values

- BPN_ClassifySelectedFeaturesOutputTab <bpnName> <image> <iscript> <selected> <&$array>
Classify image with feature classifier.
Features are calculated with internal script, %p1 is image.
Function result is the confidence.
bpnName: name of bpn variable.
image: name of image to classify
iscript: name of internal script.
selected: selection of features with “01” string.
&$array: an array with tupples (<classId>,<output>) sorted on highest output values

- BPN_ClassifyImage <bpnName> <image>
Classify image with image classifier.
Function result is string with classId and confidence seperated with a space.
bpnName: name of bpn variable.
image: name of image to classify

- BPN_ClassifyImageOutputTab <bpnName> <image> <&$array>
Classify image with image classifier.
Function result is string with classId and confidence seperated with a space.
bpnName: name of bpn variable.
image: name of image to classify
&$array: an array with tupples (<classId>,<output>) sorted on highest output values

- BPN_Create <bpnName> <func> <bias> <$minMaxInputTab> <minOutput> <maxOutput> <$layerdescrtab>
Create a bpn.
bpnName: name of bpn variable.
func: activation function, values: Hyperbolic, Linear or Sigmoid.
bias: use of BiasNodes, values: Bias NoBias
minMaxInputTab: string with min and max value for all inputs, separeted by spaces
minOutPut: minimum value for output neuron
maxOutput: maximum value for output neuron
layerdescrtab: string with: nrLayers followed by nr of neurons for each layer

- BPN_CreateClassifier <bpnName> <hiddens1> <hiddens2> <nrClasses> <bias> <$minMaxInputTab>
Create a classifier.
bpnName: name of bpn variable.
hiddens1: size of hidden layer 1
hiddens2: size of hidden layer 2
nrClasses: nr of classes
bias: use of BiasNodes, values: Bias NoBias
minMaxInputTab: string with min and max value for all inputs, separeted by spaces

- BPN_CreateFeatureClassifier <bpnName> <cfsName> <nrHiddens1> <nrHiddens2> <bias>
Create a feature classifier.
bpnName: name of bpn variable.
cfsName: name of cfs variable.
hiddens1: size of hidden layer 1
hiddens2: size of hidden layer 2
bias: use of BiasNodes, values: Bias NoBias

- BPN_CreateImageClassifier <bpnName> <imageType> <nrPixels> <hiddens1> <hiddens2> <nrClasses> <bias> <$minMaxInputTab>
Create an image classifier.
bpnName: name of bpn variable.
imagetype: type of image, like ByteImage or RGB888Image.
nrPixels: nr of pixels in image
hiddens1: size of hidden layer 1
hiddens2: size of hidden layer 2
nrClasses: nr of classes.
bias: use of BiasNodes, values: Bias NoBias
minMaxInputTab: string with min and max value for all inputs, separeted by spaces

- BPN_Delete "<bpnName>
Delete a BPN.
bpnName: name of bpn variable.

- BPN_Evaluate <bpnName> <input> <target>
Evaluate BPN by producing outputs with input and comparing with target.
Function result is the mean error in the output layer.
bpnName: name of bpn variable.
input: string with all input values separated with spaces.
target: string with all expected target values separated with spaces.

- BPN_EvaluateClass <bpnName> <input> <classExp>
Evaluate feature classifier.
Function result is string with classId and confidence.
bpnName: name of bpn variable.
input: string with all input values separated with spaces.
classExp: expected classId.

- BPN_EvaluateCIS <bpnName> <cisName> <minConfidence> <NoDetails | LowDetails | HighDetails>
Evaluate a CIS.
Function result is a string with:
maxError, meanError, nr of missclassifications and nr of low confidences
If not NoDetails is specified the result string is expanded for all miss classications by:
expected classId, result, classId, confidence, imageIndex and if high details all values for all output neurons.
If not NoDetails is specified the result string is expanded for all low confidences by:
expected classId, result, classId, confidence, imageIndex and if high details all values for all output neurons.
bpnName: name of bpn variable.
cisName: name of cis variable.
minConfidence: the minimum value for the confidence wanted.
details: NoDetails, LowDetails or HighDetails.

- BPN_EvaluateImage <bpnName> <imageName> <classExp>
Evaluate an Image.
Function result is string with classId and confidence.
bpnName: name of bpn variable.
input: string with all input values separated with spaces.
classExp: expected classId.

- BPN_EvaluateImageSet <bpnName> <minConfidence> <NoDetails | LowDetails | HighDetails> <$images> <$classes>
Evaluate an image set.
Function result is a string with:
maxError, meanError, nr of missclassifications and nr of low confidences
If not NoDetails is specified the result string is expanded for all miss classications by:
expected classId, result, classId, confidence, imageIndex and if high details all values for all output neurons.
If not NoDetails is specified the result string is expanded for all low confidences by:
expected classId, result, classId, confidence, imageIndex and if high details all values for all output neurons.
bpnName: name of bpn variable.
minConfidence: the minimum value for the confidence wanted.
details: NoDetails, LowDetails or HighDetails.
images: string with all image names.
classes: string with all classIds.

- BPN_EvaluateClassSet <bpnName> <minConfidence> <NoDetails | LowDetails | HighDetails> <inputs> <classes>
Evaluate a class set.
Function result is a string with:
maxError, meanError, nr of missclassifications and nr of low confidences
If not NoDetails is specified the result string is expanded for all miss classications by:
expected classId, result, classId, confidence, imageIndex and if high details all values for all output neurons.
If not NoDetails is specified the result string is expanded for all low confidences by:
expected classId, result, classId, confidence, imageIndex and if high details all values for all output neurons.
bpnName: name of bpn variable.
minConfidence: the minimum value for the confidence wanted.
details: NoDetails, LowDetails or HighDetails.
inputs: string with setsize followed by all inputs.
classes: string with setsize followed by all classIds.

- BPN_EvaluateSet <bpnName> <$inputs> <$targets>
Evaluate a set of inputs.
Function result is string with max error and mean error.
bpnName: name of bpn variable.
inputs: string with setsize followed by all inputs.
targets: string with setsize followed by all targets.

- BPN_GetLearnError <bpnName>
Function result is learn error of specified bpn.

- BPN_GetLearnRate <bpnName>
Function result is learn rate of specified bpn.

- BPN_GetMomentum <bpnName>
Function result is momentum of specified bpn.

- BPN_GetNameLearnSet <bpnName>
Function result is name of learnset of specified bpn.

- BPN_GetSizeLayer <bpnName> <layerNr>
Function result is size of layer with layernr of specified bpn.

- BPN_Produce <bpnName> <inputs>

Function result is the values of the output layers.
bpnName: name of bpn variable.
inputs: string with the input values.

- BPN_ReadFromFile <bpnName> <filename>
Read bpn from file.
bpnName: name of bpn variable.
filename: file to read bpn from.

- BPN_Rename <old bpnName> <new bpnName>
Rename bpn with old bpnName to new bpnName.

- BPN_Reset <bpnName> <minRand> <maxRandW>
Reset all weights of bpn to random values.

- BPN_SetNameLearnSet <bpnName> <name learn set>
Set name of learn set of bpn to specified value.

- BPN_Train <bpnName> <learnRate> <momentum> <$input> <$target>
Train bpn with one example.
Function result is learn error.
bpnName: name of bpn variable.
learnRate: learn rate.
momentum: momentum.
input: string with input values
target: string with target values

- BPN_TrainSet <bpnName> <nrOfEpochs> <learnRate> <momentum> <$inputs> <$targets>
Train bpn with a set of examples.
Function result is learn error.
bpnName: name of bpn variable.
nrOfEpochs: number of times training process is repeated.
learnRate: learn rate.
momentum: momentum.
inputs: string with input values.
targets: string with target values.

- BPN_TrainClass <bpnName> <learnRate> <momentum> <$input> <class>
Train a classifier with one examples.
Function result is learn error.
bpnName: name of bpn variable.
learnRate: learn rate.
momentum: momentum.
input: string with input values.
class: string with targetId.

- BPN_TrainClassSet <bpnName> <nrOfEpochs> <learnRate> <momentum> <setsize> <$input class> <$classes>
Train classifier with a set of examples.
Function result is the max error and mean error.
bpnName: name of bpn variable.
nrOfEpochs: number of times training process is repeated.
learnRate: learn rate.
momentum: momentum.
setsize: nr of examples.
inputs: string with input values.
classes: string with classIds.

- BPN_TrainImage <bpnName> <learnRate> <momentum> <image> <class>
Train a classifier with one image.
Function result is learn error.
bpnName: name of bpn variable.
learnRate: learn rate.
momentum: momentum.
image: string with name of image.
class: string with targetId.

- BPN_TrainImageSet <bpnName> <nrOfEpochs> <learnRate> <momentum> <setsize> <$images> <$classes>
Train a classifier with set of images.
Function result is the max error and mean error.
bpnName: name of bpn variable.
nrOfEpochs: number of times training process is repeated.
learnRate: learn rate.
momentum: momentum.
setsize: nr of examples.
images: string with name of images.
classes: string with targetIds.

- BPN_TrainCIS <bpnName> <cisName> <nrOfEpochs> <learnRate> <momentum>
Train a classifier with set of images.
Function result is the max error and mean error.
bpnName: name of bpn variable.
cisName: name of the cis variable.
nrOfEpochs: number of times training process is repeated.
learnRate: learn rate.
momentum: momentum.

- BPN_WriteToFile <bpnName> <filename>
Write bpn to file.
bpnName: name of bpn variable.
filename: name of file to write bpn.

- BPN_CreateImageOptimizer <popSize> <nrEpochs> <lowConf> <trainCIS> <evalCIS> <hidden1Low> <hidden1High> <hidden2Low> <hidden2High> <learnRateLow> <learnRateHigh> <momentumLow> <momentumHigh>
Create a BPN Image Optimizer (genetic algorithm)
popSize: the population size for the GA algorithm
nrEpochs: the number of epochs the BPN is trained before being evaluated
lowConf: the low confidency factor used in the evaluation
trainCIS: the name of the CIS to be used for training
evalCIS: the name of the CIS to be used for evaluation
hidden1Low: lowest value for size first hidden layer
hidden1High: highest value for size first hidden layer
hidden2Low: lowest value for size second hidden layer
hidden2High: highest value for size second hidden layer
learnRateLow: lowest value for learn rate
learnRateHigh: highest value for learn rate
momentumLow: lowest value for momentum
momentumHigh: highest value for momentum

- BPN_ImageOptimize <nrGenerations> <minError> <deltaError> <microP>
Optimize for nrGenerations generations
Function result: <error> <hidden1> <hidden2> <learnRate> <momentum>
MinError is the minimal target error
DeltaError is the minimal error for start of hillclimbing
MicroP is the propability during self mate that parameter is a micro mutation

- BPN_DeleteImageOptimizer
BPN Image Optimizer is deleted from memory

- BPN_CreateFeatureOptimizer <popSize> <nrEpochs> <lowConf> <trainCIS> <evalCIS> <hidden1Low> <hidden1High> <hidden2Low> <hidden2High> <learnRateLow> <learnRateHigh> <momentumLow> <momentumHigh> <selectedTab>
Create a BPN Feature Optimizer (genetic algorithm)
popSize: the population size for the GA algorithm
nrEpochs: the number of epochs the BPN is trained before being evaluated
lowConf: the low confidency factor used in the evaluation
trainCIS: the name of the CIS to be used for training
evalCIS: the name of the CIS to be used for evaluation
hidden1Low: lowest value for size first hidden layer
hidden1High: highest value for size first hidden layer
hidden2Low: lowest value for size second hidden layer
hidden2High: highest value for size second hidden layer
learnRateLow: lowest value for learn rate
learnRateHigh: highest value for learn rate
momentumLow: lowest value for momentum
momentumHigh: highest value for momentum
selectedTab: selection of features with “01” string.

- BPN_FeatureOptimize <nrGenerations> <minError> <deltaError> <microP>
Optimize for nrGenerations generations
Function result: <error> <hidden1> <hidden2> <learnRate> <momentum>
MinError is the minimal target error
DeltaError is the minimal error for start of hillclimbing
MicroP is the propability during self mate that parameter is a micro mutation

- BPN_DeleteFeatureOptimizer
BPN Feature Optimizer is deleted from memory



Back to Contents

BPN image and feature classifier

BPN classifier can be used to train a system in order to classify images. A BPN classifier must first be trained using examples before it can be used.

Menu: File | Create BPN, for creating interactively a BPN
Menu: File | Open, for opening an existing BPN (file extenstion *.BPN)
Menu: Operator | Classifier for script commands

A BPN classifier can be trained with either a Class Image Set (CIS) of Class Feature Set (CFS).
When a BPN image classifier is created a CIS of CFS file must be specified.

From this CIS the followingparameters of the BPN are extracted:
- type of images
- size of the input layer of the BPN (= number of pixels in image)
- size of the output layer of the BPN (= number of classes)
These parameters can not be changed after creating the BPN.

From this CFS the followingparameters of the BPN are extracted:
- size of the input layer of the BPN (= number of features)
- size of the output layer of the BPN (= number of classes)
These parameters can not be changed after creating the BPN.

The sizes of the two hidden layers and the use of biasnodes can be changed during the training fase, but the BPN must be resized after a change before training from scratch can start.


Training the network.

Both an CIS (or CFS) for training and evaluation can be specified. Default is that the evaluation CIS (or CFS) is the same as thetraining CIS (or CFS).

The learnrate is a small positive value and determines how fast the BPN will learn. If the learnrate is to lowlearning will be very slow. If the learnrate is too high the training error will oscillate and and stay at an highvalue.

The momentum is zero or a small positive value. This parameter influences the speed of convergence of the learing process and specifies which fraction of the "learn effect" of the previous training sample should beadded to the "learn effect" of the next training sample.

Max nr epochs specifies the maximum number of epochs for the training. The training is aborted when this number of epochs is reached.Training is also stopped if the mean error of the training process is smaller than the stop error.

The number of evaluation epochs specify after how many epochs the results of the training process are updatedon this form.

In the Training results box is information displayed about the number of the current epoch and ist mean and maximum error of the learining process.

In the Evaluation results box is information displayed which give an indication on how good the BPN performs on the evaluation CIS or CFS. The Miss classification box displays how many images are not correct classified. The Lowconfidences box displays how many correct classified image have a lower confidency then is specified as the minimum confidence in the Low confidency field in the Evaluation parameters box. Details of the not correctclassified images and the image with low confidence can be found on the Evaluation details page.

In the History box information can be found on the traces of the meanerror during the training process.With the Max error field and the update button the Y-axis can be scaled.

The training process can be started and stopped with the Start and the Stop button. The Reset button resetsthe complete training process and all what has been learned will be lost.


Analysing the Evaluation details.

Details of the not correct classified images and the images being classified with low confidence can be analyed on this page.In the table there is for each image one row. - expected: the name of the expected class.
- result: class according to the classifier
- confidency: indication how confident the classifier is about the result
1 = very confident, 0 = very unconfidident
- image index: index of the image in the image table for class expected in the evaluation CIS With the combobox at the bottom left the level of details can be changed from low to high. In the high detailmode the classification strength (output value) for each class of the images is displayed. This classification strength is a value in the range [-1..1]. A value around 1 indicates that the classifiers thinks thatthe image is of that class. A around -1 indicates that the image is not of that class.

With the Extract button the image selected in the table can be copied to an image on the desktop of VisionLabwith a name as specified in the textbox next to the button.


Classify an unknown image.

With the Classify button the image which is selected as 2nd image is classified.

A table with class name, class id and output value of the BPN is displayed. The table is sorted on output value, so best match first.

For a feature classifier a script must be selected for calculating the features.


GA Optimize.

This function is used to find automatically the best setting for the neural netwerk like: size of hidden layers,learn rate, momentum and which features to use (only for feature classifier).

This function uses a Genetical Algorithm (GA) in order to find the best solution.

NOTE: this optimizing process is very time consuming and for real problems it may take hours or even days.

In the Low/High box the user must specify the search space for size of hidden layers,learn rate and momentum, by specifying the lowest and highest border values.

In the settings box must be specified:
- the population size for the GA algorithm
- the number of epochs the BPN is trained before being evaluated
- the low confidency factor used in the evaluation
- the maximum number of generation for the GA algorithm

In the detailed setting box, specialized setting can be set, it is adviced to use the standard values.
- the MinError is the minimal target error
- the DeltaError is the minimal error for start of hillclimbing
- the MicroP is the probability during self mate that parameter is a micro mutation

For feature classifiers the features to select from box can be used to select the features that take part in the optimizing process.

With the Start button the optimizing process is started. With the Stop button the optimizing process is stopped, but first the current generation is optimized completely, note this can take some time!

In the best result box the best values found sofar for hidden layers,learn rate and momentum are displayed. Also the current generation number and the best error value found.

For feature classifiers the best features box shows the best combination of features found.

With the Accept button the best solution found is used to initialse the settings in the Parameters and Training tab. Then the normal full training is started.



Back to Contents

ExtractChannels

Extract1HSVChannel src channel plane imagetype

Extract1RGBChannel src channel plane imagetype

Extract1YUVChannel src channel plane imagetype

ExtractHSVChannels src hue saturation value imagetype

ExtractRGBChannels src red green blue imagetype

ExtractYUVChannels src y u v imagetype

Class: ColorImage, see
ColorImage.

Menu: Operator | Color

The Extract1XXXchannel operator take a color image of type YUV888Image or HSV888Image or RGB888Image or YUV161616Image or HSV161616Image or RGB161616Image and producean image of type imagetype for the specified channel in the color image.

Parameter imagetype specifies the type of the result images, possible values are:ByteImage, Int8Image, Int16Images, Int32Image, FloatImage and DoubleImage.

Note: the names of the operators in C++ library are Extract1Channel and Extract3Channels.

Back to Contents

MergeChannels

MergesHSVChannels hue saturation value dest HSVxxxImage

MergeRGBChannels red green blue dest RGBxxxImage

MergeYUVChannels y u v dest YUVxxxImage

Merges1HSVChannel colImage chanImage channel

Merge1RGBChannel colImage chanImage channel

Merge1YUVChannel colImage chanImage channel

Class: ColorImage, see
ColorImage.

Menu: Operator | Color

The first three operators take three images of the same OrdinalImage type and size and produce a HSV888Image, HSV161616Image, RGB888Image, RGB161616Image, YUV888Image or YUV161616Image.

Note: name of the operators in C++ library is Merge3Channels.

The second three operators take a color image and a channel image and insert channel image in specified channelof color image.

Note: name of the operators in C++ library is Merge1Channel.

Back to Contents

NormalizeHue

NormalizeHue srcImage destImage imageType hue minValue minSaturation notNormalisedValue
Class: ColorImage, see
ColorImage.

Menu: Operator | Color

This operator has as source image a HSVxxxImage and produces a destination RealImage of the specified imageType.
For all pixels with a value >= minValue and saturation >= minSaturation the normalised distance of the hue of the pixel to the reference hue is calculated. All other pixel get the value notNormalisedValue.

Back to Contents

NormalizeRGB

NormalizeRGB RGBxxxImage
Class: ColorImage, see
ColorImage.

Menu: Operator | Color

This operator normalises a RGBxxxImage by calculating for each pixel the relative amount of red, green and bluecompared with the whole image. The relative amount is contrast stretched.

Back to Contents

ThresholdChannels


ThresholdHSVChannels src dest imagetype hue_low hue_high saturation_low saturation_highvalue_low value_high

ThresholdRGBChannels src dest imagetype red_low red_high green_low green_highblue_low blue_high

ThresholdYUVChannels src dest imagetype y_low y_high uv_low v_high

Class: ColorImage, see
ColorImage.

Menu: Operator | Color

These operators take a color image of type HSV888Image or RGB888Image and producea binary image of type imagetype. The destination image is created by thresholding thethree color channels and ANDing the results.

Parameter imagetype specifies the type of the result images, possible values are:ByteImage, Int8Image, Int16Images, Int32Image, FloatImage and DoubleImage.

Note: name of both operators in C++ library is Threshold3Channels.

Back to Contents

Conjugate

Conjugate imageName

Class: ComplexImage, see
ComplexImage.

Menu: Operator | Complex

This operator calculates for each pixel its conjugate.

Back to Contents

Convert complex

ConvertComplex srcImage destImage newType conversion

Class: ComplexImage, see
ComplexImage.

Menu: Operator | Complex

The convertcomplex operator initialises a destination image by converting thecomplex source image to the specified NumImage

The conversion parameter specifies how the complex pixel will be converted tothe destination pixel:
- Real: destination pixel will get the real part of the complex pixel.
- Imaginary: destination pixel will get the imaginary part of the complex pixel.
- Magnitude: destination pixel will get the magnitude of the complex pixel.
- Phase: destination pixel will get the phase of the complex pixel.
- Power: destination pixel will get the power of the complex pixel.

Back to Contents

FindEdgeCircle

FindEdgeCircle image middlePoint nrSamples minR maxR outlierDistance nrIterations

Class: OrdImage, see
OrdImage.

Menu: Operator | Analyse

This operator finds with subpixel precision a circle with the largest edges within the specified disk shape specified by middlePoint, minR and maxR. In the specified disk shapenrSamples scan lines tested starting from a distance minR from the middlepoint and ending at a distance maxR from the middlepoint. The scan lines will beequally divided in the space bounded by middlePoint, minR and maxR.

Note: the number of probe lines will be nrSamples rounded up to the next multiple of 4.
maxR must be > minR + 5.

If outLayerDistance is greater then zero then the regression algorithm is repeated for nrIterations.In each next iterations only pixel with a distance smaller then outlierDistance tothe previous found line are used in the calculation of the next line.
The function result is the center coordinate, the radius and the number of pixels found on the circle.

Back to Contents

FindEdgeLine

FindEdgeLine image middlePoint endLine endBox lineDistance outlierDistance nrIterations

Class: OrdImage, see
OrdImage.

Menu: Operator | Analyse

This operator finds with subpixel precision a line with the largest edges within the specified rectangle by middlePoint, endLine and endBox. In the specified rectangleprobe lines will be tested at the specified lineDistance. The rectangle should have a width of at least 5 pixels.

If outLayerDistance is greater then zero then the regression algorithm is repeated for nrIterations.In each next iterations only pixel with a distance smaller then outlierDistance tothe previous found line are used in the calculation of the next line.

The function result is the start and the end coordinate of the line found and the number of pixels found on the line.

Back to Contents

Find First Edges

FindFirstEdges sourceImage destinationImage threshold viewpoint

Class: ordImage, see
OrdImage.

Menu: Operator | Edge detection

This operator initializes a new image with a width or height of one pixel. The destinationImage is filled with the distance from the viewpoint to the first edge higher than threshold. Each row in the destinationImage is the distance in the same row of the sourceImage. Each column in the destinationImage is the distance in the same column of the sourceImage. This operator uses a sobel edges detection.
If viewpoint = Left or viewpoint = Right then the destinationImage has a width of one pixel and a height equal to the height of sourceImage.
If viewpoint = Top or viewpoint = Bottom then the destinationImage has a height of one pixel and a width equal to the width of sourceImage.

Back to Contents

Find SubEdge(s) on Line

FindSubEdgeOnLine image startCoord endCoord
FindSubEdgesOnLine image startCoord endCoord minEdge &$edgeTab

Class: ordImage, see
OrdImage.

Menu: Operator | Edge detection

FindSubEdgeOnLine

This operator finds with subpixel precision the largest edge on the specified line.

The function result is true if an edge is found, otherwise false (all pixels same value on line).

FindSubEdgesOnLine

This operator finds with subpixel precision the all edges with an edge (difference between the 2 neighbours of a pixel)larger then minEdge on the specified line.

The function result is the number of edges found.

Back to Contents

Frei Chen

FreiChen srcImage magnitudeImage dirImage gradient dirscale minedge
gradient

Class: OrdImage, see OrdImage.

Menu: Operator | Edge detection

This operator is a gradient differential edge detection algorithm. It uses the next two masks

m1: -1 -sqrt(2) -1 m2: -1 0 1
0 0 0 -sqrt(2) 0 sqrt(2)
1 sqrt(2) 1 -1 0 1

The magnitude = sqrt((m1*m1) + (m2*m2)). Note sqrt(2) is approximated by usinginteger values where 1 is scaled to 100.

The direction = arctan(m1/m2).

Note: beware of overflow conditions. The result of the magnitude calculation easilyof a common ByteImage will result in overflow. For most applications a conversion to at least Int16Images is recommended.

Back to Contents

Kirsch

Kirsch srcImage magnitudeImage dirImage gradient dirscale gradient

Class: OrdImage, see OrdImage.

Menu: Operator | Edge detection

This operator is a template matching edge detection algorithm. It uses eight masks which are a rotation of a multiple of pi/4 radians of the mask:

-3 -3 5
-3 0 5
-3 -3 5

The magnitude = maximum value of the masks.
The direction = direction of mask with the maximum value.

Note: beware of overflow conditions. The result of the magnitude calculation easilyof a common ByteImage will result in overflow. For most applications a conversion to at least Int16Images is recommended.

Back to Contents

Prewitt

Prewitt srcImage magnitudeImage dirImage gradient dirscale minedge gradient

Class: OrdImage, see OrdImage.

Menu: Operator | Edge detection

This operator is a gradient differential edge detection algorithm. It uses the next two masks

m1: -1 -1 -1 m2: -1 0 1
0 0 0 -1 0 1
1 1 1 -1 0 1

The magnitude = sqrt((m1*m1) + (m2*m2)).
The direction = arctan(m1/m2).

Note: beware of overflow conditions. The result of the magnitude calculation easilyof a common ByteImage will result in overflow. For most applications a conversion to at least Int16Images is recommended.

Back to Contents

Roberts

Roberts srcImage magnitudeImage gradientImage gradient gradientscale minedge Edge detection parameters

Class: OrdImage, see OrdImage.

Menu: Operator | Edge detection

This operator is a gradient differential edge detection algorithm. It uses the next two masks

m1: -1 0 m2: 0 -1
0 -1 1 0

The magnitude = sqrt((m1*m1) + (m2*m2)).
The direction = arctan(m1/m2) - pi/4.

Notes:
- All edges are shifted by one-half of a pixel in x and y direction.
- The two diagonal directions are rotated by pi/4.
- Interpretation of the result of the direction is questionable.

Note: beware of overflow conditions. The result of the magnitude calculation easilyof a common ByteImage will result in overflow. For most applications a conversion to at least Int16Images is recommended.

Back to Contents

Robinson

Robinson srcImage magnitudeImage dirImage gradient dirscale gradient

Class: OrdImage, see OrdImage.

Menu: Operator | Edge detection

This operator is a template matching edge detection algorithm. It uses eight masks which are a rotation of a multiple of pi/4 radians of the mask:

-1 0 1
-2 0 2
-1 0 1

The magnitude = maximum value of the masks.
The direction = direction of mask with the maximum value.

Note: beware of overflow conditions. The result of the magnitude calculation easilyof a common ByteImage will result in overflow. For most applications a conversion to at least Int16Images is recommended.

Back to Contents

Scharr

Scharr srcImage magnitudeImage gradientImage gradient gradientscale minedge gradient

Class: OrdImage, see OrdImage.

Menu: Operator | Edge detection

This operator is a gradient differential edge detection algorithm. It uses the next two masks

m1: -3 -10 -3 m2: -3 0 3
0 0 0 -10 0 10
3 10 3 -3 0 3

The magnitude = sqrt((m1*m1) + (m2*m2)).
The direction = arctan(m1/m2).

Note: beware of overflow conditions. The result of the magnitude calculation easilyof a common ByteImage will result in overflow. For most applications a conversion to at least Int16Images is recommended.

Back to Contents

Sobel

Sobel srcImage magnitudeImage dirImage gradient dirscale minedge gradient

Class: OrdImage, see OrdImage.

Menu: Operator | Edge detection

This operator is a gradient differential edge detection algorithm. It uses the next two masks

m1: -1 -2 -1 m2: -1 0 1
0 0 0 -2 0 2
1 2 1 -1 0 1

The magnitude = sqrt((m1*m1) + (m2*m2)).
The direction = arctan(m1/m2).

Note: beware of overflow conditions. The result of the magnitude calculation easilyof a common ByteImage will result in overflow. For most applications a conversion to at least Int16Images is recommended.

Back to Contents

Canny

Canny srcImage destImage sigma low high connected
Class: IntImage, see
IntImage.

Menu: Operator | Edge detection

This operator calculates a binary image with the positions of the edges.The algortithm used is a variant of the Canny algorthm. Note: The feature synthesis phase is not included in this implementation.
This implementation use a Gaussian smoothing filter with a standard deviation sigma. If sigma is zero no smoothing is performed.

This implementation uses a Sobel edgedetection where the maxima of the edges magnitudesare searched for. Then the edges are linked. All pixels with a edge greater than high are selected as object pixels. These object pixels are used as seeds. All connected neighbours of the seeds with a edge greater than low are added to the objectpixels. This growing process is repeated until no pixels are added.

Note: beware of overflow conditions. For most applications a conversion to at least Int16Images is recommended.


Back to Contents

Marr-Hildreth

MarrHildreth srcImage destImage sigmaG sigmaLoG minedge
Class: OrdImage, see
OrdImage.

Menu: Operator | Edge detection

This operator calculates a binary image with the positions of the edges.The algortithm used is a variant of the Marr-Hildreth algorthm.
Algorithm: First the Gaussian smoothing is performed. Then the ZeroCrossings of the 2nd derivative are multiplied with the high edges of the first derivative. The Sobel operator is used for the first derivative.

This implementation use a Gaussian smoothing filter with a standard deviation sigmaG. If sigmaG is zero no smoothing is performed. Typical values are [0 .. 3].

The parameter sigmaLoG specifies standard deviation for the LoG operator whichcalculates the 2nd derivative. Typical values are [2/3 .. 3]

The parameter minedge specifies the minimal level for the first derivative.

Notes:
- Beware of overflow conditions. For most applications a conversion to at least Int16Images is recommended.
- Extra smooting will result in lower edge values, so minEdge must have a lower value.



Back to Contents

Convolution

Convolution srcImage destImage edge divisionfactor height width orgX orgY maskValues

Class: NumImage, see
NumImage.

Menu: Operator | Filter

The convolution operator initialises a destination image by sliding a mask across a source image. The pixel values under the mask are multiplied by the corresponding maskvalue. All products are summed and where after the sum is divided by the divisionfactor. This new value is assigned to the destination image at the position of the centre (= origin) of the mask.

For the edge parameter see edge

Back to Contents

ConvolutionFFT

ConvolutionFFT image mask

Class: OrdImage, see
OrdImage.

Menu: Operator | Filter

This is an implementation of the convolution algorithm using the Fast Fourier Transform.Mask and image should be of same size and height and with of image should bea power of two.

NOTE: the name of the corresponding C++ operator is the overloaded name Convolution.


Back to Contents

Correlation


Correlation image mask

Class: OrdImage, see
OrdImage.

Menu: Operator | Filter

This is an implementation of the correlation algorithm using the Fast Fourier Transform.Mask and image should be of same size and height and with of image should bea power of two.

NOTE: due to the large results of the operation at least an Int16Image is adviced to be used.


Back to Contents

DeConvolution


DeConvolution image psf k

Class: OrdImage, see
OrdImage.

Menu: Operator | Filter

This is an implementation of the Wiener filter.Mask and image should be of same size and height and with of image should bea power of two.


Back to Contents

DoGFilter

DOGFilter image sigmaLow sigmaHigh size

Class: OrdImage, see
OrdImage.

Menu: Operator | Filter

This is an implementation of the difference of Gaussians filter.

Parameters sigmaLow and sigmaHigh are the standard deviations for the DoG operator. Typical values are [0 .. 3].

Size is the size of the neighbourhoud of the operation. If size is 0 the algorithm calculates a size so that pixel at 3*sigmaHigh are neglected.

Back to Contents

GaussianFilter


GaussianFilter image sigma size

Class: OrdImage, see
OrdImage.

Menu: Operator | Filter

This is an implementation of a Gaussian smoothing filter.

Parameter sigma is the standard deviation. Typical values are [2/3 .. 3].

Size is the size of the neighbourhoud of the operation. If size is 0 the algorithm calculates a size so that pixel at 3*sigma are neglected.


Back to Contents

LoGFilter


LOGFilter image sigma size

Class: OrdImage, see
OrdImage.

Menu: Operator | Filter

This is an implementation of a Laplacian of Gaussian filter, a generalisation of the Mexican hat filter.

Parameter sigma is the standard deviation for the LoG operator. Typical values are [2/3 .. 3].

Size is the size of the neighbourhoud of the operation. If size is 0 the algorithm calculates a size so that pixels at 3*sigma are neglected.


Back to Contents

InterpolateAtSpecificPixel


InterpolateAtSpecificPixel srcImage destImage pixelValue

Class: OrdImage, see
OrdImage.

Menu: Operator | Filter

This operator assigns to all pixels with value pixelValue the average value of its neighbours with a value different from pixelValue.


Back to Contents

Genetic Algorithm


Menu: Operator | Genetic Algorithm

These operators can be used to find the a good solution for optimisation problems for whicha fitness function (error function) can be defined. This implementation uses a combination of genetic algorithms and "inverted hill climbing" to descend to the bottom of the local minima.

ga_create <gaName> <fitnessName><popSize> <paramTab> <trace> <traceFileName>
Create an instance of a Genetic Algorithm
gaName: name of variable
fitnessName: name of internal script.
%p1 is cutoff error.
%p2 is the name of an array variable without the '$'containing the parameters to optimise.
$%p2[0] is the first parameter, $%p2[1] is the second parameter, etc.
popSize: the population size
trace: = 0 then no tracing, > 0 = number of best in population to trace
traceFileName: filename to which trace log is written
paramTab: array with the description of the parameters:
- low: the lowest possible value for the parameter
- high: the highest possible value for the parameter
- delta: step size used in finding the bottom in local minimum
- micro: step size used by selfmating
- mutationP: probablity for mutation when mating, range [0..1]
- deltaP: determines how much time will be used be used for "inverted hill climbing", range [0..1]

ga_createall <gaName> <fitnessName> <popSize> <paramTab> <trace ><traceFileName>
Create an instance of a Genetic Algorithm for with the fittness function will be called one time for each generation.
gaName: name of variable
fitnessName: name of internal script.
%p1 is cutoff error.
%p2 is the name of an array variable without the '$'containing the parameters for each being to optimise. $%p2[0] contains the parameters for the first beging, $%p2[1] for the second being etc.The fittnes script will have to insert the error for each being in front of theparameters for the being.
popSize: the population size
trace: = 0 then no tracing, > 0 = number of best in population to trace
traceFileName: filename to which trace log is written
paramTab: array with the description of the parameters:
- low: the lowest possible value for the parameter
- high: the highest possible value for the parameter
- delta: step size used in finding the bottom in local minimum
- micro: step size used by selfmating
- mutationP: probablity for mutation when mating, range [0..1]
- deltaP: determines how much time will be used be used for "inverted hill climbing", range [0..1]

ga_delete <gaName>
Delete an instance of a Genetic Algorithm
gaName: name of variable

ga_randominitialize <gaName> <populationSize>
Random intialise the population
gaName: name of variable
populationSize: the population size

ga_setfounder <gaName> <populationSize> <founder>
Initialise the population with offspring from a parent
gaName: name of variable
populationSize: the population size
founder: the parameters of the founder

ga_setfounders <gaName> <&$parents>
gaName: name of variable
&$parents: an array with the parents, one line for each parent

ga_optimize <gaName> <maxGenerations><minError><deltaError><microP>
Use the genetic algorithm to find a best solution. The function result is the fitness error of the best solution.
gaName: name of variable
maxGenerations: maximum number of generations
minError: if fitness error < minError the optimization is stopped
deltaError: minimum error for start of inverted hillclimbing
microP: probability that self mate is a micro mutation

ga_getsolution <gaName>
Function result is the best solution found
gaName: name of variable

ga_getpopulation <gaName> <&$population>
Retreive the current population
gaName: name of variable
&$population: array to store the population, one line for each parent


Example: Determine the parameters for a polynome.


ga_func.jls
// y = a * x**2 + b * x + c
return %p1 * %p4 * %p4 + %p2 * %p4 + %p3

ga_fitness.jls:
$total = 0
$max = GetSizeArray &$xTab
$max = $max - 1
for $i = 0 to $max do
$y_ga = icall ga_func %p2 %p3 %p4 $xTab[$i]
$e = $yTab[$i] - $y_ga
$e = Fabs $e
$total = $total + $e
if $total > %p1 then
return $total
endif
endfor
return $total

ga_example.jls:
lAddScript ga_func ga_func.jls
lAddScript ga_fitness ga_fitness.jls
$trainSet = 10
InitRandomGen 1
for $i = 0 to $trainSet do
$xTab[$i] = Random -2 2
$yTab[$i] = icall ga_func 2 3 4 $xTab[$i]
endfor
// low high delta micro mutationP deltaP
$paramTab[0] = -10 10 0.1 0.001 0.1 0.5
$paramTab[1] = -10 10 0.1 0.001 0.1 0.5
$paramTab[2] = -10 10 0.1 0.001 0.1 0.5
ga_create ga ga_fitness 10 &$paramTab 0 tracefile.txt
// $founder = 2.1 3.1 4.1
//ga_setfounder ga 10 $founder
for $gen = 1 to 50 do
// maxGen minError deltaError microP
$_error = ga_optimize ga 1 0.1 1 0.5
$_sol = ga_getsolution ga
// VarToArray &$_sol &$array
// ga_getpopulation ga &$best
// ga_setfounders ga &$best
SyncVars
endfor
ga_delete ga




Back to Contents

Classical dilation

ClassicalDilation srcImage destImage nrNeighbours

Class: IntImage, see
IntImage.

Menu: Operator | Binary Morphology

The operator initialises a destination image. If a background pixel (=0) in the source image has equal or more than nrNeighbours object pixels (=1) as neighbours then the corresponding pixel of the destination image will get the value object. In all other cases the new pixels will get the value background.

Back to Contents

Classical erosion

ClassicalErosion srcImage destImage nrNeighbours

Class: IntImage, see
IntImage.

Menu: Operator | Binary Morphology

The operator initialises a destination image. If an object pixel (=1) in the source image has equal or more than nrNeighbours background pixels (=0) as neighbours then the corresponding pixel of the destination image will get the value background, otherwise it will get the value object.

Back to Contents

Dilation

Dilation srcImage destImage height width orgX orgY maskValues

Class: IntImage, see
IntImage.

Menu: Operator | Binary Morphology

At the start of the operation the destination image is filled with background (=0) pixel values. The mask is swept over the source image. Each time the centre (= origin) of the mask touches an object (=1) pixel in thesource image, the entire translated mask is ORed to the destination image.

Back to Contents

Erosion

Erosion srcImage destImage height width orgX orgY maskValues

Class: IntImage, see
IntImage.

Menu: Operator | Binary Morphology

The mask may be visualised as a probe that slides across the source image, testing the spatial nature of the image at every point x. Where the mask translated to x can be contained in the source image (by placing the centre (= origin) of the mask at x), then x belongs to the destination image.

Back to Contents

Opening

Opening srcImage destImage height width orgX orgY maskValues

Class: IntImage, see
IntImage.

Menu: Operator | Binary Morphology

The opening operator initialises a destination image as result of an erosion on the source image with the mask followed by a dilation with the same mask.

Back to Contents

Closing

Closing srcImage destImage height width orgX orgY maskValues

Class: IntImage, see
IntImage.

Menu: Operator | Binary Morphology

The closing operator initialises a destination image as result of a dilation on the source image with the mask followed by an erosion with the same mask.

Back to Contents

Hit and miss

HitAndMiss srcImage destImage hitMask missMask

Class: IntImage, see
IntImage.

Menu: Operator| Binary Morphology

The hitandmiss operator initialises a destination image. The new image has pixels set to the object value (= 1) at positions whereall objects in the hitmask are contained in the sourceimage and none of the object pixels in the missmask are containedin the source image.


Back to Contents

Thinning

Thinning srcImage destImage hitMask missMask

Class: IntImage, see
IntImage.

Menu: Operator| Binary Morphology

The thinning operator initialises a destination image. The new image is the same as the source image but object pixels which are covered by the hitmask and not covered by the missmask are excluded fromthe destination image.
In order to perform meaningful the origin of the hitmask should be included in the hitmask and the origin of the missmask should be excluded from the missmask.

Back to Contents

Thickening

Thickening srcImage destImage hitMask missMask

Class: IntImage, see
IntImage.

Menu: Operator | Binary Morphology

The thickening operator initialises destination image. The destination image is the same as the source image but at special positions pixels are added.These positions are where all objects in the hitmask are contained in the source image and none of the object pixels in the missmask are contained in the source image.In order to perform meaningful the origin of the hitmask should be excluded from the hitmask and the origin of the missmask should be included in the missmask.


Back to Contents

Kuwahara filter

KuwaharaFilter srcImage destImage radius edge

Class: OrdImage, see
OrdImage.

Menu: Operator | Filter

The Kuwahara filter is an edge preserving smooth filter.
The square window with the defined radius around the center pixel is divided in fouroverlapping regions.
Example for radius = 3:
window is 5x5 pixels
4 regions of 3x3 pixels, center pixel is in all regions

1 1 12 2 2
1 1 12 2 2 13 13 1234 23 23 3 3 34 4 4
3 3 34 4 4

The output value for the central pixel in the window is the mean value of that region that has thesmallest variance.

For the edge parameter see edge.

Back to Contents

Local Maximum filter

LocalMaxFilter srcImage destImage background edge height width orgX orgY maskValues

Class: OrdImage, see
OrdImage.

Menu: Operator | Filter

The local maximum filter operator initialises a destination image by sliding a mask across the source image. A new value is calculated for the destination image at the position of the centre (= origin) of the mask. This new value is the value of the origin if the origin value is the local maximum of the pixels under the mask otherwise the new value is set tothe background value.
If the source pixel value at the origin equals to the background value the correspondingdestination pixel is assigned the background value.

For the edge parameter see edge

Back to Contents

Local Minimum filter

LocalMinFilter srcImage destImage background edge height width orgX orgY maskValues

Class: OrdImage, see
OrdImage.

Menu: Operator | Filter

The local minimum filter operator initialises a destination image by sliding a mask across the source image. A new value is calculated for the destination image at the position of the centre (= origin) of the mask. This new value is the value of the origin if the origin value is the local minimum of the pixels under the mask otherwise the new value is set tothe background value.
If the source pixel value at the origin equals to the background value the correspondingdestination pixel is assigned the background value.

For the edge parameter see edge

Back to Contents

Maximum filter

MaximumFilter srcImage destImage edge height width orgX orgY maskValues

Class: OrdImage, see
OrdImage.

Menu: Operator | Filter

The maximumfilter operator initialises a destination image by sliding a mask across the source image. A new value is calculated for the destination image at the position of the centre (= origin) of the mask. This new value is the maximum value of the selected pixels under the mask.

For the edge parameter see edge

Also known as Grey-scale Dilation.


Back to Contents

Mean filter

MeanFilter srcImage destImage edge height width orgX orgY maskValues

Class: OrdImage, see
OrdImage.

Menu: Operator | Filter

The meanfilter operator initialises a destination image by sliding a mask across the source image. A new value is calculated for the destination image at the position of the centre (= origin) of the mask. This new value is the mean value of the selected pixels under the mask.

For the edge parameter see edge.

Back to Contents

Median filter

MedianFilter srcImage destImage edge height width orgX orgY maskValues

Class: OrdImage, see
OrdImage.

Menu: Operator | Filter

The medianfilter operator initialises a destination image by sliding a mask across the source image. A new value is calculated for the destination image at the position of the centre (= origin) of the mask. This new value is the median value of the selected pixels under the mask.

The median is the middle value in the sorted order of values.

For the edge parameter see edge.

Back to Contents

Minimum filter

MinimumFilter srcImage destImage edge height width orgX orgY maskValues

Class: OrdImage, see
OrdImage.

Menu: Operator | Filter

The minimumfilter operator initialises a destination image by sliding a mask across the source image. A new value is calculated for the destination image at the position of the centre (= origin) of the mask. This new value is the minimum value of the selected pixels under the mask.

For the edge parameter see edge.

Also known as Grey-scale Erosion.

Back to Contents

Mode filter

ModeFilter srcImage destImage edge height width orgX orgY maskValues

Class: OrdImage, see
OrdImage.

Menu: Operator | Filter

The modefilter operator initialises a destination image by sliding a mask across the source image. A new value is calculated for the destination image at the position of the centre (= origin) of the mask. This new value is the mode value of the selected pixels under the mask.

The mode is the value with the highest frequency of occurrence.

For the edge parameter see edge.

Back to Contents

Nth filter

NthFilter srcImage destImage nth edge height width orgX orgY maskValues

Class: OrdImage, see
OrdImage.

Menu: Operator | Filter

The NthFilter operator initialises a destination image by sliding a mask across the source image. A new value is calculated for the destination image at the position of the centre (= origin) of the mask. This new value is the nth value of the ascending sorted selected pixels under the mask.

For the edge parameter see edge.

Back to Contents

Range filter

RangeFilter srcImage destImage edge height width orgX orgY maskValues

Class: OrdImage, see
OrdImage.

Menu: Operator | Filter

The RangeFilter operator initialises a destination image by sliding a mask across the source image. A new value is calculated for the destination image at the position of the centre (= origin) of the mask. This new value is the difference between the maximum value and the minimum value of the selected pixels under the mask.

This operator is used to measure the texture of an image.

For the edge parameter see edge.

Back to Contents

Sigma filter

SigmaFilter srcImage destImage deviation edge height width orgX orgY maskValues

Class: OrdImage, see
OrdImage.

Menu: Operator | Filter

The SigmaFilter operator initialises a destination image by sliding a mask across the source image. A new value is calculated for the destination image at the position of the centre (= origin) of the mask. This new value is the mean value of the selected pixels under the mask if the absolute difference between the mean value and the original pixelis smaller then the deviation. Otherwise the new value is the value of the origin pixel.

For the edge parameter see edge.

Back to Contents

SNN filter

SNN_MeanFilter srcImage destImage radius edge
SNN_MedianFilter srcImage destImage radius edge

Class: OrdImage, see
OrdImage.

Menu: Operator | Filter

The Symmetric Nearest Neighbour (SNN) filter is an edge preserving smooth filterIt compares symmetric pairs of pixels within a defined radius with the center pixel.For each pair of pixels the one which is closest in value to the center pixel is calculated.

For the SNN_MeanFilter the new pixel value assigned to the center pixel is the mean of the closest pixels.
For the SNN_MedianFilter the new pixel value assigned to the center pixel is the median of the closest pixels.

For the edge parameter see edge.

Back to Contents

Variance filter

VarianceFilter srcImage destImage edge height width orgX orgY maskValues

Class: OrdImage, see
OrdImage.

Menu: Operator | Filter

The VarianceFilter operator initialises a destination image by sliding a mask across the source image. A new value is calculated for the destination image at the position of the centre (= origin) of the mask. This new value is the square root of the sum of the squares of the difference between values of the central pixel and its neighbours.

This operator is used to measure the texture of an image.

For the edge parameter see edge.

Back to Contents

Non Maximum Suppresion

NonMaximumSuppression srcImage destImage directionImage dirScale

Class: OrdImage, see
OrdImage.

Menu: Operator | Filter

The Non Maximum Suppresion operator is used to find the maxima in edge magnitude images (=srcImage). This is operation is performed by using the edge directionimage (=directionImage). Normally srcImage and directionImage are the result of an edgedetection operator like Sobel. See help for Sobel operator for information aboutdirScale parameter.


Back to Contents

Zero crossings

ZeroCrossings srcImage destImage connected

Class: OrdImage, see
OrdImage.

Menu: Operator | Filter

The ZeroCrossings operator searches for zero crossings in the source image. At the positionswhere a zerocrossing is found the destination image becomes an object pixel (=1). At all othet position the destination pixels will get the value background (=0).
The parameter connected has the value EightConnected or FourConnected and determines which kind of zero crossings aresearched. So EightConnected will give a 'thicker' result than FourConnected.

Back to Contents

ApproxPolygon

ApproxPolygon <image> <Connected> <minDistance> <maxVertices> <&$tab>
Class: IntImage, see
IntImage.

Menu: Operator | Geometry

The ApproxPolygon operator calculates the approximate polygon of the biggest blob.

Connected: EightConnected or FourConnected.
minDistance: the approximation search will stop if all pixels on the contour are closer minDistance pixels to the polygon. Minimum value is 1.
maxVertices the number of vertices for the polygon.
If maxVertices> 0 search for maximal max number of vertices
If maxVertices== 0 then keep searching until maxD < minDistance

The function result is the number of vertices found.

The array $tab will hold an array with coordinates for the polygon.The coordinates are sorted in clock wise orientation.


Back to Contents

Binning

Binning srcImage destImage height width BinningMode

Class: OrdImage, see
OrdImage.

Menu: Operator | Geometry

The Binning operator creates a destination image by combining pixels in a neighbourhoodof height * width pixels.

Possible values for the BinningMode parameter:
- AverageBinning, pixels in neighbourhood are averaged
- SumBinning, pixels in neighbourhood are summed


Back to Contents

Enlarge2

Enlarge2 srcImage newImage interpolation

Class: NumImage, see
NumImage.

Menu: Operator | Geometry

The enlarge2 operator initialises a destination image by enlarging thesource image with a factor two. The extra pixels in the new image willget a value which is calculated by interpolation of the neighbours pixel values.

See also interpolation

Back to Contents

FindCornersRectangle and FindCornersRectangleSq

FindCornersRectangle <image> <Connected> <deltaPhi> <Orientation> <&$tab>
FindCornersRectangleSq <image> <Connected> <&$tab>
Class: NumImage, see
NumImage.

Menu: Operator | Geometry

The FindCornersRectangle operator searches for the biggest blob the corner points of a rectangle. This operator will allow a certain degree of deformation of the rectangle, like causedby perspective distortion. DeltaPhi specifies the degree of deformation allowed, deltaPhi is in radians and the max value is PI/4. This operator will work with rounded corners like usually seen in license plates.Note: this operator will work only correctly if the shortest long side of the rectangle is longer then the two shortest sides. So it will NOT work for squares.
Connected: EightConnected or FourConnected.
Orientation: Portrait or Landscape.

The FindCornersRectangleSq operator searches for the biggest blob the corner points of a rectangle or a square. This operator will allow a certain degree of deformation of the rectangle, like causedby perspective distortion. This algorithm is sensitive for distortions at the cornerpoints and will not performoptimal with rounded corners.
Connected: EightConnected or FourConnected.

The functions result is true if rectangle is found.The array $tab will hold the coordinates in the order leftTop, rightTop, leftBottom and rightBottomt

Back to Contents

FishEye

For Class: NumImage, see NumImage.
FishEye srcImage destImage height width omega scale border interpolation
Note: the parameter interpolation is not used for ColorImages and ComplexImages.

Menu: Operator | Geometry

This operator performs a FishEye transform. If omega is positive an image taken witha fish eye objective will be stretched flat. With a negative omega a normal image can be transformto a fish eye image.

A good starting point for experimenting with a value for omege = PI / (diameter fish eye circle in pixels)

The scale factor specifies a the zoom factor.

The parameters height and width determine the size of the destination image.
The specified border value will be used as result pixel if information outside the source image is necessary for the calculation.
See for interpolation parameter interpolation.


Back to Contents

HawkEye

For Class: NumImage, see NumImage.
HawkEye srcImage destImage height width nrLevels

Menu: Operator | Geometry

This operator makes a copy of an image with the reduced specified sizes. The image is reduced by zooming out in aspecial way. The destination image consists of nrLevels concentric rectangles with the same "thinkness". The inner rectangle has is not zoomed out, everything has it's original size. The outer rectangle has been zoomed out in order to fit to the specified height and width.The intermediate rectangles have a proportinal zoomfactor between the inner and outer rectangle.

Note:
- if reduction factor is too small, not all nrLevels can be generated
- if width = 0, reduction is done with preserved aspect ratio

Typical usage is for adjusting sharpness and framing a high resolution camera. The image taken must be inspectedat full resolution for sharpness and reduced resolution in order to frame the compostion on the screen. When using HawkEye operator with nrLevels = 2, the image taken can with the outer rectangle at a reduced resolutionin order to fit on a screen and with the inner rectangle at full resolution for adjusting the sharpness.

Back to Contents

MapAxis

For Class: IntImage, see IntImage.
MapAxis sourceImage destinationImage axisMapping
The parameter axisMapping can have the values: Copy Rotate90 Rotate180 Rotate270 MirrorInXAxis MirrorInYAxis Rotate90AndMirrorInYAxis Rotate90AndMirrorInXAxis MirrorInXAxisAndRotate90 MirrorInYAxisAndRotate90 MirrorInCenter

Menu: Operator | Geometry

The MapAxis operator initializes a destination image by mapping the x-axis and y-axis of the source image to the positive or negative x-axis or y-axis.
The axisMapping parameter specifies the predefined mapping performed. The operator can be used to rotate and/or mirror the source image in one pass.
Example: If the axisMapping is Rotate90AndMirrorInXAxis, the source image is rotated 90 degrees and is mirrored in the x-axis to produce the destination image.


Back to Contents

Mirror

Mirror imagename mirroroperation

Class: NumImage, see
NumImage.

Menu: Operator | Geometry

This operator mirrors the image in the centre of the image

Possible values for the mirroroperation parameter:
- MirrorInCentre
- MirrorInXAxis
- MirrorInYAxis


Back to Contents

Optical Correction

OpticalCorrection src dest k1 k2 k3 borderValue pixelInterpolation

Class: NumImage, see
NumImage.

Menu: Operator | Geometry

This operator corrects the optical distortion.
Note the kappa's for this operator are different from the kappa's used by CamDistortion.
This operator performs "the inverse operation" and is much faster then CamDistortion.

NOTE: this operator is under construction and only for experimental use.


Back to Contents

Polar stretch

PolarStretch srcImage newImage centerx centery beginangle endangle anglesteps maxradius border interpolation

Class: OrdImage, see
OrdImage.

Menu: Operator | Geometry

This operator stretches and bends a circle (or part of a circle, a pie) to a rectangular shape.In this rectangular image the x coordinate represents the angle and the y coordinate represents the radius in pixels.So if a point is on the 5th row it means that this point is 5 pixels away from the specified center.

In short: It takes a slice of the circle and fills a column of pixels with it.

See also interpolation


Back to Contents

Reduce2

Reduce2 srcImage newImage

Class: NumImage, see
NumImage.

Menu: Operator | Geometry

The reduce2 operator initialises a destination image by reducing thesource image with a factor 2. The values of the pixels in the new image have the same value as the value of the corresponding pixels in the source image.

Back to Contents

RefineCornersRectangle

RefineCornersRectangle image cornerTab margin newCornerTab

Class: OrdImage, see
OrdImage.

Menu: Operator | Geometry
This operator has as input a grayscale image and four points that approximately correspond to the corners of a rectangle in that image. For every two points that form an edge it places a box around the line which connects the two points. In this box, it uses the operator FindEdgeLine, which gives the line of the edge in subpixel precision. Then, it takes the intersections of those lines as the new corners.

If the initial corners are so close to the border that the box cannot be placed, the image is extended margin + 1 pixels on each side using the pixel in the border, before running the algorithm explained above. It returns the number of pixels found in the quadrilateral (results of all four FindEdgeLine added together).


Back to Contents

Resample Line

ResampleLine srcImage destImage startCoord endCoord nrOfPixels

Class: OrdImage, see
OrdImage.

Menu: Operator | Geometry

The ResampleLine operator resamples nrOfPixels pixels in srcImage on the line fromstartCoord to endCoord. The result is a one dimensional destination image.

Back to Contents

Rotate

For Class: NumImage, see NumImage.
- Rotate srcImage destImage xc yc phi border interpolation
- RotateFull srcImage destImage phi border interpolation

Note: the parameter interpolation is only used for images of type OrdImage. For all other type of images are interpolated with NearestNeighbour.

Menu: Operator | Geometry

The rotate operator initialises a destination image by rotating thesource image at rotation centre (xc,yc) by phi radians. The source and destination imagesare of the same size. So some of the source pixels will rotate off the screen and some of the destination pixels will have an unknown value. Those destination pixels will be initialised with the specified border value.

The rotatefull operator initialises a destination image by rotating thesource image by phi radians. The destination image will be big enough to accomodate allrotated source pixels. Some of the destination pixels will have an unknown value. Those destination pixels will be initialised with the specified border value. The functionresult is the position of the srcImage origin(0,0) in the destImage.

See for interpolation parameter interpolation.


Back to Contents

Swap Axis

For Class: IntImage, see IntImage.
- SwapAxis srcImage destImage direction scale

The parameter direction can have the values: SwapAxisLeft SwapAxisRight SwapAxisTop SwapAxisBottom SwapAxisBack.
The parameter scale is a positive integer value.

Menu: Operator | Geometry

The SwapAxis operator interprets the source image as a three dimensional object where the pixel value is the third dimension, the z axis. This z axis is perpendicular to the screen.
The parameter direction specifies from which new direction the three dimensional object is to be viewed.This means the x or y axis is exchanged with the z axis. Before starting the projection the maximum pixel value in the image is calculated, this is the maximum value in the z axis. All values in the z direction are dividedby the scale parameter.
Multiple pixels in the source image can be projected to one pixel in the destination image. In this case the coordinate of the pixel which is the closest to the plane of view is chosen.

Example: if direction is SwapAxisLeft then in the destination image the z axis and x axis are exchanged.

SwapAxisBack will view the object from the backside.



Back to Contents

Swap quadrants

SwapQuadrants imageName

Class: NumImage, see
NumImage.

Menu: Operator | Geometry

This operator swaps the four quadrants of an image in the following way:
AB to DC
CD BA

Note: works only with even height and width of the image.

Back to Contents

Translate cyclic

TranslateCyclic srcImage destImage x y

Class: NumImage, see
NumImage.

Menu: Operator | Geometry

This operator translated the sourceImage to the destinationImage over thevector (x,y) in a cyclic way, so columns and rows which are translated of theimage window are wrapped to the other side of the image.

Back to Contents

Warp

For Class: NumImage, see NumImage.
Warp srcImage destImage direction leftTop rightTop leftBottom rightBottom height width border interpolation

Function result is false if 3 or more coordinates are (almost) in line.
Note: the parameter interpolation is not used for ColorImages and ComplexImage.

Menu: Operator | Geometry

With the parameter direction can be selected the forward transform or the reversed transform.

The parameters height and width determine the size of the destination image.
The forward transform calculates the perspective mapping of the quadranqledelimited by the coordinates leftTop, rightTop, leftBottom and rightBottom in the srcImage to the total rectangle area of the destImage.

The inverse transform calculates the inverse perspective mapping of the total rectangle area of the scrImage to the quadranqledelimited by the coordinates leftTop, rightTop, leftBottom and rightBottom in the destImage.

The specified border value will be used as result pixel if information outside the source image is necessary for the calculation.
See for interpolation parameter interpolation.


Back to Contents

Zoom

Zoom srcImage destImage height width interpolation
ZoomXY srcImage destImage factorX factorY interpolation

Class: NumImage, see
NumImage.

Menu: Operator | Geometry

The zoom operator initialises a destination image by enlarging of reducing thesource image with the specified height and width using the specified interpolation technic.

The zoomxy operator initialises a destination image by enlarging of reducing thesource image with the specified factors for x and y direction using the specified interpolation technic.

Note: both operators have a c++ prototype with the same name Zoom.

See also interpolation

Back to Contents

Abs

Abs image

Class: NumImage, see
NumImage.

Menu: Operator | Image Math

The Abs operator calculates for each pixel its absolute value.

Back to Contents

Add

Add destImage sourceImage

Class: NumImage, see
NumImage.

Menu: Operator | Image Math

The add operator adds the pixel values in two images. Each pixel in the destination image will get the value of the destination pixel value plus the pixel value in the corresponding source image.

See also: how to select the second image for a dyadic operator. Select 2nd and 3rd

For the C++ SDK operator + and operator += on images is supported.

Back to Contents

Add pixel

AddPixel image value

Class: NumImage, see
NumImage.

Menu: Operator | Image Math

The addpixel operator adds to the value of each pixel in the image the specified value.

For the C++ SDK operator + and operator += on image and pixel are supported.

Back to Contents

And

And destImage sourceImage

Class: IntImage, see
IntImage.

Menu: Operator | Image Math

This operator is intended for a Binary image

The and operator ANDs the pixel values in two images. Each pixel in the destination image will get the value of the destination pixel value ANDed by the pixel value in the corresponding source image.

See also: how to select the second image for a dyadic operator. Select 2nd and 3rd

For the C++ SDK operator & and operator &= on images is supported.

Back to Contents

And pixel

AndPixel image pixelvalue

Class: IntImage, see
IntImage.

Menu: Operator | Image Math

This operator is intended for a Binary image

The and operator ANDs the pixel values in an image with a constantpixel value.

For the C++ SDK operator & and operator &= on image and pixel are supported.

Back to Contents

Divide

Divide destImage sourceImage

Class: NumImage, see
NumImage.

Menu: Operator | Image Math

The divide operator divides the pixel values in two images. Each pixel in the destination image will get the value of the source pixel value divided by the pixel value in the corresponding source image.

NOTE: the operation will be aborted if the source image contains a pixel with the value of zero.

See also: how to select the second image for a dyadic operator. Select 2nd and 3rd

For the C++ SDK operator / and operator /= on images is supported.

Back to Contents

Divide pixel

Divide image pixelvalue

Class: NumImage, see
NumImage.

Menu: Operator | Image Math

The divide operator divides all pixel values in an image by aconstant pixelvalue.

NOTE: the operation will be aborted if pixelvalue is zero.

For the C++ SDK operator / and operator /= on image and pixel are supported.

Back to Contents

ExOr

Exor destImage sourceImage

Class: IntImage, see
IntImage.

Menu: Operator | Image Math

This operator is intended for a Binary image

The exor operator EXORs the pixel values in two images. Each pixel in the destination image will get the value of the destination pixel value EXORed by the pixel value in the corresponding source image.

See also: how to select the second image for a dyadic operator. Select 2nd and 3rd

For the C++ SDK operator ^ and operator ^= on images are supported.

Back to Contents

ExOr Pixel

ExorPixel image pixelvalue

Class: IntImage, see
IntImage.

Menu: Operator | Image Math

This operator is intended for a Binary image

The exor operator EXORs the pixel values in an image is exored witha constant value.

For the C++ SDK operator ^ and operator ^= on image and pixel are supported.

Back to Contents

Max

Max destImage sourceImage

Class: OrdImage, see
OrdImage.

Menu: Operator | Image Math

Each pixel in the destination image will get the maximum value of the destination pixel value and the pixel value in the corresponding source image.

See also: how to select the second image for a dyadic operator. Select 2nd and 3rd

Back to Contents

Mean

Mean destImage sourceImage

Class: OrdImage, see
OrdImage.

Menu: Operator | Image Math

Each pixel in the destination image will get the mean value of the destination pixel value and the pixel value in the corresponding source image.

See also: how to select the second image for a dyadic operator. Select 2nd and 3rd

Back to Contents

Min

Min destImage sourceImage

Class: OrdImage, see
OrdImage.

Menu: Operator | Image Math

Each pixel in the destination image will get the minimum value of the destination pixel value and the pixel value in the corresponding source image.

See also: how to select the second image for a dyadic operator. Select 2nd and 3rd

Back to Contents

Modulo

Modulo destImage sourceImage

Class: IntImage, see
IntImage.

Menu: Operator | Image Math

The Modulo operator performs the modulo (%) of all the pixel values in two images.
See also: how to select the second image for a dyadic operator. Select 2nd and 3rd

For the C++ SDK operator % and operator %= on images are supported.

Back to Contents

Modulo pixel

ModuloPixel image pixelvalue

Class: IntImage, see
IntImage.

Menu: Operator | Image Math

The Modulo operator performs the modulo (%) of all the pixel values in an image with a constant pixelvalue.

For the C++ SDK operator % and operator %= on image and pixel are supported.

Back to Contents

Multiply

Multiply destImage sourceImage

Class: NumImage, see
NumImage.

Menu: Operator | Image Math

The multiply operator multiplies the pixel values in two images. Each pixel in the destination image will get the value of the destination pixel value multiplied by the pixel value in the corresponding source image.

See also: how to select the second image for a dyadic operator. Select 2nd and 3rd

For the C++ SDK operator * and operator *= on images are supported.

Back to Contents

Multiply pixel

MultiplyPixel image pixelvalue

Class: NumImage, see
NumImage.

Menu: Operator | Image Math

The multiply operator multiplies all pixel values in an image with a constant pixelvalue.

For the C++ SDK operator * and operator *= on image and pixel are supported.

Back to Contents

Not

Not image

Class: IntImage, see
IntImage.

Menu: Operator | Filter | Morphology

Menu: Operator | Image Math

This operator is intended for a Binary image

The not operator inverts the pixel values in the image. Each pixel in the destination image will get the inverted value of the source pixel value.

For the C++ SDK operator ! on images is supported.

Back to Contents

Or

Or destImage sourceImage

Class: NumImage, see
NumImage.

Menu: Operator | Image Math

This operator is intended for a Binary image

The or operator ORs the pixel values in two images. Each pixel inthe destination image will get the value of the destination pixel value ORed by the pixel value in the corresponding source image.

See also: how to select the second image for a dyadic operator. Select 2nd and 3rd

For the C++ SDK operator | and operator |= on images are supported.

Back to Contents

Or pixel

OrPixel image pixelvalue

Class: NumImage, see
NumImage.

Menu: Operator | Image Math

This operator is intended for a Binary image

The or operator ORs the pixel values in an image with a constant pixelvalue.

For the C++ SDK operator | and operator |= on image and pixel are supported.

Back to Contents

Power

Power imageX imageY

Class: OrdImage, see
OrdImage.

Menu: Operator | Image Math

The Power operator takes the power of the pixel values in two images. Each pixel inimageX will get the value of the imageX pixel value to the power of the corresponding pixel in imageY.

See also: how to select the second image for a dyadic operator. Select 2nd and 3rd

Back to Contents

Power pixel

PowerPixel image value

Class: OrdImage, see
OrdImage.

Menu: Operator | Image Math

The PowerPixel operator takes the power of the pixel values of an image to a specified value.


Back to Contents

Remainder

Remainder destImage sourceImage

Class: IntImage, see
IntImage.

Menu: Operator | Image Math

Each pixel in the destination image will get the remainder part value of the division of the destination pixel value by the pixel value in the corresponding source image.

See also: how to select the second image for a dyadic operator. Select 2nd and 3rd

Back to Contents

Subtract

Subtract destImage sourceImage

Class: NumImage, see
NumImage.

Menu: Operator | Image Math

The subtract operator subtracts the pixel values in two images. Each pixel in the destination image will get the value of the destination pixel value subtracted by the pixel value in the corresponding source image.

See also: how to select the second image for a dyadic operator. Select 2nd and 3rd

For the C++ SDK operator - and operator -= on images are supported.

Back to Contents

Subtract pixel

SubtractPixel image value

Class: NumImage, see
NumImage.

Menu: Operator | Image Math

The subtractpixel operator subtracts from the value of each pixel in the image the specified value.

For the C++ SDK operator - and operator -= on image and pixel are supported.

Back to Contents

Blob analysis [script]

BlobAnalysis imagename sort sorton xory blobanalyseset [modifier]
GrayScaleBlobAnalysis labeledImage grayImage sort sorton xory blobanalyseset [modifier]
BlobAnalysisArray imagename &$array sort sorton xory blobanalyseset [modifier]
GrayScaleBlobAnalysisArray labeledImage grayImage &$array sort sorton xory blobanalyseset [modifier]

Class: IntImage, see
IntImage.

Menu: Operator | Label

These operators analysis a labeled image. Which analysis are performedare indicated in the blobanalyseset. These operators are a text based version of (Grayscale) Blob analysis, see (Grayscale) Blob analysis (array)

Note: the result of BlobAnalysis and GrayScaleBlobAnalysis is a string of text with all blob analysis in alfabethical order of the selected analysis.

Note: For BlobAnalysisArray and GrayScaleBlobAnalysisArray the result of the blob analysis is storedin the specified array variable. For each blob there is a record with the result of the analysis.The function result is maximum index in the array. If there are no blobs the function result is -1 and array[0] is anempty string.

Example of use:

lread i cells.jl
ThresholdIsodata i BrightObject
$nrBlobs = LabelBlobs i EightConnected
$maxBlob = BlobAnalysisArray i &$tab SortUp Area UseY Area FormFactor
$total = 0
for $i = 0 to $maxBlob do
VarToArray &$tab[$i] &$elm
$label = $elm[0]
$area = $elm[1]
$ff = $elm[2]
$total = $total + $area
endfor
$avgArea = $total / $nrBlobs



Back to Contents

(Grayscale) Blob analysis (array)

BlobAnalysis imagename sort sorton xory blobanalyseset [modifier]
GrayScaleBlobAnalysis labeledImage grayImage sort sorton xory blobanalyseset [modifier]

Class: IntImage, see
IntImage.

Menu: Operator | Label

This operators analyse a labeled image. Which analysis are performedare indicated in the set of blobanalyse tools. The GrayScaleBlobAnalyse has an extra image as parameter, this image is a grayscale imageand is used to measure the grayscale pixels of the objects.

With this operator a blob analysis of a labeled image is performed.The result of the analysis is a table called "label" with in each row thelabel number (=pixel value) of all blobs.This table is sorted depending on the parameter sort and sorted using sorton assort criterium.

Possible values for sort:
- NoSort: no sorting of result, result is display on increasing label number.
- SortUp: result is sorted based on sorton, results are displayed in decreasing order.
- SortDown: result is sorted based on sorton, results are displayed in increasing order.

Sorton specifies the result of which analyse tool is used for the sorting.

XorY specifies if the result is to be sorted on a coordinate whether the x or y value should be used for the sorting.

modifier is an optional parameter which can override the default behaviour of certain analyse tools.

By single click with the mouse pointer on a row in the table "label" more detailed information about the blob is displayed in the table "analyse result".

Notes for C++ programmers:
- the corresponding c++ procedure needs an extra parameter maxLabel. This is the highest value of the label in the image. This parameter should normally be the function result of the procedure LabelBlobs.
- the resulting BlobTab does NOT have an entry for the background label (=0).

Some definitions for using blob analyse tools:

- BoundingBox: Description of the smallest rectangular box around the blob and aligned to the orientation of the principle axis.Parameters are length, breadth, left, top, right and bottom.

- Extremes: Description of the 8 extreme points where the blob touches the surrounding box. Parameters are top most left, top most right, right most top, right most bottom,bottom most right, bottom most left, left most bottom and left most top.

- SurroundingBox: Description of the smallest rectangular box around the blob and aligned to x and y axis. Parameters are height, width, top left, top right, bottom left and bottom right.

The blob analyse tools are:

- Area: number of pixels in the blob.
- AreaHoles: number of pixels in all holes of the blob.
- AreaHolesRatio: AreaHoles / Area.
- Bottom: coordinate of the bounding box.
- BottomLeft: coordinate of the surrounding box.
- BottomMostLeft: one of the extreme points of the surrounding box.
- BottomMostRight: one of the extreme points of the surrounding box.
- BottomRight: coordinate of the surrounding box.
- Breadth: breadth (=width) of the bounding box.
- CentreOfGravity: centre of gravity of the blob.
- Eccentricity: [0 = circular .. 1 = line shaped object].
- EllipsFit: Area / (PI * 0.5 * Length * 0.5 * Breadth).
- ExCircleCentre: approximation of the centre of the smallest circle that encloses the blob. Based on the middle of longest distance between pixels on the border.
- ExCircleC1 and ExCircleC2: the coordinates of the 2 pixels of the blob with the biggest distance.
- ExCircleR: the radius of the smallest circle that enclosed the blob.
- FormFactor: 4*pi*area/(perimeter*perimeter), so: [0 = line .. 1 = circular shaped object].
- Height: height of the surrounding box.
- HeightWidthRatio: the quotient height and width of the surrounding box.
- Hu1 .. Hu7: the seven Hu moments, the are position, scale and rotation invariant, because of the high dynamical range of the moments a logarithmical scaling function is used.
- InCircleCentre: the centre of the biggest circle that is enclosed in the blob.
- InCircleC1 and InCircleC2: the coordinates of the 2 pixels where the inner circle touches the background.
- InCircleR: the radius of the the biggest circle that is enclosed in the blob.
- Left: coordinate of the bounding box.
- LeftMostBottom: one of the extreme points of the surrounding box.
- LeftMostTop: one of the extreme points of the surrounding box.
- Length: lenght of the bounding box.
- LengthBreadthRatio the quotient length and Breadth of the bounding box.
- MaxCord: maximum distance between 2 pixels in blob.
- MaxCordC1 and MaxCordC2: the coordinates of the 2 pixels of the blob with the biggest distance
- Moments_xx: the net moments about the x-axis.
- Moments_xy: the net moments about the x-axis and y-axis.
- Moments_yy: the net moments about the y-axis.
- MomentsScale_xx: the net moments about the x-axis normalized for the size of the object.
- MomentsScale_xy: the net moments about the x-axis and y-axis normalized for the size of the object.
- MomentsScale_yy: the net moments about the y-axis normalized for the size of the object.
- MomentsSR1: the net moments normalised for scale and rotation.
- MomentsSR2: the net moments normalised for scale and rotation.
- NrOfHoles: number of holes in the blob.
- Orientation: orientation of the principal axis of the blob, value = angle in radians (-pi/2..pi/2]).Note: the orientation of symmetrical blobs can not be calculated reliable.
- Perimeter: length of the inner border of the blob (no holes counted).
- PerimeterHoles: length of all perimeters of all holes in the blob.
- PolygonVertices: calculates the number of vertices for the approximate polygon of the blob.With the modifier parameter the accuracy of the approximation can be set.
- Right: coordinate of the bounding box.
- RightMostBottom: one of the extreme points of the surrounding box.
- RightMostTop: one of the extreme points of the surrounding box.
- SumX: the sum of all x coordinates in the blob.
- SumXX: the sum of the square of all x coordinates in the blob.
- SumXY: the sum of product of all x and y coordinates in the blob.
- SumY: the sum of all y coordinates in the blob.
- SumYY: the sum of the square of all y coordinates in the blob.
- Top: coordinate of the bounding box.
- TopLeft: coordinate of the surrounding box.
- TopMostLeft: one of the extreme points of the surrounding box.
- TopMostRight: one of the extreme points of the surrounding box.
- TopRight: coordinate of the surrounding box.
- Width: width of the surrounding box.

For GrayScaleBlobAnlysis there extra analyse tools retieving information fromthe grayscale image:

- AveragePixel, the average of the pixel values of the blob
- BendingEnergy, the energy in the sharp bendings in the perimeter of the blobWith the modifier parameter the sensivity can be set.
- Curvature, the number of sharp bendings in the perimeter of the blobWith the modifier parameter the sensivity can be set.
- IsoData, the "2 means value" of bi-modal distribution of the histogram
- MaxPixel, the maximum of the pixel values of the blob
- MedianPixel, the median of the pixel values of the blob
- MinPixel, the miniumum of the pixel values of the blob
- ModalPixel, the modal of the pixel values of the blob
- StandardDeviation, the standard deviation of the pixel values of the blob
- SumPixels, the sum of all pixel values of the blob
- SumWX, the sum of the product of all pixel values and their x-coordinate
- SumWY, the sum of the product of all pixel values and their y-coordinate
- WeightedCoG, the weighted (by pixel value) centre of gravity of the blob

Note: due to performance reasons logging of this operation in the server logis disabled. If you want the logging (eg for writing it to a log file) you should use the text based variant of this operation. See Blob analysis [script]

modifier is an optional parameter which can override the default behaviour of certain analyse tools.This parameter is an array variable. Each array element can override the bevaviour for one tool.Syntax is: <parameters> <value>. This parameter should be a reference to an array variable.

Possible parameters:
- bendingEnergyMaxEdgeDiff
- approxPolygonMinDistance

Parameter bendingEnergyMaxEdgeDiff:
you can influence the BendingEnergy and Curvature analyse tools. A Sharr edge detection is usedto calculate the direction at the perimeter. If the difference in edge direction is bigger then maxEdgeDiff the position is a sharp bending. The scale factor used in the calculation = 1000.The default value for bendingEnergyMaxEdgeDiff is 500.

Parameter approxPolygonMinDistance:
This parameter determines the behaviour of the analyse tool PolygonVertices.The polygon approximation search will stop if all pixels on the contour are closer then approxPolygonMinDistance pixels to the polygon. Minimum and default value is 1.

Example:
$baMod[0] = "approxPolygonMinDistance 10"
$baMod[1] = "bendingEnergyMaxEdgeDiff 300"
BlobAnalysisArray label &$tab SortUp Area UseX Area PolygonVertices &$baMod


Back to Contents

Blob Measure

BlobMeasure imageName blobanalyse scale xory [modifier]

Class: IntImage, see
IntImage.

Menu: Operator | Label

This operator measures blobs in a labeled image with name imageName.All pixels of a blob will get the same value according to theblobanalyse tool chosen.

The parameter scale is used if the measurement delivers a floating point answer which must be representedin integer notation. In this case the answer is multiplied by scale.

The parameter xory is used if blobanalyse specifies a tool which measuresa coordinate. This parameter specifies whether the x or the y of the coordinateis used for the result of the operation.

See for a description of the blob analyse tools .


Back to Contents

Count labels

CountLabels imageName low high

Class: OrdImage, see
OrdImage.

Menu: Operator | Label

This operator calculates how many different labels in the range [low..high] exists in the image.

Back to Contents

Label and

LabelAnd imageName maskImageName

Class: IntImage, see
IntImage.

Menu: Operator | Label

The original labeled image is anded pixel by pixel with the (binary) maskimage. This operator produces a labeled image in which the complete labelsof the original image are present for which one or more pixels where leftin above mentioned and operation.


Back to Contents

Label blobs

LabelBlobs srcImage labeledImage connected

Class: IntImage, see
IntImage.

Menu: Operator | Label

The labelblobs operator takes a binary image andinitialises a labeled image. The parameter connected has the value EightConnected or FourConnected and determines how the blobs areconnected.

The background pixels will get the value 0.

All pixels belonging to a blob will get the same value. Pixels belonging todifferent blobs will get different values.

The return value is he total number of found blobs. (= highest label number)


Back to Contents

Remove selected labels

RemoveSelectedLabels imageName low high

Class: OrdImage, see
OrdImage.

Menu: Operator | Label

All pixelvalues in therange [low..high] are converted to the value zero (=0).


Back to Contents

Remove (Grayscale) Labels

RemoveLabels imageName blobanalyse low high xory [modifier]

RemoveGrayScaleLabels labeledImage grayImage blobanalyse low high xory [modifier]

RemoveLabelsExp imageName connected expression [modifier]

RemoveGrayscaleLabelsExp binImage grayImage connected expresion [modifier]

Class: IntImage, see
IntImage.

Menu: Operator | Label

These operators remove blobs in a labeled image with name imageName.The RemoveGrayscaleLabels has an extra image as parameter, this image is a grayscale imageand is used to measure the grayscale pixels of the objects.
The first two operators specify one blobanalyse tool in order to remove the labels. All labels are measured according to the blobanalyse tool chosen and the labelss with measurement result in therange [low..high] are removed from imageName.

The last two operators use a regular expression in order to specify the labels to remove.The following operators are supported: and or ! == != < <= > >=.
== != < <= > >= are dyadic operators, both parameters are interpreted as floating point numbers and the result is a boolean. One of the parameters must be the name of a blobanalyse tool. If the blobanalyse tool returns a coordinate, the name must be extended with either .x or .y. If no extension is provided, the default value x is assumed.
The other parameter must be either a constant or a $variable.
Use brackets ( ) for priorities in the expression.
Examples of expression:
(Area < 50) or (Area > 500)
(LeftTop.x < 100) 0r (LeftTop.y > 200)

The parameter xory is used if blobanalyse specifies a tool which measuresa coordinate. This parameter specifies whether the x or the y of the coordinateis used for the result of the operation.

See for a description of the blob analyse tools .


Back to Contents

Remove border labels

RemoveBorderLabels imageName

Class: IntImage, see
IntImage.

Menu: Operator | Label

This operator removes all labels from a labeled image which touch thespecified borders of the image.
The parameter borders can have one of the following values: AllBorders, LeftBorder, RightBorder, TopBorder, BottomBorder,LeftAndTopBorder, TopAndRightBorder, RightAndBottomBorder or BottomAndLeftBorder.


Back to Contents

Add border

AddBorder srcImage destImage top left right bottom value

Class: NumImage, see
NumImage.

Menu: Operator | Synthetic

The add border operator initialises a destination image by embedding thesource image in a bigger destination image. The destination image has an extendedborder in top, left, right and bottom direction. The new border pixels are initialisedwith the specified pixel value.

Back to Contents

Block pattern

BlockPattern imageName left top height width value repeatx repeaty zeroOrOriginal

Class: NumImage, see
NumImage.

Menu: Operator | Synthetic

This operator generates a block pattern. The first block starts at (left,top) and has the specified height and width. The blocks are repeated with a translation (x,y) in the specified x and ydirection untill the blocks move out of the image. Pixels in the blocks have the specified value, allother pixels have the value zero.

The zeroOrOrginal parameter specifies whether the image is first cleared with zero or not.

Back to Contents

Circle shape

CircleShape imageName centrex centrey radius value zeroOrOriginal

Class: NumImage, see
NumImage.

Menu: Operator | Synthetic

This operator generates a circle with radius at (centrex, centrey) and specified value.The zeroOrOrginal parameter specifies whether the image is first cleared with zero or not.



Back to Contents

Cosine window

CosineWindow imageName multiplier

Class: OrdImage, see
OrdImage.

Menu: Operator | Synthetic

This operator generates an image with pixel values: image[x,y] = multiplier *sin (PI * x / (width-1)) * sin (PI * y / (height-1)).

Back to Contents

Disk shape

DiskShape imageName centrex centrey radius value zeroOrOriginal

Class: NumImage, see
NumImage.

Menu: Operator | Synthetic

This operator generates a disk with radius at (centrex, centrey) and specified value. The zeroOrOrginal parameter specifies whether the image is first cleared with zero or not.


Back to Contents

Draw line, Draw lines and Draw polygon

DrawLine imageName start_coordinate end_coordinate value zeroOrOriginal
DrawLines imageName &startTab &endTab value zeroOrOriginal
DrawPolygon imageName &tab value zeroOrOriginal

Class: NumImage, see
NumImage.

Menu: Operator | Synthetic

These operators draw line(s) or polygon with the specified value.The zeroOrOrginal parameter specifies whether the image is first cleared with zero or not.

Note: DrawLines require a reference to an array variable for both tables containing the start and the endpoints.
Example: &$tab instead of $tab.



Back to Contents

Extend border

ExtendBorder srcImage destImage top left right bottom

Class: NumImage, see
NumImage.

Menu: Operator | Synthetic

The extend border operator initialises a destination image by embedding thesource image in a bigger destination image. The destination image has an extendedborder in top, left, right and bottem direction. The new border pixels are initialisedwith the pixel values of the original border.

Back to Contents

Gaussian shape

GaussianShape imageName xc yc sigma max

Class: OrdImage, see
OrdImage.

Menu: Operator | Synthetic

This operator set the pixels to a Gaussian shape with as centre (xc,yc), a standard deviation of sigma and a maximum value of max.

The formula used for the shape is: G(x,y) = exp (-(r*r)/(sigma*sigma)),where r is the distance from (x,y) to the centre.

Back to Contents

Gaussian shape R

GaussianShapeR imageName xc yc r max

Class: OrdImage, see
OrdImage.

Menu: Operator | Synthetic

This operator set the pixels to a Gaussian shape with as centre (xc,yc), a radius of r and a maximum value of max. At distance r the pixels have a value of 50%.

The formula used for the shape is: G(x,y) = exp (-(r*r)/(sigma*sigma)),where r is the distance from (x,y) to the centre.

Back to Contents

Line pattern

LinePattern imageName startx starty value repeatx repeaty zeroOrOriginal

Class: NumImage, see
NumImage.

Menu: Operator | Synthetic

This operator generates a line pattern. The first vertical line starts at (startx,0) and isrepeated after repeatx pixels. The first horizontal line starts at (0,starty) and isrepeated after repeaty pixels. Pixels at the line have the specified value, allother pixels have the value zero.

The zeroOrOrginal parameter specifies whether the image is first cleared with zero or not.


Back to Contents

Noise

Noise imageName prob low high

Class: OrdImage, see
OrdImage.

Menu: Operator | Synthetic

The noise operator changes the values of pixels random in order to simulate noise. The parameter prob gives the probability that the value of a pixel is changed. If the value of a pixel is changed then the new value will be the old value plus a random value in the interval [low..high].

Back to Contents

Ramp pattern

RampPattern imageName periodx periody amplitude

Class: OrdImage, see
OrdImage.

Menu: Operator | Synthetic

This operator generates a ramp (sawtooth) pattern with specified amplitude,a periodx in x direction and a periody in y direction.

Back to Contents

Resample

Resample image rate

Class: NumImage, see
NumImage.

Menu: Operator | Synthetic

The resample operator simulates sampling the image with a lowersampling rate. Intermediate pixels are set to zero.

Back to Contents

Set all pixels

SetAllPixels imageName value

Class: NumImage, see
NumImage.

Menu: Operator | Synthetic

The setallpixels operator set the value of all pixels to the specified value.

Back to Contents

Set borders

SetBorders imageName value borders

Class: IntImage, see
IntImage.

Menu: Operator | Synthetic

This operator set all pixels at the specified borders of the image to the specifiedvalue.
The parameter borders can have one of the following values: AllBorders, LeftBorder, RightBorder, TopBorder, BottomBorder,LeftAndTopBorder, TopAndRightBorder, RightAndBottomBorder or BottomAndLeftBorder.

Back to Contents

SetMultiToValue(LUT)

SetMultiToValue imageName value selectvalue1 selectvalue2 selectvalue3 ....SetMultiToValueLUT imageName value selectvalue1 selectvalue2 selectvalue3 ....

Class: OrdImage for setmultitovalue, see
OrdImage.

Class: IntImage for setmultitovalueLIT, see IntImage.

Menu: Operator | Synthetic

This operator takes a greyscale image andproduces a greyscale image.

All pixels with have a value which is mentioned in the list of selectvaluesare converted to the specified value.

Back to Contents

Set selected to value

SetSelectedToValue imageName low high value

Class: OrdImage, see
OrdImage.

Menu: Operator | Synthetic

The threshold operator takes a greyscale image andproduces a greyscale image.

If all pixelvalues in therange [low..high] are converted to the specified value.

Back to Contents

Set to zero

SetToZero imageName

Class: NumImage, see
NumImage.

Menu: Operator | Synthetic

The SetToZero operator set the value of all pixels to zero.

Back to Contents

Sinus pattern

SinusPattern imageName periodx periody amplitude

Class: OrdImage, see
OrdImage.

Menu: Operator | Synthetic

This operator generates a sinus pattern with specified amplitude,a periodx in x direction and a periody in y direction.

Back to Contents

Text on Image (Coord2D)

TextOnImage imageName left top fontName text
TextOnImageCoord2D imageName (x,y) fontName text

Class: NumImage, see
NumImage.

Menu: Operator | Synthetic

This operator displays the specified text with font fontName on image at position top left or (x,y).


Other related operators are:
- AvailableFonts, returns a string with a list of available fonst
- FontHeight <fontName>, returns the height of the specfied font


Back to Contents

Blob matching

The Blob Matcher is a tool which finds the best match for a blob from a list of blobs. For good operation it is required that the blobs can be segmentated reliable.

Menu: File | Create Blob Matcher, for creating interactively a Blob Matcher
Menu: File | Open, for opening an existing Blob Matcher (file extenstion *.PM)
Menu: Operator | Pattern Machting, for script commands

Idea:
- Training:
add one example pattern for each class
- Matching:
For all patterns do
Resize blob to same size as pattern
For n rotations do
Rotate resized blob
Calculate difference by mapping center of gravities
Best match is pattern with the smallest difference

Calculating the differences:
- Contour matching: using the contour pixels only (fast)
- Filling matching: the interior of the object is sampled to find more accurate match (slower)

Filling matching has 2 parameters:
- fillSampleSize, the number of samples on each rotation ray
- perimeterFillRatio, the ratio of the contribution between the error calculated by the contour match and the filling matching
total error = contour error + perimeterFillRatio * filling error

The implementation of the Blob Matcher in VisionLab uses a combination of 3 techniques:
- Contour matching, compulsory, parameter: number of rotations
Only the contour pixels are used to find the scaling and rotation
- Filling matching, optional, parameters: perimeterFillRatio and fillSampleSize
The interior of the object is sampled to find more accurate scaling and rotation
- Random check, optional, normally NOT used, default value = 0,
Parameter: randomSampleSize, maximum number of pixels which are selected to check the matching

Scripts commands for Blob Matching:


- PM_AddPattern <imageName> <pmName>
Add image as pattern to pattern matcher
Function result is a string with patternId
imageName: name of the image to be addded
pmName: name of the pattern matcher

- PM_AllMatches <imageName> <pmName> <beginAngle> <endAngle> <&$array>
Match image with all patterns and give result in an array
imageName: name of the image to match
pmName: name of the pattern matcher
beginAngle and endAngle: limit the search range for the rotation
&$array: an array with tupples (<patternId> <error> <scale> <angle>) sorted on lowest error

- PM_BestMatch <imageName> <pmName> <beginAngle> <endAngle>
Find the best match for image with all patterns and give result in an array
Function result is <patternId> <confidence> <error> <scale> <angle>
imageName: name of the image to match
pmName: name of the pattern matcher
beginAngle and endAngle: limit the search range for the rotation

- PM_ChangeBlobMatcher <bmName> <nrOfRotations> <perimeterFillRatio> <fillSampleSize> <randomSampleSize>
Change the parameters of the blob matcher
bmName: name of the blob matcher
nrOfRotations: the number of rotations in the search space
perimeterFillRatio: error ratio between contour match and interior match
fillSampleSize: number of pixels sampled on ray in interior of blob
randomSampleSize: Maximum number of pixels which are selected to check the matching

- PM_CreateBlobMatcher <bmName> <imagetype> <nrOfRotations> <perimeterFillRatio> <fillSampleSize> <randomSampleSize>
Create a blob matcher
bmName: name of the blob matcher
imagetype: type of image for the patterns
nrOfRotations: the number of rotations in the search space
perimeterFillRatio: error ratio between contour match and interior match
fillSampleSize: number of pixels sampled on ray in interior of blob
randomSampleSize: Maximum number of pixels which are selected to check the matching

- PM_Delete <pmName>
Delete pattern matcher from memory
pmName: name of the pattern matcher

- PM_EvaluateCIS <pmName> <cisName> <beginAngle> <endAngle> <minConfidence> <detailsStr>
Evaluate blob matcher with a Class Image Set
Function result is string with the evaluation report
pmName: name of the pattern matcher
cisName: name of the class image set
beginAngle and endAngle: limit the search range for the rotation
minConfidence: image will be reported if confidence is lower then minConfidence
detailsStr: <HightDetails> | <LowDetails>, specifies the details in the report

- PM_FindPatterns <imageName> <pmName> <maxError> <minConfindence> <beginAngle> <endAngle> <&$labelTab> <&$patternTab>"
Find patterns in blobs of labeled image
Function result is number of patterns found
imageName: name of labeled image
pmName: name of the pattern matcher
maxError: maximum error of best found pattern for blob
minConfindence: minimum confidence of best found pattern for blob
beginAngle and endAngle: limit the search range for the rotation
&$labelTab: an array with tupples (<patternId> <error> <scale> <angle>).Index is labelNr.A table with the search results for each label, including the BackGround (= 0).If for blob with label search was not successfull, patternId = -1 will be used
&$patternTab: an array with tupples (<labelnr1> .. <labelnrN>), index is patternId. A table with label numbers of the blobs for which the pattern was found

- PM_GetImageType <pmName>
Get image type of pattern matcher
pmName: name of the pattern matcher

- PM_GetParams <pmName>
Get the parameters of the pattern matcher
Function result is a string with the parameters
pmName: name of the pattern matcher

- PM_GetPatternsNameTab <pmName>
Function result is a string with <nr of patterns> [<patternName> <patternId>]
pmName: name of the pattern matcher

- PM_NumberOfPatterns <pmName>
Function result is a string with <nr of patterns>
pmName: name of the pattern matcher

- PM_PatternName <pmName> <id>
Function result is a string with the pattern name for the specified pattern id
pmName: name of the pattern matcher
id: pattern id

- PM_PatternId <pmName> <name>
Function result is a string with the pattern id for the specified pattern name
pmName: name of the pattern matcher
name: pattern name

- PM_PatternNameImage <pmName> <nameImage> <patternName>
Make a copy of the specified pattern image
pmName: name of the pattern matcher
nameImage: name of the destination image
patternName: pattern name

- PM_PatternIdImage <pmName> <nameImage> <id>
Make a copy of the specified pattern image
pmName: name of the pattern matcher
nameImage: name of the destination image
id: pattern id

-PM_Rename <pmNameOld> <pmNameNew>
Rename pattern matcher
pmNameOld: old name
pmNameNew: new name

- PM_ReadFromFile <pmName> <fileName>
Read pattern matcher from file
pmName: name of the pattern matcher
fileName: file name to read from

- PM_RemovePattern <pmName> <name>
Remove pattern with specified name from pattern matcher
pmName: name of the pattern matcher
name: name of the pattern to remove

- PM_WriteToFile <pmName> <fileName>
Write pattern matcher to file
pmName: name of the pattern matcher
fileName: file name to write to


Back to Contents

Class Lexicon

Menu: Operator | Class Lexicon, for script commands

A class lexicon can be to improve the reliability of classifying items that consist of more then one objects.

Example: identifying street names on street name signposts in a city.
First a classifier like a pattern matcher is trained for the character font.
Then the lexicon is filled with all street names in the city.
After the pattern matcher has identified the best match for each individual character found in the signpost, the lexicon is consulted for the best match for the street name.
In this way errors in individual matches of characters can be compensated.
Commands:

- CLX_AddWord <clxName> <$word>
Add word to class lexicon
clxName: name of the class lexicon
word: variable with string containing all classNames of word seperated bij spaces

- CLX_Clear <clxName>
Remove all words from class lexicon
clxName: name of the class lexicon

- CLX_CreateClassLexicon <clxName> <$slassTab>
Create class lexicon from classTab, this information can be retrived with PM_GetPatternsNameTab, CIS_GetClassTab or CFS_GetClassTab, format of classTab: <nrClasses> [<className> <classId>]
clxName: name of the class lexicon

- CLX_Delete <clxName>
Delete class lexicon with name clxName
clxName: name of the class lexicon

- CLX_FindBestWord <clxName> <&$wordMatchTab> <&$bestWord> <optimize>
Find best matched word in class lexicon
clxName: name of the class lexicon
wordMatchTab: array with for each letter the pattern match result for all classes, format [<classId> <value>]
bestWord: string with best matched word in class lexicon, classNames are seperated by spaces
optimize: possible values = OptimizeForMinimum and OptimizeForMaximum, indicateswhether FindBestWord operator searches for best minimal or maximal values

- CLX_GetWords <clxName> <&$wordTab>
Get all words in class lexicon
clxName: name of the class lexicon
wordTab: array with the words
function result is number of words in lexicon

- CLX_NrClasses <clxName>
Get number of classes in class lexicon
clxName: name of the class lexicon
function result is number of classes in lexicon

- CLX_NrWords <clxName>
Get number of words in class lexicon
clxName: name of the class lexicon
function result is number of words in lexicon

- CLX_RemoveWord <clxName> <$word>
Remove word from class lexicon
clxName: name of the class lexicon
word: variable with string containing all classNames of word seperated bij spaces

- CLX_Rename <clxNameOld> <clxNameNew>
Change name of class lexicon
clxNameOld: old name of the class lexicon
clxNameNew: new name of the class lexicon

- CLX_ReadFromFile <clxName> <fileName>
Read class lexicon from file
clxName: name of the class lexicon
fileName: file name to read from

- CLX_WriteToFile <clxName> <fileName>
Write class lexicon to file
clxName: name of the class lexicon
fileName: file name to write to

Note: Raw class lexicons contain only classIds and no classNames
- CLX_AddRawWord <clxName> <$word>
Add raw word to class lexicon
clxName: name of the class lexicon
word: variable with string containing all classIds of word seperated bij spaces

- CLX_CreateRawClassLexicon <clxName> <nrClasses>
Create raw class lexicon with nrClasses classes.
clxName: name of the class lexicon

- CLX_FindBestRawWord <clxName> <&$wordMatchTab> <&$bestWord> <optimize>
Find best matched word in raw class lexicon
clxName: name of the class lexicon
wordMatchTab: array with for each letter the pattern match result for all classes, format [<classId> <error>]
bestWord: string with best matched word in class lexicon, classIds are seperated by spaces
optimize: possible values = OptimizeForMinimum and OptimizeForMaximum, indicateswhether FindBestWord operator searches for best minimal or maximal values

- CLX_RemoveRawWord <clxName> <$word>
Remove raw word from class lexicon
clxName: name of the class lexicon
word: variable with string containing all classIds of word seperated bij spaces


Back to Contents

Find Blob

Class: OrdImage, see OrdImage.

FindBlob srcImage patImage destImage connected maxError beginAngle endAngle nrOfRotations perimeterFillRatio fillSampleSize randomSampleSize

The FindBlob operator finds a blob in a image.
For good operation it is required that the blobs can be segmentated reliable.
All images are binary images.
The result of the search is an image with the blobs found.
Note: in contrast to the BlobMatcher, the FindBlob operator can NOT use blobgroups.

Menu: Operator | Pattern Machting

The implementation of the FindBlob in VisionLab uses a combination of 3 technics:
- Contour matching, compulsory, parameter: number of rotations
Only the contour pixels are used to find the scaling and rotation
- “Filling” matching, optional, parameters: perimeterFillRatio and fillSampleSize
The interior of the object is sampled to find more accurate scaling and rotation
- Random check, optional, parameter: randomSampleSize
Maximum number of pixels which are selected to check the matching

Parameters:
srcImage: name of the binary image to search in
patImage: name of the binary image with the pattern to search
destImage: name of the binary image with the result of the search
connected: the connectivity for the images, FourConnected or Eightconnected
beginAngle and endAngle: limit the search range for the rotation
nrOfRotations: the number of rotations in the search space
perimeterFillRatio: error ratio between contour match and interior match
fillSampleSize: number of pixels sampled on ray in interior of blob
randomSampleSize: maximum number of pixels which are selected to check the matching


Back to Contents

Clip pixel value

ClipPixelValue image low high

Class: OrdImage, see
OrdImage.

Menu: Operator | Point

The clippixelvalue operator restricts the pixel values in the image to the range [low..high]. Pixels with a value lower then low will get the value low. Pixels with a value higher then high will get the value high.

Back to Contents

Contrast stretch (LUT)

ContrastStretch image low high
ContrastStretchLUT image low high

Class: OrdImage, see
OrdImage.

Menu: Operator | Point

The contraststretch operator stretches, in a linear fashion, the pixel values in the image to the range [low..high]. The pixels with the lowest value in the source image will get the value low. The pixels with the highest value in the source image will get the value high.
The contraststretchlut operator performs the same operation but uses a lookup table.

Back to Contents

Convert

Convert srcImage destImage newType

Class: NumImage, see
NumImage.

Menu: Operator | Point

The convert operator initialises a destination image by converting thesource image to the specified NumImage


Back to Contents

Copy

Copy srcImage destImage

Class: NumImage, see
NumImage.

Menu: Operator | Point

The copy operator initialises a destination image by copying thesource image.

Back to Contents

Difference

Difference destImage sourceImage

Class: OrdImage, see
OrdImage.

Menu: Operator | Point

The difference operator calculates the absolute (arithmetic) difference between the pixel values in two images. The destination image is overwrittenby the difference pixels.
See also: how to select the second image for a dyadic operator. Select 2nd and 3rd

Back to Contents

DeInterlace

DeInterlace imageName

Class: NumImage, see
NumImage.

Menu: Operator | Point

This operator 'deinterlaces' the image by copying each odd lineto the next even line in the image


Back to Contents

Find First Transitions

FindFirstTransitions sourceImage destinationImage threshold viewpoint objectBrightness

Class: ordImage, see
OrdImage.
Menu: Operator | Point
This operator initializes a new image with a width or height of one pixel. The destinationImage is filled with the distance from the viewpoint to the first transition. Each row in the destinationImage is the distance in the same row of the sourceImage. Each column in the destinationImage is the distance in the same column of the sourceImage.
If objectBrightness = brightObject then the first transition is defined as the first occurrence of a pixel value higher than the threshold value.

If objectBrightness = darkObject then the first transition is defined as the first occurrence of a pixel value lower than, or equal to the threshold value.

If viewpoint = Left or viewpoint = Right then the destinationImage has a width of one pixel and a height equal to the height of sourceImage.
If viewpoint = Top or viewpoint = Bottom then the destinationImage has a height of one pixel and a width equal to the width of sourceImage.


Back to Contents

Gamma (LUT)

Gamma imageName factor
GammaLUT imageName factor

Class: OrdImage, see
OrdImage.

Menu: Operator | Point

This operator modifies the contrast in the image. The parameter factor is afloat.

If factor < 1.0 then the contrast range at the dark end of the range is expandedand at the light end of the range is compressed.
If factor > 1.0 then the contrast range at the dark end of the range is compressedand at the light end of the range is expanded.

The gamalut operator performs the same operation but uses a lookup table.

Back to Contents

Histogram equalize

HistogramEqualize imageName

Class: IntImage, see
IntImage.

Menu: Operator | Point

The histogramequalize operator equalizes the distribution of the pixel values in the image. The values of the pixels are reassigned based on the histogram of the image. Individual pixels retain their value order but the values are shifted, so that as far as possible, an equal numberof pixels have each possible value.

Back to Contents

Invert (LUT)


Invert imageName
InvertLUT imageName

Class: OrdImage, see
OrdImage.

Menu: Operator | Point

The invert operator inverts the pixel values in the image. The minimal pixel value becomes the maximum pixel value and so on.

The invertlut operator performs the same operation but uses a lookup table.

Back to Contents

Insert

Insert image insert x y

Class: NumImage, see
NumImage.

Menu: Operator | Point

The image insert is inserted in the image at position topleft (x,y).

Back to Contents

Sum columns and Sum rows

SumColumns src destination
SumRows src destination

Class: OrdImage, see
OrdImage.

Menu: Operator | Point

The columns or rows of the src image are summed in the destination image.

Beware of the possiblity of overfow during the operation, it is adviced to useInt32Image, FloatImage or DoubleImage.


Back to Contents

Transitions columns and Transitions rows

TransitionsColumns src destination threshold
TransitionsRows src destination threshold

Class: OrdImage, see
OrdImage.

Menu: Operator | Point

The columns or rows of the src image are scanned for transitions.
The number of transitions is stored in the destination image.
A transition is defined if:
- a pixel has value lower then threshold and its neighbour column or row pixel has a value greater or equal threshold
or
- a pixel has value greater or equal then threshold and its neighbour column or row pixel has a value lower threshold



Back to Contents

ROI

ROI srcImage destImage x y height width

Class: NumImage, see
NumImage.

Menu: Operator | Point

The Region Of Interest operator initialises a destination image by copying a section of thesource image. The section has as left top co-ordinate in the orininal image (top,left) and the specified height and width.

Back to Contents

ROIR

ROIR srcImage destImage middlePoint endPoint1 endPoint2 orientation border interpolation

Class: NumImage, see
NumImage.

Menu: Operator | Point

The Region Of Interest Rotated operator initialises a destination image by copying a section of the source image. The section is described by a rectangle specified with 3 co-ordinates: middlePoint, endPoint1, endPoint2.
The border parameter specifies how big an extra border around the specified rectangle is chosen.

The orientation parameter specifies whether the destination image is oriented as Portrait or Landscape.

Possible values for the interpolation parameter:
- NearestPixelInterpolation: the destination pixel will be mapped to thenearest source pixel.
- BilinearPixelInterpolation: the destination pixel will be interpolated to the four surrounding source pixels.

Back to Contents

Blob and

BlobAnd imageName maskImageName connected

Class: IntImage, see
IntImage.

Menu: Operator | Segmentation

The original (binary) image is anded pixel by pixel with the (binary) maskimage. This operator produces a binary image in which the complete blobsof the original image are present for which one or more pixels where leftin above mentioned and operation.

The parameter connected has the value EightConnected or FourConnected and determines how the blobs areconnected.

A synonym for this operation is region growing.


Back to Contents

Fill or Find (Specific) (Grayscale) Holes

FillHoles imageName connected
FillSpecificHoles imageName connected blobanalyse low high xory [modifier]
FillSpecificGrayscale Holes binImage grayImage connected blobanalyse low high xory [modifier]
FindHoles imageName connected
FindSpecificHoles imageName connected blobanalyse low high xory [modifier]
FindSpecificGrayscaleHoles binImage grayImage connected blobanalyse low high xory [modifier]

Class: IntImage, see
IntImage.

Menu: Operator | Segmentation

These operators fills or finds the holes in blobs in binary images.The Grayscale operatores have an extra image as parameter, this image is a grayscale imageand is used to measure the grayscale pixels of the objects. The parameter connected has the value EightConnected or FourConnected and determines how the holes areconnected.
The operation returns the number of filled or find holes.

The following parameters are for the operators with specify the holes:

All holes are measured according to theblobanalyse tool chosen and the holes with measurement result in therange [low..high] are filled or found.

The parameter xory is used if blobanalyse specifies a tool which measuresa coordinate. This parameter specifies whether the x or the y of the coordinateis used for the result of the operation.

See for a description of the blob analyse tools .

Back to Contents

Nr of Neighbours

NrOfNeighbours srcImage destImage connected

Class: IntImage, see
IntImage.

Menu: Operator | Segmentation
The nrofneighbours operator takes a binary image andinitialises a greyscale image. The parameter connected has the value EightConnected or FourConnected and determines how the blobs areconnected.

The background pixels will get the value 0.

All pixels belonging to a blob will get the value of its number of neighbours.


Back to Contents

Remove (Grayscale) Blobs (Exp)

RemoveBlobs imageName connected blobanalyse low high xory [modifier]

RemoveGrayscaleBlobs binImage grayImage connected blobanalyse low high xory [modifier]

RemoveBlobsExp imageName connected expression [modifier]

RemoveGrayscaleBlobsExp binImage grayImage connected expresion [modifier]

Class: IntImage, see
IntImage.

Menu: Operator | Segmentation

This operators removes blobs in a binary image with name imageName.The RemoveGrayscaleBlobs has an extra image as parameter, this image is a grayscale imageand is used to measure the grayscale pixels of the objects.

The first two operators specify one blobanalyse tool in order to remove the blobs. All blobs are measured according to the blobanalyse tool chosen and the blobs with measurement result in therange [low..high] are removed from imageName.

The last two operators use a regular expression in order to specify the blobs to remove.The following operators are supported: and or ! == != < <= > >=.
== != < <= > >= are dyadic operators, both parameters are interpreted as floating point numbers and the result is a boolean.One of the parameters must be the name of a blobanalyse tool. If the blobanalyse tool returns a coordinate, the name must be extended with either .x or .y. If no extension is provided, the default value x is assumed.
The other parameter must be either a constant or a $variable.
Use brackets ( ) for priorities in the expression.
Examples of expression:
(Area < 50) or (Area > 500)
(LeftTop.x < 100) 0r (LeftTop.y > 200)

The parameter xory is used if blobanalyse specifies a tool which measuresa coordinate. This parameter specifies whether the x or the y of the coordinateis used for the result of the operation.

The parameter connected has the value EightConnected or FourConnected and determines how the bobs areconnected

See for a description of the blob analyse tools .


Back to Contents

Remove border blobs

RemoveBorderBlobs imageName connected borders

Class: IntImage, see
IntImage.

Menu: Operator | Segmentation

This operator removes all blobs from a binary image which touch thespecified borders of the image.The parameter connected has the value EightConnected or FourConnected and determines how the bobs areconnected.
The parameter borders can have one of the following values: AllBorders, LeftBorder, RightBorder, TopBorder, BottomBorder,LeftAndTopBorder, TopAndRightBorder, RightAndBottomBorder or BottomAndLeftBorder.


Back to Contents

Separate blobs

SeparateBlobs srcName destName size

Class: IntImage, see
IntImage.

Menu: Operator | Segmentation

This operator separates blobs that are "grown" together.
The size parameter gives the high limit in pixels that is possible for blobs to have overlap in orderto be considered two distinct blobs.
Note: all blobs with a height of width smaller then size will be removed from the result.



Back to Contents

Threshold

Threshold imageName low high

Class: OrdImage, see
OrdImage.

Menu: Operator | Segmentation

The threshold operator takes a greyscale image andproduces a Binary image

If low <= high then all pixelvalues in therange [low..high] are converted to the value Object (=1) and all otherpixelvalues are converted to the value Background (=0).

If low > high then all pixelvalues not in the range (high..low) are converted to the value Object and all other pixelvalues are converted to the value Background.

Back to Contents

Threshold Fast

ThresholdFast imageName low high min max

Class: IntImage, see
Intmage.

Menu: Operator | Segmentation

The ThresholdFast operator takes a greyscale image andproduces a Binary image
Min and max are the minimum and maximum pixel values in the image.

If low <= high then all pixelvalues in therange [low..high] are converted to the value Object (=1) and all otherpixelvalues are converted to the value Background (=0).

If low > high then all pixelvalues not in the range (high..low) are converted to the value Object and all other pixelvalues are converted to the value Background.

Back to Contents

ThresholdHysteresis


ThresholdHysteresis imageName low high connected

Class: IntImage, see
Intmage.

Menu: Operator | Segmentation

The thresholdhysteresis operator takes a greyscale image andproduces a Binary image
If high >= low thenall pixels with a value greater than high are selected as object pixels.These object pixels are used as seeds. All connected neighbours of the seedswith a pixel value greater than low are added to the objectpixels. This growingprocess is repeated until no pixels are added.

If high < low thenall pixels with a value smaller than high are selected as object pixels.These object pixels are used as seeds. All connected neighbours of the seedswith a pixel value smaller than low are added to the objectpixels. This growingprocess is repeated until no pixels are added.

Back to Contents

Threshold IsoData and Threshold IsoData ROI

ThresholdIsodata imageName objectbrightness
ThresholdIsodataROI imageName roiName objectbrightness

Class: IntImage, see
Intmage.

Menu: Operator | Segmentation

The thresholdisodata operator takes a greyscale image andproduces a Binary image

If objectbrighness = DarkObject then all pixelvalues in therange [minimum..threshold] are converted to the value Object (=1) and all otherpixelvalues are converted to the value Background (=0).

If objectbrighness = BrightObject then all pixelvalues not in the range [threshold..maximum] are converted to the value Object and all other pixelvalues are converted to the value Background.

The operator returns as return value its chosen thresholdvalue.

The thresholdisodataroi operator performs the same operation as thresholdisodata, but the calculation of the threshold is performed only with the corresponding pixels wich are seleceted by the roi.


Back to Contents

Threshold Local

ThresholdLocal imageName maskName objectbrightness

Class: IntImage, see
Intmage.

Menu: Operator | Segmentation

The thresholdlocal operator takes a greyscale image andproduces a Binary image

If objectbrighness = DarkObject then all pixelvalues in therange [minimum..threshold] are converted to the value Object (=1) and all otherpixelvalues are converted to the value Background (=0).

If objectbrighness = BrightObject then all pixelvalues not in the range [threshold..maximum] are converted to the value Object and all other pixelvalues are converted to the value Background.

Back to Contents

ThresholdMulti

ThresholdMulti imageName selectvalue1 selectvalue2 selectvalue3 ....

Class: IntImage, see
IntImage.

Menu: Operator | Segmentation

This operator takes a greyscale image andproduces a Binary image

All pixels with have a value that is mentioned in the list of selectvaluesare converted to the value Object (=1) and all otherpixelvalues are converted to the value Background (=0).

Back to Contents

Threshold Simple

ThresholdSimple imageName threshold objectbrightness

Class: OrdImage, see
OrdImage.

Menu: Operator | Segmentation

The thresholdsimple operator takes a greyscale image andproduces a Binary image

If objectbrighness = DarkObject then all pixelvalues in therange [minimum..threshold] are converted to the value Object (=1) and all otherpixelvalues are converted to the value Background (=0).

If objectbrighness = BrightObject then all pixelvalues not in the range [threshold..maximum] are converted to the value Object and all other pixelvalues are converted to the value Background.

Back to Contents

ThresholdRATS, RATS

ThresholdRATS imageName minedge objectbrightness
ThresholdRATSROI imageName roiName minedge objectbrightness
RATS imageName minedge
RATSROI imageName roiName minedge

Class: OrdImage, see
OrdImage.

Menu: Operator | Segmentation

The thresholdrats operator takes a greyscale image andproduces a Binary image

If objectbrighness = DarkObject then all pixelvalues in therange [minimum..threshold] are converted to the value Object (=1) and all otherpixelvalues are converted to the value Background (=0).

If objectbrighness = BrightObject then all pixelvalues not in the range [threshold..maximum] are converted to the value Object and all other pixelvalues are converted to the value Background.

The operator returns the used threshold value and the total strength of the edges.

The rats operator does the same calculation but does not perform the finalthreshold operation.

The ratsroi and thresholdratsroi operators perform the same operation as the counterparts without roi with the exception that the threshold is calculated only using the selectedpixels in the roi.

NOTE: because of the internal calculations that are performed at least Int32Image are necessaryto avoid overflow

Back to Contents

ThresholdRATSLocal, RATSLocal

ThresholdRatsLocal imageName minedge minavgedges nrlevels objectbrightness
RatsLocal imageName maskName minedge minavgedges nrlevels

Class: OrdImage, see
OrdImage.

Menu: Operator | Segmentation

The thresholdratslocal operator takes a greyscale image andproduces a Binary image

If objectbrighness = DarkObject then all pixelvalues in therange [minimum..threshold] are converted to the value Object (=1) and all otherpixelvalues are converted to the value Background (=0).

If objectbrighness = BrightObject then all pixelvalues not in the range [threshold..maximum] are converted to the value Object and all other pixelvalues are converted to the value Background.

The operator returns the total strenght of the edges.

The ratslocal operator does the same calculation but does not perform the finalthreshold operation but returns the image with the mask of the local threshold values..

Implementation restriction: only square images can be used and (height % 2**nrlevels) must be zero.

Examples:

nrlevels 1 2 3 4 5 6 n
nrsquares 4 16 64 256 1024 4096 2**(2*n)
image 256x256:
sqsize 128 64 32 16 8 4 256/(2**n)
image 512x512:
sqsize 256 128 64 32 16 8 512/(2**n)

NOTE: because of the internal calculations that are performed at least Int32Image are necessaryto avoid overflow


Back to Contents

Distance transform

DistanceT srcImage destImage connected

Class: IntImage, see
IntImage.

Menu: Operator | Transform

This operator works on Binary image

Each pixel in an object is assigned a pixel value equal toits (eight or four connected) distance from the nearest background pixel or border of the image.

Possible values for the parameter connected: 'EightConnected' or 'FourConnected'.


Back to Contents

Euclidean distance transform

EuclideanDistanceT srcImage destImage mask result precision ydivx

Class: IntImage, see
IntImage.

Menu: Operator | Transform

This operator works on Binary image

Each pixel in an object is assigned a pixel value equal toits euclidean distance from the nearest background pixel or border of the image.

The parameter mask gives the size of the mask which is used. Possible values'Mask3x3', 'Mask5x5' or 'Mask7x7'.

All distance calculations are done with integer arithmetic. The precisionspecifies the 'base' for the arithmetic.
Example for Int16Images a good value is41, sqrt(2) ~58. Maximum blob height/width <= 1599 pixels

The parameter result indicates whether the the newImage is scaled toreal pixel distances (rounded to nearest integer value) or not. Possible values are 'noscale' or 'scale'.
Note: if not scaled pixel value is the distance * precision.

The parameter ydivx gives the ratio of the pixelsize, = 1 for square pixels.

Implementation restrictions:
- blobs should be at least n pixels distance from the border of the image.
(mask3x3: n=1, mask5x5: n=2, mask7x7: n=3)
- due to propagation algorithm used the operation is sensitive to rotationof the object. Maximum errors: mask3x3 = 7.9%, mask5x5 = 2.5% and mask7x7 = 1.2%.


Back to Contents

Exact Distance transform

ExactDistanceT image precision

Class: IntImage, see
IntImage.

Menu: Operator | Transform

This operator works on Binary image

Each pixel in an object is assigned a pixel value equal toits exact distance from the nearest background pixel or border of the image.

The distances are calculated with floating point precision. The final result for each distance is multiplied with the precision factor (2nd parameter) and converted to an integer value.


Back to Contents

Vector Distance transform

VectorDistanceT srcImage destImage

Class: IntImage, see
IntImage.

Menu: Operator | Transform

This operator works on Binary image

Each pixel in an object is assigned a pixel value equal tothe vector with the smallest distance from the nearest background pixel or border of the image.

The vector is represented as a complex pixel.


Back to Contents

Hough circle transform

FindBestCircle imageName minR maxR deltaR
FindBestCircles imageName minR maxR deltaR nrCircles minDistance minHits

FindFastBestCircle imageName brightness edgeMin minR maxR deltaR
FindFastBestCircles imageName brightness edgeMin minR maxR deltaR nrCircles minDistance minHits

Auxilirary operators in order to study intermediate results:

HoughCircleT srcName destName minR maxR deltaR
FastHoughCircleT srcName destName brightness edgeMin minR maxR deltaR
HTBestCircle srcName minR maxR deltaR
HTBestCircle srcNames minR maxR deltaR nrCircles minDistance minHits

Class: OrdImage, see
OrdImage.

Menu: Operator | Transform

FindBestCircle is intended for a Binary images
FindFastBestCircle is intended for a grayscale images.

The operator searches in the image for the best match for a circle with minimum radius minR and maximum radius maxR and with a resolution of deltaR pixel .

FindFastBestCircle has two extra parameters:
- brightness: determines whether the circle is dark, light or can be both relative to the background.
- edgeMin: the border of the circle is found using the Sharr edge detectionmethod, all edge with a magnitude higher than edgMin are considered as candidate for the circle.
The operators will give as result the following string: (centre co-ordinate) radius numberOfHits.

FindFastBestCircle and FindBestCircles have three extra parameters:
- nrCircles: number of circles to be found
- minDistance: minimum distance in pixles between the circles to be found
- minHits: minimum number of hits for a circle

The operators will give as result the following string: nrofcirclesfound (centre co-ordinate) radius numberOfHits .. (centre co-ordinate) radius numberOfHits

Note for FindFastBestCircle(s): beware of overflow conditions. The result of the scharr edge detectioncalculation easily of a common ByteImage will result in overflow. For most applications a conversion to at least Int16Images is recommended.

Back to Contents

Hough line transform

FindBestLine srcName minR maxR deltaR minPhi maxPhi deltaPhi
FindBestLines srcName minR maxR deltaR minPhi maxPhi deltaPhi nrLines minRDistance minPhiDistance minHits

FindFastBestLine srcName minR maxR deltaR minPhi maxPhi deltaPhi edgeMin
FindFastBestLines srcName minR maxR deltaR minPhi maxPhi deltaPhi edgeMinnrLines minRDistance minPhiDistance minHits


Auxilirary operators in order to study intermediate results:

HoughLineT srcName destName minR maxR deltaR minPhi maxPhi deltaPhi
FastHoughLineT srcName destName minR maxR deltaR minPhi maxPhi deltaPhi edgeMin
HTBestline srcName minR maxR deltaR minPhi maxPhi deltaPhi

Class: OrdImage, see
OrdImage.

Menu: Operator | Transform

FindBestLine(s) is intended for a Binary images
FindFastBestLine(s) is intended for a grayscale images.

This operator searches in the image for the best match for a line.The normal vector of this line is returned as result.

This line is searched for in the area of the image with the following limitations (in polar co-ordinates): r in [minR..maxR] and phi in [minPhi..maxPhi] in degress. Limitation of phi: -pi/2 <= phi <= pi, due to that normal vector can not be in the fourth qwadrant.

The resolution of the search is determined by deltaR and deltaPhi.

FindFastBestLine has an extra parameter:
- edgeMin: the border of the line is found using the Sharr edge detectionmethod, all edge with a magnitude higher than edgMin are considered as candidate for the line.
This operator will give as result the following string:(r,phi) numberOfHits.

FindFastBestLine and FindBestLines have four extra parameters:
- nrLines: number of lines to be found
- minRDistance: minimum distance of radius
- minPhiDistance: minimum distance of phi
- minHits: minimum number of hits for a line

Note: two lines are considered to be different if they are minRDistance or minPhiDistance appart.

The operators will give as result the following string: nrofcirclesfound (centre co-ordinate) radius numberOfHits .. (centre co-ordinate) radius numberOfHits

Note for FindFastBestLine(s): beware of overflow conditions. The result of the scharr edge detectioncalculation easily of a common ByteImage will result in overflow. For most applications a conversion to at least Int16Images is recommended.

Back to Contents

Discrete Fourier transform

DiscreteFourierT imageName Transform direction parameter

Class: ComplexImage, see ComplexImage.

Menu: Operator | Transform

This operator perform the discrete Fourier transformation in the specified direction.

NOTE:
- Works only on square (height = width) images.
- After the forward transform and before the reversed transform a SwapQuadrants operation is performed.The DC component is than visible at the center of the image.
- In order to perform the SwapQuadrants operation the height and the width of the image should be even.

Back to Contents

Fast Fourier transform

FastFourieT imageName Transform direction parameter

Class: ComplexImage, see ComplexImage.

Menu: Operator | Transform

This operator perform the Fast Fourier transformation in the specified direction.

NOTES:
- Works only on square (height = width) images with size of power of two.
- After the forward transform and before the reversed transform a SwapQuadrants operation is performed.The DC component is than visible at the centre of the image.

Back to Contents

Find Calibration points

Camera FindCalPoints imageName nrRows nrCols minPixels maxPixels

Class: IntImage, see
IntImage.

Menu: Camera | Find Calibration points

This operator examines a binary image with imageName in order to find thecalibration points. A fix pattern of circles is expected with nrCols circles verticaland nrRows circles horizontal. Each circle has minimal minPixels and maximal maxPixels.The positions of the calibration pointsare displayed on the screen.

Back to Contents

Camera Calibration

Camera CalibrateGA height width populationsize maxgenerations minError deltaError trace pixelcfile worldcfile gaparamsfile camcalibfile tracefile

Menu: Camera | Camera Calibration

This operator generates a camera calibration file with name camcalibfile foran image with specified height and width using a genetic algorithm (ga).

- height: height of the image
- width: width of the image
- populationsize: size of the population used by the ga
- maxgenerations: maximum number of generations used by the ga
- minError: if this error level is reached the ga stops and returns it results
- microP: probability during self mate that param is a micro mutation
- precision: number of significant numbers for the results
- pixelcoords: the coordinates of the calibration points of the testimage
- worldcoords: the positions of the calibration points in the real world
- calculated: mapping of the pixelcoords to the real worldcoords using the calibration
- trace: number of best parents that will be traced during ga
- tracefile: file with trace information for the ga process

- Camera parameters are:
dx: center-to-center distance of pixels in x direction
dy: center-to-center distance of pixels in y direction]
xp: x-coordinate for principal point, relative to centre of image
yp: y-coordinate for principal point, relative to centre of image
sx: scale factor for timing digitizer
kappa1: first order lens distortion coefficient
kappa2: second order lens distortion coefficient
kappa3: third order lens distortion coefficient
f: camera constant (approximation of focal length)
Rx: rotation around x-axis
Ry: rotation around y-axis
Rz: rotation around z-axis
Tx: translation in x direction
Ty: translation in y direction
Tz: translation in z direction

- Min Max values: upper and lower bound for each camera parameter, those value limit optimalisation proces.

- Mean error: mean error over all calculated pixels
- Max error: maximum error over all calculated pixels


Back to Contents

Options

Menu: Options

With this window the default behaviour of the system is defined.

Image creation: when as result of an operator, a new image is produced,
- 'new': a new window can be created in which the image is displayed.
- 'inplace': the new image is displayed in the current active image window.

Reduce factor: factor by which the images are reduced in size before being displayed.

Print scale: enlarge factor used when an image is printed.

Timer: Vision operations are timed for their duration. Possible values: - 'accumulate':all times for consecutive operations are summed.
- 'single': each operation is timed individual.
Timer can be reset to 0 with server menu: Reset timer

Visionlab.ini: whether the current settings should be saved or not saved atexit of the system.

Synchronise scripts: whether at the end of the execution of scripts the imagesin the client must be synchronised (refreshed) by the server.

Stay on top: For several forms it is possible to specify whether the will stay on top are not. Thedefault value for such forms is specified here.

Precision: number of digits used to display the value of floating point numbers.

Server log: wheter the operations send to the server are logged on the Server lof form. Possible values: 'log' and 'nolog'.

Toolbox: wheter toolbox is displayed or not. Possible values: 'on' and 'off'.

Auto startup script: name of script to start when client is started. <none> for no script.

Default LUT's: used when an image is loaded from file or created by a camera snapshot operation. See also
LUT's

Back to Contents

Scripts introduction

With the use of scripts a user can write his own dedicated commands. Scripts canbe parameterised, can call each other and can be added to the system as anew operator.

It is the convention in the VisionLab system to save scripts with the fileextension .jls or .jlx. Scripts with extension .jlx can be protected by a password.

Scripts can contain different kind of commands:
- variables and expressions
Variables and expressions
- image operators Image operators
- control statements Control statements
- internal commands Internal commands
- special server commands Special server commands
- preprocessor commands Pre-processor commands


There are three different kind of scripts:
- local scripts: script is executed in the client or called with the lCall(X) command from a script executed in the client
- remote file scripts: script is executed in the server. Script is started with a Call(X) <remote fileName> <params> command.
- internal script: script is executed in the server. Before being started with aiCall <internal scriptName> <params> command the script has te be stored in the server.

lCallX and CallX are used for password protected scripts.

Scripts can have parameters. The formel parameters have the form %pn, where n startsat 1. The first parameter is %p1, the next %p2 etc. Arrays can be passed as actual parameters using &$arrayName.

A script can return a function result with the return command.
return <function result>

- lCall <local filename> p1 p2 .... : A call of local script with <local filename> on the client and with maximum of 25 parameters. When the script is finished the command following the call is executed. The script is read from the client.

- lCallX <local filename> <password> p1 p2 .... : A call of local script with <local filename> on the client and with maximum of 25 parameters. When the script is finished the command following the call is executed. The script is read from the client.

- Call <remote filename> p1 p2 .... : A call of script with <remote filename> on the server and with an unlimited number of parameters. When script <name> is finished the command following the call is executed. The script is read from the server.
- CallX <remote filename> <password> p1 p2 .... : A call of script with <remote filename> on the server and with an unlimited number of parameters. When script <name> is finished the command following the call is executed. The script is read from the server.

- iCall <internal scriptName> p1 p2 .... : A call of an internal script on the server and with an unlimited number of parameters. When script <name> is finished the command following the icall is executed.


Scripts can be stored as internal scripts in the server using the commands:
- AddScript <scriptName> <remote fileName>
- AddScriptX <scriptName> <remote fileName> <password>
- lAddScript <scriptName> <local fileName>
- lAddScriptX <scriptName> <local fileName> <password>
- using the store button in the script form

Internal scripts can be examined (downloaded) and modified (uploaded) with the 'Examine internal scripts' item in the server menu.

All names of internal scripts can be retrieved with the command listallscripts. The result is a string.
Internal scripts also can be downloaded with the command getscript <scriptName>. The result is a string.

A local script can be interrupted with the 'Abort scripts' item in the file menu. Note it is not yet possible to interrupt a script running at the server.

Breakpoints can be inserted in local script with the command break (in lower case).

When debugging the Step into button in the script form can be used to step intoa local script called bij the lcall command. It is not possible to step into a scriptexecuted in the server.

A comment line starts with double slash. Example:
// this is a comment line

A command can be written on multiple consequative lines. A '\' before the <cr/lf> can be used to make a long command, example:
this is a command on \
three \
lines

Scripts can be protected against accidently overwriting by setting the protection checkbox.

With the command IsServerScript can be tested whether a script is running on the client side or server side.Function result is true or false.

Back to Contents

Variables and expressions

Variables in scripts are in essence of type string. When neccesary a conversion is applied to type integer, float or boolean.

There are two type of variables:
- global: Scope is all scripts and outside the scripts. Lifetime is from creation tothe moment it is removed explicitly by the user. The name of a global variablestarts with one $ sign, example: $global
- local: scope and lifetime is the script in which the variable is created. The name of a local variable starts with two $ signs, example: $$local


The value of the variables can be examined and modified with the 'Examine vars' item in the server menu.


Aritmetic and boolean expressions are possible, use brackets ( ) for priorities in boolean expressions.
Note: all operators and must seperated by spaces.
Examples:
$r = ($x + $v) * 4
$b = ! ($b1 and (bt[$i] or $b2))

It is not possible to call a function in expressions.

A variable can be initialised with a string using double quotes.
Example:
$s = "here are spaces allowed"

This will also prohibit evaluation, example:
$cg = "(10,15)"


The following operators are supported: + - * / div mod and or ! == != < <= > >= !== === << <<= >> >>=.

+ - * / are dyadic operators, both parameters are interpreted as floating point numbers and the result is a floating point number converted to a string.

div is dyadic operators, both parameters are interpreted as integer numbers and the result is a integer number converted to a string.

mod is a dyadic operator, both parameters are interpreted as an integer and the result (modulus) is an integer converted to a string.

== != < <= > >= are dyadic operators, both parameters are interpreted as floating point numbers and the result is a boolean (true or false) converted to a string.

and or are dyadic operators, both parameters are interpreted as booleans and the result is a boolean (true or false) converted to a string.

! operator as one parameters which is interperted as boolean and the result is a boolean converted to a string.

=== !== << <<= >> >>= are dyadic operators for string comparison, both parameters are interpreted as stringand the result is a boolean (true or false) converted to a string.

. is dyadic operator used for string concatenation.
Note this operator is used for concatenation of chars in a word.
If used as $v . $w, both $v and $w must be non empty variables with one word as value.
Use for concatenation of words the string operator Concat.


Note: some operators require a reference to a variable. This is indicated with <&var>.
Example: &$var instead of $var.


Array's of variable are also possible using [ and ] for indexing.
First index = 0.
Indexes must be either constants, variables or indexed arrays.
Expressions as index are not allowed.
Example of use: $array[$i] = $array[$tab[0]].
$array is a short notation for $array[0].
Operators for manipulation of array's:
- ArrayToVar &$array &$var, convert array to var
- CopyVar &$src &$dest, copy array from src to dest
- ForEach &$array scriptCommand, for each element in array scriptCommand is executed. Before executing scriptCommand, occurrences of '#n' in scriptCommand are substituted by nth word in element of array
- GetSizeArray &$array, result is dimension of array
- InitArray &$array value, set all elements to value
- IsEqualArray &$array1 &$array2, return true if both arrays are equal
- IsSameArray &$array1 &$array2 diff, return true if for all elements fabs(array1[i]-array2[i]) <= diff
- SetSizeArray &$array dimension
- SubArray &$src &$dest pos length, create sub array from $src[pos] .. $src[pos+length-1]
- TestEqualArray &$array1 &$array2, raises an exception if both arrays are not equal
- TestSameArray &$array1 &$array2 diff, raises an exception if not for all elements fabs(array1[i]-array2[i]) <= diff
- VarToArray &$var &$array, convert var to array, each word in var is new element in array, result is size of array
- ArrayToFile <fileName> &$array, write array to file
- ArrayFromFile <fileName> &$array, read array from file
- LArrayToFile <fileName> &$array, write array to local file
- LArrayFromFile <fileName> &$array, read array from local file

Operators for string manipulation on simple variables (not for arrays):

- Find <&str> <key> <offset>, result is first occurence of key (=string) in str searching to left from offset or -1 if key is not found
- FindFirstOf <&str> <key> <offset>, result is first occurence of key (=character) in str searching to left from offset or -1 if key is not found
- FindLastOf <&str> <key> <offset>, result is first occurence of key (=character) in str searching to right from offset or -1 if key is not found
- ListAllVars, result is a list with all variables and their value. Format for each variable on a line: var_name = value
- GetFirstWord <var>, result is first word in var
- GetFirstNWords <n> <var>, result is first n words of var
- GetNthWord <n> <var>, result is nth word in var
- GetNthFromVector <n> <var>, result is nth item from vector list of the form of (i1,i2,i3, ....)
- GetSizeOfVector <var>, result is nummer of elements in vector list of the form of (i1,i2,i3, ....)
- Vector <i1> <i2> <i3> ....., result is the string (i1,i2,i3,...)
- Length <&var>, result is the length of the string
- RemoveFirstWord <&var>, result is first word removed from var, result is removed from var
- RemoveFirstNWords <n> <&var>, result is first n words of var, result is removed from var
- RemoveUntilWord <str> <&var>, words are removed from var until str is found, result is removed from var
- ResetFile <filename>, make file with filename empty
- SubStr <&var> <offset> <count>, result is the substring at offset with length count
- Strip <&var>, all leading and trailing white spaces are removed from var
- Quote <&var>, set string between quotes
- VarFromFile <filename>, read var from file with filename
- VarToFile <filename> <var>, append var to file with filename
- NewLineToFile <filename>, append CR/LF to file
- IsVar <varname without $>, return false or true, test if var is defined, note only for global vars
- GetVar <&var>, result is value of var, alternative: = $var
- IsEqualVar <&var1> <&var2>, return false or true
- IsSameCoord2 <&c1> <&c2> <diff>, return false or true
- IsSameCoord3 <&c1> <&c2> <diff>, return false or true
- IsSameVar <&var1> <&var2> <diff>, return false or true
- RemoveVar <&var>, var is removed from the table with variables and no longer accessable
- RemoveAllVars, all variables are removed
- SetVar <&var> <value>, is equivalent to: $var = value
- TestEqualVar <&var1> <&var2>, raises an exception if vars are not equal
- TestSameCoord2 <&c1> <&c2> <diff>, raises an exception if coordinates are not the same
- TestSameCoord3 <&c1> <&c2> <diff>, raises an exception if coordinates are not the same
- TestSameVar <&var1> <&var2> <diff>, raises an exception if vars are not the same
- Concat <sequence of <var> and text>, result is the macro expansion of the variables and the text
- Coord2DToXYCoord <coord2D> <CConv_LeftTop | CConv_RightTop | CConv_LeftBotom | CConv_RightBotom | CConv_Round>, result conversion to XYCoord


Math operators for number manipulation on variables:
- ASin <x>, inverse of sine x in range [-pi/2..pi/2], x in [-1..1]
- ACos <x>, inverse of cosine x in range [0..pi], x in [-1..1]
- ATan <x>, inverse of tangent x in range [-pi/2..pi/2]
- ATan2 <y><x>, inverse of tangent(y/x) in range [-pi..pi]
- Ceil <x>, smallest integer not less than x
- Cos <x>, cosine x
- Cosh <x>, hyperbolic cosine x
- Exp <x>, e to the power x
- Fabs <x>, absolute value of x
- FloatToInt <x>, convert float to int
- Floor <x>, largest integer not greater than x
- FMod <x><y>, x modulus y (remainder from division)
- InitRandomGen <x>, initialise random generator with seed x
- Log <x>, natural logorithm of x, x > 0
- Log10 <x>, base 10 logorithm of x, x > 0
- Mod <x><y>, x modulus y (remainder from division)
- PolarLinesIntersection <pc1> <pc2>, result Coord2D of intersection of the two lines represented by the polarlines pc1 and pc2
- Pow <x><y>, x to the power y
- Random <low><high>, random float number between low and high
- RandomInt <low><high>, random integer number between low and high
- Round <x>, x is round to the nearest integer value
- Sgn <x>, sign of x, result -1, 0 or 1
- Sin <x>, sine x
- Sinh <x>, hyperbolic sine x
- Sqrt <x>, square root of x, x >= 0
- Tan <x>, tangent x
- Tanh <x>, hyperbolic tangent x


Back to Contents

Internal commands

Internal commands are special local commands for which there is not a (direct) servercommand.

- DisableBreak: break (point) commands are disabled.

- EnableBreak: break (point) commands are enabled (= default).

- changeimagename <oldname> <newname>. Changes imagename from oldname to newname.

- lCWD <path>: change working directory of client to path.

- lPWD: return working directory of client.

- lFileNamesInDir <fileSpec> <&$array>: match fileSpec to filename, result of match is returnedin array, function result is number of matches.
Example to find all *.jl files in current directory:
$nr = lFileNamesInDir *.jl &$tab

- Display <name>: The image with <name> is displayed. If this command is called froma script with is executed from the server (using call) the image is displayed in the clipboard. If this command is called from the GUI client (using lcall) the image is displayed in the GUI.

- Move <name> <top> <left>: The displayed image with <name> is moved on the screen to position <top> <left>. Only to be used in GUI scripts

- CloseImage <name>: image is deleted from server and form is closed

- lResetFile <filename>, make file with filename empty

- lVarFromFile <var> <filename>, read var from file with filename

- lVarToFile <filename> <var>, append var to file with filename

- LArrayToFile <fileName> <&$array>, write array to local file

- LArrayFromFile <fileName> <&$array>, read array from local file

- lLastAnswerToLogFile <filename> <terminator>: answer of last operation is writtento specified logfile. Filename is preprocessed for %xxxx.

- lLastTimeToLogFile <filename> <terminator>: time used for last operation is writtento specified logfile. Filename is preprocessed for %xxxx.

- lTextToLogFile <filename> <text> <terminator>: specified text is writtento specified logfile. Filename and text are preprocessed for %xxxx.

- lRead <imagename> <filename>: The file with <filename> is read on the client and added to the server as image with <imagename>.
Note: both jl and bmp file formats are supported.
Jl format will store the images in the orginal VisionLab image type without any lose of accurracy.
Bmp format will store VisionLab images "as the aredisplayed" in the GUI. So the image is saved as it is displayed with its currentLUT settings (Clip, Stretch, FloatLinear or FloatLog) and it is converted to rgb888image before saving. So there is possible lost of accuracy
It is adviced to use the jl format only.

- lWrite <imagename> <filename>: The image with <imagename> is written on the client as file with <filename>.
Note: both jl and bmp file formats are supported.
Jl format will store the images in the orginal VisionLab image type without any lose of accurracy.
Bmp format will store VisionLab images "as the aredisplayed" in the GUI. So the image is saved as it is displayed with its currentLUT settings (Clip, Stretch, FloatLinear or FloatLog) and it is converted to rgb888image before saving. So there is possible lost of accuracy
It is adviced to use the jl format only.

- Synchronise: synchronise the server and the client by redisplaying allimages and updating the variable form

- SyncImages: synchronise the server and the client by redisplaying allimages

- SyncVars: synchronise the server and the client by updating the variable form


- GUIForm <caption> {<spinedit> | <editbox>} displays a dynamic form from a script in order to query the user with inputs, result is a string with the answers .
- spinedit <prompt> <default> <low> <high>: A spinedit field is added to the form with a prompt and a default value. Low and high specify the extreme possible values.
- editbox <prompt> <default>: An editfield is added to the form with a prompt and a default value.
example:
GUIForm caption editbox prompt_e 1 spinedit prompt_s 1 0 10

Back to Contents

Special server commands

- CWD <path>: change working directory of server to path.

- FileNamesInDir <fileSpec> <&$array>: match fileSpec to filename, result of match is returnedin array, function result is number of matches.
Example to find all *.jl files in current directory:
$nr = lFileNamesInDir *.jl &$tab

- GetConnected <imagename> : connectivity of image

- GetHeight <imagename> : height of image

- GetHistory <imagename> : history of image

- GetLUT <imagename> : set lut for image. See for luts:
Displaying of greyscale images (LUTs).

- GetPixel <imagename> <x> <y>

- GetPrecision : number of digits for display floating point nrs

- GetProcessPriority: process priority

- GetWidth <imagename> : width of image

- PWD: return working directory of server.

- Read <imagename> <filename>: The file with <filename> is read on the server and added to the server as image with <imagename>.

- Read_BMP <imagename> <filename>: The .bmp file with <filename> is read on the server and added to the server as RGB888Image with <imagename>.
Note: not all sub-types of the bmp are supported. Files writen to file with write_bmp are supported.

- Read_PNG <imagename> <filename>: The .png file with <filename> is read on the server and added to the server with <imagename>.
Note: not all sub-types of the png are supported. Files writen to file with write_png are supported.

- SetConnected <imagename> <connected> : set connectivity of image

- SetDefaultLUT <imagetype> <lut>: Set lut for imagetype. See for luts: Displaying of greyscale images (LUTs).

- SetLUT <imagename> <lut>: Set lut for image. See for luts: Displaying of greyscale images (LUTs).

- SetPixel <imagename> <x> <y> <value>

- SetProcessPriority <priority>: process priority

- SetPrecision <precision>: number of digits for display floating point nrs

- Snapshot <cameraName> <imageType> <roiNr> <imagename>: The camera takes a snapshot of specified roi with imagename.

- SnapshotROIs <cameraName> <imageType> <imagename> .... <imagename>: The camera takes a snapshot off all rois with specified imagenames.

- System <system cmd>: execute system command in system shell.

- TestEqual <image1> <image2>: The images are compared for equalness. If theyare equal the next line is executed. If they are not equal executing isinterrupted and a message is displayed on the client.

- TestLastAnswer <multi-line text, terminated with the word endanswer on thebeginning of a new line>: The last answer given by server on a server commandsis compared with the multi-line text. If theyare equal the next line is executed. If they are not equal executing isinterrupted and a message is displayed on the client.

- Write <imagename> <filename>: The image with <imagename> is written on the server as file with <filename>.

- Write_BMP <imagename> <filename>: The image with <imagename> is converted to RGB888Image and written on the server as .bmp file with <filename>.

- Write_PNG <imagename> <filename>: The image with <imagename> is written on the server as .png file with <filename>.


Date and time commands, can be found in the system menu:

- GetLastTime: returns time in us for last operation

- Time: returns <day> <month> <dayInMonth> <hh:mm:ss> <year>

- Delay <secs>: delay operations for secs seconds time.

- MicroDelay <us>: delay operations for us micro-seconds time.

- MilliDelay <ms>: delay operations for ms milli-seconds time.

- ResetTimeStamp: reset time stamp counter to zero

- MicroTimeStamp: return a time stamp in micro seconds, note: maximum time for overflow after reset is 35 minutes.

- MilliTimeStamp: return a time stamp in mille seconds, note: maximum time for overflow after reset is 583 hours.

- WaitMicroTimeStamp <micro time stamp>: spin lock until time stamp in micro seconds, note: maximum time for overflow after reset is 35 minutes.

- WaitMilliTimeStamp <milli time stamp>: spin lock until time stamp in milli seconds, note: maximum time for overflow after reset is 583 hours.


Back to Contents

Pre-processor commands

A command is pre-processed before it is executed. The following pre-processorcommands are only available in the client:

- %currentimage: this command is replaced with the name of the current selectedimage or the name of the image selected as script image. See also
Select script image

- %secondimage: this command is replaced with the name of the image selected assecond image. See also Select 2nd and 3rd

- %thirdimage: this command is replaced with the name of the image selected asthird image. See also Select 2nd and 3rd

- %startupdir: directory name from which the client has been launched


Back to Contents

Adding a script as new operator

New operators can be added to the system by editing the file visionlab.ini.See for more details Adding a new operator to the client

Example:
An operator with the name Script must be added to the usermenu. When the operator isselected the script with name test.jls is to be executed and it will receivethree parameters.
In order to make this possible add the following lines to the file visionlab.iniand startup the system.

[examplescript]
menu=UserMenu
caption=Example &Script
class=IntImage
script=test.jls
paramform=scriptparam
selectedimage source
editbox low 0
editbox high 80


Explanation:

[examplescript]: In [] the name of the operator. Note: no white space behind ] is allowed.

menu: The menu where the operator is added to the system.

caption: The name used for the operator in the menu. The & give the letter forthe shortkey.

class: The highest class in the class hierachy

script: The filename of the script which is to be executed.

paramform: Specifies the form which to be used to ask the user for theparameters. Currently for user scripts only 'scriptparam' is supported.

The section following paramform specifies the parameters for the operator.The maximal number of parameters is 25. The parameters are displayed and sent tothe server in the same order as they are declared.There are the following possibilities:

- selectedimage <prompt>: An editfield is added with a prompt
and the image name of the currently selected image.


- 2ndselected <prompt>: An editfield is added with a prompt
and the image name of the 2ndselected image.


- 3rdselected <prompt>: An editfield is added with a prompt
and the image name of the 3rdselected image.


- genimagename <prompt>: An edit field is added with a prompt
and a generated image name.


- spinedit <prompt> <default> <low> <high>: A spinedit field is added
with a prompt and a default value. Low and high specify the
extreme possible values.

- editbox <prompt> <default>: An editfield is added with a prompt
and a default value.

- combobox <prompt> <default> <item1> ... <itemN>: A combo box is
added with a prompt and a default value. The combobox is filled
with the specified items. If prompt equals to 'none' combobox
is invisible.

Back to Contents

Adding a new operator to the client

New operators can be added to the client by editing the file visionlab.ini. Thenew operators will be active the next time the system is started.

The descriptor for an operator with name opnew looks like:

[opnew]
menu=Usermenu
caption=&opnew
class=IntImage
shortcut=ctrl+a
command=opnew
source=original
result=image
paramform=varparam
selectedimage source
genimagename destination
spinedit low 0 -10000 10000
editbox name 1
combobox name second first second third


[opnew]: In [] the name of the operator. Note: no white space behind ] is allowed.

menu: The menu where the operator is added to the system.

caption: The name used for the operator in the menu. The & give the letter forthe shortkey.

class: The highest class in the
class hierarchy

shortcut: The name for a key on the keyboard, which can activate the operatorwithout using the menu. Possible values: none, ctrl+a, .. ctrl+z, f1, .. f12,ctrl+f1, .. ctrl+f12, shift+f1, .. shift+f12, shift+ctrl+f1, .. shift+ctrl+f12,ins, shift+ins, ctrl+ins, del, shift+del, ctrl+del, alt+bksp and shift+alt+bksp.

command: The command name which is sent to the server.

source: Specifies on which image operation is performed, possible values:
- original: operation is performed on the source image.
- copy: operation is performed on a copy of the original, the name of the copyis either specified by a imagename parameter (see below: description ofparamform) or generated by the system.
- none: operation is not performed on an image.

result: Determines how the result of the operation is to be displayed.Possible values:
- image: The image (= first parameter) on which the operation was performed is displayed.
- 2ndimage: The image specified as second parameter in the parameter list
of the server command is displayed.
- 3rdimage: The image specified as third parameter in the parameter list
of the server command is displayed.
- 4thimage: The image specified as fourthparameter in the parameter list
of the server command is displayed.
- 2nd3rdimage: The images specified as second and third parameter in the parameter list
of the server command are displayed.
- 2nd3rd4thimage: The images specified as second, third and fourth parameter in the parameter list
of the server command are displayed.
- bothimages: image and 2ndimage are displayed, see above.
- box: As result a string with the format '(x1,y1) (x2,y2)' is expected
from the server. A box with lefttop (x1,y1) and rightbottom (x2,y2)
is drawn in the current active image.
- circle: As result a string with the format '(x,y) r h' is expected from
the server. A circle with centre (x,y) and radius r is drawn in the
current active image. h is the number of hits.
- circles: As result a string with the format 'n (x,y) r h ... (x,y) r h' is expected from
the server. N circles with centres (x,y) and radius r are drawn in the
current active image.
- line: As result a string with the format '(x1,y1) (x2,y2) is expected
from the server. A line from (x1,y1) to (x2,y2) is drawn in the
current active image.
- polarline: As result a string with the format '(r,phi) h' is expected
from the server. A line with polarcoordinates is drawn in the
current active image. h is the number of hits.
- polarlines: As result a string with the format 'n (r,phi) h ... (r,phi) h is expected
from the server. N lines with polarcoordinates is drawn in the
current active image. h is the number of hits.
- string: As result a string is expected from the server which is
displayed in the info bar.
- stringlist: As result a list of strings (lines of string seperated by cr/lf) is expected from the
server which is displayed in a window.
- nothing: Nothing is displayed.

paramform: Specifies the form which to be used to ask the user for theparameters. Currently for user C++ operators only 'varparam' is supported.

The section following paramform specifies the parameters for the operator.The maximal number of parameters is 25. The parameters are displayed and sent tothe server in the same order as they are declared.There are the following possibilities:

- selectedimage <prompt>: An editfield is added with a prompt
and the image name of the currently selected image.

- 2ndselected <prompt>: An editfield is added with a prompt
and the image name of the 2ndselected image.

- 3rdselected <prompt>: An editfield is added with a prompt
and the image name of the 3rdselected image.

- genimagename <prompt>: An editfield is added with a prompt
and a generated image name.

- spinedit <prompt> <default> <low> <high>: A spinedit field is added
with a prompt and a default value. Low and high specify the
extreme possible values.

- editbox <prompt> <default>: An editfield is added with a prompt
and a default value.

- combobox <prompt> <default> <item1> ... <itemN>: A combo box is
added with a prompt and a default value. The combobox is filled
with the specified items.

- checklistbox <prompt> <defaults> <|> <item1> ... <itemN>: A
checklistbox is added with a prompt and default check values.
The listbox is filled with the specified items.
NOTE: this parameter can ONLY be used as the last parameter of
a command.

Back to Contents

image.h

/* File : image.h
* Project : visionlib V3.0
* Author : Jaap van de Loosdrecht
* Van de Loosdrecht Machine Vision BV
* www.vdlmv.nl
* Date : 13-1-2010
*
* Copyright (c) 1993-2017, Van de Loosdrecht Machine Vision BV,
* all rights reserved.
*/

#ifndef JL_VISIONLIB_IMAGE
#define JL_VISIONLIB_IMAGE


#include "coord.h"
#include <string>
#include <stdexcept>
#include <iostream>

namespace JL_VisionLib_V3 {

int InitVisionLib (void); // must be called before using any lib function
void FreeVisionLib (void); // free all memory used, last call before exit program

class Image; // forward declaration
class ImageCreator { // factory method for image creation
public:
virtual Image* CreateImage (const std::string typeName,
const int height, const int width) const;
}; // ImageCreator

class Error: public std::exception {
public:
Error (const std::string& msg);
Error (const std::string& opName, const std::string& msg);
virtual const char *what() const throw();
virtual ~Error() throw() {}
protected:
std::string msg;
};

struct HeightWidth {
HeightWidth (const int h = 0, const int w = 0) { height = h; width = w; }
int height;
int width;
bool operator == (const HeightWidth &hw) const {
return ((hw.height == height) && (hw.width == width));
}
bool operator != (const HeightWidth &hw) const {return !(operator==(hw));}
};

enum IOType {BinIO, AsciiIO};

class Image {
public:
virtual ~Image ();
virtual void Clear () = 0;
virtual Image* Clone (const bool copyOrg = true) const = 0;
virtual void ReadAsciiFromStream (std::istream& is) = 0;
virtual void WriteAsciiToStream (std::ostream& os) const = 0;
virtual void ReadBinFromStream (std::istream& is) = 0;
virtual void WriteBinToStream (std::ostream& os) const = 0;
virtual void Resize (const HeightWidth &hw) = 0;
int GetWidth () const { return width; }
int GetHeight () const { return height; }
HeightWidth GetHeightWidth () const { return HeightWidth(height,width); }
int GetImageSize () const { return imageSize; }
int GetNrPixels () const { return nrPixels; }
void* GetBufPtr() const { return bufPtr; }
virtual void SetBuf (const char *buf, const int height, const int width, const bool deleteOrg = true) = 0;
int GetBytesPerLine() const { return bytesPerLine; }

void WriteToFile (const std::string &fileName, const IOType io = BinIO) const;
static Image* ReadFromFile (const std::string &fileName, const IOType io = BinIO);
void WriteToStream (std::ostream& os, const IOType io = BinIO) const;
static Image* ReadFromStream (std::istream& is, const IOType io = BinIO);

static void ReplaceImageCreator (ImageCreator *creator);

protected:
Image ();
static ImageCreator* imageCreator;
int height;
int width;
int bytesPerLine;
int imageSize;
int nrPixels;
void* bufPtr;
}; // Image

bool CheckImage (const Image &image);
bool CheckHeightWidth (const Image &image1, const Image &image2);
bool CheckHeightWidth (const Image &image, const int height, const int width);
bool CheckHeightWidth (const Image &image, const HeightWidth &hw);
bool CheckXYCoordInImage (const Image &image, const XYCoord &xy);
bool CheckCoord2DInImage (const Image &image, const Coord2D &xy);
inline bool SameImage (const Image &image1, const Image &image2) { return (image1.GetBufPtr() == image2.GetBufPtr()); }

std::string IOTypeToStr (const IOType b);
IOType StrToIOType(const std::string &str);
std::istream& operator>> (std::istream& is, IOType &b);
std::ostream& operator<< (std::ostream& os, const IOType b);

} // namespace JL_VisionLib_V3


#endif



Back to Contents

numimage.h

/* File : numimage.h
* Project : visionlib V3.0
* Author : Jaap van de Loosdrecht
* Van de Loosdrecht Machine Vision BV
* www.vdlmv.nl
* Date : 26-8-2010
*
* Copyright (c) 1993-2017, Van de Loosdrecht Machine Vision BV,
* all rights reserved.
*/

#ifndef JL_VIS_LIB_NUMBER_IMAGE
#define JL_VIS_LIB_NUMBER_IMAGE

#include "image.h"
#include <vector>

namespace JL_VisionLib_V3 {

template<class Pixel> class NumImage : public Image {
public:
typedef Pixel PixelType;
typedef std::vector<PixelType *> PixelQ;
NumImage ();
NumImage (const int height, const int width);
NumImage (const HeightWidth &hw);
NumImage (const NumImage &image);
~NumImage ();
virtual void Clear ();
void SetBuf (const char *buf, const int height, const int width, const bool deleteOrg = true);
virtual void Resize (const HeightWidth &hw);
virtual void Resize (const HeightWidth &hw, const NumImage &properties);
virtual NumImage<Pixel>* Clone (const bool copyOrg = true) const;
virtual void ReadAsciiFromStream (std::istream& is);
virtual void WriteAsciiToStream (std::ostream& os) const;
virtual void ReadBinFromStream (std::istream& is);
virtual void WriteBinToStream (std::ostream& os) const;

void ReadFromFile (const std::string fileName, const IOType io = BinIO);
void ReadFromStream (std::istream& is, const IOType io = BinIO);

Pixel* GetFirstPixelPtr () const { return firstPixelPtr; }
Pixel* GetLastPixelPtr () const { return lastPixelPtr; }

NumImage& operator = (const NumImage &image);
NumImage& operator = (const Pixel pixel);
bool operator == (const NumImage &image) const;
bool operator != (const NumImage &image) const;
Pixel& operator () (const int x, const int y) const {
return *(firstPixelPtr + (y * width) + x); }
Pixel& operator () (const XYCoord xy) const {
return *(firstPixelPtr + (xy.y * width) + xy.x); }
bool CheckCoord (const int x, const int y) const {
return ((x >= 0) && (x < width) && (y >= 0) && (y < height)); }
bool CheckCoord (const XYCoord xy) const {
return ((xy.x >= 0) && (xy.x < width) && (xy.y >= 0) && (xy.y < height)); }
Pixel* GetPixelPtr (const int x, const int y) const {
return (firstPixelPtr + (y * width) + x); }
Pixel* GetPixelPtr (const XYCoord xy) const {
return (firstPixelPtr + (xy.y * width) + xy.x); }
XYCoord GetXYCoord (const Pixel *ptr) const {
int d = ptr - firstPixelPtr;
return XYCoord(d % width, d / width); }
void SetPixel (const int x, const int y, const Pixel value) {
if ((x >= 0) && (x < width) && (y >= 0) && (y < height)) {
*(firstPixelPtr + (y * width) + x) = value;
}}
protected:
bool hostToNetworkConv;
private:
void InitForNewImage (const int height, const int width);
Pixel* firstPixelPtr;
Pixel* lastPixelPtr;
}; // NumImage

// note: low level operations, operation only the pixels
// for reading: first set height and width to the correct values
template<class Pixel>
std::istream& operator>> (std::istream& is, NumImage<Pixel> &image);
template<class Pixel>
std::ostream& operator<< (std::ostream& os, const NumImage<Pixel> &image);

} // namespace JL_VisionLib_V3

#endif



Back to Contents

rgb888im.h

/* File : rgbimage.h
* Project : visionlib V3.0
* Author : Jaap van de Loosdrecht
* Van de Loosdrecht Machine Vision BV
* www.vdlmv.nl
* Date : 7-2-2009
*
* Copyright (c) 1993-2017, Van de Loosdrecht Machine Vision BV,
* all rights reserved.
*/

#ifndef JL_VIS_LIB_RGB_IMAGE
#define JL_VIS_LIB_RGB_IMAGE

#include "word.h"
#include "colorima.h"
#include "util.h"

namespace JL_VisionLib_V3 {

enum RGBColor {Red, Green, Blue, NrOfRGBColors};

class RGB888Pixel {
public:
typedef JL_Word::Byte ColorType;
explicit RGB888Pixel (const int v = 0) {
red = green = blue = JL_Util::ClipByte(v); pad = 0;
}
RGB888Pixel (const JL_Word::Byte r, const JL_Word::Byte g, const JL_Word::Byte b) {
red = r; green = g; blue = b; pad = 0;
}
bool operator == (const RGB888Pixel p) const {
return ((red == p.red) && (green == p.green) && (blue == p.blue));
}
bool operator != (const RGB888Pixel p) const {
return !(operator==(p));
}
RGB888Pixel& operator += (const RGB888Pixel p) {
red = JL_Util::ClipByte (int(red) + int(p.red));
green = JL_Util::ClipByte (int(green) + int(p.green));
blue = JL_Util::ClipByte (int(blue) + int(p.blue));
return *this;
}
RGB888Pixel& operator -= (const RGB888Pixel p) {
red = JL_Util::ClipByte (int(red) - int(p.red));
green = JL_Util::ClipByte (int(green) - int(p.green));
blue = JL_Util::ClipByte (int(blue) - int(p.blue));
return *this;
}
RGB888Pixel& operator *= (const RGB888Pixel p) {
red = JL_Util::ClipByte (int(red) * int(p.red));
green = JL_Util::ClipByte (int(green) * int(p.green));
blue = JL_Util::ClipByte (int(blue) * int(p.blue));
return *this;
}
RGB888Pixel& operator /= (const RGB888Pixel p) {
red = JL_Util::ClipByte (int(red) / int(p.red));
green = JL_Util::ClipByte (int(green) / int(p.green));
blue = JL_Util::ClipByte (int(blue) / int(p.blue));
return *this;
}
RGB888Pixel operator + (const RGB888Pixel p) const {
return (RGB888Pixel(*this) += p);
}
RGB888Pixel operator - (const RGB888Pixel p) const {
return (RGB888Pixel(*this) -= p);
}
RGB888Pixel operator * (const RGB888Pixel p) const {
return (RGB888Pixel(*this) *= p);
}
RGB888Pixel operator / (const RGB888Pixel p) const {
return (RGB888Pixel(*this) /= p);
}

static const int colOffTab[3]; // = {0, 1, 2}; // offsets within RGBValue for RGBColors;
static const JL_Word::Byte MAXValue; // = 255;

#ifdef __BIG_ENDIAN__
JL_Word::Byte pad;
JL_Word::Byte red; // big endian
JL_Word::Byte green;
JL_Word::Byte blue;
#else
JL_Word::Byte blue; // MS Windows compatible and alligned to longs!!
JL_Word::Byte green;
JL_Word::Byte red;
JL_Word::Byte pad;
#endif
};

class RGB161616Pixel {
public:
typedef JL_Word::Int16 ColorType;
explicit RGB161616Pixel (const int v = 0) {
red = green = blue = v;
}
RGB161616Pixel (const JL_Word::Int16 r, const JL_Word::Int16 g, const JL_Word::Int16 b) {
red = r; green = g; blue = b;
}
RGB161616Pixel (const RGB888Pixel &pixel) {
red = pixel.red; green = pixel.green; blue = pixel.blue;
}
bool operator == (const RGB161616Pixel p) const {
return ((red == p.red) && (green == p.green) && (blue == p.blue));
}
bool operator != (const RGB161616Pixel p) const {
return !(operator==(p));
}
RGB161616Pixel& operator += (const RGB161616Pixel p) {
red = red + p.red;
green = green + p.green;
blue = blue + p.blue;
return *this;
}
RGB161616Pixel& operator -= (const RGB161616Pixel p) {
red = red - p.red;
green = green - p.green;
blue = blue - p.blue;
return *this;
}
RGB161616Pixel& operator *= (const RGB161616Pixel p) {
red = red * p.red;
green = green * p.green;
blue = blue * p.blue;
return *this;
}
RGB161616Pixel& operator /= (const RGB161616Pixel p) {
red = red / p.red;
green = green / p.green;
blue = blue / p.blue;
return *this;
}
RGB161616Pixel operator + (const RGB161616Pixel p) const {
return (RGB161616Pixel(*this) += p);
}
RGB161616Pixel operator - (const RGB161616Pixel p) const {
return (RGB161616Pixel(*this) -= p);
}
RGB161616Pixel operator * (const RGB161616Pixel p) const {
return (RGB161616Pixel(*this) *= p);
}
RGB161616Pixel operator / (const RGB161616Pixel p) const {
return (RGB161616Pixel(*this) /= p);
}

static const int colOffTab[3]; // = {0, 1, 2}; // offsets within RGBValue for RGBColors;

JL_Word::Int16 blue;
JL_Word::Int16 green;
JL_Word::Int16 red;
};

// [Sangwine] p. 72
inline int ConvertRGB888PixelToInt (const RGB888Pixel &rgb) {
return (((30 * rgb.red) + (59 * rgb.green) + (11 * rgb.blue) + 50) / 100);
}

inline RGB888Pixel ConvertIntToRGB888Pixel (const int i) {
return RGB888Pixel(i);
}

// [Sangwine] p. 72
inline int ConvertRGB161616PixelToInt (const RGB161616Pixel &rgb) {
return (((30 * rgb.red) + (59 * rgb.green) + (11 * rgb.blue) + 50) / 100);
}

inline RGB161616Pixel ConvertIntToRGB161616Pixel (const int i) {
return RGB161616Pixel(i);
}

inline RGB161616Pixel ConvertRGB888PixelTo161616 (const RGB888Pixel &pixel) {
return RGB161616Pixel(pixel);
}

inline RGB888Pixel ConvertRGB161616PixelTo888 (const RGB161616Pixel &pixel) {
return RGB888Pixel(pixel.red, pixel.green, pixel.blue);
}

typedef ColorImage<RGB888Pixel> RGB888Image;
typedef ColorImage<RGB161616Pixel> RGB161616Image;

std::string RGB888PixelToStr (const RGB888Pixel p);
RGB888Pixel StrToRGB888Pixel(const std::string &str);
std::ostream& operator << (std::ostream& os, const RGB888Pixel pixel);
std::istream& operator >> (std::istream& is, RGB888Pixel& pixel);

std::string RGB161616PixelToStr (const RGB161616Pixel p);
RGB161616Pixel StrToRGB161616Pixel(const std::string &str);
std::ostream& operator << (std::ostream& os, const RGB161616Pixel pixel);
std::istream& operator >> (std::istream& is, RGB161616Pixel& pixel);

std::string RGBColorToStr (const RGBColor col);
RGBColor StrToRGBColor(const std::string &str);
std::istream& operator>> (std::istream& is, RGBColor &col);
std::ostream& operator<< (std::ostream& os, const RGBColor col);

}// namespace JL_VisionLib_V3


#endif



Back to Contents

hsv888im.h

/* File : hsvimage.h
* Project : visionlib V3.0
* Author : Jaap van de Loosdrecht
* Van de Loosdrecht Machine Vision BV
* www.vdlmv.nl
* Date : 21-11-2013
*
* Copyright (c) 1993-2017, Van de Loosdrecht Machine Vision BV,
* all rights reserved.
*/

#ifndef JL_VIS_LIB_HSV_IMAGE
#define JL_VIS_LIB_HSV_IMAGE

#include "word.h"
#include "colorima.h"
#include "util.h"

namespace JL_VisionLib_V3 {

enum HSVColor {Hue, Saturation, Value, NrOfHSVColors};

class HSV888Pixel {
public:
typedef JL_Word::Byte ColorType;
explicit HSV888Pixel (const int v = 0) {
hue = JL_Util::ModuloByte(v); // can not be 0, due to / Pixel(1)
saturation = JL_Util::ClipByte(v);
value = JL_Util::ClipByte(v);
pad = 0;
}
HSV888Pixel (const JL_Word::Byte h, const JL_Word::Byte s, const JL_Word::Byte i) {
hue = h; saturation = s; value = i; pad = 0;
}
bool operator == (const HSV888Pixel p) const {
return ((hue == p.hue) && (saturation == p.saturation) && (value == p.value));
}
bool operator != (const HSV888Pixel p) const {
return !(operator==(p));
}
HSV888Pixel& operator += (const HSV888Pixel p) {
hue = JL_Util::ModuloByte (int(hue) + int(p.hue));
saturation = JL_Util::ClipByte (int(saturation) + int(p.saturation));
value = JL_Util::ClipByte (int(value) + int(p.value));
return *this;
}
HSV888Pixel& operator -= (const HSV888Pixel p) {
hue = JL_Util::ModuloByte (int(hue) - int(p.hue));
saturation = JL_Util::ClipByte (int(saturation) - int(p.saturation));
value = JL_Util::ClipByte (int(value) - int(p.value));
return *this;
}
HSV888Pixel& operator *= (const HSV888Pixel p) {
hue = JL_Util::ModuloByte (int(hue) * int(p.hue));
saturation = JL_Util::ClipByte (int(saturation) * int(p.saturation));
value = JL_Util::ClipByte (int(value) * int(p.value));
return *this;
}
HSV888Pixel& operator /= (const HSV888Pixel p) {
hue = JL_Util::ModuloByte (int(hue) / int(p.hue));
saturation = JL_Util::ClipByte (int(saturation) / int(p.saturation));
value = JL_Util::ClipByte (int(value) / int(p.value));
return *this;
}
HSV888Pixel operator + (const HSV888Pixel p) const {
return (HSV888Pixel(*this) += p);
}
HSV888Pixel operator - (const HSV888Pixel p) const {
return (HSV888Pixel(*this) -= p);
}
HSV888Pixel operator * (const HSV888Pixel p) const {
return (HSV888Pixel(*this) *= p);
}
HSV888Pixel operator / (const HSV888Pixel p) const {
return (HSV888Pixel(*this) /= p);
}

static const int colOffTab[3]; // = {0, 1, 2}; // offsets within HSVValue for HSVColors;
static const JL_Word::Byte MAXValue; // = 255;

#ifdef __BIG_ENDIAN__
JL_Word::Byte pad;
JL_Word::Byte hue;
JL_Word::Byte saturation;
JL_Word::Byte value;
#else
JL_Word::Byte value;
JL_Word::Byte saturation;
JL_Word::Byte hue;
JL_Word::Byte pad;
#endif
}; // HSV888Pixel


#undef max
const JL_Word::Int16 MaxHue16 = numeric_limits<JL_Word::Int16>::max();
const JL_Word::Int16 MaxSaturation16 = numeric_limits<JL_Word::Int16>::max();
inline JL_Word::Int16 ModuloHue16 (const int value) {
return JL_Word::Int16(value % MaxHue16);
} // JL_Word::Int16

class HSV161616Pixel {
public:
typedef JL_Word::Int16 ColorType;
explicit HSV161616Pixel (const int v = 0) {
hue = ModuloHue16(v);
saturation = v;
value = v;
}
HSV161616Pixel (const JL_Word::Int16 h, const JL_Word::Int16 s, const JL_Word::Int16 i) {
hue = h; saturation = s; value = i;
}
HSV161616Pixel (const HSV888Pixel &pixel) {
hue = pixel.hue * (MaxHue16 / 255); saturation = pixel.saturation * (MaxSaturation16 / 255); value = pixel.value;
}
bool operator == (const HSV161616Pixel p) const {
return ((hue == p.hue) && (saturation == p.saturation) && (value == p.value));
}
bool operator != (const HSV161616Pixel p) const {
return !(operator==(p));
}
HSV161616Pixel& operator += (const HSV161616Pixel p) {
hue = ModuloHue16(hue + p.hue);
saturation = saturation + p.saturation;
value = value + p.value;
return *this;
}
HSV161616Pixel& operator -= (const HSV161616Pixel p) {
hue = ModuloHue16(hue - p.hue);
saturation = saturation - p.saturation;
value = value - p.value;
return *this;
}
HSV161616Pixel& operator *= (const HSV161616Pixel p) {
hue = ModuloHue16(hue * p.hue);
saturation = saturation * p.saturation;
value = value * p.value;
return *this;
}
HSV161616Pixel& operator /= (const HSV161616Pixel p) {
hue = ModuloHue16(hue / p.hue);
saturation = saturation / p.saturation;
value = value / p.value;
return *this;
}
HSV161616Pixel operator + (const HSV161616Pixel p) const {
return (HSV161616Pixel(*this) += p);
}
HSV161616Pixel operator - (const HSV161616Pixel p) const {
return (HSV161616Pixel(*this) -= p);
}
HSV161616Pixel operator * (const HSV161616Pixel p) const {
return (HSV161616Pixel(*this) *= p);
}
HSV161616Pixel operator / (const HSV161616Pixel p) const {
return (HSV161616Pixel(*this) /= p);
}

static const int colOffTab[3]; // = {0, 1, 2}; // offsets within HSVValue for HSVColors;
static const JL_Word::Int16 MAXValue; // = MaxHue16;

JL_Word::Int16 value;
JL_Word::Int16 saturation;
JL_Word::Int16 hue;
}; // HSV161616Pixel

int ConvertHSV888PixelToInt (const HSV888Pixel &pixel);
HSV888Pixel ConvertIntToHSV888Pixel (const int i);

int ConvertHSV161616PixelToInt (const HSV161616Pixel &pixel);
HSV161616Pixel ConvertIntToHSV161616Pixel (const int i);

inline HSV161616Pixel ConvertHSV888PixelTo161616 (const HSV888Pixel &pixel) {
return HSV161616Pixel(pixel);
}
inline HSV888Pixel ConvertHSV161616PixelTo888 (const HSV161616Pixel &pixel) {
return HSV888Pixel(pixel.hue / (MaxHue16 / 255), pixel.saturation / (MaxSaturation16 / 255), pixel.value);
}

typedef ColorImage<HSV888Pixel> HSV888Image;
typedef ColorImage<HSV161616Pixel> HSV161616Image;

std::string HSV888PixelToStr (const HSV888Pixel p);
HSV888Pixel StrToHSV888Pixel(const std::string &str);
std::ostream& operator << (std::ostream& os, const HSV888Pixel pixel);
std::istream& operator >> (std::istream& is, HSV888Pixel& pixel);

std::string HSV161616PixelToStr (const HSV161616Pixel p);
HSV161616Pixel StrToHSV161616Pixel(const std::string &str);
std::ostream& operator << (std::ostream& os, const HSV161616Pixel pixel);
std::istream& operator >> (std::istream& is, HSV161616Pixel& pixel);

std::string HSVColorToStr (const HSVColor col);
HSVColor StrToHSVColor(const std::string &str);
std::istream& operator>> (std::istream& is, HSVColor &col);
std::ostream& operator<< (std::ostream& os, const HSVColor col);

}// namespace JL_VisionLib_V3


#endif



Back to Contents

yuv888im.h

/* File : YUVimage.h
* Project : visionlib V3.0
* Author : Jaap van de Loosdrecht
* Van de Loosdrecht Machine Vision BV
* www.vdlmv.nl
* Date : 7-2-2009
*
* Copyright (c) 1993-2017, Van de Loosdrecht Machine Vision BV,
* all rights reserved.
*/

#ifndef JL_VIS_LIB_YUV_IMAGE
#define JL_VIS_LIB_YUV_IMAGE

#include "word.h"
#include "colorima.h"
#include "util.h"

namespace JL_VisionLib_V3 {

enum YUVColor {Y, U, V, NrOfYUVColors};

class YUV888Pixel {
public:
typedef JL_Word::Byte ColorType;
explicit YUV888Pixel (const int value = 0) {
y = u = v = JL_Util::ClipByte(value); pad = 0;
}
YUV888Pixel (const JL_Word::Byte r, const JL_Word::Byte g, const JL_Word::Byte b) {
y = r; u = g; v = b; pad = 0;
}
bool operator == (const YUV888Pixel p) const {
return ((y == p.y) && (u == p.u) && (v == p.v));
}
bool operator != (const YUV888Pixel p) const {
return !(operator==(p));
}
YUV888Pixel& operator += (const YUV888Pixel p) {
y = JL_Util::ClipByte (int(y) + int(p.y));
u = JL_Util::ClipByte (int(u) + int(p.u));
v = JL_Util::ClipByte (int(v) + int(p.v));
return *this;
}
YUV888Pixel& operator -= (const YUV888Pixel p) {
y = JL_Util::ClipByte (int(y) - int(p.y));
u = JL_Util::ClipByte (int(u) - int(p.u));
v = JL_Util::ClipByte (int(v) - int(p.v));
return *this;
}
YUV888Pixel& operator *= (const YUV888Pixel p) {
y = JL_Util::ClipByte (int(y) * int(p.y));
u = JL_Util::ClipByte (int(u) * int(p.u));
v = JL_Util::ClipByte (int(v) * int(p.v));
return *this;
}
YUV888Pixel& operator /= (const YUV888Pixel p) {
y = JL_Util::ClipByte (int(y) / int(p.y));
u = JL_Util::ClipByte (int(u) / int(p.u));
v = JL_Util::ClipByte (int(v) / int(p.v));
return *this;
}
YUV888Pixel operator + (const YUV888Pixel p) const {
return (YUV888Pixel(*this) += p);
}
YUV888Pixel operator - (const YUV888Pixel p) const {
return (YUV888Pixel(*this) -= p);
}
YUV888Pixel operator * (const YUV888Pixel p) const {
return (YUV888Pixel(*this) *= p);
}
YUV888Pixel operator / (const YUV888Pixel p) const {
return (YUV888Pixel(*this) /= p);
}

static const int colOffTab[3]; // = {0, 1, 2}; // offsets within YUVValue for YUVColors;
static const JL_Word::Byte MAXValue; // = 255;

#ifdef __BIG_ENDIAN__
JL_Word::Byte pad;
JL_Word::Byte y;
JL_Word::Byte u;
JL_Word::Byte v; // alligned to longs!!
#else
JL_Word::Byte v; // alligned to longs!!
JL_Word::Byte u;
JL_Word::Byte y;
JL_Word::Byte pad;
#endif
};

class YUV161616Pixel {
public:
typedef JL_Word::Int16 ColorType;
explicit YUV161616Pixel (const int value = 0) {
y = u = v = value;
}
YUV161616Pixel (const JL_Word::Int16 yy, const JL_Word::Int16 uu, const JL_Word::Int16 vv) {
y = yy; u = uu; v = vv;
}
YUV161616Pixel (const YUV888Pixel &pixel) {
y = pixel.y; u = pixel.u; v = pixel.v;
}
bool operator == (const YUV161616Pixel p) const {
return ((y == p.y) && (u == p.u) && (v == p.v));
}
bool operator != (const YUV161616Pixel p) const {
return !(operator==(p));
}
YUV161616Pixel& operator += (const YUV161616Pixel p) {
y = y + p.y;
u = u + p.u;
v = v + p.v;
return *this;
}
YUV161616Pixel& operator -= (const YUV161616Pixel p) {
y = y - p.y;
u = u - p.u;
v = v - p.v;
return *this;
}
YUV161616Pixel& operator *= (const YUV161616Pixel p) {
y = y * p.y;
u = u * p.u;
v = v * p.v;
return *this;
}
YUV161616Pixel& operator /= (const YUV161616Pixel p) {
y = y / p.y;
u = u / p.u;
v = v / p.v;
return *this;
}
YUV161616Pixel operator + (const YUV161616Pixel p) const {
return (YUV161616Pixel(*this) += p);
}
YUV161616Pixel operator - (const YUV161616Pixel p) const {
return (YUV161616Pixel(*this) -= p);
}
YUV161616Pixel operator * (const YUV161616Pixel p) const {
return (YUV161616Pixel(*this) *= p);
}
YUV161616Pixel operator / (const YUV161616Pixel p) const {
return (YUV161616Pixel(*this) /= p);
}

static const int colOffTab[3]; // = {0, 1, 2}; // offsets within YUVValue for YUVColors;

JL_Word::Int16 v;
JL_Word::Int16 u;
JL_Word::Int16 y;
};

// [Sangwine] p. 72
inline int ConvertYUV888PixelToInt (const YUV888Pixel &yuv) {
return (((30 * yuv.y) + (59 * yuv.u) + (11 * yuv.v) + 50) / 100);
}

inline YUV888Pixel ConvertIntToYUV888Pixel (const int i) {
return YUV888Pixel(i);
}

// [Sangwine] p. 72
inline int ConvertYUV161616PixelToInt (const YUV161616Pixel &yuv) {
return (((30 * yuv.y) + (59 * yuv.u) + (11 * yuv.v) + 50) / 100);
}

inline YUV161616Pixel ConvertIntToYUV161616Pixel (const int i) {
return YUV161616Pixel(i);
}

inline YUV161616Pixel ConvertYUV888PixelTo161616 (const YUV888Pixel &pixel) {
return YUV161616Pixel(pixel);
}

inline YUV888Pixel ConvertYUV161616PixelTo888 (const YUV161616Pixel &pixel) {
return YUV888Pixel(pixel.y, pixel.u, pixel.v);
}

typedef ColorImage<YUV888Pixel> YUV888Image;
typedef ColorImage<YUV161616Pixel> YUV161616Image;

std::string YUV888PixelToStr (const YUV888Pixel p);
YUV888Pixel StrToYUV888Pixel(const std::string &str);
std::ostream& operator << (std::ostream& os, const YUV888Pixel pixel);
std::istream& operator >> (std::istream& is, YUV888Pixel& pixel);

std::string YUV161616PixelToStr (const YUV161616Pixel p);
YUV161616Pixel StrToYUV161616Pixel(const std::string &str);
std::ostream& operator << (std::ostream& os, const YUV161616Pixel pixel);
std::istream& operator >> (std::istream& is, YUV161616Pixel& pixel);

std::string YUVColorToStr (const YUVColor col);
YUVColor StrToYUVColor(const std::string &str);
std::istream& operator>> (std::istream& is, YUVColor &col);
std::ostream& operator<< (std::ostream& os, const YUVColor col);

}// namespace JL_VisionLib_V3


#endif



Back to Contents

mask.h

/* File : mask.h
* Project : visionlib V3.0
* Author : Jaap van de Loosdrecht
* Van de Loosdrecht Machine Vision BV
* www.vdlmv.nl
* Date : 7-10-13
*
* Copyright (c) 1993-2017, Van de Loosdrecht Machine Vision BV,
* all rights reserved.
*/

#ifndef JL_VIS_LIB_MASK
#define JL_VIS_LIB_MASK

#include <string>
#include <iostream>

namespace JL_VisionLib_V3 {

class MaskBase {
public:
int height, width, size, orgX, orgY;
protected:
MaskBase () {};
}; // MaskBase

template<class Value> class Mask: public MaskBase {
public:
Mask ();
Mask (const Mask &mask);
Mask (const int height, const int width);
Mask (const int height, const int width, const Value v);
Mask (const int height, const int width, const int orgX, const int orgY, const Value v);
Mask (const int height, const int width,
const int orgX, const int orgY, ...);
~Mask ();
bool operator == (const Mask &mask) const;
bool operator != (const Mask &mask) const;
Mask& operator = (const Mask &mask);
void SetMask (const int height, const int width,
const int orgX, const int orgY, ...);
virtual Value& operator () (const int x, const int y) const;
virtual void operator () (const int x, const int y, const Value v);
Value GetMaskValue (const int x, const int y) const { return (*this)(x,y); }
void SetMaskValue (const int x, const int y, const Value v) { (*this)(x,y,v); }
Value *tab;
}; // Mask

template <class Value>
std::istream& operator>> (std::istream& is, Mask<Value> &mask);
template <class Value>
std::ostream& operator<< (std::ostream& os, const Mask<Value> &mask);
template <class Value>
std::string MaskToStr (const Mask<Value> &mask);
template <class Value>
Mask<Value> StrToMask (const std::string &str);

} // namespace JL_VisionLib_V3

#endif



Back to Contents

blob.h

/* File : blob.h
* Project : visionlib V3.0
* Author : Jaap van de Loosdrecht
* Van de Loosdrecht Machine Vision BV
* www.vdlmv.nl
* Date : 24-12-2012
*
* Copyright (c) 1993-2017, Van de Loosdrecht Machine Vision BV,
* all rights reserved.
*/


#ifndef JL_VISIONLIB_BLOB
#define JL_VISIONLIB_BLOB


#include "coord.h"
#include "image.h"
#include "intimage.h"
#include <string>
#include <vector>
#include <iostream>
#include <set>
#include <limits>
#include <math.h>

#undef max // troubles with std::numeric_limits<int>::max()

namespace JL_VisionLib_V3 {

enum BlobAnalyse {BA_Area, BA_AreaHoles, BA_AreaHolesRatio, BA_AveragePixel, BA_BendingEnergy, BA_Bottom, BA_BottomLeft,
BA_BottomMostLeft, BA_BottomMostRight, BA_BottomRight,
BA_Breadth, BA_CentreOfGravity, BA_Curvature,
BA_Eccentricity, BA_EllipsFit, BA_ExCircleCentre, BA_ExCircleC1, BA_ExCircleC2, BA_ExCircleR,
BA_FormFactor,
BA_Height, BA_HeightWidthRatio, BA_Hu1, BA_Hu2, BA_Hu3, BA_Hu4, BA_Hu5, BA_Hu6, BA_Hu7,
BA_InCircleCentre, BA_InCircleC1, BA_InCircleC2, BA_InCircleR, BA_IsoData,
BA_Left, BA_LeftMostBottom, BA_LeftMostTop,
BA_Length, BA_LengthBreadthRatio, BA_MaxCord, BA_MaxCordC1, BA_MaxCordC2, BA_MaxPixel,
BA_MedianPixel, BA_MinCord, BA_MinCordC1, BA_MinCordC2, BA_MinPixel, BA_ModalPixel,
BA_Moments_xx, BA_Moments_xy, BA_Moments_yy,
BA_MomentsScale_xx, BA_MomentsScale_xy, BA_MomentsScale_yy,
BA_MomentsSR1, BA_MomentsSR2,
BA_NrOfHoles, BA_Orientation,
BA_Perimeter, BA_PerimeterHoles, BA_PolygonVertices,
BA_Right, BA_RightMostBottom, BA_RightMostTop,
BA_StandardDeviation,
BA_SumPixels, BA_SumWX, BA_SumWY, BA_SumX, BA_SumXX, BA_SumXY, BA_SumY, BA_SumYY,
BA_Top, BA_TopLeft, BA_TopMostLeft, BA_TopMostRight,
BA_TopRight, BA_WeightedCoG, BA_Width,
BA_NotUsed};

class Blob {
public:
explicit Blob (const int l = 0) {
label = l;
nrPixels = 0;
sumPixels = sumWX = sumWY = 0;
M01 = M02 = M03 = M10 = M11 = M12 = M13 = M20 = M21 = M22 = M23 = M30 = 0;
maxX = maxY = maxXMinY = maxXMaxY = 0;
minX = minY = minXMinY = minXMaxY = std::numeric_limits<int>::max();
nrOfHoles = 0; areaHoles = 0;
perimeterHoles = 0; perimeter = 0;
formFactor = 0;
hu1 = hu2 = hu3 = hu4 = hu5 = hu6 = hu7 = 0;
}
bool operator< (const Blob &b) const { return (nrPixels < b.nrPixels); }
bool operator> (const Blob &b) const { return (nrPixels > b.nrPixels); } // MSVC5 bug ???
bool operator== (const Blob &b) const;
bool IsTheSame(const Blob &b, const double dev) const; // dev in %, 0.01 = 1%
int Area () const { return nrPixels; }
int AreaHoles () const { return areaHoles; };
double AreaHolesRatio () const { return (double)areaHoles/(double)nrPixels; };
double AveragePixel () const { return avgPixel; };
double BendingEnergy () const { return bendingEnergy; };
XYCoord Bottom () const {return bottom; };
XYCoord BottomLeft () const { return XYCoord (minX, maxY); }
XYCoord BottomMostLeft () const { return XYCoord(minXMaxY,maxY); }
XYCoord BottomMostRight () const { return XYCoord(maxXMaxY,maxY); }
XYCoord BottomRight () const { return XYCoord (maxX, maxY); }
double Breadth() const;
Coord2D CentreOfGravity () const;
double Curvature () const { return curvature; }
double Eccentricity () const;
double EllipsFit () const { return (nrPixels / (M_PI * 0.25 * Length() * Breadth())) ; }
Coord2D ExCircleCentre() const { return Coord2D(((double)maxCordC1.x+(double)maxCordC2.x)/2,
((double)maxCordC1.y+(double)maxCordC2.y)/2); }
XYCoord ExCircleC1() const { return maxCordC1; }
XYCoord ExCircleC2() const { return maxCordC2; }
double ExCircleR() const { return JL_VisionLib_V3::Distance(maxCordC1,maxCordC2)/2; }
double FormFactor () const { return formFactor; };
HeightWidth GetHeightWidth () const { return HeightWidth (maxY - minY + 1, maxX - minX + 1); }
int Height () const { return (maxY - minY + 1); }
double HeightWidthRatio () const { return (double)Height() / (double)Width(); }
double Hu1 () const { return hu1; };
double Hu2 () const { return hu2; };
double Hu3 () const { return hu3; };
double Hu4 () const { return hu4; };
double Hu5 () const { return hu5; };
double Hu6 () const { return hu6; };
double Hu7 () const { return hu7; };
XYCoord InCircleCentre() const { return inCircleCentre; }
XYCoord InCircleC1() const { return inCircleC1; }
XYCoord InCircleC2() const { return inCircleC2; }
double InCircleR() const { return JL_VisionLib_V3::Distance(inCircleC1,inCircleC2)/2; }
int IsoData () const { return isoData; };
int Label () const { return label; }
XYCoord Left () const {return left; };
XYCoord LeftMostBottom () const { return XYCoord(minX,maxYMinX); }
XYCoord LeftMostTop () const { return XYCoord(minX,minYMinX); }
double Length () const;
double LengthBreadthRatio () const { return (double)Length() / (double)Breadth(); }
double MaxCord () const { return maxCord; };
XYCoord MaxCordC1 () const { return maxCordC1; };
XYCoord MaxCordC2 () const { return maxCordC2; };
double MaxPixel () const { return maxPixel; };
double MedianPixel () const { return medianPixel; };
double MinCord () const { return minCord; };
XYCoord MinCordC1 () const { return minCordC1; };
XYCoord MinCordC2 () const { return minCordC2; };
double MinPixel () const { return minPixel; };
double ModalPixel () const { return modalPixel; };
double StandardDeviation () const { return stdDev; };
double Moments_xx() const;
double Moments_xy() const;
double Moments_yy() const;
double MomentsScale_xx() const;
double MomentsScale_xy() const;
double MomentsScale_yy() const;
double MomentsSR1() const;
double MomentsSR2() const;
int NrOfHoles () const { return nrOfHoles; };
int NrPixels () const { return nrPixels; }
double Orientation () const;
double Perimeter () const { return perimeter; };
double PerimeterHoles () const { return perimeterHoles; };
int PolygonVertices () const { return polygonVertices; };
XYCoord Right () const {return right; };
XYCoord RightMostBottom () const { return XYCoord(maxX,maxYMaxX); }
XYCoord RightMostTop () const { return XYCoord(maxX,minYMaxX); }
double SumPixels() const {return sumPixels; };
double SumWX() const {return sumWX; };
double SumWY() const {return sumWY; };
double SumX() const {return M10; };
double SumXX() const {return M20; };
double SumXY() const {return M11; };
double SumY() const {return M01; };
double SumYY() const {return M02; };
XYCoord Top () const {return top; };
XYCoord TopLeft () const { return XYCoord(minX, minY); }
XYCoord TopMostLeft () const { return XYCoord(minXMinY,minY); }
XYCoord TopMostRight () const { return XYCoord(maxXMinY,minY); }
XYCoord TopRight () const { return XYCoord(maxX, minY); }
int Width () const { return (maxX - minX + 1); }
Coord2D WeightedCoG () const;
// data
int label, nrPixels;
int minX, maxX, minY, maxY;
int minYMinX, maxYMinX, minYMaxX, maxYMaxX;
int minXMinY, maxXMinY, minXMaxY, maxXMaxY;
double sumPixels, sumWX, sumWY;
double M01, M02, M03, M10, M11, M12, M13, M20, M21, M22, M23, M30; // moments Mxy;
int nrOfHoles;
int areaHoles;
double perimeterHoles;
double perimeter;
double formFactor;
XYCoord left, top, right, bottom; // boundingbox
int isoData, minPixel, maxPixel;
double avgPixel, bendingEnergy, curvature, medianPixel, modalPixel, stdDev;
double hu1, hu2, hu3, hu4, hu5, hu6, hu7;
double maxCord, minCord;
XYCoord maxCordC1, maxCordC2, minCordC1, minCordC2, inCircleCentre, inCircleC1, inCircleC2;
int polygonVertices;
}; // Blob
typedef std::vector<Blob> BlobTab;

class BlobDownCompare {
public:
BlobDownCompare (const BlobAnalyse b, const UseXOrY xy = UseX) {
ba = b;
xory = xy;
}
bool operator() (const Blob &b1, const Blob &b2);
private:
BlobAnalyse ba;
UseXOrY xory;
};

class BlobUpCompare {
public:
BlobUpCompare (const BlobAnalyse b, const UseXOrY xy = UseX) {
ba = b;
xory = xy;
}
bool operator() (const Blob &b1, const Blob &b2);
private:
BlobAnalyse ba;
UseXOrY xory;
};

// Note: minMinCord is preliminary and under construction
class BlobAnalyseModifier {
public:
explicit BlobAnalyseModifier (const int bEMED = 500, const int aPMD = 10, const int mMC = 1) {
bendingEnergyMaxEdgeDiff = bEMED;
approxPolygonMinDistance = aPMD;
minMinCord = mMC;
}
int bendingEnergyMaxEdgeDiff;
int approxPolygonMinDistance;
int minMinCord;
}; // BlobAnalyseModifier;
extern BlobAnalyseModifier defaultBAModifier;

double BlobFieldToDouble (const Blob &b, const BlobAnalyse ba, const UseXOrY xy = UseX);
int BlobFieldToInt (const Blob &b, const BlobAnalyse ba, const int scale = 1, const UseXOrY xy = UseX);

enum SortOrder {NoSort, SortUp, SortDown};

template <class IntImageT>
void BlobAnalysis (const IntImageT &labelledImage, const std::set<BlobAnalyse> &s,
const int maxLabelNr, BlobTab &blobs,
const SortOrder so = NoSort, const BlobAnalyse sortBA = BA_Area,
const UseXOrY xy = UseX,
const BlobAnalyseModifier &baMod = defaultBAModifier);

template <class IntImageT, class PixelT>
void BlobMeasure (IntImageT &labelledImage, const IntImageT &grayImage, const BlobAnalyse meas,
const PixelT scale = 1, const UseXOrY xy = UseX);

template <class IntImageT>
void GrayScaleBlobAnalysis (const IntImageT &labelledImage, const IntImageT &grayImage, const std::set<BlobAnalyse> &s,
const int maxLabelNr, BlobTab &blobs,
const SortOrder so = NoSort, const BlobAnalyse sortBA = BA_Area,
const UseXOrY xy = UseX,
const BlobAnalyseModifier &baMod = defaultBAModifier);

template <class IntImageT, class PixelT>
void BlobMeasure (IntImageT &labelledImage, const BlobAnalyse meas,
const PixelT scale = 1, const UseXOrY xy = UseX,
const BlobAnalyseModifier &baMod = defaultBAModifier);

template <class IntImageT, class PixelT>
void GrayScaleBlobMeasure (IntImageT &labelledImage, const IntImageT &grayImage, const BlobAnalyse meas,
const PixelT scale = 1, const UseXOrY xy = UseX,
const BlobAnalyseModifier &baMod = defaultBAModifier);


bool IsTheSame (const BlobTab &b1, const BlobTab &b2, const double dev);

// ---------------------- string and stream utils -----------------------

std::string BlobToStr (const Blob &b);
Blob StrToBlob(const std::string &str);
std::istream& operator>> (std::istream& is, Blob &b);
std::ostream& operator<< (std::ostream& os, const Blob &b);

std::string SortOrderToStr (const SortOrder s);
SortOrder StrToSortOrder(const std::string &str);
std::istream& operator>> (std::istream& is, SortOrder &s);
std::ostream& operator<< (std::ostream& os, const SortOrder s);

std::string BlobAnalyseToStr (const BlobAnalyse b);
BlobAnalyse StrToBlobAnalyse(const std::string &str);
std::istream& operator>> (std::istream& is, BlobAnalyse &b);
std::ostream& operator<< (std::ostream& os, const BlobAnalyse b);

std::string BlobAnalyseSetToStr (const std::set<BlobAnalyse> &s);
std::set<BlobAnalyse> StrToBlobAnalyseSet(const std::string &str);

std::string BlobAnalyseHeaderText (const std::set<BlobAnalyse> &s,
const bool csv = false);
std::string BlobAnalyseTabToStr (const std::set<BlobAnalyse> &s, BlobTab &blobs,
const int precision = 6);
void BlobAnalyseTabToVectorStr (std::vector<std::string> &vs, const std::set<BlobAnalyse> &s, BlobTab &blobs,
const int precision = 6);

} // namespace JL_VisionLib_V3


#endif




Back to Contents

coord.h

/* File : coord.h
* Project : visionlib V3.0
* Author : Jaap van de Loosdrecht
* Van de Loosdrecht Machine Vision BV
* www.vdlmv.nl
* Date : 30-12-2010
*
* Copyright (c) 1993-2017, Van de Loosdrecht Machine Vision BV,
* all rights reserved.
*/

#ifndef JL_VISIONLIB_COORDINATES
#define JL_VISIONLIB_COORDINATES

#include <string>
#include <vector>
#include <iostream>
#include <cmath>
#include "compiler.h"
#include "util.h"

namespace JL_VisionLib_V3 {

enum UseXOrY {UseX, UseY};

class XYCoord {
public:
explicit XYCoord (const int xx = 0, const int yy = 0) { x=xx; y=yy; }
bool operator == (const XYCoord &c) const { return (c.x == x) && (c.y == y); }
bool operator != (const XYCoord &c) const { return (c.x != x) || (c.y != y); }
XYCoord operator + (const XYCoord &c) const { return XYCoord(x+c.x,y+c.y); }
XYCoord operator - (const XYCoord &c) const { return XYCoord(x-c.x,y-c.y); }
XYCoord operator * (const double &f) const { return XYCoord(JL_Util::Round(x*f),JL_Util::Round(y*f)); }
XYCoord operator / (const double &f) const { return XYCoord(JL_Util::Round(x/f),JL_Util::Round(y/f)); }
XYCoord operator += (const XYCoord &c) { x += c.x; y += c.y; return *this;}
XYCoord operator -= (const XYCoord &c) { x -= c.x; y -= c.y; return *this;}
XYCoord operator *= (const double &f) { x = JL_Util::Round(x*f); y = JL_Util::Round(y*f); return *this;}
XYCoord operator /= (const double &f) { x = JL_Util::Round(x/f); y = JL_Util::Round(y/f); return *this;}
bool operator < (const XYCoord &) const { return true; } // dummy
int x, y;
}; // XYCoord

class Coord2D {
public:
explicit Coord2D (const double xx = 0, const double yy = 0) { x=xx; y=yy; }
explicit Coord2D (const XYCoord &xy) { x=xy.x; y=xy.y; }
bool operator == (const Coord2D &c) const { return (c.x == x) && (c.y == y); }
bool operator != (const Coord2D &c) const { return (c.x != x) || (c.y != y); }
Coord2D operator + (const Coord2D &c) const { return Coord2D(x+c.x,y+c.y); }
Coord2D operator - (const Coord2D &c) const { return Coord2D(x-c.x,y-c.y); }
Coord2D operator * (const double &f) const { return Coord2D(x*f,y*f); }
Coord2D operator / (const double &f) const { return Coord2D(x/f,y/f); }
Coord2D operator += (const Coord2D &c) { x += c.x; y += c.y; return *this;}
Coord2D operator -= (const Coord2D &c) { x -= c.x; y -= c.y; return *this;}
Coord2D operator *= (const double &f) { x = x*f; y = y*f; return *this;}
Coord2D operator /= (const double &f) { x = x/f; y = y/f; return *this;}
bool operator <(const Coord2D &) const { return true; } // dummy
double x, y;
}; // Coord2D

class Coord3D {
public:
explicit Coord3D (const double xx = 0, const double yy = 0, const double zz = 0)
{ x=xx; y=yy; z=zz; }
bool operator == (const Coord3D &c) const
{ return (c.x == x) && (c.y == y) && (c.z == z); }
bool operator != (const Coord3D &c) const
{ return (c.x != x) || (c.y != y) || (c.z != z); }
Coord3D operator + (const Coord3D &c) const { return Coord3D(x+c.x,y+c.y,z+c.z); }
Coord3D operator - (const Coord3D &c) const { return Coord3D(x-c.x,y-c.y,z-c.z); }
Coord3D operator * (const double &f) const { return Coord3D(x*f,y*f,z*f); }
Coord3D operator / (const double &f) const { return Coord3D(x/f,y/f,z*f); }
Coord3D operator += (const Coord3D &c) { x += c.x; y += c.y; z += c.z; return *this;}
Coord3D operator -= (const Coord3D &c) { x -= c.x; y -= c.y; z -= c.z; return *this;}
Coord3D operator *= (const double &f) { x = x*f; y = y*f; z = z*f; return *this;}
Coord3D operator /= (const double &f) { x = x/f; y = y/f; z = z/f; return *this;}
bool operator < (const Coord3D &) const {return true; } // dummy
double x, y, z;
}; // Coord3D

class PolarCoord {
public:
explicit PolarCoord (const double rr = 0, const double pphi = 0) { r=rr; phi=pphi; }
bool operator == (const PolarCoord &c) const { return (c.r == r) && (c.phi == phi); }
bool operator != (const PolarCoord &c) const { return (c.r != r) || (c.phi != phi); }
bool operator < (const PolarCoord &) const { return true; } // dummy
double r; // pixels
double phi; // radians
};

class LineXY {
public:
LineXY () {}
LineXY (const XYCoord &s, const XYCoord &e) { start=s; end=e; }
double Length() const { return std::sqrt((double)(start.x-end.x)*(start.x-end.x) +
(start.y-end.y)*(start.y-end.y)); }
double Orientation() const { return std::atan2(double(end.y-start.y), double(end.x-start.x)); }
XYCoord start, end;
};

class Line2D {
public:
Line2D () {}
Line2D (const Coord2D &s, const Coord2D &e) { start=s; end=e; }
double Length() const { return std::sqrt((double)(start.x-end.x)*(start.x-end.x) +
(start.y-end.y)*(start.y-end.y)); }
double Orientation() const { return std::atan2(double(end.y-start.y), double(end.x-start.x)); }
Coord2D start, end;
};

class Line3D {
public:
Line3D () {}
Line3D (const Coord3D &s, const Coord3D &e) { start=s; end=e; }
double Length() const { return std::sqrt((double)(start.x-end.x)*(start.x-end.x) +
(start.y-end.y)*(start.y-end.y) +
(start.z-end.z)*(start.z-end.z)); }
Coord3D start, end;
};

typedef std::vector<XYCoord> XYCoordTab;
typedef std::vector<Coord2D> Coord2DTab;
typedef std::vector<Coord3D> Coord3DTab;
typedef std::vector<PolarCoord> PolarCoordTab;
typedef std::vector<LineXY> LineXYTab;
typedef std::vector<Line2D> Line2DTab;
typedef std::vector<Line3D> Line3DTab;

double Angle (const XYCoord &m, const XYCoord &c1, const XYCoord &c2);

// line : y = slope * x + yIntercept1
// line perpendicular : y = -1/slope * x + yIntercept2
inline Coord2D NearestPoint (const Line2D &line, const Coord2D &p) {
double dx = line.end.x - line.start.x;
double dy = line.end.y - line.start.y;
if (std::fabs(dy) < 0.00000001) return Coord2D(p.x,line.start.y);
if (std::fabs(dx) < 0.00000001) return Coord2D(line.start.x, p.y);
double slope = dy/dx;
double yIntercept = line.start.y - slope * line.start.x;
double slope90 = -1/slope;
double yIntercept2 = p.y - slope90 * p.x;
// calculate interception point of the two lines
double x = (yIntercept2-yIntercept)/(slope-slope90);
return Coord2D(x, slope90 * x + yIntercept2);
}
inline double DistanceSQ (const Line2D &line, const Coord2D &p) {
Coord2D np = NearestPoint(line,p);
return (p.x - np.x) * (p.x - np.x) + (p.y - np.y) * (p.y - np.y);
}
inline double Distance (const Line2D &line, const Coord2D &p) {
return std::sqrt(DistanceSQ(line,p));
}
inline double DistanceSQ (const LineXY &line, const XYCoord &p) {
Line2D line2d (Coord2D(line.start), Coord2D(line.end));
Coord2D np = NearestPoint(line2d,Coord2D(p));
return (p.x - np.x) * (p.x - np.x) + (p.y - np.y) * (p.y - np.y);
}
inline double Distance (const LineXY &line, const XYCoord &p) {
return std::sqrt(DistanceSQ(line,p));
}

inline double Distance (const XYCoord &p1, const XYCoord &p2) {
return std::sqrt((double)(p1.x-p2.x)*(p1.x-p2.x) + (p1.y-p2.y)*(p1.y-p2.y));
}
inline double Distance (const Coord2D &p1, const Coord2D &p2) {
return std::sqrt((double)(p1.x-p2.x)*(p1.x-p2.x) + (p1.y-p2.y)*(p1.y-p2.y));
}
inline double Distance (const Coord3D &p1, const Coord3D &p2) {
return std::sqrt((double)(p1.x-p2.x)*(p1.x-p2.x) + (p1.y-p2.y)*(p1.y-p2.y) + (p1.z-p2.z)*(p1.z-p2.z));
}

LineXY LongestLineBetweenCoords (const XYCoordTab &tab, int &startIndex, int &endIndex);
Line2D LongestLineBetweenCoords (const Coord2DTab &tab, int &startIndex, int &endIndex);
Line3D LongestLineBetweenCoords (const Coord3DTab &tab, int &startIndex, int &endIndex);

// calculate new position of xy after rotating around centre with phi radians
inline void RotateCoord (XYCoord &xy, const XYCoord centre, const double phi) {
double sinPhi = sin(phi);
double cosPhi = cos(phi);
int xc = centre.x;
int yc = centre.y;
int x = xy.x;
int y = xy.y;
xy.x = (int)((x - xc) * cosPhi - (y - yc) * sinPhi + xc + 0.5);
xy.y = (int)((y - yc) * cosPhi + (x - xc) * sinPhi + yc + 0.5);
} // RotateCoord

inline void RotateCoord (XYCoord &xy, const XYCoord centre, const double sinPhi, const double cosPhi) {
int xc = centre.x;
int yc = centre.y;
int x = xy.x;
int y = xy.y;
xy.x = (int)((x - xc) * cosPhi - (y - yc) * sinPhi + xc + 0.5);
xy.y = (int)((y - yc) * cosPhi + (x - xc) * sinPhi + yc + 0.5);
} // RotateCoord

inline void RotateCoord (Coord2D &xy, const Coord2D centre, const double phi) {
double sinPhi = sin(phi);
double cosPhi = cos(phi);
int xc = centre.x;
int yc = centre.y;
int x = xy.x;
int y = xy.y;
xy.x = (x - xc) * cosPhi - (y - yc) * sinPhi + xc;
xy.y = (y - yc) * cosPhi + (x - xc) * sinPhi + yc;
} // RotateCoord

Coord2D PolarLinesIntersection (const PolarCoord &pc1, const PolarCoord &pc2);
Line2D LineairRegression (const Coord2DTab &tab);
void CircleRegression (const Coord2DTab &tab, Coord2D ¢er, double &radius);

enum CoordConversion {CConv_LeftTop, CConv_RightTop, CConv_LeftBotom, CConv_RightBotom, CConv_Round};

inline XYCoord Coord2DToXYCoord (const Coord2D &c, CoordConversion conv = CConv_Round) {
XYCoord res;
switch (conv) {
case CConv_LeftTop:
res = XYCoord((int)c.x, (int)c.y);
break;
case CConv_RightTop:
res = XYCoord((int)std::ceil(c.x), (int)c.y);
break;
case CConv_LeftBotom:
res = XYCoord((int)c.x, (int)std::ceil(c.y));
break;
case CConv_RightBotom:
res = XYCoord((int)std::ceil(c.x), (int)std::ceil(c.y));
break;
case CConv_Round:
res = XYCoord((int)(c.x + 0.5), (int)(c.y + 0.5));
} // switch conv
return res;
} // Coord2DToXYCoord

XYCoordTab LineXYToCoords (const XYCoord &startOrg, const XYCoord &endOrg);
XYCoordTab LineXYToCoords (const LineXY &xy);
void LineXYToCoords (const XYCoord &startOrg, const XYCoord &endOrg, XYCoordTab &tab);
void LineXYToCoords (const LineXY &xy, XYCoordTab &tab);

Coord2DTab Line2DToCoords (const Coord2D &start, const Coord2D &end, const int nrCoords);
Coord2DTab Line2DToCoords (const Line2D &line, const int nrCoords);
void Line2DToCoords (const Coord2D &start, const Coord2D &end, const int nrCoords, Coord2DTab &res);
void Line2DToCoords (const Line2D &line, const int nrCoords, Coord2DTab &res);

std::string UseXOrYToStr (const UseXOrY xy);
UseXOrY StrToUseXOrY(const std::string &str);
std::istream& operator>> (std::istream& is, UseXOrY &xy);
std::ostream& operator<< (std::ostream& os, const UseXOrY xy);

std::string XYCoordToStr (const XYCoord &xy);
XYCoord StrToXYCoord(const std::string &str);
std::istream& operator>> (std::istream& is, XYCoord &xy);
std::ostream& operator<< (std::ostream& os, const XYCoord &xy);

std::string Coord2DToStr (const Coord2D &xy);
Coord2D StrToCoord2D(const std::string &str);
std::istream& operator>> (std::istream& is, Coord2D &xy);
std::ostream& operator<< (std::ostream& os, const Coord2D &xy);

std::string Coord3DToStr (const Coord3D &xyz);
Coord3D StrToCoord3D(const std::string &str);
std::istream& operator>> (std::istream& is, Coord3D &xyz);
std::ostream& operator<< (std::ostream& os, const Coord3D &xyz);

std::string PolarCoordToStr (const PolarCoord &polar);
PolarCoord StrToPolarCoord(const std::string &str);
std::istream& operator>> (std::istream& is, PolarCoord &polar);
std::ostream& operator<< (std::ostream& os, const PolarCoord &polar);

std::string XYCoordTabToStr (const XYCoordTab &tab);
XYCoordTab StrToXYCoordTab(const std::string &str);
std::istream& operator>> (std::istream& is, XYCoordTab &tab);
std::ostream& operator<< (std::ostream& os, const XYCoordTab &tab);

std::string Coord2DTabToStr (const Coord2DTab &tab);
Coord2DTab StrToCoord2DTab(const std::string &str);
std::istream& operator>> (std::istream& is, Coord2DTab &tab);
std::ostream& operator<< (std::ostream& os, const Coord2DTab &tab);

std::string Coord3DTabToStr (const Coord3DTab &tab);
Coord3DTab StrToCoord3DTab(const std::string &str);
std::istream& operator>> (std::istream& is, Coord3DTab &tab);
std::ostream& operator<< (std::ostream& os, const Coord3DTab &tab);

std::string PolarCoordTabToStr (const PolarCoordTab &tab);
PolarCoordTab StrToPolarCoordTab(const std::string &str);
std::istream& operator>> (std::istream& is, PolarCoordTab &tab);
std::ostream& operator<< (std::ostream& os, const PolarCoordTab &tab);

std::string CoordConversionToStr (const CoordConversion conv);
CoordConversion StrToCoordConversion(const std::string &str);
std::istream& operator>> (std::istream& is, CoordConversion &conv);
std::ostream& operator<< (std::ostream& os, const CoordConversion conv);

} // namespace JL_VisionLib_V3

#endif




Back to Contents

chaincod.h

/* File : chaincod.h
* Project : visionlib V3.0
* Author : Jaap van de Loosdrecht
* Van de Loosdrecht Machine Vision BV
* www.vdlmv.nl
* Date : 20-10-2010
*
* Copyright (c) 1993-2017, Van de Loosdrecht Machine Vision BV,
* all rights reserved.
*/

#ifndef JL_VIS_LIB_CHAIN_CODE
#define JL_VIS_LIB_CHAIN_CODE

#include "intimage.h"
#include <vector>
#include <string>
#include <iostream>

namespace JL_VisionLib_V3 {

enum ChainCodeType {ChainCode4, ChainCode8};
enum ChainCode4Dir {CC4_E, CC4_S, CC4_W, CC4_N};
enum ChainCode8Dir {CC8_E, CC8_SE, CC8_S, CC8_SW,
CC8_W, CC8_NW, CC8_N, CC8_NE};
class ChainCode {
public:
ChainCode(const ChainCodeType t = ChainCode8) {type = t;};
bool operator == (const ChainCode &c) const;
bool operator != (const ChainCode &c) const;
int ConvToXYCoordTab (XYCoordTab &tab) const;
LineXY MaxCord() const;
double Perimeter() const;
int ApproxPolygon (const double minDistance, const int maxVertices, XYCoordTab &tab) const;
ChainCodeType type;
XYCoord topMostLeft;
std::vector<int> chain;

};


/* under construction
template <class IntImageT>
void ChainCodeToPixelQ (const IntImageT &image, const ChainCode &cc, typename IntImageT::PixelQ &pixelQ);
*/

// image is 4 or 8 labeled image, object with label not touching the borders
template <class IntImageT>
void TrackBoundary (const IntImageT &image, const int label, const XYCoord &tml,
ChainCode &cc);

/* under construction
// image is 4 or 8 labeled image, object with label not touching the borders
template <class IntImageT>
void TrackBoundary (const IntImageT &image, const int label, const XYCoord &tml,
typename IntImageT::PixelQ &pixelQ);
*/

std::string ChainCodeTypeToStr (const ChainCodeType c);
ChainCodeType StrToChainCodeType(const std::string &str);
std::istream& operator>> (std::istream& is, ChainCodeType &c);
std::ostream& operator<< (std::ostream& os, const ChainCodeType c);

std::string ChainCode4DirToStr (const ChainCode4Dir c);
ChainCode4Dir StrToChainCode4Dir(const std::string &str);
std::istream& operator>> (std::istream& is, ChainCode4Dir &c);
std::ostream& operator<< (std::ostream& os, const ChainCode4Dir c);

std::string ChainCode8DirToStr (const ChainCode8Dir c);
ChainCode8Dir StrToChainCode8Dir(const std::string &str);
std::istream& operator>> (std::istream& is, ChainCode8Dir &c);
std::ostream& operator<< (std::ostream& os, const ChainCode8Dir c);

} // namespace JL_VisionLib_V3

#endif



Back to Contents

histogram.h

/* File : histogram.h
* Project : visionlib V3.0
* Author : Jaap van de Loosdrecht
* Van de Loosdrecht Machine Vision BV
* www.vdlmv.nl
* Date : 21-12-2009
*
* Copyright (c) 1993-2017, Van de Loosdrecht Machine Vision BV,
* all rights reserved.
*/

#ifndef JL_VISIONLIB_HISTOGRAM
#define JL_VISIONLIB_HISTOGRAM

#include <iostream>
#include <string>
#include <vector>

namespace JL_VisionLib_V3 {

enum HistogramType {HistogramFrequency, HistogramPartialSum,
HistogramOpticalDensity, HistogramIOD};

class Histogram {
public:
Histogram () {}
Histogram (const int min, const int max,
const HistogramType state = HistogramFrequency);
Histogram (const Histogram &his);
~Histogram ();

bool operator== (const Histogram &his) const;
bool operator!= (const Histogram &his) const;
Histogram& operator= (const Histogram &his);
double& operator[] (const int v) { return tab[v-minValue]; }
double& ValueAtIndex (const int i) { return tab[i]; }

HistogramType State () const { return state; }
int Size() const { return maxValue-minValue+1; }
int MinValue() const { return minValue; }
int MaxValue() const { return maxValue; }
int NearestHisPixel (const int t);

void Reset (const HistogramType state = HistogramFrequency);
void PartialSum ();
void OpticalDensity ();
void IntegratedOpticalDensity ();

double Sum();
double NrElms();
double Mean();
int Median();
int Modal();
double StdDeviation();
int IsoData();

private:
friend std::istream& operator>> (std::istream& is, Histogram &his);
friend std::ostream& operator<< (std::ostream& os, const Histogram &his);
HistogramType state;
int minValue, maxValue;
typedef std::vector<double> HistogramTab;
HistogramTab tab;
}; // Histogram


std::string HistogramToStr (const Histogram &his);
Histogram StrToHistogram (const std::string &str);
std::istream& operator>> (std::istream& is, Histogram &his);
std::ostream& operator<< (std::ostream& os, const Histogram &his);

std::string HistogramTypeToStr (const HistogramType t);
HistogramType StrToHistogramType(const std::string &str);
std::istream& operator>> (std::istream& is, HistogramType &t);
std::ostream& operator<< (std::ostream& os, const HistogramType t);

} // namespace JL_VisionLib_V3

#endif



Back to Contents

barcode.h

/* File : barcode.h
* Project : visionlib V3.0
* Author : Jaap van de Loosdrecht
* Van de Loosdrecht Machine Vision BV
* www.vdlmv.nl
* Date : 1-1-2004
*
* Copyright (c) 1993-2017, Van de Loosdrecht Machine Vision BV,
* all rights reserved.
*/

#ifndef JL_VISIONLIB_BARCODE
#define JL_VISIONLIB_BARCODE


#include "intimage.h"
#include <string>

namespace JL_VisionLib_V3 {

enum BarCodeType {Bookland, CODE_39, CODE_128, EAN_8, EAN_13, Industrial_2of5,
Interleaved_2of5, Standard_2of5, UPC_A, UPC_E, USD_3};
enum BarCodeRes {BarCodeIdentified, InvalidNrOfElms,
InvalidNrOfBars, BarWidthTooSmall, BarWidthTooBig,
WidthRatio1_0Invalid, InvalidGuard, DecodeError, CheckError,
InvalidNrOfChars};
enum BarCodeScanDir {NormalScanDir, ReversedScanDir, BothScanDirs};
enum BarCodeCheck {Check, NoCheck};

template <class IntImageT>
BarCodeRes IdentifyBarCode (const IntImageT &image, const BarCodeType type,
std::string &code,
const int nrOfChars = 0,
const int lineDistance = 1,
const BarCodeScanDir dir = NormalScanDir,
const BarCodeCheck check = Check);

std::string BarCodeTypeToStr (const BarCodeType t);
BarCodeType StrToBarCodeType(const std::string &str);
std::istream& operator>> (std::istream& is, BarCodeType &t);
std::ostream& operator<< (std::ostream& os, const BarCodeType t);

std::string BarCodeResToStr (const BarCodeRes r);
BarCodeRes StrToBarCodeRes(const std::string &str);
std::istream& operator>> (std::istream& is, BarCodeRes &r);
std::ostream& operator<< (std::ostream& os, const BarCodeRes r);

std::string BarCodeScanDirToStr (const BarCodeScanDir s);
BarCodeScanDir StrToBarCodeScanDir(const std::string &str);
std::istream& operator>> (std::istream& is, BarCodeScanDir &s);
std::ostream& operator<< (std::ostream& os, const BarCodeScanDir s);

std::string BarCodeCheckToStr (const BarCodeCheck s);
BarCodeCheck StrToBarCodeCheck(const std::string &str);
std::istream& operator>> (std::istream& is, BarCodeCheck &s);
std::ostream& operator<< (std::ostream& os, const BarCodeCheck s);

} // namespace JL_VisionLib_V3

#endif




Back to Contents

binary.h

/* File : binary.h
* Project : visionlib V3.0
* Author : Jaap van de Loosdrecht
* Van de Loosdrecht Machine Vision BV
* www.vdlmv.nl
* Date : 24-12-2012
*
* Copyright (c) 1993-2017, Van de Loosdrecht Machine Vision BV,
* all rights reserved.
*/


#ifndef JL_VIS_LIB_BINARY_OPERATORS
#define JL_VIS_LIB_BINARY_OPERATORS

#include "intimage.h"
#include "complexi.h"
#include "mask.h"
#include "blob.h"
#include "numoper.h"
#include <vector>
#include <list>

namespace JL_VisionLib_V3 {

enum EDTMask {EDTMask3x3, EDTMask5x5, EDTMask7x7};
enum EDTScale {NoScaleEDT, ScaleEDT};

template <class IntImageT>
int ApproxPolygon (const IntImageT &image, const Connected connected,
const double minDistance, const int maxVertices, XYCoordTab &tab);

template <class IntImageT>
void BlobAnd (IntImageT &image, const IntImageT &maskImage, const Connected connected);

template <class IntImageT>
void DistanceT (IntImageT &image, const Connected connected);

template <class IntImageT>
void DistanceT (IntImageT &image,
const Mask<int> &downMaskOrg, const Mask<int> &upMaskOrg);

template <class IntImageT>
void EuclideanDistanceT (IntImageT &image, const EDTMask mask,
const EDTScale scale, const double precision = 41,
const double ydivx = 1);

template <class IntImageT>
void ExactDistanceT (IntImageT &image, const int precision = 10);

template <class IntImageT, class ComplexImageT>
void VectorDistanceT (const IntImageT &src, ComplexImageT &dest);

template <class IntImageT>
int FillHoles (IntImageT &image, const Connected connected);

template <class IntImageT>
int FillSpecificHoles (IntImageT &image, const Connected connected,
const BlobAnalyse ba,
const double low, const double high,
const UseXOrY xy = UseX,
const BlobAnalyseModifier &baMod = defaultBAModifier);

template <class IntImageT>
int FillSpecificGrayScaleHoles (IntImageT &image, const IntImageT &grayImage,
const Connected connected,
const BlobAnalyse ba,
const double low, const double high,
const UseXOrY xy = UseX,
const BlobAnalyseModifier &baMod = defaultBAModifier);

template <class IntImageT>
bool FindCornersRectangle (const IntImageT &image, const Connected connected,
const double deltaPhi, const Orientation orient,
XYCoord &leftTop, XYCoord &rigthTop,
XYCoord &leftBottom, XYCoord &rightBottom);

template <class IntImageT>
bool FindCornersRectangleSq (const IntImageT &image, const Connected connected,
XYCoord &leftTop, XYCoord &rigthTop,
XYCoord &leftBottom, XYCoord &rightBottom);

template <class IntImageT>
int FindHoles (IntImageT &image, const Connected connected);

template <class IntImageT>
int FindSpecificHoles (IntImageT &image, const Connected connected,
const BlobAnalyse ba,
const double low, const double high,
const UseXOrY xy = UseX,
const BlobAnalyseModifier &baMod = defaultBAModifier);

template <class IntImageT>
int FindSpecificGrayScaleHoles (IntImageT &image, const IntImageT &grayImage,
const Connected connected,
const BlobAnalyse ba,
const double low, const double high,
const UseXOrY xy = UseX,
const BlobAnalyseModifier &baMod = defaultBAModifier);

template <class IntImageT>
void LabelAnd (IntImageT &image, const IntImageT &maskImage);

template <class IntImageT>
int LabelBlobs (IntImageT &image, const Connected connected);

template<class IntImageT>
void NrOfNeighbours (const IntImageT &src, IntImageT &dest,
const Connected connected);

template <class IntImageT>
int RemoveBlobs (IntImageT &image, const Connected connected,
const BlobAnalyse ba,
const double low, const double high,
const UseXOrY xy = UseX,
const BlobAnalyseModifier &baMod = defaultBAModifier);

template <class IntImageT>
int RemoveGrayScaleBlobs (IntImageT &image, const IntImageT &grayImage,
const Connected connected,
const BlobAnalyse ba,
const double low, const double high,
const UseXOrY xy = UseX,
const BlobAnalyseModifier &baMod = defaultBAModifier);
template <class IntImageT>
int RemoveBlobsExp (IntImageT &image, const Connected connected,
const string &exp,
const BlobAnalyseModifier &baMod = defaultBAModifier);

template <class IntImageT>
int RemoveGrayScaleBlobsExp (IntImageT &image, const IntImageT &grayImage,
const Connected connected,
const string &exp,
const BlobAnalyseModifier &baMod = defaultBAModifier);

template <class IntImageT>
void RemoveBorderBlobs (IntImageT &image, const Connected connected,
const Border borders = AllBorders);

template <class IntImageT>
void RemoveBorderLabels (IntImageT &image,
const Border borders = AllBorders);

template <class IntImageT>
int RemoveLabels (IntImageT &image, const BlobAnalyse ba,
const double low, const double high,
const UseXOrY xy = UseX,
const BlobAnalyseModifier &baMod = defaultBAModifier);

template <class IntImageT>
int RemoveGrayScaleLabels (IntImageT &image, const IntImageT &grayImage,
const BlobAnalyse ba,
const double low, const double high,
const UseXOrY xy = UseX,
const BlobAnalyseModifier &baMod = defaultBAModifier);

template <class IntImageT>
int RemoveLabelsExp (IntImageT &image,
const string &exp,
const BlobAnalyseModifier &baMod = defaultBAModifier);

template <class IntImageT>
int RemoveGrayScaleLabelsExp (IntImageT &image, const IntImageT &grayImage,
const string &exp,
const BlobAnalyseModifier &baMod = defaultBAModifier);

template <class IntImageT>
void SeparateBlobs (const IntImageT &src, IntImageT &dest, const int size);

// ---------------------- string and stream utils -----------------------

std::string EDTMaskToStr (const EDTMask mask);
EDTMask StrToEDTMask(const std::string &str);
std::istream& operator>> (std::istream& is, EDTMask &mask);
std::ostream& operator<< (std::ostream& os, const EDTMask mask);

std::string EDTScaleToStr (const EDTScale scale);
EDTScale StrToEDTScale(const std::string &str);
std::istream& operator>> (std::istream& is, EDTScale &scale);
std::ostream& operator<< (std::ostream& os, const EDTScale scale);

} // namespace JL_VisionLib_V3

#endif



Back to Contents

binmorph.h

/* File : binmorph.h
* Project : visionlib V3.0
* Author : Jaap van de Loosdrecht
* Van de Loosdrecht Machine Vision BV
* www.vdlmv.nl
* Date : 1-1-2004
*
* Copyright (c) 1993-2017, Van de Loosdrecht Machine Vision BV,
* all rights reserved.
*/


#ifndef JL_VIS_LIB_BINARY_MORPHOLOGY
#define JL_VIS_LIB_BINARY_MORPHOLOGY

#include "intimage.h"
#include "mask.h"

namespace JL_VisionLib_V3 {

template<class IntImageT>
void Closing (const IntImageT &src, IntImageT &dest,
const Mask<int> &mask);

template<class IntImageT>
void Dilation (const IntImageT &src, IntImageT &dest,
const int nrNeighbours);

template<class IntImageT>
void Dilation (const IntImageT &src, IntImageT &dest,
const Mask<int> &mask);

template<class IntImageT>
void Erosion (const IntImageT &src, IntImageT &dest,
const int nrNeighbours);

template<class IntImageT>
void Erosion (const IntImageT &src, IntImageT &dest,
const Mask<int> &mask);

template<class IntImageT>
void HitAndMiss (const IntImageT &src, IntImageT &dest,
const Mask<int> &hitMask, const Mask<int> &missMask);

template<class IntImageT>
void Opening (const IntImageT &src, IntImageT &dest,
const Mask<int> &mask);

template<class IntImageT>
void Skeleton (const IntImageT &src, IntImageT &dest);

template<class IntImageT>
void Thickening (const IntImageT &src, IntImageT &dest,
const Mask<int> &hitMask, const Mask<int> &missMask);

template<class IntImageT>
void Thinning (const IntImageT &src, IntImageT &dest,
const Mask<int> &hitMask, const Mask<int> &missMask);

} // namespace JL_VisionLib_V3

#endif



Back to Contents

edge.h

/* File : edge.h
* Project : visionlib V3.0
* Author : Jaap van de Loosdrecht
* Van de Loosdrecht Machine Vision BV
* www.vdlmv.nl
* Date : 5-11-20114
*
* Copyright (c) 1993-2017, Van de Loosdrecht Machine Vision BV,
* all rights reserved.
*/

#ifndef JL_VIS_LIB_EDGE_OPERATORS
#define JL_VIS_LIB_EDGE_OPERATORS

#include "ordimage.h"
#include "intimage.h"
#include "mask.h"
#include "binary.h"
#include <vector>

namespace JL_VisionLib_V3 {


enum Gradient {GradientMagnitude, GradientDirection, GradientBoth};

template <class OrdImageT, class PixelT>
void DGEdgeMagnitude (const OrdImageT &conv1,
const OrdImageT &conv2,
OrdImageT &destMag);

template <class OrdImageT, class PixelT>
void DGEdgeDirection (const OrdImageT &conv1,
const OrdImageT &conv2,
OrdImageT &destDir,
const PixelT dirScale);

template <class OrdImageT, class PixelT>
void DGEdgeMagAndDir (const OrdImageT &conv1,
const OrdImageT &conv2,
OrdImageT &destMag,
OrdImageT &destDir,
const PixelT dirScale,
const PixelT minEdge);

template <class OrdImageT, class PixelT, class Value>
void DGEdgeDetection (const OrdImageT &src,
OrdImageT &destMag, OrdImageT &destDir,
const Mask<Value> &mask1, const Value div1,
const Mask<Value> &mask2, const Value div2,
const Gradient grad,
const PixelT dirScale,
const PixelT minEdge = 0);

template <class OrdImageT, class PixelT, class Value>
void TMEdgeDetection (const OrdImageT &src,
OrdImageT &destMag, OrdImageT &destDir,
const int nrMasks, const Mask<Value> maskTab[],
const PixelT alfaTab[], const Gradient grad);

template <class OrdImageT>
int FindEdgeCircle (const OrdImageT &image, const Coord2D &middle, const int nrSamples,
const double minR, const double maxR,
const double outlierDistance, const int nrIterations,
Coord2D ¢er, double &radius);

template <class OrdImageT>
int FindEdgeLine (const OrdImageT &image,
const XYCoord &middle, const XYCoord &endLine, const XYCoord &endBox,
const int lineDistance, const double outlierDistance, const int nrIterations,
Line2D &line);

template <class OrdImageT>
bool FindSubEdgeOnLine (const OrdImageT &image, const Coord2D &start, const Coord2D &end, Coord2D &edge);

template <class OrdImageT>
void FindSubEdgesInScanLines (const OrdImageT &image, const XYCoordTab &startLineTab, const XYCoordTab &endLineTab,
Coord2DTab &xTab);

template <class OrdImageT, class PixelT>
int FindSubEdgesOnLine (const OrdImageT &image, const Coord2D &start, const Coord2D &end,
const PixelT minEdge, Coord2DTab &edges);


template <class OrdImageT, class PixelT>
void FreiChen (const OrdImageT &src,
OrdImageT &destMag, OrdImageT &destDir,
const Gradient grad = GradientBoth, const PixelT dirScale = 100,
const PixelT minEdge = 0);

template <class OrdImageT, class PixelT>
void Kirsch (const OrdImageT &src,
OrdImageT &destMag ,OrdImageT &destDir,
const Gradient grad = GradientBoth, const PixelT dirScale = 100);

template <class OrdImageT, class PixelT>
void Prewitt (const OrdImageT &src,
OrdImageT &destMag, OrdImageT &destDir,
const Gradient grad = GradientBoth, const PixelT dirScale = 100,
const PixelT minEdge = 0);

template <class OrdImageT, class PixelT>
void Roberts (const OrdImageT &src,
OrdImageT &destMag ,OrdImageT &destDir,
const Gradient grad = GradientBoth, const PixelT dirScale = 100,
const PixelT minEdge = 0);

template <class OrdImageT, class PixelT>
void Robinson (const OrdImageT &src,
OrdImageT &destMag ,OrdImageT &destDir,
const Gradient grad = GradientBoth, const PixelT dirScale = 100);

template <class OrdImageT, class PixelT>
void Scharr (const OrdImageT &src,
OrdImageT &destMag, OrdImageT &destDir,
const Gradient grad = GradientBoth, const PixelT dirScale = 100,
const PixelT minEdge = 0);

template <class OrdImageT, class PixelT>
void Sobel (const OrdImageT &src,
OrdImageT &destMag, OrdImageT &destDir,
const Gradient grad = GradientBoth, const PixelT dirScale = 100,
const PixelT minEdge = 0);

// ---------------------- operators with binary result ------------------

template <class IntImageT, class PixelT>
void Canny (const IntImageT &src, IntImageT &dest,
const double sigma,
const PixelT low, const PixelT high,
const Connected connected = EightConnected);

template <class OrdImageT, class PixelT>
void MarrHildreth (const OrdImageT &src, OrdImageT &dest,
const double sigmaGaussian, const double sigmaLoG,
const PixelT minEdge);

// ---------------------- Special operators
template <class OrdImageT>
int RefineCornersRectangle (OrdImageT &image, const Coord2DTab &corners, const int margin, Coord2DTab &newCorners);

// ---------------------- string and stream utils -----------------------

std::string GradientToStr (const Gradient edge);
Gradient StrToGradient(const std::string &str);
std::istream& operator>> (std::istream& is, Gradient &edge);
std::ostream& operator<< (std::ostream& os, const Gradient edge);

} // namespace JL_VisionLib_V3

#endif



Back to Contents

filter.h

/* File : filter.h
* Project : visionlib V3.0
* Author : Jaap van de Loosdrecht
* Van de Loosdrecht Machine Vision BV
* www.vdlmv.nl
* Date : 20-11-2013
*
* Copyright (c) 1993-2017, Van de Loosdrecht Machine Vision BV,
* all rights reserved.
*/

#ifndef JL_VIS_LIB_FILTER_OPERATORS
#define JL_VIS_LIB_FILTER_OPERATORS

#include "numoper.h"
#include "ordimage.h"
#include "intimage.h"
#include "rgbimage.h"
#include "hsvimage.h"
#include "yuvimage.h"
#include "complexi.h"
#include "mask.h"
#include <vector>

namespace JL_VisionLib_V3 {

HeightWidth ConvolutionHW (const Image &src, const FixEdge edge,
const MaskBase &mask);
template <class OrdImageT, class Value>
void Convolution (const OrdImageT &src, OrdImageT &dest,
const Value divideFactor, const FixEdge edge, const Mask<Value> &mask);

template <class NumImageT>
void Convolution (NumImageT &image, const NumImageT &mask);

void Convolution (ComplexFloatImage &image, const ComplexFloatImage &mask);
void Convolution (ComplexDoubleImage &image, const ComplexDoubleImage &mask);
void Convolution (RGB888Image &image, const RGB888Image &mask);
void Convolution (RGB161616Image &image, const RGB161616Image &mask);
void Convolution (HSV888Image &image, const HSV888Image &mask);
void Convolution (HSV161616Image &image, const HSV161616Image &mask);
void Convolution (YUV888Image &image, const YUV888Image &mask);
void Convolution (YUV161616Image &image, const YUV161616Image &mask);

template <class OrdImageT>
void Correlation (OrdImageT &image, const OrdImageT &mask);

template <class OrdImageT>
void DeConvolution (OrdImageT &image, const OrdImageT &psf, const double k);

template <class OrdImageT>
void DoGFilter (OrdImageT &image, const double sigmaLow, const double sigmaHigh,
const int size = 0);

template <class OrdImageT>
void GaussianFilter (OrdImageT &image, const double sigma, const int size = 0);

template <class OrdImageT, class PixelT>
void InterpolateAtSpecificPixel (const OrdImageT &src, OrdImageT &dest, const PixelT value);

template <class OrdImageT, class Value>
void KuwaharaFilter (const OrdImageT &src, OrdImageT &dest, const Value radius, const FixEdge edge);

HeightWidth LocalMaxFilterHW (const Image &src, const FixEdge edge,
const MaskBase &mask);
template <class OrdImageT, class PixelT>
void LocalMaxFilter (const OrdImageT &src, OrdImageT &dest,
const PixelT backGround, const FixEdge edge, const Mask<int> &mask);

HeightWidth LocalMaxFilterHW (const Image &src, const FixEdge edge,
const MaskBase &mask);
template <class OrdImageT, class PixelT>
void LocalMinFilter (const OrdImageT &src, OrdImageT &dest,
const PixelT backGround, const FixEdge edge, const Mask<int> &mask);

template <class OrdImageT>
void LoGFilter (OrdImageT &image, const double sigma, const int size = 0);

HeightWidth MaximumFilterHW (const Image &src, const FixEdge edge,
const MaskBase &mask);
template <class OrdImageT>
void MaximumFilter (const OrdImageT &src, OrdImageT &dest,
const FixEdge edge, const Mask<int> &mask);

HeightWidth MeanFilterHW (const Image &src, const FixEdge edge,
const MaskBase &mask);
template <class OrdImageT, class Value>
void MeanFilter (const OrdImageT &src, OrdImageT &dest,
const FixEdge edge, const Mask<Value> &mask);

HeightWidth MedianFilterHW (const Image &src, const FixEdge edge,
const MaskBase &mask);
template <class OrdImageT>
void MedianFilter (const OrdImageT &src, OrdImageT &dest,
const FixEdge edge, const Mask<int> &mask);

HeightWidth MinimumFilterHW (const Image &src, const FixEdge edge,
const MaskBase &mask);
template <class OrdImageT>
void MinimumFilter (const OrdImageT &src, OrdImageT &dest,
const FixEdge edge, const Mask<int> &mask);

HeightWidth ModeFilterHW (const Image &src, const FixEdge edge,
const MaskBase &mask);
template <class OrdImageT>
void ModeFilter (const OrdImageT &src, OrdImageT &dest,
const FixEdge edge, const Mask<int> &mask);

template <class OrdImageT, class PixelT>
void NonMaximumSuppression (const OrdImageT &src, OrdImageT &dest,
const OrdImageT &direction, const PixelT dirScale);

HeightWidth NthFilterHW (const Image &src, const FixEdge edge,
const MaskBase &mask);
template <class OrdImageT>
void NthFilter (const OrdImageT &src, OrdImageT &dest,
const int nth, const FixEdge edge, const Mask<int> &mask);

HeightWidth RangeFilterHW (const Image &src, const FixEdge edge,
const MaskBase &mask);
template <class OrdImageT>
void RangeFilter (const OrdImageT &src, OrdImageT &dest,
const FixEdge edge, const Mask<int> &mask);

template <class OrdImageT, class PixelT, class Value>
void SigmaFilter (const OrdImageT &src, OrdImageT &dest,
const PixelT deviation, const FixEdge edge, const Mask<Value> &mask);

template <class OrdImageT, class Value>
void SNN_MeanFilter (const OrdImageT &src, OrdImageT &dest, const Value radius, const FixEdge edge);

template <class OrdImageT, class Value>
void SNN_MedianFilter (const OrdImageT &src, OrdImageT &dest, const Value radius, const FixEdge edge);

HeightWidth SigmaFilterHW (const Image &src, const FixEdge edge,
const MaskBase &mask);

HeightWidth VarianceFilterHW (const Image &src, const FixEdge edge,
const MaskBase &mask);
template <class OrdImageT, class Value>
void VarianceFilter (const OrdImageT &src, OrdImageT &dest,
const FixEdge edge, const Mask<Value> &mask);

template <class OrdImageT>
void ZeroCrossings (const OrdImageT &src, OrdImageT &dest,
const Connected con = EightConnected);

} // namespace JL_VisionLib_V3

#endif



Back to Contents

hough.h

/* File : hough.h
* Project : visionlib V3.0
* Author : Jaap van de Loosdrecht
* Van de Loosdrecht Machine Vision BV
* www.vdlmv.nl
* Date : 29-5-2012
*
* Copyright (c) 1993-2017, Van de Loosdrecht Machine Vision BV,
* all rights reserved.
*/

#ifndef JL_VIS_LIB_HOUGH_TRANSFORM
#define JL_VIS_LIB_HOUGH_TRANSFORM

#include "ordimage.h"
#include <limits>
#include <vector>
#include "ordoper.h"

namespace JL_VisionLib_V3 {

class HoughCircle{
public:
explicit HoughCircle (const Coord2D &c = Coord2D(0,0),
const double radius = 0,
const int accuValue = 0) {
xy = c;
r = radius;
hits = accuValue;
}
Coord2D xy; // center of circle
double r; // radius of circle
int hits; // nr of hits in best accu
};
typedef std::vector<HoughCircle> HoughCircleTab;

template <class OrdImageT>
void HoughCircleT (const OrdImageT &src,
const double minR, const double maxR, const double deltaR,
std::vector<OrdImageT> &destTab);


enum CircleBrightness {DarkCircle, BrightCircle, DarkOrBrightCircle};

template <class OrdImageT, class PixelT>
void FastHoughCircleT (const OrdImageT &src,
const CircleBrightness brightness,
const PixelT edgeMin,
const double minR, const double maxR, const double deltaR,
std::vector<OrdImageT> &destTab);


template <class OrdImageT>
HoughCircle HTBestCircle (const std::vector<OrdImageT> &srcTab,
const double minR, const double maxR, const double deltaR);

template <class OrdImageT>
HoughCircleTab HTBestCircles (const std::vector<OrdImageT> &srcTab,
const double minR, const double maxR, const double deltaR,
const int nrCircles = 1, const int minDistance = 1, const int minHits = 1);

template <class OrdImageT>
HoughCircle FindBestCircle (const OrdImageT &src,
const double minR, const double maxR, const double deltaR);

template <class OrdImageT>
HoughCircleTab FindBestCircles (const OrdImageT &src,
const double minR, const double maxR, const double deltaR,
const int nrCircles = 1, const int minDistance = 1, const int minHits = 1);

template <class OrdImageT, class PixelT>
HoughCircle FindFastBestCircle (const OrdImageT &src,
const CircleBrightness brightness,
const PixelT edgeMin,
const double minR, const double maxR, const double deltaR);

template <class OrdImageT, class PixelT>
HoughCircleTab FindFastBestCircles (const OrdImageT &src,
const CircleBrightness brightness,
const PixelT edgeMin,
const double minR, const double maxR, const double deltaR,
const int nrCircles = 1, const int minDistance = 1, const int minHits = 1);


class HoughLine{
public:
explicit HoughLine (const PolarCoord &c = PolarCoord(0,0),
const int accuValue = 0) {
pc = c;
hits = accuValue;
}
PolarCoord pc;
int hits;
};

class HLParams {
public:
explicit HLParams (const double nR = 0, const double mR = 0, const double dR = 0,
const double nP = 0, const double mP = 0, const double dP = 0) {
minR = nR; maxR = mR; deltaR = dR;
minPhi = nP; maxPhi = mP; deltaPhi = dP;
}
double minR, maxR, deltaR;
double minPhi, maxPhi, deltaPhi;
};

typedef std::vector<HoughLine> HoughLineTab;

template <class OrdImageT>
void HoughLineT (const OrdImageT &src, HLParams &p, OrdImageT &dest);

template <class OrdImageT, class PixelT>
void FastHoughLineT (const OrdImageT &src, HLParams &p,
const PixelT edgeMin, OrdImageT &dest);

template <class OrdImageT>
HoughLine HTBestLine (const OrdImageT &src, const HLParams &p);

template <class OrdImageT>
HoughLineTab HTBestLines (const OrdImageT &src, const HLParams &p,
const int nrLines, const double minR, const double minPhi, const int minHits);

template <class OrdImageT>
HoughLine FindBestLine (const OrdImageT &src, HLParams &p);

template <class OrdImageT>
HoughLineTab FindBestLines (const OrdImageT &src, HLParams &p,
const int nrLines, const double minR, const double minPhi, const int minHits);

template <class OrdImageT, class PixelT>
HoughLine FindFastBestLine (const OrdImageT &src, HLParams &p, const PixelT edgeMin);

template <class OrdImageT, class PixelT>
HoughLineTab FindFastBestLines (const OrdImageT &src, HLParams &p, const PixelT edgeMin,
const int nrLines, const double minR, const double minPhi, const int minHits);

EnumStrIODeclaration(CircleBrightness);


} // namespace JL_VisionLib_V3

#endif // JL_VIS_LIB_HOUGH_TRANSFORM



Back to Contents

intoper.h

/* File : intoper.h
* Project : visionlib V3.0
* Author : Jaap van de Loosdrecht
* Van de Loosdrecht Machine Vision BV
* www.vdlmv.nl
* Date : 7-7-2016
*
* Copyright (c) 1993-2017, Van de Loosdrecht Machine Vision BV,
* all rights reserved.
*/

#ifndef JL_VIS_LIB_INT_OPERATORS
#define JL_VIS_LIB_INT_OPERATORS

#include "intimage.h"
#include "ordoper.h"
#include "histogram.h"
#include "binary.h"
#include <set>

namespace JL_VisionLib_V3 {

template <class IntImageT>
Histogram CalcHistogram (const IntImageT &image,
const HistogramType t = HistogramFrequency);

template <class IntImageT>
Histogram CalcHistogram (const IntImageT &image, const IntImageT &roi,
const HistogramType t = HistogramFrequency);

template <class IntImageT>
void CalcHistogram0 (const IntImageT &image, const int hisSize, int *his);

template <class IntImageT>
void LocalHistogramEqualize (IntImageT &image, const int nrRsX, const int nrRsY, const int nrBins, const float clipLimit);

template <class IntImageT, class PixelT>
void ContrastStretchLUT (IntImageT &image, const PixelT low, const PixelT high);

template <class IntImageT>
void GammaLUT (IntImageT &image, const double gamma);

template <class IntImageT>
void HistogramEqualize (IntImageT &image);

template <class IntImageT>
void InvertLUT (IntImageT &image);

template <class IntImageT, class PixelT>
void LUT (IntImageT &image, const PixelT minPixel, const PixelT tab[]);

template <class IntImageT, class PixelT>
void LUT (IntImageT &image, const PixelT minPixel, const std::vector<PixelT> &tab);

template <class IntImageT>
void Not (IntImageT &image);

template <class IntImageT>
void Remainder (IntImageT &dest, const IntImageT &src);

template <class IntImageT, class PixelT>
void SetMultiToValueLUT (IntImageT &image, const std::set<PixelT> &selectSet,
const PixelT value);
// note obsolete, use LUT: is faster

template <class IntImageT>
int SumIntPixels (const IntImageT &image);

template <class IntImageT>
void SwapAxis (const IntImageT &src, IntImageT &dest,
const ViewPoint viewPoint, const int scale);

template <class IntImageT, class PixelT>
void ThresholdFast (IntImageT &image, const PixelT thres, const ObjectBrightness object,
const PixelT min = 0, const PixelT max = PixelT(255));

template <class IntImageT, class PixelT>
void ThresholdFast (IntImageT &image, const PixelT low, const PixelT high,
const PixelT min = 0, const PixelT max = PixelT(255));

template <class IntImageT, class PixelT>
void ThresholdHysteresis (IntImageT &image, const PixelT low, const PixelT high,
const Connected connected);

template <class IntImageT>
int ThresholdIsoData (IntImageT &image, const ObjectBrightness object);

template <class IntImageT>
int ThresholdIsoData (IntImageT &image, const IntImageT &roi,
const ObjectBrightness object);

template <class IntImageT, class PixelT>
void Watershed(const IntImageT &src, IntImageT &dest, const PixelT first, const PixelT last, const PixelT coreLimit, const int minArea = 0 );

template <class IntImageT, class PixelT>
void ThresholdMulti (IntImageT &image, const std::set<PixelT> &selectSet);
// note obsolete, use LUT: is faster

template<class Pixel>
IntImage<Pixel> operator ! (const IntImage<Pixel> &image);

template<class Pixel>
void operator &= (IntImage<Pixel> &dest,
const IntImage<Pixel> &source);
template <class Pixel>
void operator &= (IntImage<Pixel> &image,
const Pixel pixel);
template<class Pixel>
IntImage<Pixel> operator & (const IntImage<Pixel> &image1,
const IntImage<Pixel> &image2);
template <class Pixel>
IntImage<Pixel> operator & (const IntImage<Pixel> &image,
const Pixel pixel);
template <class Pixel>
IntImage<Pixel> operator & (const Pixel pixel,
const IntImage<Pixel> &image);

template<class Pixel>
void operator |= (IntImage<Pixel> &dest,
const IntImage<Pixel> &source);
template <class Pixel>
void operator |= (IntImage<Pixel> &image,
const Pixel pixel);
template<class Pixel>
IntImage<Pixel> operator | (const IntImage<Pixel> &image1,
const IntImage<Pixel> &image2);
template <class Pixel>
IntImage<Pixel> operator | (const IntImage<Pixel> &image,
const Pixel pixel);
template <class Pixel>
IntImage<Pixel> operator | (const Pixel pixel,
const IntImage<Pixel> &image);

template<class Pixel>
void operator ^= (IntImage<Pixel> &dest,
const IntImage<Pixel> &source);
template <class Pixel>
void operator ^= (IntImage<Pixel> &image,
const Pixel pixel);
template<class Pixel>
IntImage<Pixel> operator ^ (const IntImage<Pixel> &image1,
const IntImage<Pixel> &image2);
template <class Pixel>
IntImage<Pixel> operator ^ (const IntImage<Pixel> &image,
const Pixel pixel);
template <class Pixel>
IntImage<Pixel> operator ^ (const Pixel pixel,
const IntImage<Pixel> &image);

template<class Pixel>
void operator %= (IntImage<Pixel> &dest,
const IntImage<Pixel> &source);
template <class Pixel>
void operator %= (IntImage<Pixel> &image,
const Pixel pixel);
template<class Pixel>
IntImage<Pixel> operator % (const IntImage<Pixel> &image1,
const IntImage<Pixel> &image2);
template <class Pixel>
IntImage<Pixel> operator % (const IntImage<Pixel> &image,
const Pixel pixel);
template <class Pixel>
IntImage<Pixel> operator % (const Pixel pixel,
const IntImage<Pixel> &image);

} // namespace JL_VisionLib_V3

#include "intoper.cxx" // MSVC5 does not allow for operator template instantiation !!

#endif



Back to Contents

numoper.h

/* File : numoper.h
* Project : visionlib V3.0
* Author : Jaap van de Loosdrecht
* Van de Loosdrecht Machine Vision BV
* www.vdlmv.nl
* Date : 7-7-2016
*
* Copyright (c) 1993-2017, Van de Loosdrecht Machine Vision BV,
* all rights reserved.
*/

#ifndef JL_VIS_LIB_NUMBER_OPERATORS
#define JL_VIS_LIB_NUMBER_OPERATORS

#include "numimage.h"
#include "mask.h"
#include <set>
#include <vector>
// #include <cmath>

namespace JL_VisionLib_V3 {

enum AxisType {PositiveX, NegativeX, PositiveY, NegativeY};
enum AxisMapping {AM_Copy, AM_Rotate90, AM_Rotate180, AM_Rotate270, AM_MirrorInXAxis, AM_MirrorInYAxis,
AM_Rotate90AndMirrorInYAxis, AM_Rotate90AndMirrorInXAxis, AM_MirrorInXAxisAndRotate90,
AM_MirrorInYAxisAndRotate90, AM_MirrorInCentre};
enum Border {AllBorders, LeftBorder, RightBorder, TopBorder, BottomBorder,
LeftAndTopBorder, TopAndRightBorder, RightAndBottomBorder,
BottomAndLeftBorder};
enum FixEdge {EdgeCopy, EdgeZero, EdgeRemove, EdgeExtend};
enum MirrorOperation {MirrorInCentre, MirrorInXAxis, MirrorInYAxis};
enum Orientation {Portrait, Landscape};
enum PixelInterpolation {NearestPixelInterpolation, BilinearPixelInterpolation};
enum TransformDirection {ForwardT, ReverseT};
enum ZeroOrOriginal {ZeroImage, KeepOriginal};

// bilinear interpolation [Machine Vision BV] page 383 (13.54)
template <class OrdImageT, class PixelT>
inline PixelT BilinearInterpolation (const OrdImageT &src, const double orgXf, const double orgYf, const PixelT border = 0) {
int orgX = (int)std::floor(orgXf);
int orgY = (int)std::floor(orgYf);
if ((orgX >= 0) && (orgX < src.GetWidth()-1) &&
(orgY >= 0) && (orgY < src.GetHeight()-1)) {
PixelT z11 = src(orgX,orgY);
PixelT z21 = src(orgX+1,orgY);
PixelT z12 = src(orgX,orgY+1);
PixelT z22 = src(orgX+1,orgY+1);
double deltaX = orgXf - orgX;
double deltaY = orgYf - orgY;
return PixelT((z11 + deltaX*(z21-z11) + deltaY*(z12-z11) + deltaX*deltaY*(z11-z12-z21+z22)) /* + 0.5 */); // for integer only ??!!
} else {
if ((orgX >= 0) && (orgX < src.GetWidth()) &&
(orgY >= 0) && (orgY < src.GetHeight())) {
return src(orgX,orgY); // bottom line
} else {
return border;
}
} // if org in image
} // BilinearInterpolation

HeightWidth AddBorderHW (const Image &src, const int top, const int left,
const int right, const int bottom);
template <class NumImageT, class PixelT>
void AddBorder (const NumImageT &src, NumImageT &dest,
const int top, const int left, const int right, const int bottom,
const PixelT value);

template <class NumImageT, class PixelT>
void BlockPattern (NumImageT &image, const XYCoord leftTop, const int height,
const int width, const PixelT value, const int repeatx, const int repeaty,
const ZeroOrOriginal zorg = ZeroImage);

template <class NumImageT, class PixelT>
void CircleShape (NumImageT &image, const XYCoord centre, const int r,
const PixelT value, const ZeroOrOriginal zorg = ZeroImage);

template <class NumImageT, class PixelT>
int CountPixel (const NumImageT &image, const PixelT value);

template <class NumImageT>
void DeInterlace (NumImageT &image);

template <class NumImageT, class PixelT>
void DiskShape (NumImageT &image, const XYCoord centre, const double r,
const PixelT value, const ZeroOrOriginal zorg = ZeroImage);

template <class NumImageT, class PixelT>
void DrawLines (NumImageT &image, const LineXYTab &tab, const PixelT value, const ZeroOrOriginal zorg = ZeroImage);

template <class NumImageT, class PixelT>
void DrawPolygon (NumImageT &image, const XYCoordTab &tab, const PixelT value, const ZeroOrOriginal zorg = ZeroImage);

HeightWidth Enlarge2HW (const Image &src);
template <class NumImageT>
void Enlarge2 (const NumImageT &src, NumImageT &dest, const PixelInterpolation pi);

HeightWidth ExtendBorderHW (const Image &src, const int top, const int left,
const int right, const int bottom);
template <class NumImageT>
void ExtendBorder (const NumImageT &src, NumImageT &dest,
const int top, const int left, const int right, const int bottom);

HeightWidth ExtendBorderHW (const Image &src, const MaskBase &mask);
template <class NumImageT>
void ExtendBorder (const NumImageT &src, NumImageT &dest,
const MaskBase &mask);

template <class NumImageT, class PixelT>
void FishEye (const NumImageT &src, NumImageT &dest,
const int height, const int width,
const double omega, const double scale,
const PixelT border);

template <class NumImageT>
void FixEdges (const NumImageT &src, NumImageT &dest,
const FixEdge edge, const int upper, const int lower,
const int left, const int right);

template <class NumImageT>
void HawkEye (const NumImageT &src, NumImageT &dest, const HeightWidth &hw, const int nrLevels = 2);

template <class NumImageT>
void Insert (NumImageT &image, const NumImageT &insert, const XYCoord topLeft);

template <class NumImageT, class PixelT>
void LinePattern (NumImageT &image, const int startx, const int starty,
const PixelT value, const int repeatx, const int repeaty,
const ZeroOrOriginal zorg = ZeroImage);

template <class NumImageT>
void MapAxis(const NumImageT &inputImage, NumImageT &outputImage, const AxisType xAxis, const AxisType yAxis);

template <class NumImageT>
void MapAxis(const NumImageT &inputImage, NumImageT &outputImage, const AxisMapping axisMapping);

template <class NumImageT>
void Mirror (const NumImageT &image, const MirrorOperation op);

template <class NumImageT, class PixelT>
void OpticalCorrection (const NumImageT &src, NumImageT &dest,
const double k1, const double k2, const double k3, const PixelT borderValue);

template <class NumImageT, class PixelT>
int PixelPtrTabFromImage (const NumImageT &image, std::vector<PixelT *> &tab,
const PixelT pixel);

HeightWidth Reduce2HW (const Image &src);
template <class NumImageT>
void Reduce2 (const NumImageT &src, NumImageT &dest);

template <class NumImageT>
void Resample (NumImageT &image, const int rate);

template <class NumImageT>
void ROI (const NumImageT &src, NumImageT &dest,
const XYCoord &topLeft, const HeightWidth &hw);

template <class NumImageT>
void ROIR (const NumImageT &src, NumImageT &dest,
const XYCoord &middle, const XYCoord &endpoint1, const XYCoord &endpoint2,
const Orientation orien, const int border = 3);

template <class NumImageT, class PixelT>
void Rotate (const NumImageT &src, NumImageT &dest,
const XYCoord center, const double phi,
const PixelT borderValue);

HeightWidth RotateFullHW (const Image &src, const double phi, XYCoord &trans);
template <class NumImageT, class PixelT>
XYCoord RotateFull (const NumImageT &src, NumImageT &dest,
const double phi, const PixelT borderValue);

template <class NumImageT, class PixelT>
void SetAllPixels (NumImageT &image, const PixelT value);

template <class NumImageT, class PixelT>
void SetBorders (NumImageT &image, const PixelT value,
const Border borders = AllBorders);

template <class IntImageT>
void SetToZeros (IntImageT &image);

template <class NumImageT>
void SwapQuadrants (const NumImageT &src, NumImageT &dest);

template <class NumImageT>
void TranslateCyclic (const NumImageT &src, NumImageT &dest,
const XYCoord vector);

bool WarpCoordsValid (const Coord2D leftTop, const Coord2D rightTop,
const Coord2D leftBottom, const Coord2D rightBottom);

template <class NumImageT, class PixelT>
bool Warp (const NumImageT &src, NumImageT &dest,
const TransformDirection dir,
const Coord2D leftTop, const Coord2D rightTop,
const Coord2D leftBottom, const Coord2D rightBottom,
const int height, const int width, const PixelT border);

template <class NumImageT, class PixelT>
int XYCoordTabFromImage (const NumImageT &image, XYCoordTab &tab, const PixelT pixel);

template <class NumImageT>
void Zoom (const NumImageT &src, NumImageT &dest,
const double factorX, const double factorY);

template <class NumImageT>
void Zoom (const NumImageT &src, NumImageT &dest,
const HeightWidth &hw);

// ---------------------- string and stream utils -----------------------

std::string AxisTypeToStr (const AxisType at);
AxisType StrToAxisType(const std::string &at);
std::istream& operator>> (std::istream& is, AxisType &at);
std::ostream& operator<< (std::ostream& os, const AxisType at);

std::string AxisMappingToStr (const AxisMapping am);
AxisMapping StrToAxisMapping(const std::string &am);
std::istream& operator>> (std::istream& is, AxisMapping &am);
std::ostream& operator<< (std::ostream& os, const AxisMapping am);

std::string FixEdgeToStr (const FixEdge edge);
FixEdge StrToFixEdge(const std::string &str);
std::istream& operator>> (std::istream& is, FixEdge &edge);
std::ostream& operator<< (std::ostream& os, const FixEdge edge);

std::string PixelInterpolationToStr (const PixelInterpolation pi);
PixelInterpolation StrToPixelInterpolation(const std::string &str);
std::istream& operator>> (std::istream& is, PixelInterpolation &pi);
std::ostream& operator<< (std::ostream& os, const PixelInterpolation pi);

std::string MirrorOperationToStr (const MirrorOperation m);
MirrorOperation StrToMirrorOperation(const std::string &str);
std::istream& operator>> (std::istream& is, MirrorOperation &m);
std::ostream& operator<< (std::ostream& os, const MirrorOperation m);

std::string OrientationToStr (const Orientation orien);
Orientation StrToOrientation(const std::string &str);
std::istream& operator>> (std::istream& is, Orientation &orien);
std::ostream& operator<< (std::ostream& os, const Orientation orien);

std::string BorderToStr (const Border b);
Border StrToBorder(const std::string &str);
std::istream& operator>> (std::istream& is, Border &b);
std::ostream& operator<< (std::ostream& os, const Border b);

std::string TransformDirectionToStr (const TransformDirection dir);
TransformDirection StrToTransformDirection(const std::string &str);
std::istream& operator>> (std::istream& is, TransformDirection &dir);
std::ostream& operator<< (std::ostream& os, const TransformDirection dir);

std::string ZeroOrOriginalToStr (const ZeroOrOriginal dir);
ZeroOrOriginal StrToZeroOrOriginal(const std::string &str);
std::istream& operator>> (std::istream& is, ZeroOrOriginal &dir);
std::ostream& operator<< (std::ostream& os, const ZeroOrOriginal dir);

// ---------------------- function operators -----------------------------

template<class Pixel>
std::istream& operator>> (std::istream& is, NumImage<Pixel> &image);

template<class Pixel>
std::ostream& operator<< (std::ostream& os, const NumImage<Pixel> &image);

template<class Pixel>
void operator += (NumImage<Pixel> &dest,
const NumImage<Pixel> &source);
template <class Pixel>
void operator += (NumImage<Pixel> &image,
const Pixel pixel);
template<class Pixel>
NumImage<Pixel> operator + (const NumImage<Pixel> &image1,
const NumImage<Pixel> &image2);
template <class Pixel>
NumImage<Pixel> operator + (const NumImage<Pixel> &image,
const Pixel pixel);
template <class Pixel>
NumImage<Pixel> operator + (const Pixel pixel,
const NumImage<Pixel> &image);
template<class Pixel>
void operator -= (NumImage<Pixel> &dest,
const NumImage<Pixel> &source);
template <class Pixel>
void operator -= (NumImage<Pixel> &image,
const Pixel pixel);
template<class Pixel>
NumImage<Pixel> operator - (const NumImage<Pixel> &image1,
const NumImage<Pixel> &image2);
template <class Pixel>
NumImage<Pixel> operator - (const NumImage<Pixel> &image,
const Pixel pixel);
template <class Pixel>
NumImage<Pixel> operator - (const Pixel pixel,
const NumImage<Pixel> &image);
template<class Pixel>
void operator *= (NumImage<Pixel> &dest,
const NumImage<Pixel> &source);
template <class Pixel>
void operator *= (NumImage<Pixel> &image,
const Pixel pixel);
template<class Pixel>
NumImage<Pixel> operator * (const NumImage<Pixel> &image1,
const NumImage<Pixel> &image2);
template <class Pixel>
NumImage<Pixel> operator * (const NumImage<Pixel> &image,
const Pixel pixel);
template <class Pixel>
NumImage<Pixel> operator * (const Pixel pixel,
const NumImage<Pixel> &image);
template<class Pixel>
void operator /= (NumImage<Pixel> &image,
const NumImage<Pixel> ÷r);
template <class Pixel>
void operator /= (NumImage<Pixel> &image,
const Pixel pixel);
template<class Pixel>
NumImage<Pixel> operator / (const NumImage<Pixel> &image1,
const NumImage<Pixel> &image2);
template <class Pixel>
NumImage<Pixel> operator / (const NumImage<Pixel> &image,
const Pixel pixel);
template <class Pixel>
NumImage<Pixel> operator / (const Pixel pixel,
const NumImage<Pixel> &image);

} // namespace JL_VisionLib_V3

#include "numoper.cxx" // MSVC5 does not allow for operator template instantiation !!

#endif



Back to Contents

ordoper.h

/* File : ordoper.h
* Project : visionlib V3.0
* Author : Jaap van de Loosdrecht
* Van de Loosdrecht Machine Vision BV
* www.vdlmv.nl
* Date : 10-10-2013
*
* Copyright (c) 1993-2017, Van de Loosdrecht Machine Vision BV,
* all rights reserved.
*/

#ifndef JL_VIS_LIB_ORDINAL_OPERATORS
#define JL_VIS_LIB_ORDINAL_OPERATORS

#include "numoper.h"
#include "ordimage.h"
#include <set>

namespace JL_VisionLib_V3 {

enum ObjectBrightness {DarkObject, BrightObject};
enum BinningMode {AverageBinning, SumBinning};
enum ViewPoint {Left, Right, Top, Bottom, Back, Front};

template <class OrdImageT>
void Abs (OrdImageT &image);

template <class OrdImageT, class PixelT>
PixelT AveragePixel (const OrdImageT &image);

// Note: Value type is used as type for sum
template <class OrdImageT, class Value>
void Binning (const OrdImageT &src, OrdImageT &dest, const Value height, const Value width, const BinningMode mode);

template <class OrdImageT, class PixelT>
void ClipPixelValue (OrdImageT &image, const PixelT low, const PixelT high);

template <class OrdImageT, class PixelT>
void ContrastStretch (OrdImageT &image, const PixelT low, const PixelT high);

template <class OrdImageT>
void CosineWindow (OrdImageT &image, const double multiplier);

template <class OrdImageT, class PixelT>
int CountLabels (OrdImageT &image, const PixelT low, const PixelT high);

template <class OrdImageT, class PixelT>
int CountPixels (const OrdImageT &image, const PixelT low, const PixelT high);

template<class SrcImage, class DestImage>
void OrdImageConversion (const SrcImage &src, DestImage &dest);

template <class OrdImageT>
void Difference (OrdImageT &dest, const OrdImageT &src);

template <class OrdImageT, class PixelT>
void FindFirstEdges (const OrdImageT &src, OrdImageT &dest, const PixelT minEdge, const ViewPoint viewPoint);

template <class OrdImageT, class PixelT>
void FindFirstTransitions (const OrdImageT &src, OrdImageT &dest, const PixelT threshold,
const ViewPoint viewPoint, const ObjectBrightness objectBrightness);

template <class OrdImageT, class PixelT>
void FishEye (const OrdImageT &src, OrdImageT &dest,
const int height, const int width,
const double omega, const double scale,
const PixelT border, const PixelInterpolation pi);

template <class OrdImageT>
void Gamma (OrdImageT &image, const double gamma);

template <class OrdImageT>
void GaussianShape (OrdImageT &image, const XYCoord centre, const double sigma,
const double max);

template <class OrdImageT>
void GaussianShapeR (OrdImageT &image, const XYCoord centre, const double r,
const double max);

template <class OrdImageT>
double InFocusValue (const OrdImageT &image, const int lowestFreqNr = 50);

template <class OrdImageT>
void Invert (OrdImageT &image);

template <class OrdImageT, class PixelT>
bool IsTheSame (const OrdImageT &i1, const OrdImageT &i2, const PixelT diff);

template <class OrdImageT, class PixelT>
PixelT LowestButZeroPixel (const OrdImageT &image);

template <class OrdImageT>
void Max (OrdImageT &dest, const OrdImageT &src);

template <class OrdImageT, class PixelT>
PixelT MaxLabel (const OrdImageT &image);

template <class OrdImageT, class PixelT>
PixelT MaxPixel (const OrdImageT &image);

template <class OrdImageT>
void Mean (OrdImageT &dest, const OrdImageT &src);

template <class OrdImageT>
void Min (OrdImageT &dest, const OrdImageT &src);

template <class OrdImageT, class PixelT>
PixelT MinLabel (const OrdImageT &image);

template <class OrdImageT, class PixelT>
void MinMaxLabel (const OrdImageT &image, PixelT &minP, PixelT &maxP);

template <class OrdImageT, class PixelT>
void MinMaxPixel (const OrdImageT &image, PixelT &minP, PixelT &maxP);

template <class OrdImageT, class PixelT>
PixelT MinPixel (const OrdImageT &image);

template <class OrdImageT, class PixelT>
void Noise (OrdImageT &image, const double probability,
const PixelT low, const PixelT high);

template <class OrdImageT, class PixelT>
void OpticalCorrection (const OrdImageT &src, OrdImageT &dest,
const double k1, const double k2, const double k3,
const PixelT borderValue, const PixelInterpolation pi);

template <class OrdImageT, class PixelT>
int PixelPtrTabFromImage (const OrdImageT &image, std::vector<PixelT *> &tab,
const PixelT low, const PixelT high);

template <class OrdImageT, class PixelT>
void PolarStretch(const OrdImageT &src, OrdImageT &dest,
const Coord2D centerPos,
const double beginAngle, const double endAngle,
const int angleSteps, const int maxRadius,
const PixelT borderValue,
PixelInterpolation pixelInterpolation);

template <class OrdImageT>
void Pow (OrdImageT &imageX, const OrdImageT &imageY);

template <class OrdImageT, class PixelT>
void Pow (OrdImageT &image, PixelT value);

template <class OrdImageT>
void RampPattern (OrdImageT &image, const int periodx, const int periody,
const double amplitude);

template <class OrdImageT, class PixelT>
double RATS (const OrdImageT &image, const PixelT minEdge, PixelT &thres);

template <class OrdImageT, class PixelT>
double RATS (const OrdImageT &image, const OrdImageT &roi,
const PixelT minEdge, PixelT &thres);

template <class OrdImageT, class PixelT>
double RATSLocal (const OrdImageT &image, OrdImageT &mask,
const PixelT minEdge, const double minAvgEdges, const int nrLevels);

template <class OrdImageT, class PixelT>
void RemoveSelectedLabels (OrdImageT &image, const PixelT low, const PixelT high);

template <class OrdImageT, class PixelT>
void ResampleLine (const OrdImageT &image, const Coord2D &start, const Coord2D &end, const int nrPixels,
Coord2DTab &cTab, std::vector<PixelT> &pTab);

template <class OrdImageT>
void ResampleLine (const OrdImageT &src, OrdImageT &dest, const Coord2D &start, const Coord2D &end, const int nrPixels,
Coord2DTab &cTab);

template <class OrdImageT>
void ROIR (const OrdImageT &src, OrdImageT &dest,
const XYCoord &middle, const XYCoord &endpoint1, const XYCoord &endpoint2,
const Orientation orien, const PixelInterpolation pi,
const int border = 3);

template <class OrdImageT, class PixelT>
void Rotate (const OrdImageT &src, OrdImageT &dest,
const XYCoord centre, const double phi,
const PixelT borderValue, const PixelInterpolation pi);

template <class OrdImageT, class PixelT>
XYCoord RotateFull (const OrdImageT &src, OrdImageT &dest,
const double phi, const PixelT borderValue, const PixelInterpolation pi);

template <class OrdImageT, class PixelT>
void SetMultiToValue (OrdImageT &image, const std::set<PixelT> &selectSet,
const PixelT value);
// note obsolete, use LUT: is faster

template <class OrdImageT, class PixelT>
void SetSelectedBorders (OrdImageT &image, const PixelT low, const PixelT high,
const PixelT value, const Border borders = AllBorders);

template <class OrdImageT, class PixelT>
void SetSelectedToValue (OrdImageT &image, const PixelT low, const PixelT high,
const PixelT value);

template <class OrdImageT>
void SinusPattern (OrdImageT &image, const int periodx, const int periody,
const double amplitude);

template <class OrdImageT>
double StandardDeviation (const OrdImageT &image);

template <class OrdImageT>
void SumColumns (const OrdImageT &src, OrdImageT &dest);

template <class OrdImageT>
double SumFloatPixels (const OrdImageT &image);

template <class OrdImageT>
void SumRows (const OrdImageT &src, OrdImageT &dest);

template <class OrdImageT, class PixelT>
void Threshold (OrdImageT &image, const PixelT low, const PixelT high);

template <class OrdImageT>
void ThresholdLocal (OrdImageT &image, const OrdImageT &mask,
const ObjectBrightness object);

template <class OrdImageT, class PixelT>
PixelT ThresholdOnHighest (OrdImageT &image);

template <class OrdImageT, class PixelT>
PixelT ThresholdOnLowest (OrdImageT &image);

template <class OrdImageT, class PixelT>
PixelT ThresholdOnLowestButZero (OrdImageT &image);

template <class OrdImageT, class PixelT>
double ThresholdRATS (OrdImageT &image, const PixelT minEdge,
const ObjectBrightness object, PixelT &thres);

template <class OrdImageT, class PixelT>
double ThresholdRATS (OrdImageT &image, const OrdImageT &roi,
const PixelT minEdge, const ObjectBrightness object,
PixelT &thres);

template <class OrdImageT, class PixelT>
double ThresholdRATSLocal (OrdImageT &image, const PixelT minEdge,
const double minAvgEdges, const int nrLevels,
const ObjectBrightness object);

template <class OrdImageT, class PixelT>
void ThresholdSimple (OrdImageT &image, const PixelT thres, const ObjectBrightness object);

template <class OrdImageT, class PixelT>
void TransitionsColumns (const OrdImageT &src, OrdImageT &dest, const PixelT thres);

template <class OrdImageT, class PixelT>
void TransitionsRows (const OrdImageT &src, OrdImageT &dest, const PixelT thres);

template <class OrdImageT, class PixelT>
bool Warp (const OrdImageT &src, OrdImageT &dest,
const TransformDirection dir,
const Coord2D leftTop, const Coord2D rightTop,
const Coord2D leftBottom, const Coord2D rightBottom,
const int height, const int width,
const PixelT border, const PixelInterpolation pi);

template <class OrdImageT, class PixelT>
int XYCoordTabFromImage (const OrdImageT &image, XYCoordTab &tab, const PixelT low,
const PixelT high);

template <class OrdImageT>
void Zoom (const OrdImageT &src, OrdImageT &dest,
const double factorX, const double factorY, const PixelInterpolation pi);

template <class OrdImageT>
void Zoom (const OrdImageT &src, OrdImageT &dest,
const HeightWidth &hw, const PixelInterpolation pi);

// ---------------------- string and stream utils -----------------------

std::string ObjectBrightnessToStr (const ObjectBrightness o);
ObjectBrightness StrToObjectBrightness(const std::string &str);
std::istream& operator>> (std::istream& is, ObjectBrightness &o);
std::ostream& operator<< (std::ostream& os, const ObjectBrightness o);

std::string BinningModeToStr (const BinningMode m);
BinningMode StrToBinningMode(const std::string &str);
std::istream& operator>> (std::istream& is, BinningMode &m);
std::ostream& operator<< (std::ostream& os, const BinningMode m);

std::string ViewPointToStr (const ViewPoint vp);
ViewPoint StrToViewPoint(const std::string &vp);
std::istream& operator>> (std::istream& is, ViewPoint &vp);
std::ostream& operator<< (std::ostream& os, const ViewPoint vp);

} // namespace JL_VisionLib_V3

#endif



Back to Contents

patternmatch.h

/* File : patternmatch.h
* Project : visionlib V3.0
* Author : Jaap van de Loosdrecht
* Van de Loosdrecht Machine Vision BV
* www.vdlmv.nl
* Date : 22-8-2009
*
* Copyright (c) 1993-2017, Van de Loosdrecht Machine Vision BV,
* all rights reserved.
*/

#ifndef JL_VIS_LIB_PATTERN_MATCH
#define JL_VIS_LIB_PATTERN_MATCH

#include <vector>
#include <string>
#include <iostream>
#include <map>
#include "intimage.h"
#include "blob.h"
#include "bpn.h"

namespace JL_VisionLib_V3 {

// NOTE: experimental
template <class IntImageT>
void FindOccludedBlob (const IntImageT &src, const IntImageT &pat, IntImageT &dest,
const float occlusion, const int maxDistance, const float margin);

struct PatternMatchResult {
explicit PatternMatchResult () { id = -1; error = scale = angle = 0; }
PatternMatchResult (const int i, float e, float s, float a) {
id = i; error = e; scale = s; angle = a; }
bool operator< (const PatternMatchResult &m) const { return (error < m.error); }
bool operator> (const PatternMatchResult &m) const { return (error > m.error); }
bool operator== (const PatternMatchResult &m) const {
return ((id == m.id) && (error == m.error) && (scale == m.scale) && (angle == m.angle)); }
int id;
float error;
float scale;
float angle;
}; // PatternMatchResult
typedef std::vector<PatternMatchResult> PatternMatchResultTab;
typedef std::vector<std::vector<int> > PatternLabelTab;
const int NoPatternFound = -1;

typedef std::map<std::string, int> PatternNamesTab;
std::string PatternIdToName (const PatternNamesTab &tab, const int id);

struct PatternEvalResult {
explicit PatternEvalResult () { expectedId = imageId = 0; confidence = 0; }
PatternEvalResult (const int eId, const int iId, const PatternMatchResultTab &pmRes, float conf) {
expectedId = eId; imageId = iId; matchTab = pmRes; confidence = conf; }
int expectedId; // in CIS
int imageId; // for expectedId in CIS
PatternMatchResultTab matchTab;
float confidence;
}; // PatternEvalResult
typedef std::vector<PatternEvalResult> PatternEvalResultTab;

template<class NumImageT>
class PatternMatcher {
public:
PatternMatcher () {};
~PatternMatcher () {};
virtual int AddPattern (const NumImageT &image, const std::string &name) = 0; // fres = id
virtual void RemovePattern (const std::string &name) = 0;
virtual int BestMatch (const NumImageT &blob, const float beginAngle, const float endAngle,
float &confidency, float &error, float &scale, float &angle) = 0; // fres = id
virtual float AllMatches (const NumImageT &blob, const float beginAngle, const float endAngle,
PatternMatchResultTab &tab) = 0; // fres = confidency
virtual float EvaluateClassImageSet (JL_BPN::ClassImageSet<NumImageT> &cis,
const float beginAngle, const float endAngle,
PatternEvalResultTab &tabs, float &meanError) = 0; //fres = max error
virtual int FindPatterns (const NumImageT &image, // labelled image to search in, fres = number found
const float maxError, const float minConfindence,
const float beginAngle, const float endAngle,
PatternMatchResultTab &labelTab,
PatternLabelTab &patTab) = 0;
std::string GetImageType() const;
PatternNamesTab GetPatternNamesTab () const;
int NumberOfPatterns () const;
std::string PatternName (const int id) const;
int PatternId (const std::string &name) const;
virtual NumImageT& PatternImage (const int id) const = 0;
virtual NumImageT& PatternImage (const std::string &name) const = 0;
virtual void WriteToFile (const std::string &fileName) = 0;
virtual void ReadFromFile (const std::string &fileName) = 0;
virtual void WriteToStream (std::ostream& os) = 0;
virtual void ReadFromStream (std::istream& is) = 0;
protected:
mutable PatternNamesTab nameTab;
}; // PatternMatcher


template<class IntImageT>
class BlobMatcher : public PatternMatcher<IntImageT> {
public:
explicit BlobMatcher (const int nrOfRotations = 3, const float perimeterFillRatio = 0, const int fillSampleSize = 0,
const int randomSampleSize = 0);
~BlobMatcher ();
void ChangeParams (const int nrOfRotations, const float perimeterFillRatio = 0, const int fillSampleSize = 0,
const int randomSampleSize = 0);
int AddPattern (const IntImageT &image, const std::string &name); // fres = id
void RemovePattern (const std::string &name);
int BestMatch (const IntImageT &blob, const float beginAngle, const float endAngle,
float &confidence, float &error, float &scale, float &angle); // fres = id
float AllMatches (const IntImageT &blob, const float beginAngle, const float endAngle,
PatternMatchResultTab &tab); // fres = confidence
float EvaluateClassImageSet (JL_BPN::ClassImageSet<IntImageT> &cis,
const float beginAngle, const float endAngle,
PatternEvalResultTab &tabs, float &meanError); // fres = max error
int FindPatterns (const IntImageT &image, // labelled image to search in, fres = number found
const float maxError, const float minConfindence,
const float beginAngle, const float endAngle,
PatternMatchResultTab &labelTab,
PatternLabelTab &patTab);
IntImageT& PatternImage (const int id) const;
IntImageT& PatternImage (const std::string &name) const;
void WriteToFile (const std::string &fileName);
void ReadFromFile (const std::string &fileName);
void WriteToStream (std::ostream& os);
void ReadFromStream (std::istream& is);
int NrOfRotations () { return nrOfRotations; }
float FillRatio () { return fillRatio; }
int FillSize () { return fillSize; }
int SampleSize () { return sampleSize; }
private:
void InitNewBM (const int nrOfRotations, const float perimeterFillRatio,
const int fillSampleSize, const int randomSampleSize);
int nrOfRotations;
float fillRatio;
int fillSize;
int sampleSize;
void *patternTab;
}; // BlobMatcher


template <class IntImageT>
int FindBlob (const IntImageT &src, //fres = number found
const IntImageT &pat,
IntImageT &dest,
const Connected connected,
const float maxError,
const float beginAngle, const float endAngle,
const int nrOfRotations, const float perimeterFillRatio = 0,
const int fillSampleSize = 0, const int randomSampleSize = 0);

std::string PatternMatchResultToStr (const PatternMatchResult &mr);
PatternMatchResult StrToPatternMatchResult (const std::string &str);
std::istream& operator>> (std::istream& is, PatternMatchResult &mr);
std::ostream& operator<< (std::ostream& os, const PatternMatchResult &mr);

std::string PatternMatchResultTabToStr (const PatternMatchResultTab &tab);
PatternMatchResultTab StrToPatternMatchResultTab(const std::string &str);
std::istream& operator>> (std::istream& is, PatternMatchResultTab &tab);
std::ostream& operator<< (std::ostream& os, const PatternMatchResultTab &tab);

std::string PatternLabelTabToStr (const PatternLabelTab &tab);
PatternLabelTab StrToPatternLabelTab(const std::string &str);
std::istream& operator>> (std::istream& is, PatternLabelTab &tab);
std::ostream& operator<< (std::ostream& os, const PatternLabelTab &tab);

std::string PatternNamesTabToStr (const PatternNamesTab &t);
PatternNamesTab StrToPatternNamesTab(const std::string &str);
std::istream& operator>> (std::istream& is, PatternNamesTab &t);
std::ostream& operator<< (std::ostream& os, const PatternNamesTab &t);

std::string PatternEvalResultToStr (const PatternEvalResult &mr);
PatternEvalResult StrToPatternEvalResult (const std::string &str);
std::istream& operator>> (std::istream& is, PatternEvalResult &mr);
std::ostream& operator<< (std::ostream& os, const PatternEvalResult &mr);

std::string PatternEvalResultTabToStr (const PatternEvalResultTab &tab);
PatternEvalResultTab StrToPatternEvalResultTab(const std::string &str);
std::istream& operator>> (std::istream& is, PatternEvalResultTab &tab);
std::ostream& operator<< (std::ostream& os, const PatternEvalResultTab &tab);

} // namespace JL_VisionLib_V3

#endif



Back to Contents

coloboper.h

/* File : colooper.h
* Project : visionlib V3.0
* Author : Jaap van de Loosdrecht
* Van de Loosdrecht Machine Vision BV
* www.vdlmv.nl
* Date : 2-7-2016
*
* Copyright (c) 1993-2017, Van de Loosdrecht Machine Vision BV,
* all rights reserved.
*/

#ifndef JL_VIS_LIB_COLOR_OPERATORS
#define JL_VIS_LIB_COLOR_OPERATORS

#include "word.h"
#include "colorima.h"

namespace JL_VisionLib_V3 {

class Color888Pixel {
public:
typedef JL_Word::Byte ColorType;
explicit Color888Pixel (const int v = 0) {
c1 = JL_Word::Byte(v);
c2 = JL_Word::Byte(v);
c3 = JL_Word::Byte(v);
pad = 0;
}
Color888Pixel (const JL_Word::Byte ch1, const JL_Word::Byte ch2, const JL_Word::Byte ch3) {
c1 = ch1; c2 = ch2; c3 = ch3; pad = 0;
}
bool operator == (const Color888Pixel p) const {
return ((c1 == p.c1) && (c2 == p.c2) && (c3 == p.c3));
}
bool operator != (const Color888Pixel p) const {
return !(operator==(p));
}
bool operator < (const Color888Pixel p) const {
return ((p.c1 < p.c1) || (p.c2 < p.c2) || (p.c3 < p.c3));
}
#ifdef __BIG_ENDIAN__
JL_Word::Byte pad;
JL_Word::Byte c1;
JL_Word::Byte c2;
JL_Word::Byte c3;
#else
JL_Word::Byte c3;
JL_Word::Byte c2;
JL_Word::Byte c1;
JL_Word::Byte pad;
#endif
};

class Color161616Pixel {
public:
typedef JL_Word::Int16 ColorType;
explicit Color161616Pixel (const int v = 0) {
c1 = JL_Word::Int16(v);
c2 = JL_Word::Int16(v);
c3 = JL_Word::Int16(v);
}
Color161616Pixel (const JL_Word::Int16 ch1, const JL_Word::Int16 ch2, const JL_Word::Int16 ch3) {
c1 = ch1; c2 = ch2; c3 = ch3;
}
bool operator == (const Color161616Pixel p) const {
return ((c1 == p.c1) && (c2 == p.c2) && (c3 == p.c3));
}
bool operator != (const Color161616Pixel p) const {
return !(operator==(p));
}
bool operator < (const Color888Pixel p) const {
return ((p.c1 < p.c1) || (p.c2 < p.c2) || (p.c3 < p.c3));
}
JL_Word::Int16 c3;
JL_Word::Int16 c2;
JL_Word::Int16 c1;
};

template<class ColImageT>
void ContrastStretchLUT1Channel (ColImageT &image, const int chanNr, const int low, const int high);

template<class ColImageT>
void ContrastStretchLUT3Channels (ColImageT &image, const int low, const int high);

enum FalseColorStretch { FC_Stretch, FC_NoStretch };
template<class ColImageT, class OrdImageT>
void ConvertToFalseColor (const OrdImageT &src, const ColImageT &lut, ColImageT &dest, const FalseColorStretch stretch = FC_Stretch);

template <class ColImageT, class OrdImageT>
void Extract1Channel (const ColImageT &image, const int chanNr, OrdImageT &chan);
// first channel is chanNr 0

template <class ColImageT, class OrdImageT>
void Extract3Channels (const ColImageT &image,
OrdImageT &chan1, OrdImageT &chan2, OrdImageT &chan3);

template <class ColImageT, class OrdImageT>
void Merge1Channel (ColImageT &image, const OrdImageT &chan, const int chanNr);
// first channel is chanNr 0

template <class OrdImageT, class ColImageT>
void Merge3Channels (const OrdImageT &chan1, const OrdImageT &chan2,
const OrdImageT &chan3, ColImageT &image);

template<class ColImageT,class OrdImageT>
void RangeToFalseColor(const OrdImageT &src, const ColImageT &lut, ColImageT &dest, const typename OrdImageT::PixelType low, const typename OrdImageT::PixelType high);

template <class ColImageT, class OrdImageT>
void Threshold3Channels (const ColImageT &image, OrdImageT &thresImage,
const int lowChan1, const int highChan1,
const int lowChan2, const int highChan2,
const int lowChan3, const int highChan3);

EnumStrIODeclaration(FalseColorStretch) ;

} // namespace JL_VisionLib_V3

#endif



Back to Contents

rgboper.h

/* File : rgboper.h
* Project : visionlib V3.0
* Author : Jaap van de Loosdrecht
* Van de Loosdrecht Machine Vision BV
* www.vdlmv.nl
* Date : 20-1-2014
*
* Copyright (c) 1993-2017, Van de Loosdrecht Machine Vision BV,
* all rights reserved.
*/

#ifndef JL_VIS_LIB_RGB_OPERATORS
#define JL_VIS_LIB_RGB_OPERATORS

#include "rgbimage.h"
#include "ordimage.h"
#include "intimage.h"
#include "util.h"

namespace JL_VisionLib_V3 {

enum CFAType {BayerGB, BayerGR, BayerBG, BayerRG, NrOfCFATypes}; // Color Filter Array

template<class OrdImageT>
void ConvertOrdToRGB888Image (const OrdImageT &src, RGB888Image &dest);

template<class OrdImageT>
void ConvertRGB888ToOrdImage (const RGB888Image &src, OrdImageT &dest);

template<class OrdImageT>
void ConvertOrdToRGB161616Image (const OrdImageT &src, RGB161616Image &dest);

template<class OrdImageT>
void ConvertRGB161616ToOrdImage (const RGB161616Image &src, OrdImageT &dest);

void ConvertRGB888To161616Image (const RGB888Image &src, RGB161616Image &dest);

void ConvertRGB161616To888Image (const RGB161616Image &src, RGB888Image &dest);

CFAType CFATypeROIConversion (const CFAType type, const int topLeftX, const int topLeftY);

template<class IntImageT>
void ConvertCFAToRGB888Image (const IntImageT &src, RGB888Image &dest, const CFAType cfa = BayerGB);

template<class IntImageT>
void ConvertCFAToRGB161616Image (const IntImageT &src, RGB161616Image &dest, const CFAType cfa = BayerGB);

template<class OrdImageT>
void Extract1Channel (const RGB888Image &image, const RGBColor plane, OrdImageT &chan);

template<class OrdImageT>
void Extract1Channel (const RGB161616Image &image, const RGBColor plane, OrdImageT &chan);

template<class RGBImageT>
void NormaliseRGB (RGBImageT &image);

std::string CFATypeToStr (const CFAType cfa);
CFAType StrToCFAType(const std::string &str);
std::istream& operator>> (std::istream& is, CFAType &cfa);
std::ostream& operator<< (std::ostream& os, const CFAType cfa);


} // namespace JL_VisionLib_V3

#endif



Back to Contents

hsvoper.h

/* File : hsvoper.h
* Project : visionlib V3.0
* Author : Jaap van de Loosdrecht
* Van de Loosdrecht Machine Vision BV
* www.vdlmv.nl
* Date : 16-12-2011
*
* Copyright (c) 1993-2017, Van de Loosdrecht Machine Vision BV,
* all rights reserved.
*/

#ifndef JL_VIS_LIB_HSV_OPERATORS
#define JL_VIS_LIB_HSV_OPERATORS

#include "rgbimage.h"
#include "hsvimage.h"
#include "yuvoper.h"
#include "realimag.h"

namespace JL_VisionLib_V3 {

RGB888Pixel ConvertHSV888ToRGB888Pixel (const HSV888Pixel &hsv);
HSV888Pixel ConvertRGB888ToHSV888Pixel (const RGB888Pixel &rgb);

RGB161616Pixel ConvertHSV161616ToRGB161616Pixel (const HSV161616Pixel &hsv);
HSV161616Pixel ConvertRGB161616ToHSV161616Pixel (const RGB161616Pixel &rgb);

void ConvertHSV888ToRGB888Image (const HSV888Image &src, RGB888Image &dest);
void ConvertRGB888ToHSV888Image (const RGB888Image &src, HSV888Image &dest);

void ConvertHSV161616ToRGB161616Image (const HSV161616Image &src, RGB161616Image &dest);
void ConvertRGB161616ToHSV161616Image (const RGB161616Image &src, HSV161616Image &dest);

void ConvertHSV888To161616Image (const HSV888Image &src, HSV161616Image &dest);
void ConvertHSV161616To888Image (const HSV161616Image &src, HSV888Image &dest);

void InitFastYUVToHSV (void);
void InitFastRGBToHSV (void);
void FreeFastYUVToHSV (void);
void FreeFastRGBToHSV (void);
void FastYUVToHSV (const YUV888Image &src, HSV888Image &dest);
void FastRGBToHSV (const RGB888Image &src, HSV888Image &dest);

template<class OrdImageT>
void Extract1Channel (const HSV888Image &image, const HSVColor plane, OrdImageT &chan);

template<class OrdImageT>
void Extract1Channel (const HSV161616Image &image, const HSVColor plane, OrdImageT &chan);

template<class HSVImageT, class ColorT, class FloatImageT>
void NormaliseHue (const HSVImageT &src, const ColorT hue, const ColorT minVal, const ColorT minSat, FloatImageT &dest, const float notNormalised = 0);
//template<class HSVImageT, class FloatImageT>
//void NormaliseHue (const HSVImageT &src, const typename HSV888Image::PixelType::ColorType hue, const typename HSV888Image::PixelType::ColorType minVal, const typename HSV888Image::PixelType::ColorType minSat, FloatImageT &dest, const float notNormalised = 0);

} // namespace JL_VisionLib_V3

#endif



Back to Contents

yuvoper.h

/* File : yuvoper.h
* Project : visionlib V3.0
* Author : Jaap van de Loosdrecht
* Van de Loosdrecht Machine Vision BV
* www.vdlmv.nl
* Date : 20-1-2014
*
* Copyright (c) 1993-2017, Van de Loosdrecht Machine Vision BV,
* all rights reserved.
*/

#ifndef JL_VIS_LIB_YUV_OPERATORS
#define JL_VIS_LIB_YUV_OPERATORS

#include "yuvimage.h"
#include "rgbimage.h"
#include "intimage.h"

namespace JL_VisionLib_V3 {

inline RGB888Pixel ConvertYUV888ToRGB888Pixel (const YUV888Pixel &yuv) {
RGB888Pixel rgb;
int c = yuv.y -16;
int d = yuv.u - 128;
int e = yuv.v - 128;
rgb.red = JL_Util::ClipByte((298*c + 409*e + 128) >> 8);
rgb.green = JL_Util::ClipByte((298*c - 100*d - 208*e + 128) >> 8);
rgb.blue = JL_Util::ClipByte((298*c + 516*d + 128) >> 8);
return rgb;
}

inline YUV888Pixel ConvertRGB888ToYUV888Pixel (const RGB888Pixel &rgb) {
YUV888Pixel yuv;
yuv.y = (( 66*rgb.red + 129*rgb.green + 25*rgb.blue + 128) >> 8) + 16;
yuv.u = ((-38*rgb.red - 74*rgb.green + 112*rgb.blue + 128) >> 8) + 128;
yuv.v = ((112*rgb.red - 94*rgb.green - 18*rgb.blue + 128) >> 8) + 128;
return yuv;
}

inline RGB161616Pixel ConvertYUV161616ToRGB161616Pixel (const YUV161616Pixel &yuv) { // to do
RGB161616Pixel rgb;
int c = yuv.y -16;
int d = yuv.u - 128;
int e = yuv.v - 128;
rgb.red = JL_Util::ClipByte((298*c - + 409*e + 128) >> 8);
rgb.green = JL_Util::ClipByte((298*c - 100*d - 208*e + 128) >> 8);
rgb.blue = JL_Util::ClipByte((298*c + 516*d + 128) >> 8);
return rgb;
}

inline YUV161616Pixel ConvertRGB161616ToYUV161616Pixel (const RGB161616Pixel &rgb) { // to do
YUV161616Pixel yuv;
yuv.y = (( 66*rgb.red + 129*rgb.green + 25*rgb.blue + 128) >> 8) + 16;
yuv.u = ((-38*rgb.red - 74*rgb.green + 112*rgb.blue + 128) >> 8) + 128;
yuv.u = ((112*rgb.red - 94*rgb.green - 18*rgb.blue + 128) >> 8) + 128;
return yuv;
}

void ConvertYUV888ToRGB888Image (const YUV888Image &src, RGB888Image &dest);
void ConvertRGB888ToYUV888Image (const RGB888Image &src, YUV888Image &dest);

void ConvertYUV161616ToRGB161616Image (const YUV161616Image &src, RGB161616Image &dest);
void ConvertRGB161616ToYUV161616Image (const RGB161616Image &src, YUV161616Image &dest);

void ConvertYUV888To161616Image (const YUV888Image &src, YUV161616Image &dest);
void ConvertYUV161616To888Image (const YUV161616Image &src, YUV888Image &dest);

template<class OrdImageT>
void Extract1Channel (const YUV888Image &image, const YUVColor plane, OrdImageT &chan);

template<class OrdImageT>
void Extract1Channel (const YUV161616Image &image, const YUVColor plane, OrdImageT &chan);



} // namespace JL_VisionLib_V3

#endif



Back to Contents

firepack.h

/* File : firepack.h
* Project : visionlib V3.36
* Author : Alex Beemsterboer
* Klaas Dijkstra
* Date : 26-12-2006
*
* Copyright (c) 1993-2014, Computer Vision Lab NHL and
* Van de Loosdrecht Machine Vision BV,
* all rights reserved.
*/

#ifndef JL_FIREPACK
#define JL_FIREPACK

#include <windows.h>
#include "intimage.h"
#include "yuvimage.h"
#include "rgbimage.h"
#include "camera.h"
#include "fgcamera.h"

namespace JL_VisionLib_V3 {

typedef struct {
UINT32 CycOffset : 12;
UINT32 CycCount : 13;
UINT32 Second : 7;
}TCycleTime;

typedef struct {
UINT32 Second : 7;
UINT32 CycCount : 13;
UINT32 CycOffset : 12;
}TCycleTimeInv;

typedef struct {
UINT32 SecondCount;
UINT32 CycleCount;
UINT32 CycleOffset;
} TTimeStamp;

typedef struct {
TTimeStamp FrameTimeStamp;
TTimeStamp BusTimeStamp;
UINT32 FrameCounter;
UINT32 TriggerCounter;
} TFrameMetaData;

//Timestamp Location
#define TSL_FRAME 1
#define TSL_BUS 2
//Counter Name
#define CN_TRIGGER 3
#define CN_FRAME 4

class FirePack: public Camera<ByteImage> , public Camera<RGB888Image> {
public:
static int camCount;
TFrameMetaData FrameMetaData;

bool AutoGainEnabled;
bool AutoWhiteBalanceEnabled;
bool AutoShutterEnabled;

FirePack (int camNodeId, int modeNr, int bufferCnt, string dmaMode, FG_PHYSPEED busspeed);
~FirePack ();

static std::string CamsInfo();
std::string GetDeviceName();
UINT32 GetCamBitValue(UINT32 value, short start, short count);
void SetCamBitValue(UINT32 Register, short Start, short Count, UINT32 Value);
void HandleError(string procName, string errMsg, int value);

// virtual void Reset () {};
virtual std::string GetImageType() const;
virtual Image* SnapShot (const int roiNr = 0);
virtual void SnapShot (ByteImage &image, const int roiNr = 0);
virtual void SnapShot (YUV888Image &image, const int roiNr = 0);
virtual void SnapShot (RGB888Image &image, const int roiNr = 0);
virtual void SnapShot (Int16Image &image, const int roiNr = 0);
virtual std::vector<Image*> SnapShotROIs ();
virtual void SnapShotROIs (std::vector<ByteImage> &images);
virtual void SnapShotROIs (std::vector<RGB888Image> &images);
virtual void SnapShotROIs (std::vector<YUV888Image> &images);
virtual void SnapShotROIs (std::vector<Int16Image> &images);

virtual int AddROI (const CamROI &roi);
virtual void SetROI (const int n, const CamROI &roi);
virtual void SetROIsTab (const CamROIsTab &tab);

int SetAutoExposure (const int value);
int GetAutoExposure ();
int SetBrightness (const int value);
int GetBrightness ();
int SetFocus (const int value);
int GetFocus ();
int SetGain (const int value);
int GetGain ();
int SetGamma (const int value);
int GetGamma ();
int SetHue (const int value);
int GetHue ();
int SetIris (const int value);
int GetIris ();
int SetSaturation (const int value);
int GetSaturation ();
int SetSharpness(const int value);
int GetSharpness ();
int SetShutter (const int value);
int GetShutter ();
int SetWhiteBalanceU (const int value);
int GetWhiteBalanceU ();
int SetWhiteBalanceV (const int value);
int GetWhiteBalanceV ();
void WhiteBalanceOnePush ();
int SetOpticalFilter (const int value);
int GetOpticalFilter ();
int SetPan(const int value);
int GetPan ();
int SetTemperature (const int value);
int GetTemperature ();
int SetTilt (const int value);
int GetTilt ();
int SetZoom (const int value);
int GetZoom ();
int SetCaptureSize (const int value);
int GetCaptureSize ();
int SetCaptureQuality(const int value);
int GetCaptureQuality ();
int SetTriggerDelay (const int value);
int GetTriggerDelay ();
int SetWhiteShade (const int value);
int GetWhiteShade ();
int SetFrameTimeout (const int value);
int GetFrameTimeout ();
std::string SetTrigger (const std::string &input);
std::string GetTrigger ();
int SetTriggerPolarity (const int value);
int GetTriggerPolarity ();
int SetMirror(const int value);
int GetMirror();

//High Dynamic Range
int GetHDREnabled();
int SetHDREnabled(const int value);
int GetHDR1();
int SetHDR1(const int value);
int GetHDR2();
int SetHDR2(const int value);
int GetHDR3();
int SetHDR3(const int value);

//Auto features
string SetAutoGain(const string &);
string GetAutoGain();
string SetAutoWhiteBalance(const string &);
string GetAutoWhiteBalance();
string SetAutoShutter(const string &);
string GetAutoShutter();
int SetAutoShutterMin(const int);
int GetAutoShutterMin();
int SetAutoShutterMax(const int);
int GetAutoShutterMax();

//Enable Frame/Trigger Timestamp/Counting
string SetFrameMetaDataEnabled(const string &);
string GetFrameMetaDataEnabled();

int SetFrameMetaDataLine(const int);
int GetFrameMetaDataLine();

void ResetFrameMetaDataCounters();
bool TriggeringStart ();
bool TriggeringStop();

string ToBinary(unsigned int input);
TTimeStamp GetTimeStamp(FGFRAME * frame, short TimeStampLocation, UINT32 ByteOffSet);
UINT32 GetCounter(FGFRAME * frame, short CounterName, UINT32 ByteOffSet);
TFrameMetaData GetFrameMetaData(FGFRAME * frame, UINT32 ByteOffSet);

protected:
CFGCamera cam;
UINT32 height;
UINT32 width;
UINT32 colorFormat;
bool modeIsScalable;
bool dmaModeIsLimp;
std::string deviceName;

const static int maxNrOfCams = 10;
int frameTimeoutMS;

class ScalableROI
{
public:
int xpos;
int ypos;
int xsize;
int ysize;
};
ScalableROI sROI;

void FinalizeConstruction();
int SetCamParam(UINT16 type, const int value);
int GetCamParam(UINT16 type);
void SetScalableROI();
}; // FirePack

} // namespace JL_VisionLib_V3

#endif // JL_FirePack




Back to Contents

dxcam.h

#ifndef DX_CAM
#define DX_CAM


#include "intimage.h"
#include "rgbimage.h"
#include "camera.h"
#include "word.h"
#include "compiler.h"
#include <typeinfo.h>
#include <windows.h>
#include <stdio.h>
#include "word.h"
#include "util.h"
#include "intimage.h"
#include "vislibsv.h"
#include "convers.h"
#include "numoper.h"

// changed since VS2005 (error C4430: missing type specifier - int assumed. Note: C++ does not support default-int)
// Klaas: rgboper.h line 21 needs a type.
#pragma warning (disable : 4430)
#include "rgboper.h"
#pragma warning (default : 4430)
// end

#include "yuvimage.h"
#include "yuvoper.h"
#include "DX_WDM_Cam.h"

using namespace std;
using namespace JL_Util;
using namespace JL_Word;

namespace JL_VisionLib_V3 {

class DXCam: public Camera<RGB888Image> {
public:
DXCam(int camID, int mode = 0);
~DXCam(void);
int SetMode(const int mode);
int GetMode(){ return cam->CurrentMode(); }
string GetModeDescription(int mode);
string CamName(){return cam->CamName();};

virtual Image* SnapShot(const int roiNr = 0);
virtual std::vector<Image*> SnapShotROIs();
virtual std::string GetImageType() const;
virtual void Reset (){};

//virtual void SnapShot (ByteImage &image, const int roiNr = 0){};
virtual void SnapShot (RGB888Image &image, const int roiNr = 0);
//virtual void SnapShotROIs (std::vector<ByteImage> &images){};
virtual void SnapShotROIs (std::vector<RGB888Image> &images);

virtual void SnapShot (YUV888Image &image, const int roiNr = 0);
virtual void SnapShotROIs (std::vector<YUV888Image> &images);

int SetBacklightCompensation(const int bc);
int SetBrightness(const int b);
int SetColorEnable(const int b);
int SetContrast(const int b);
int SetGain(const int b);
int SetGamma(const int b);
int SetHue(const int b);
int SetSaturation(const int b);
int SetSharpness(const int b);
int SetWhiteBalance(const int b);

int SetPan(const int b);
int SetTilt(const int b);
int SetRoll(const int b);
int SetZoom(const int b);
int SetExposure(const int b);
int SetIris(const int b);
int SetFocus(const int b);

int GetBacklightCompensation(){ return GetControlValue(8); };
int GetBrightness() { return GetControlValue(0); };
int GetColorEnable() { return GetControlValue(6); };
int GetContrast() { return GetControlValue(1); };
int GetGain() { return GetControlValue(9); };
int GetGamma() { return GetControlValue(5); };
int GetHue() { return GetControlValue(2); };
int GetSaturation() { return GetControlValue(3); };
int GetSharpness() { return GetControlValue(4); };
int GetWhiteBalance() { return GetControlValue(7); };
int GetPan(){ return GetVControlValue(0); }
int GetTilt(){ return GetVControlValue(1); }
int GetRoll(){ return GetVControlValue(2); }
int GetZoom(){ return GetVControlValue(3); }
int GetExposure(){ return GetVControlValue(4); }
int GetIris(){ return GetVControlValue(5); }
int GetFocus(){ return GetVControlValue(6); }
protected:
DX_WDM_Cam *cam;
int GetControlValue(int control);
int GetVControlValue(int control);
void ReadFromBuffer(BYTE *buffer, CamROI roi, RGB888Image *image);
void ReadFromBuffer(BYTE *buffer, CamROI roi, YUV888Image *image);

};

}

#endif



Back to Contents

camrecord.h

/* File : camrecord.h
* Project : visionlib V3.0
* Author : Jaap van de Loosdrecht
* Van de Loosdrecht Machine Vision BV
* www.vdlmv.nl
* Date : 14-2-2013
*
* Copyright (c) 1993-2017, Van de Loosdrecht Machine Vision BV,
* all rights reserved.
*/

// note: restriction: only first roi is used !!!!!!!! <----------------

#ifndef JL_CAM_RECORDER
#define JL_CAM_RECORDER

#include "image.h"
#include "camera.h"
#include <vector>
#include <string>

namespace JL_VisionLib_V3 {

// note: restriction: only first roi is used !!!!!!!! <----------------
class CamRecorderBase {
public:
virtual ~CamRecorderBase () {};
virtual std::string Record () = 0;
}; // CamRecorderBase

template<class ImageT>
class CamRecorder : public CamRecorderBase {
public:
CamRecorder (Camera<ImageT> &cam, const std::string &fileNameBase,
const int firstNr, const int nrShots);
~CamRecorder ();
std::string Record ();
Camera<ImageT>* GetCamPtr () { return camPtr; }
private:
std::vector<ImageT> imageTab;
Camera<ImageT> *camPtr;
std::string fileNameBase;
int shotNr;
}; // CamRecorder


enum ImageLoggerType {LinearImageLogger, CircularImageLogger};
enum ImageLoggerMode {DisgardNImageLogger, ForceImageLogger};

class ImageLoggerBase {
public:
virtual ~ImageLoggerBase () {};
virtual void Clear () = 0;
virtual int NrImages () const = 0;
virtual int SaveToFiles (const std::string &fileNameBase) const = 0;
virtual std::string GetImageType() const = 0;
virtual HeightWidth GetHeightWidth() const = 0;
}; // ImageLoggerBase

template<class ImageT>
class ImageLogger : public ImageLoggerBase {
public:
ImageLogger (const ImageLoggerType lt, const int maxNrImages, const HeightWidth &hw, const int maxStrSize, const int disgard = 0);
~ImageLogger ();
void Add (const ImageT &image, const std::string &str, const ImageLoggerMode mode = DisgardNImageLogger);
void Clear ();
int NrImages () const { return nrImages; }
int SaveToFiles (const std::string &fileNameBase) const;
std::string GetNth (const int nth, ImageT &image) const;
std::string GetImageType() const;
HeightWidth GetHeightWidth() const { return heightWidth; };
private:
ImageLoggerType logType;
std::vector<ImageT> imageBuf;
std::vector<string> strBuf;
int nrImages, maxNrImages, first, last, disgard, disgardCount;
HeightWidth heightWidth;
}; // ImageLogger

EnumStrIODeclaration(ImageLoggerType)
EnumStrIODeclaration(ImageLoggerMode)

} // namespace JL_VisionLib_V3

#endif // JL_CAM_RECORDER



Back to Contents

cambase.h

/* File : cambase.h
* Project : visionlib V3.0
* Author : Jaap van de Loosdrecht
* Van de Loosdrecht Machine Vision BV
* www.vdlmv.nl
* Date : 5-4-2012
*
* Copyright (c) 1993-2017, Van de Loosdrecht Machine Vision BV,
* all rights reserved.
*/


#ifndef JL_VISLIB_CAMERA_BASE
#define JL_VISLIB_CAMERA_BASE

#include "image.h"
#include <string>
#include <vector>
#include <map>

namespace JL_VisionLib_V3 {

struct CamROI {
CamROI (const int t = 0, const int l = 0, const int h = 0, const int w = 0) {
top = t; left = l; height = h; width = w;
}
int top, left, height, width;
}; // CamROI
typedef std::vector<CamROI> CamROIsTab;

enum CamParamType {CAM_IntParam, CAM_FloatParam, CAM_StringParam, CAM_OnePushParam, CAM_InvalidParam};

class CameraBase {
public:
CameraBase ();
virtual ~CameraBase ();

virtual Image* SnapShot(const int roiNr = 0) = 0;
virtual std::vector<Image*> SnapShotROIs() = 0;
virtual std::string GetImageType() const = 0;
virtual void Reset() {};

virtual int GetMinHeight() const;
virtual int GetMinWidth() const;
virtual int GetMaxHeight() const;
virtual int GetMaxWidth() const;
virtual int GetMaxNrOfROIs() const;

virtual void ClearROITab();
virtual int NrOfROIs () const;
virtual int MaxNrOfROIs () const;
virtual int AddROI (const CamROI &roi);
virtual void SetROI (const int n, const CamROI &roi);
virtual CamROI GetROI (const int n) const;
virtual void SetROIsTab (const CamROIsTab &tab);
virtual CamROIsTab GetROIsTab () const;

virtual std::string SetParam (const std::string ¶m, const std::string &value);
virtual int SetIntParam (const std::string ¶m, const int value);
virtual double SetFloatParam (const std::string ¶m, const double value);
virtual std::string SetStringParam (const std::string ¶m, const std::string &value);
virtual void OnePushParam (const std::string ¶m);

virtual std::string GetParam (const std::string ¶m) const;
virtual int GetIntParam (const std::string ¶m) const;
virtual double GetFloatParam (const std::string ¶m) const;
virtual std::string GetStringParam (const std::string ¶m) const;

virtual std::string GetParamNames () const ;
virtual std::string GetParamInfo (const std::string ¶m) const;
virtual std::string GetParamsInfo () const;
virtual std::string GetParamInfoFromCamera (const std::string ¶m) const;
virtual std::string GetParamsInfoFromCamera () const;
virtual std::string GetParams () const ;
virtual CamParamType GetParamType (const std::string ¶m) const;
virtual float GetParamMinValue (const std::string ¶m) const;
virtual float GetParamMaxValue (const std::string ¶m) const;

virtual void WriteToFile (const std::string &fileName) const;
virtual void ReadFromFile (const std::string &fileName);

class SetIntCmd {
public:
virtual ~SetIntCmd() {};
virtual int Execute (const int) = 0;
virtual SetIntCmd* Clone () const = 0;
protected:
SetIntCmd () {};
};

class GetIntCmd {
public:
virtual ~GetIntCmd() {};
virtual int Execute (void) = 0;
virtual GetIntCmd* Clone () const = 0;
protected:
GetIntCmd () {};
};

class SetFloatCmd {
public:
virtual ~SetFloatCmd() {};
virtual double Execute (const double) = 0;
virtual SetFloatCmd* Clone () const = 0;
protected:
SetFloatCmd () {};
};

class GetFloatCmd {
public:
virtual ~GetFloatCmd() {};
virtual double Execute (void) = 0;
virtual GetFloatCmd* Clone () const = 0;
protected:
GetFloatCmd () {};
};

class SetStringCmd {
public:
virtual ~SetStringCmd() {};
virtual std::string Execute (const std::string &) = 0;
virtual SetStringCmd* Clone () const = 0;
protected:
SetStringCmd () {};
};

class GetStringCmd {
public:
virtual ~GetStringCmd() {};
virtual std::string Execute (void) = 0;
virtual GetStringCmd* Clone () const = 0;
protected:
GetStringCmd () {};
};

class OnePushCmd {
public:
virtual ~OnePushCmd() {};
virtual void Execute () = 0;
virtual OnePushCmd* Clone () const = 0;
protected:
OnePushCmd () {};
};


protected:
void AddParam (const std::string &name, const SetIntCmd &set, const GetIntCmd &get,
const int min, const int max);
void AddParam (const std::string &name, const SetFloatCmd &set, const GetFloatCmd &get,
const double min, const double max);
void AddParam (const std::string &name, const SetStringCmd &set, const GetStringCmd &get,
const std::string &values);
void AddParam (const std::string &name, const OnePushCmd &set);
void ClearParamTab ();
void RemoveParam (const std::string &name);
int minHeight, minWidth, maxHeight, maxWidth, maxNrOfROIs;
CamROIsTab roiTab;
struct Param_Rec {
Param_Rec () {
paramType = CAM_InvalidParam;
seqNr = 0;
iValue = iMin = iMax = 0;
fValue = fMin = fMax = 0;
setIntCmd = 0; getIntCmd = 0;
setFloatCmd = 0; getFloatCmd = 0;
setStringCmd = 0; getStringCmd = 0;
onePushCmd = 0;
}
void Clear () {
paramType = CAM_InvalidParam;
seqNr = 0;
if (setIntCmd != 0) delete setIntCmd;
if (getIntCmd != 0) delete getIntCmd;
if (setFloatCmd != 0) delete setFloatCmd;
if (getFloatCmd != 0) delete getFloatCmd;
if (setStringCmd != 0) delete setStringCmd;
if (getStringCmd != 0) delete getStringCmd;
if (onePushCmd != 0) delete onePushCmd;
}
~Param_Rec () { Clear(); }
CamParamType paramType;
int seqNr;
int iValue;
int iMin;
int iMax;
double fValue;
double fMin;
double fMax;
std::string strValue;
std::vector<std::string> strValues;
SetIntCmd *setIntCmd;
GetIntCmd *getIntCmd;
SetFloatCmd *setFloatCmd;
GetFloatCmd *getFloatCmd;
SetStringCmd *setStringCmd;
GetStringCmd *getStringCmd;
OnePushCmd *onePushCmd;
}; // Param_Rec
typedef std::map<std::string, Param_Rec, std::less<std::string> > ParamTab;
int paramSeqNr;
ParamTab paramTab;
void CheckROI (const std::string &opName, const CamROI &roi);
}; // CameraBase

std::istream& operator>> (std::istream& is, CameraBase &cb);
std::ostream& operator<< (std::ostream& os, const CameraBase &cb);

std::string CamParamTypeToStr (const CamParamType t);
CamParamType StrToCamParamType(const std::string &str);
std::istream& operator>> (std::istream& is, CamParamType &t);
std::ostream& operator<< (std::ostream& os, const CamParamType t);

std::string CamROIToStr (const CamROI &r);
CamROI StrToCamROI(const std::string &str);
std::istream& operator>> (std::istream& is, CamROI &r);
std::ostream& operator<< (std::ostream& os, const CamROI &r);

std::string CamROIsTabToStr (const CamROIsTab &tab);
CamROIsTab StrToCamROIsTab (const std::string &str);
std::istream& operator>> (std::istream& is, CamROIsTab &tab);
std::ostream& operator<< (std::ostream& os, const CamROIsTab &tab);

} // namespace JL_VisionLib_V3

#endif // JL_VISLIB_CAMERA_BASE



Back to Contents

camcalib.h

/* File : camcalib.h
* Project : visionlib V3.0
* Author : Jaap van de Loosdrecht
* Van de Loosdrecht Machine Vision BV
* www.vdlmv.nl
* Date : 5-12-2007
*
* Copyright (c) 1993-2017, Van de Loosdrecht Machine Vision BV,
* all rights reserved.
*/


#ifndef JL_VISLIB_CAMERA_CALIBRATION
#define JL_VISLIB_CAMERA_CALIBRATION

#include <string>
#include <vector>
#include "image.h"
#include "coord.h"
#include "genalgfp.h"
#include "intimage.h"

namespace JL_VisionLib_V3 {


class CamCalibration {
public:
CamCalibration ();
explicit CamCalibration (const std::string &fileName);
CamCalibration (const CamCalibration &cal);
virtual ~CamCalibration ();
CamCalibration& operator = (const CamCalibration &cal);

Coord3D PixelCToWorldC (const Coord2D &pixelC);

Coord2D PixelCToUnCorrImageC (const Coord2D &pixelC);
Coord2D UnCorrImageCToImageC (const Coord2D &unCorrImageC);
Coord3D ImageCToCamC (const Coord2D &imageC);
Coord3D CamCToWorldC (const Coord3D &camC);

//protected:
void Init();
void CalcRotationMatrix();
// data members:
int height;
int width;
double meanError; // calibration error
double maxError; // calibration error
// interior orientation parameters
double dx; // center-to-center distance of pixels in x direction
double dy; // center-to-center distance of pixels in y direction
double xp; // x-coordinate for principal point, relative to centre of image (cx)
double yp; // y-coordinate for principal point, relative to centre of image (cy)
double sx; // scale factor for timing digitizer
double kappa1; // first order lens distortion coefficient
double kappa2; // second order lens distortion coefficient
double kappa3; // third order lens distortion coefficient
double f; // camera constant (approximation of focal length)
// exterior orientation parameters
double Rx; // rotation around x-axis
double Ry; // rotation around y-axis
double Rz; // rotation around z-axis
double Tx; // translation in x direction
double Ty; // translation in y direction
double Tz; // translation in z direction
//private:
friend std::istream& operator>> (std::istream& is, CamCalibration &cal);
friend std::ostream& operator<< (std::ostream& os, const CamCalibration &cal);
double cx; // first estimate for x-coordinate center of image
double cy; // first estimate for y-coordinate center of image
double rxx, rxy, rxz, ryx, ryy, ryz, rzx, rzy, rzz;
}; // CamCalibration

std::string CamCalibrationToStr (const CamCalibration &cal);
CamCalibration StrToCamCalibration(const std::string &str);
std::istream& operator>> (std::istream& is, CamCalibration &cal);
std::ostream& operator<< (std::ostream& os, const CamCalibration &cal);

XYCoord CorrectXYCoord (const XYCoord &xy, const int height, const int width, const Coord2D &principlePoint,
const double sx, const double dx, const double dy, const double k1, const double k2, const double k3);
Coord2D CorrectCoord2D (const Coord2D &xy, const int height, const int width, const Coord2D &principlePoint,
const double sx, const double dx, const double dy, const double k1, const double k2, const double k3);

template <class NumImageT>
void CamDistortion (const NumImageT &src, NumImageT &dest,
const Coord2D &principlePoint, const double sx, const double dx, const double dy,
const double k1, const double k2, const double k3);

struct CamCalLowHigh {
double low;
double high;
};

typedef std::vector<CamCalLowHigh> CamCalLowHighTab;

class CamCalibGA {
public:
CamCalibGA (const HeightWidth &hw,
const CamCalLowHighTab &tab,
const Coord2DTab &pixelTab, const Coord3DTab &worldTab,
const double mutationP, const double deltaP,
const int populationSize = 0,
const int trace = 1,
const std::string &traceFileName = "");
virtual ~CamCalibGA ();
void RandomInitialize (const int populationSize);
void SetFounder (const int populationSize, const CamCalibration &cal);
double Optimize (const int maxGen,
const double minError,
const double deltaError,
CamCalibration &camCalib,
const double microP = 0.5);
protected:
double Fitness (const JL_GA::Params &pTab, const double maxError);
void ConvToParams (JL_GA::Params &pTab);
void ConvFromParams (const JL_GA::Params &pTab);
int sizeParams;
CamCalibration camCalib;
JL_GA::GenAlgFP *ga;
Coord2DTab pixelTab;
Coord3DTab worldTab;
}; // CamcalibGA

// Note: assumption is that all circles are horizontal and vertical equidistant
template <class IntImageT>
Coord2DTab FindCalPoints (const IntImageT &image,
const int nrRows, const int nrCols,
const int minPixels, const int maxPixels);

} // namespace JL_VisionLib_V3


#endif // JL_VISLIB_CAMERA_CALIBRATION




Back to Contents

vislibcm.h

/* File : vislibcm.h
* Project : visionlib V3.0
* Author : Jaap van de Loosdrecht
* Van de Loosdrecht Machine Vision BV
* www.vdlmv.nl
* Date : 11-2-2013
*
* Copyright (c) 1993-2017, Van de Loosdrecht Machine Vision BV,
* all rights reserved.
*/

#ifndef JL_VIS_LIB_CMD_INTERPETER
#define JL_VIS_LIB_CMD_INTERPETER

#include <string>
#include <map>
#include "cmdinter.h"
#include "image.h"
#include "stopwatc.h"
#include "cambase.h"
#include "display.h"
#include "bpn.h"
#include "intimage.h"
#include "realimag.h"
#include "complexi.h"
#include "rgbimage.h"
#include "hsvimage.h"
#include "yuvimage.h"


using namespace JL_VisionLib_V3;

namespace JL_VisionLib_V3 {

class VisLibCmdInt; // forward definition

typedef void (*CmdIntProc)(std::istream &is, std::ostream &os, VisLibCmdInt &cmdInt);
class CmdIntCommand : public CmdInterpreter::Command {
public:
CmdIntCommand (CmdIntProc proc, VisLibCmdInt &cInt) {
cmdInt = &cInt;
cmdProc = proc;
}
virtual ~CmdIntCommand() {};
virtual void Execute (std::istream &is, std::ostream &os) {
cmdProc(is, os, *cmdInt);
}
virtual CmdInterpreter::Command* Clone () const {
return new CmdIntCommand(*this);
}
private:
VisLibCmdInt *cmdInt;
CmdIntProc cmdProc;
};


typedef CameraBase* (*InstallCamProc) (std::istream &is, std::ostream &os);
class CamInstallCmd {
public:
CamInstallCmd (InstallCamProc proc = 0) {
installProc = proc;
}
virtual ~CamInstallCmd() {};
virtual CameraBase* Execute (std::istream &is, std::ostream &os) {
return installProc(is, os);
}
virtual CamInstallCmd* Clone () const {
return new CamInstallCmd(*this);
}
private:
InstallCamProc installProc;
};

class CmdIntCallBackCmd {
public:
virtual ~CmdIntCallBackCmd() {};
virtual bool Execute (void) = 0;
virtual CmdIntCallBackCmd* Clone () const = 0;
protected:
CmdIntCallBackCmd () {};
};

enum EchoMode {EchoOn, EchoOff};
enum LogMode {LogNormal, LogCSV};
typedef std::vector<std::string> Script;

class VisLibCmdInt {
public:

VisLibCmdInt (const CmdIntCallBackCmd &callBack,
const int maxHisSize = 4000, const EchoMode echo = EchoOn,
const bool debug = false, const std::string test = "");
~VisLibCmdInt ();
std::string ExecRequest (const std::string &request);

void StartTimer ();
void StopTimer ();
void ResetTimer ();
std::string GetTimer ();
std::string GetMicroTimer ();
std::string GetLastTime ();
bool GetTimerAccumulate() const;
bool SetTimerAccumulate(const bool accum);
void CalibrateTimerOverhead ();

bool IsCmd (const std::string &cmdName) const;
void InsertCmd (const std::string &cmdName,
const CmdInterpreter::Command &svrCmd,
const std::string &helpMsg,
const bool override = false);
void EraseCmd (const std::string &cmdName);
int NrCmds () const { return cmdInt.NrCmds(); }

bool IsImage (const std::string &imageName) const;
void InsertImage (const std::string &imageName,
Image *image,
const DisplayLUT lut,
const std::string &oldHistory,
const bool override = true);
void EraseImage (const std::string &imageName);
void EraseAllImages ();
void ChangeImageName (const std::string &oldName,
const std::string &newName);
Image* GetImage (const std::string &imageName) const;
bool GetImage (const std::string &imageName, ByteImage &image) const;
bool GetImage (const std::string &imageName, Int8Image &image) const;
bool GetImage (const std::string &imageName, Int16Image &image) const;
bool GetImage (const std::string &imageName, Int32Image &image) const;
bool GetImage (const std::string &imageName, FloatImage &image) const;
bool GetImage (const std::string &imageName, DoubleImage &image) const;
bool GetImage (const std::string &imageName, RGB888Image &image) const;
bool GetImage (const std::string &imageName, RGB161616Image &image) const;
bool GetImage (const std::string &imageName, HSV888Image &image) const;
bool GetImage (const std::string &imageName, HSV161616Image &image) const;
bool GetImage (const std::string &imageName, YUV888Image &image) const;
bool GetImage (const std::string &imageName, YUV161616Image &image) const;
bool GetImage (const std::string &imageName, ComplexFloatImage &image) const;
bool GetImage (const std::string &imageName, ComplexDoubleImage &image) const;
std::string ImageInfo (const std::string &imageName) const;
std::string ListAllImages () const;
std::string GetHistory (const std::string &imageName) const;
void AddToHistory (const std::string &imageName,
const std::string &hisLine);
void Add2ndToHistory (const std::string &imageName,
const std::string &image2Name);
void AddLastCmdToHistory (const std::string &imageName);
void SetDisplayLUT (const std::string &imageName,
const DisplayLUT lut);
DisplayLUT GetDisplayLUT (const std::string &imageName) const;
std::string GetLastAnswer () const;

void* GetPatternMatcher (const std::string &pmName);
JL_BPN::BPN* GetBPN (const std::string &bpnName);
void* GetCFS (const std::string &cfsName);
void* GetCIS (const std::string &cisName);

void RegisterCamera (const std::string &camType, CamInstallCmd cmd);
std::string GetRegisteredCameras() const;
void InstallCamera (const std::string &camName, const std::string &camType,
std::istream &is, std::ostream &os);
std::string GetInstalledCameras() const;
CameraBase* GetCamera(const std::string &camName) const;
void RemoveCamera (const std::string &camName);

bool IsVar (const std::string &name) const;
std::string GetVar (const std::string &name);
void SetVar (const std::string &name, const std::string &value);
std::string GetArrayStr (const std::string &name);
void SetArrayStr (const std::string &name, const std::string &value);
void SetSizeArray (const std::string &name, const int size);
int GetSizeArray (const std::string &name) const;
std::string GetArrayVar (const std::string &name, const int index);
void SetArrayVar (const std::string &name, const int index, const std::string &value);
void CopyVar (const std::string &src, const std::string &dest);
int VarToArray (const std::string &var, const std::string &array);
void ArrayToVar (const std::string &array, const std::string &var);
void RemoveVar (const std::string &name);
void RemoveAllVars ();
void GetArray (const std::string &name, std::vector<std::string> &vs);
void SetArray (const std::string &name, const std::vector<std::string> &vs);
std::string SubstituteVars (const std::string &istr);
std::string ListAllVars () const;
int GetNewLocalVarNr ();

std::string ExecuteScript (const std::string &scriptName,
const std::string ¶ms,
Script &lines);
Script GetScript (const std::string &name) const;
void SetScript (const std::string &name, const Script &script);
void RemoveScript (const std::string &name);
std::string ListAllScripts () const;

LogMode logMode;
bool logNewCmds;
int precision;
std::string test;
private:
struct ImageMapRec {
Image *image;
DisplayLUT lut;
std::string his;
};
typedef std::map <std::string, ImageMapRec, std::less<std::string> > ImageMap;
typedef std::map <std::string, CamInstallCmd, std::less<std::string> > RegisteredCamMap;
typedef std::map <std::string, CameraBase *, std::less<std::string> > InstalledCamMap;
typedef std::map <std::string, Script, std::less<std::string> > ScriptMap;
typedef std::map <std::string, std::string, std::less<std::string> > LocalVarMap;
void RequestHandler (const std::string &request);
void PreProcessScript (const std::string ¶ms, Script &script,
LocalVarMap &localVarMap);
void PostProcessScript (LocalVarMap &localVarTab);
CmdIntCallBackCmd *callBackCmd;
mutable ImageMap imageMap;
RegisteredCamMap regCamMap;
mutable InstalledCamMap instCamMap;
mutable ScriptMap scriptMap;
CmdInterpreter cmdInt;
JL_Util::StopWatch stopWatch;
bool accumulateTime;
JL_Word::Word64 timerOverhead;
EchoMode echo;
bool debug;
std::string lastCmd;
std::string lastAnswer;
int localVarNr;
std::size_t maxHisSize;
int lastTime;
}; // class VisLibCmdInt

std::string GetImageType (const VisLibCmdInt &cmdInt, const std::string &imageName);

void CheckIsImage (const VisLibCmdInt &cmdInt, const std::string &imageName);
void CheckIsNotImage (const VisLibCmdInt &cmdInt, const std::string &imageName);
void CheckIsByteImage (const VisLibCmdInt &cmdInt, const std::string &imageName);
void CheckIsInt8Image (const VisLibCmdInt &cmdInt, const std::string &imageName);
void CheckIsInt16Image (const VisLibCmdInt &cmdInt, const std::string &imageName);
void CheckIsInt32Image (const VisLibCmdInt &cmdInt, const std::string &imageName);
void CheckIsFloatImage (const VisLibCmdInt &cmdInt, const std::string &imageName);
void CheckIsDoubleImage (const VisLibCmdInt &cmdInt, const std::string &imageName);
void CheckIsRGB888Image (const VisLibCmdInt &cmdInt, const std::string &imageName);
void CheckIsRGB161616Image (const VisLibCmdInt &cmdInt, const std::string &imageName);
void CheckIsHSV888Image (const VisLibCmdInt &cmdInt, const std::string &imageName);
void CheckIsHSV161616Image (const VisLibCmdInt &cmdInt, const std::string &imageName);
void CheckIsYUV888Image (const VisLibCmdInt &cmdInt, const std::string &imageName);
void CheckIsYUV161616Image (const VisLibCmdInt &cmdInt, const std::string &imageName);
void CheckIsComplexFloatImage (const VisLibCmdInt &cmdInt, const std::string &imageName);
void CheckIsComplexDoubleImage (const VisLibCmdInt &cmdInt, const std::string &imageName);

// obsolete, do NOT use
bool CheckIsImage (const VisLibCmdInt &cmdInt, const std::string &imageName, std::ostream &os);
bool CheckIsNotImage (const VisLibCmdInt &cmdInt, const std::string &imageName, std::ostream &os);
bool CheckIsByteImage (const VisLibCmdInt &cmdInt, const std::string &imageName, std::ostream &os);
bool CheckIsInt8Image (const VisLibCmdInt &cmdInt, const std::string &imageName, std::ostream &os);
bool CheckIsInt16Image (const VisLibCmdInt &cmdInt, const std::string &imageName, std::ostream &os);
bool CheckIsInt32Image (const VisLibCmdInt &cmdInt, const std::string &imageName, std::ostream &os);
bool CheckIsFloatImage (const VisLibCmdInt &cmdInt, const std::string &imageName, std::ostream &os);
bool CheckIsDoubleImage (const VisLibCmdInt &cmdInt, const std::string &imageName, std::ostream &os);
bool CheckIsRGB888Image (const VisLibCmdInt &cmdInt, const std::string &imageName, std::ostream &os);
bool CheckIsRGB161616Image (const VisLibCmdInt &cmdInt, const std::string &imageName, std::ostream &os);
bool CheckIsHSV888Image (const VisLibCmdInt &cmdInt, const std::string &imageName, std::ostream &os);
bool CheckIsHSV161616Image (const VisLibCmdInt &cmdInt, const std::string &imageName, std::ostream &os);
bool CheckIsYUV888Image (const VisLibCmdInt &cmdInt, const std::string &imageName, std::ostream &os);
bool CheckIsYUV161616Image (const VisLibCmdInt &cmdInt, const std::string &imageName, std::ostream &os);
bool CheckIsComplexFloatImage (const VisLibCmdInt &cmdInt, const std::string &imageName, std::ostream &os);
bool CheckIsComplexDoubleImage (const VisLibCmdInt &cmdInt, const std::string &imageName, std::ostream &os);
// end obsolete

Script EncryptScript (const Script &s, const std::string &password);
Script DecryptScript (const Script &s, const std::string &password);
std::string RemoveTimeMsg (const std::string &str);

// ---------------------- string and stream utils -----------------------

std::string EchoModeToStr (const EchoMode mode);
EchoMode StrToEchoMode(const std::string &str);
std::istream& operator>> (std::istream& is, EchoMode &mode);
std::ostream& operator<< (std::ostream& os, const EchoMode mode);

std::string LogModeToStr (const LogMode mode);
LogMode StrToLogMode(const std::string &str);
std::istream& operator>> (std::istream& is, LogMode &mode);
std::ostream& operator<< (std::ostream& os, const LogMode mode);

std::istream& operator>> (std::istream& is, Script &script);
std::ostream& operator<< (std::ostream& os, const Script script);


} // namespace JL_VisionLib_V3


#endif



Back to Contents

vislibsv.h

/* File : vislibsv.h
* Project : visionlib V3.0
* Author : Jaap van de Loosdrecht
* Van de Loosdrecht Machine Vision BV
* www.vdlmv.nl
* Date : 13-1-2012
*
* Copyright (c) 1993-2017, Van de Loosdrecht Machine Vision BV,
* all rights reserved.
*/

#ifndef JL_VIS_LIB_SERVER
#define JL_VIS_LIB_SERVER

#include <string>
#include <map>
#include <strstream>
#include "cmdinter.h"
#include "sockcom.h"
#include "vislibcm.h"
#include "image.h"
#include "stopwatc.h"
#include "cambase.h"
#include "display.h"

namespace JL_VisionLib_V3 {

class VisLibSvr; // forward definition

typedef void (*SvrCmdProc)(std::istream &is, std::ostream &os, VisLibSvr &server);
class SvrCommand : public CmdInterpreter::Command {
public:
SvrCommand (SvrCmdProc proc, VisLibSvr &svr) {
server = &svr;
cmdProc = proc;
}
virtual ~SvrCommand() {};
virtual void Execute (std::istream &is, std::ostream &os) {
cmdProc(is, os, *server);
}
virtual CmdInterpreter::Command* Clone () const {
return new SvrCommand(*this);
}
private:
VisLibSvr *server;
SvrCmdProc cmdProc;
};


class VisLibSvr: public JL_Sockets::Server {
public:
VisLibSvr (VisLibCmdInt &cmdInt, const int port,
const JL_Sockets::ByteOrder order,
const int timeOutInSecs = 10);
~VisLibSvr ();
void Run ();
bool IsCmd (const std::string &cmdName) const;
void InsertCmd (const std::string &cmdName,
const CmdInterpreter::Command &svrCmd,
const std::string &helpMsg,
const bool override = false);
void EraseCmd (const std::string &cmdName);
VisLibCmdInt& CmdInt() const { return *cmdInt; };
private:
void RequestHandler (const std::string &request);
VisLibCmdInt *cmdInt;
}; // class VisLibSvr

} // namespace JL_VisionLib_V3


#endif



Back to Contents

visserv.cpp

/* File : visserv.cpp
* Project : visionlib V3.0
* Author : Jaap van de Loosdrecht
* Van de Loosdrecht Machine Vision BV
* www.vdlmv.nl
* Date : 12-8-2015
*
* Copyright (c) 1993-2017, Van de Loosdrecht Machine Vision BV,
* all rights reserved.
*/

/* How to add camera support to this component:
* DXCam:
* - add "RegisterDXCam(cmdInt);" to main
* - add dxcam.lib from the ReleaseLib directory to this project
* - build the project
* Firewire FirePack:
* - add "RegisterFirePackCam(cmdInt);" to main
* - add firepack.lib from the ReleaseLib directory to this project
* - build the project
* Gen<I>Cam:
* - add "RegisterJL_GenICam(cmdInt);" to main
* - add genicam.lib from the ReleaseLib directory to this project
* - add "$(GENICAM_ROOT_V1_1)\library\CPP\include" to c++ include directories
* - build the project
* IDSCam:
* - add "RegisterIDSCam(cmdInt);" to main
* - add idscam.lib from the ReleaseLib directory to this project
* - build the project
*/

#ifdef __GNUC__
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#endif

#include "compiler.h"
#include <stdexcept>
#include <iostream>
#include <cstdio>
#include <cstring>
#include "vislibsv.h"
#include "vislibcm.h"
#include "util.h"
#include "osspecif.h"

// includes for extensions:
#ifdef _MSC_VER
//#include "dxcam_cmd.h"
//#include "firepackcmds.h"
//#include "jl_genicamcmds.h"
//#include "idscamcmds.h"
//#include "ximeacamcmds.h"
//#include "WI_KinectCamcmds.h"
//#include "pyloncamcmds.h"
#include "MFCam_cmd.h"
#endif


#ifdef __GNUC__
#include "pyloncamcmds.h"
#include "v4lcamcmds.h"
#endif

#ifdef VisionComponents
#include "VCCamCmds.h"
#endif

#include "dcamcmds.h"
#include "fcamcmds.h"
#include "useroper.h"

using namespace std;
using namespace JL_VisionLib_V3;
using namespace JL_Sockets;
using namespace JL_Util;
using namespace JL_OS_Specific;

typedef bool (*DefaultCallBackProc)(void);
class DefaultCallBackCmd : public CmdIntCallBackCmd {
public:
DefaultCallBackCmd (DefaultCallBackProc proc) {
callBackProc = proc;
}
virtual ~DefaultCallBackCmd() {};
virtual bool Execute (void) {
return (*callBackProc)();
}
virtual CmdIntCallBackCmd* Clone () const {
return new DefaultCallBackCmd(*this);
}
private:
DefaultCallBackProc callBackProc;
}; // DefaultCallBackCmd

bool DefCallBackProc (void) {return true;}

int main (int argc, char *argv[]) {
InitOsSpecific();

// default values:
int port = 2066;
ByteOrder byteOrder = NativeByteOrder;
int timeOut = 100;
EchoMode echo = EchoOff;
//EchoMode echo = EchoOn;
char echoStr[32];
bool debug = false;
char debugStr[32];
string test = "";
int maxHisSize = 10000;

string autoStartScript = "noautostartscript";
const string usageStr = "usage: vissvr <port> <byteorder> <timeout> <maxhissize> <EchoOn|EchoOff> <autoStartScript|noautostartscript> <(no)debug> <test>";
try {
switch (argc) {
case 1:
break;
case 2:
char arg1Str[32];
(void) sscanf (argv[1], "%s", arg1Str);
if (strchr(arg1Str,'?') != NULL) {
cout << usageStr;
return 1;
}
(void) sscanf (argv[1], "%d", &port);
break;
case 3:
(void) sscanf (argv[1], "%d", &port);
byteOrder = StrToByteOrder(argv[2]);
break;
case 4:
(void) sscanf (argv[1], "%d", &port);
byteOrder = StrToByteOrder(argv[2]);
(void) sscanf (argv[3], "%d", &timeOut);
break;
case 5:
(void) sscanf (argv[1], "%d", &port);
byteOrder = StrToByteOrder(argv[2]);
(void) sscanf (argv[3], "%d", &timeOut);
(void) sscanf (argv[4], "%d", &maxHisSize);
break;
case 6:
(void) sscanf (argv[1], "%d", &port);
byteOrder = StrToByteOrder(argv[2]);
(void) sscanf (argv[3], "%d", &timeOut);
(void) sscanf (argv[4], "%d", &maxHisSize);
(void) sscanf (argv[5], "%s", echoStr);
echo = StrToEchoMode(echoStr);
break;
case 7:
(void) sscanf (argv[1], "%d", &port);
byteOrder = StrToByteOrder(argv[2]);
(void) sscanf (argv[3], "%d", &timeOut);
(void) sscanf (argv[4], "%d", &maxHisSize);
(void) sscanf (argv[5], "%s", echoStr);
echo = StrToEchoMode(echoStr);
autoStartScript = argv[6];
break;
case 8:
(void) sscanf (argv[1], "%d", &port);
byteOrder = StrToByteOrder(argv[2]);
(void) sscanf (argv[3], "%d", &timeOut);
(void) sscanf (argv[4], "%d", &maxHisSize);
(void) sscanf (argv[5], "%s", echoStr);
echo = StrToEchoMode(echoStr);
autoStartScript = argv[6];
(void) sscanf (argv[7], "%s", debugStr);
debug = (strncmp(debugStr,"debug",5) == 0);
break;
case 9:
(void) sscanf (argv[1], "%d", &port);
byteOrder = StrToByteOrder(argv[2]);
(void) sscanf (argv[3], "%d", &timeOut);
(void) sscanf (argv[4], "%d", &maxHisSize);
(void) sscanf (argv[5], "%s", echoStr);
echo = StrToEchoMode(echoStr);
(void) sscanf (argv[6], "%s", debugStr);
debug = (strncmp(debugStr,"debug",5) == 0);
autoStartScript = argv[6];
(void) sscanf (argv[7], "%s", debugStr);
debug = (strncmp(debugStr,"debug",5) == 0);
test = argv[8];
break;
default:
cout << usageStr;
HitAKey();
return 1;
} // switch argc

VisLibCmdInt cmdInt(DefaultCallBackCmd(DefCallBackProc), maxHisSize, echo, debug, test);

// register camera's
#ifdef _MSC_VER
//RegisterDummyCam(cmdInt);
//RegisterDXCam(cmdInt);
//RegisterFirePackCam(cmdInt); // Note: disable all other cams!!!!
//RegisterJL_GenICam(cmdInt);
//RegisterIDSCam(cmdInt);
//RegisterXIMEACam (cmdInt);
//RegisterWI_KinectCam (cmdInt);
//RegisterPylonCam(cmdInt);
RegisterMFCam(cmdInt);
#endif
RegisterFileCam(cmdInt);
#ifdef __GNUC__
#ifndef VisionComponents
// RegisterPylonCam(cmdInt);
RegisterV4LCam(cmdInt);
#endif
#endif
#ifdef VisionComponents
RegisterVCCam(cmdInt);
#endif
// examples:
InsertUserOperCmds (cmdInt); // simple user defined operator

// insert your own cmds <----------
// InsertMasterCmds(cmdInt); // to remove from distribution <----------------------------------------------

if (autoStartScript != "noautostartscript") {
try {
cmdInt.ExecRequest(string("call ") + autoStartScript);
cout << autoStartScript << " executed" << endl;
if (autoStartScript == "stopafterautostart.jls") return(0); // for profiling NVIDIA only
} // try
catch(...) {
cout << "no " << autoStartScript << " found" << endl;
}
}
VisLibSvr server(cmdInt, port, byteOrder, timeOut);
server.Run();
}
catch (exception &e) {
const string msg = string(e.what ()) + "\nserver aborted\n";
cout << msg;
SystemMsg (msg);
HitAKey ();
return 1;
}
catch (...) {
const string msg = "unknown exception caught, server aborted\n";
cout << msg;
SystemMsg (msg);
HitAKey ();
return 1;
}
FreeVisionLib();
return 0;
} // main




Back to Contents

useroper.cpp

/* File : useroper.cpp
* Project : visionlib V3.0
* Author : Jaap van de Loosdrecht
* Van de Loosdrecht Machine Vision BV
* www.vdlmv.nl
* Date : 1-1-2014
*
* Copyright (c) 1993-2017, Van de Loosdrecht Machine Vision BV,
* all rights reserved.
*/

// This an example of adding a new operator to the cmd interperter.
// For extending the server InsertUserOperCmds should be called from main in vislib.cpp .
// For extending the JL_VisionLib_NET library InsertUserOperCmds should be called from
// the constructor VisLibCmdIntNET in JL_VisionLib_NET.cpp .

#include "compiler.h"
#include <string>
#include "useroper.h"
#include "intimage.h"
#include "vislibcm.h"
#include "qstring.h"

#include "rgboper.h"
#include "numoper.h"
#include "colooper.h"
#include "ordoper.h"
#include <algorithm>

using namespace std;
using namespace JL_VisionLib_V3;

// the new operator itself

void UserSetAll (Int16Image &image, const Int16Pixel pixel) {
for (int y = 0; y < image.GetHeight(); y++) {
for (int x = 0; x < image.GetWidth(); x++) {
image(x,y) = pixel;
} // for x
} // for y
/* alternative faster solution using pointers:
Int16Pixel *ownPtr = image.GetFirstPixelPtr();
Int16Pixel *lastPtr = image.GetLastPixelPtr();
while (ownPtr <= lastPtr) {
*ownPtr++ = pixel;
} // for all pixels */
} // UserSetAll

// the following code envelope is necessary to add the new operator to the server

static void SetAllCmd (istream &is, ostream &os, VisLibCmdInt &cmdInt) {
QString imageName;
Int16Pixel pixel;
is >> imageName >> pixel;
if (is.fail()) throw(Error("[SetAll] input error"));
CheckIsInt16Image(cmdInt, imageName);
Int16Image *src = dynamic_cast <Int16Image *>(cmdInt.GetImage(imageName));
cmdInt.StartTimer();
UserSetAll (*src, pixel);
cmdInt.StopTimer();
cmdInt.AddLastCmdToHistory (imageName);
os << "example of a result string";
} // SetAllCmd

static void MultiplyWBGain (RGB161616Image &image, const double redGain, const double greenGain, const double blueGain) {
RGB161616Pixel *pTab = image.GetFirstPixelPtr();
const int nrPixels = image.GetNrPixels();
for (int i = 0; i < nrPixels; i++) {
RGB161616Pixel rgb = pTab[i];
rgb.red = RGB161616Pixel::ColorType(rgb.red * redGain);
rgb.green = RGB161616Pixel::ColorType(rgb.green * greenGain);
rgb.blue = RGB161616Pixel::ColorType(rgb.blue * blueGain);
pTab[i] = rgb;
} // for all pixels
} // MultiplyWBGain

void WhiteBalanceRaw (const Int16Image &src, RGB161616Image &dest, const XYCoord &topLeft, const HeightWidth &hw, const Int16Pixel avgPixelVal, const CFAType cfa = BayerGB) {
const int maxIter = 25;
const double MaxGain = 5;
const double MinGain = 0.01;
const double DeltaMaxDiv = 10;
const double DeltaDiv = 2;
double redGain = 1.0;
double greenGain = 1.0;
double blueGain = 1.0;
double deltaGainB = MaxGain / DeltaMaxDiv;
double deltaGainR = MaxGain / DeltaMaxDiv;
int iter = 1;
ConvertCFAToRGB161616Image(src, dest, cfa);
RGB161616Image roi, roiWB;
ROI(dest, roi, topLeft, hw);
roiWB.Resize(roi.GetHeightWidth());
Int16Image r,g,b;
Int16Pixel rAvg, gAvg, bAvg;
bool lowR = false;
bool lowB = false;
do {
roiWB = roi;
MultiplyWBGain(roiWB, redGain, greenGain, blueGain);
Extract3Channels(roiWB,r,g,b);
//rAvg = Int16Pixel(AveragePixel<Int16Image, Int16Pixel>(r) * 0.30);
//gAvg = Int16Pixel(AveragePixel<Int16Image, Int16Pixel>(g) * 0.59);
//bAvg = Int16Pixel(AveragePixel<Int16Image, Int16Pixel>(b) * 0.11);
rAvg = AveragePixel<Int16Image, Int16Pixel>(r);
gAvg = AveragePixel<Int16Image, Int16Pixel>(g);
bAvg = AveragePixel<Int16Image, Int16Pixel>(b);
if (rAvg < gAvg) {
if (!lowR) { lowR = true; deltaGainR /= DeltaDiv; }
redGain = min(redGain + deltaGainR, MaxGain);
} else if (rAvg > gAvg) {
if (lowR) { lowR = false; deltaGainR /= DeltaDiv; }
redGain = max(redGain - deltaGainR, MinGain);
} // if rAvg
if (bAvg < gAvg) {
if (!lowB) { lowB = true; deltaGainB /= DeltaDiv; }
blueGain = min(blueGain + deltaGainB, MaxGain);
} else if (bAvg > gAvg) {
if (lowB) { lowB = false; deltaGainB /= DeltaDiv; }
blueGain = max(blueGain - deltaGainB, MinGain);
} // if bAvg
if (fabs(redGain - MaxGain) <= numeric_limits<double>::epsilon()) {
greenGain -= deltaGainR;
blueGain -= deltaGainR;
deltaGainB = max (deltaGainB, deltaGainR);
} else if (fabs(redGain - MinGain) <= numeric_limits<double>::epsilon()) {
greenGain += deltaGainR;
blueGain += deltaGainR;
deltaGainB = max (deltaGainB, deltaGainR);
} // if redGain
if (fabs(blueGain - MaxGain) <= numeric_limits<double>::epsilon()) {
greenGain -= deltaGainB;
redGain -= deltaGainB;
deltaGainR = max (deltaGainB, deltaGainR);
} else if (fabs(blueGain - MinGain) <= numeric_limits<double>::epsilon()) {
greenGain += deltaGainB;
redGain += deltaGainB;
deltaGainR = max (deltaGainB, deltaGainR);
} // if blueGain
} while ((((rAvg != gAvg) || (bAvg != gAvg)) && (iter++ <= maxIter)));
double gain = double(avgPixelVal) / double(gAvg);
MultiplyWBGain(dest, gain * redGain, gain * greenGain, gain * blueGain);
} // WhiteBalanceRaw

static void WhiteBalanceRawCmd (istream &is, ostream &, VisLibCmdInt &cmdInt) {
QString srcName;
QString destName;
int x, y, h, w, avg;
CFAType cfa;
is >> srcName >> destName >> x >> y >> h >> w >> avg >> cfa;
if (is.fail()) throw(Error("[WhiteBalanceRaw] input error"));
CheckIsInt16Image(cmdInt, srcName);
const Int16Image *src = dynamic_cast <const Int16Image *>(cmdInt.GetImage(srcName));
RGB161616Image *dest = new RGB161616Image;
try {
cmdInt.StartTimer();
WhiteBalanceRaw (*src, *dest, XYCoord(x,y), HeightWidth(h,w), Int16Pixel(avg), cfa);
cmdInt.StopTimer();
}
catch (...) {
delete dest;
throw;
}
cmdInt.InsertImage (destName, dest, cmdInt.GetDisplayLUT(srcName),
cmdInt.GetHistory(srcName));
cmdInt.AddLastCmdToHistory (destName);
} // WhiteBalanceRawCmd

// called by the main program
void InsertUserOperCmds (VisLibCmdInt &cmdInt) {
cmdInt.InsertCmd ("usersetall", CmdIntCommand(SetAllCmd, cmdInt), "<imageName> <pixelvalue>");
cmdInt.InsertCmd ("whitebalanceraw", CmdIntCommand(WhiteBalanceRawCmd, cmdInt), "to do");
} // InsertUserOperCmds




Back to Contents

genalgfp.h

/* File : genalgfp.h
* Project : visionlib V3.0
* Author : Jaap van de Loosdrecht
* Van de Loosdrecht Machine Vision BV
* www.vdlmv.nl
* Date : 26-2-2008
*
* Copyright (c) 1993-2017, Van de Loosdrecht Machine Vision BV,
* all rights reserved.
*/

/* Ideas:
* Genetic Algorithm for Floating Points
* Optimalisation using both Genetic Algortitms and Hill Climbing.
* - During the first fase only GA is used, until the error level reaches
* deltaError. In this fase the params are mutated in the full range
* [low..high].
* - In the next fase GA is combined with HC. For deltaP of the mutations
* the mutation will be a delta mutation in the range random[-delta..+delta]
* - When there is a self mating it is possible there is a micro mutation
* in the range random[-micro..+micro]
*/

#ifndef JL_GENETIC_ALGORITHMS
#define JL_GENETIC_ALGORITHMS

#include <string>
#include <vector>
#include <stdexcept>

namespace JL_GA {

class Error: public std::exception {
public:
Error (const std::string& opName, const std::string& m): std::exception() {
msg = "[" + opName + "] " + m; };
virtual const char *what() const throw() { return msg.c_str(); };
virtual ~Error() throw() {}
protected:
std::string msg;
};

// description for each parameter to be optimized
struct FPParamDesc {
explicit FPParamDesc (const double l=0, const double h=0, const double d=0,
const double m=0, const double mp=0, const double dp=0) {
low=l; high=h; delta=d; micro=m; mutationP=mp;
deltaP=dp; };
bool operator == (const FPParamDesc &) const { return true; }; // dummy
bool operator < (const FPParamDesc &) const { return true; }; // dummy
double low; // lowest possible value
double high; // highest possible value
double delta; // new = old + random[-delta..+delta]
double micro; // new = old + random[-micro..+micro]
double mutationP; // propability for mutation
double deltaP; // propability that mutation is a delta mutation
};

typedef std::vector<double> Params;
typedef std::vector<Params> Population;
typedef std::vector<FPParamDesc> FPParamDescTab;

class FitnessCmd {
public:
virtual ~FitnessCmd() {};
virtual double Execute (const Params &p, const double maxError) = 0;
virtual FitnessCmd* Clone () const = 0;
protected:
FitnessCmd () {};
};

struct ParamsError { // should be private to class GenAlgFP
ParamsError () {};
explicit ParamsError (const Params &p, const double e = 0) { params = p; error = e; };
bool operator == (const ParamsError &) const { return true; }; // dummy
bool operator < (const ParamsError &pe) const { return error < pe.error; };
double error;
Params params;
};
typedef std::vector<ParamsError> ParamsErrorTab;

class FitnessAllCmd {
public:
virtual ~FitnessAllCmd() {};
virtual void Execute (ParamsErrorTab &p, const double maxError) = 0;
virtual FitnessAllCmd* Clone () const = 0;
protected:
FitnessAllCmd () {};
};

class GenAlgFP {
public:
GenAlgFP (const FPParamDescTab &tab, FitnessCmd &cmd,
const int populationSize = 0,
const int trace = 0, const std::string &traceFileName = "");
GenAlgFP (const FPParamDescTab &tab, FitnessAllCmd &cmd,
const int populationSize = 0,
const int trace = 0, const std::string &traceFileName = "");
~GenAlgFP ();
void RandomInitialize(const int populationSize);
void SetFounder (const int populationSize, const Params &founder);
void SetFounders (const Population &parents);
double Optimize (const int maxGenerations,
const double minError, // minimal target error
const double deltaError, // min error for start of hillclimbing
const double microP); // propability during self mate that param is a micro mutation
Params GetSolution () const;
Population GetPopulation () const;
int NrOfParams () const { return descTab.size(); }
//private: // patch for test Klaas 11-11-2010
void Mate (Params &child, const Params &p1, const Params &p2);
void MateSelf (Params &child, const Params &p1);
void DeltaMutation (const int index, double &f);
void MicroMutation (const int index, double &f);
void TraceBestParents (const std::string &msg);
FPParamDescTab descTab;
FitnessCmd *Fitness;
FitnessAllCmd *FitnessAll;
ParamsErrorTab parents;
ParamsErrorTab offsprings;
double microP; // propability that self mate is a micro mutation
int trace; // 0 = no trace, > 0 nr of best parents in trace
std::string traceFileName; // filename for logging trace
bool deltaMutations; // en/disable delta mutations
int genCount; // count nr of generations
}; // class GenAlgFP

void ParamsToArrayStr (const Params &p, std::vector<std::string> &vs);

std::istream& operator>> (std::istream& is, Params &p);
std::ostream& operator<< (std::ostream& os, const Params &p);
std::string ParamsToStr (const Params &v);
Params StrToParams (const std::string &str);

std::istream& operator>> (std::istream& is, Population &p);
std::ostream& operator<< (std::ostream& os, const Population &p);
std::string PopulationToStr (const Population &v);
Population StrToPopulation (const std::string &str);

std::istream& operator>> (std::istream& is, FPParamDesc &d);
std::ostream& operator<< (std::ostream& os, const FPParamDesc &d);
std::string FPParamDescToStr (const FPParamDesc &v);
FPParamDesc StrToFPParamDesc (const std::string &str);

std::istream& operator>> (std::istream& is, FPParamDescTab &t);
std::ostream& operator<< (std::ostream& os, const FPParamDescTab &t);
std::string FPParamDescTabToStr (const FPParamDescTab &v);
FPParamDescTab StrToFPParamDescTab (const std::string &str);

} // namespace JL_GA

#endif



Back to Contents

JL_VisionLib_plugin.h

/* File : JL_VisionLib_plugin.h
* Author : Klaas Dijkstra
* modified by Jaap van de Loosdrecht
* Date : 26-11-2008
*
* Copyright (c) 1993-2017, Van de Loosdrecht Machine Vision BV,
* all rights reserved.
* Description: VisionLab plugin interface
*/

#ifndef JL_VISIONLIB_PLUGIN
#define JL_VISIONLIB_PLUGIN

#include <cstdint>
#include <vector>
#include <limits>
#include <cstring>
#include <iostream>

#ifdef _MSC_VER

//prefix for Dynamic Linkable function
#define EXTERN_DL extern "C" __declspec(dllexport)

//snprintf function on Windows (better match than _snprintf)
#define VL_SNPRINTF(...) sprintf_s( __VA_ARGS__ )

#else

//prefix for Dynamic Linkable function
#define EXTERN_DL extern "C"

//snprintf function on Linux
#define VL_SNPRINTF(...) snprintf( __VA_ARGS__ )

#endif





//Image type enumeration
enum JL_ImageType
{
BYTEIMAGE, //unsigned 8 bits per pixel
INT8IMAGE, //signed 8 bits per pixel
INT16IMAGE, //signed 16 bits per pixel
INT32IMAGE, //signed 32 bits per pixel
FLOATIMAGE, //floating point 32 bits per pixel
DOUBLEIMAGE, //floating point 64 bits per pixel
RGB888IMAGE, //32 bits per pixel (including 8 bits padding)
RGB161616IMAGE, //48 bits per pixel
HSV888IMAGE, //32 bits per pixel (including 8 bits padding)
HSV161616IMAGE, //48 bits per pixel
YUV888IMAGE, //32 bits per pixel (including 8 bits padding)
YUV161616IMAGE, //48 bits per pixel
COMPLEXFLOATIMAGE, //64 bits per pixel
COMPLEXDOUBLEIMAGE //128 bits per pixel
};

// table with the bytes per pixel for each image type
const int JL_BytesPerPixelTab[] =
{ sizeof(unsigned char), sizeof(char), sizeof(short int), sizeof(int), sizeof(float), sizeof(double), sizeof(unsigned char) * 4, sizeof(unsigned short int) * 3, sizeof(unsigned char) * 4, sizeof(unsigned short int) * 3, sizeof(unsigned char) * 4, sizeof(unsigned short int) * 3, sizeof(float) * 2, sizeof(double) * 2 };

typedef int(*PlugInProc)(const int ParameterCount, const char* const *Parameters, char** Result, void * cmdInt);

typedef void(*InsertPluginProc)(PlugInProc cmd, const char * cmdName, const char * help, void * cmdInt, bool overrideOld);

//Callback to create a new image
typedef void * (*JL_CreateImageProc)(const char *imageName, const JL_ImageType type, int height, int width, void *cmdInt);

//Callback to get image information
typedef void * (*JL_GetImageProc)(const char *imageName, JL_ImageType *type, int *height, int *width, void *cmdInt);

//Callback to create a new string
typedef char * (*JL_CreateStringProc)(const int length);

// Callback to execute VisionLab command from plugin, plugin must reserve memory with size maxSizeResult for result
typedef void(*JL_ExecuteCmdProc)(const char *cmd, char * const result, const int maxSizeResult, void *cmdInt);

EXTERN_DL
//This function is called to initialize the callback functions when linking the DLL
void JL_PlugInInitialize(JL_CreateImageProc createImageProc, JL_GetImageProc getImageProc, JL_CreateStringProc createStringProc, JL_ExecuteCmdProc executeCmdProc, void *cmdInt);

EXTERN_DL
//This function is called to initialize the callback functions when linking the DLL
//it will return a vector of JL_PluginCmdRecord for autodetect purposes
void VL_PluginInitializeAuto(JL_CreateImageProc createImageProc, JL_GetImageProc getImageProc, JL_CreateStringProc createStringProc, JL_ExecuteCmdProc executeCmdProc, InsertPluginProc insertProc, void *cmdInt);

/*
The prototype for the plugin functions inside the DLL
#ifdef WIN32
extern "C" __declspec(dllexport)
#endif
int JL_PlugIn (const int nrParams, const char* const *paramArray, char** result, void *cmdInt);
function result == 0 means success
function result != 0 means failure, possible extra error information in result
notes about string result conventions in VisionLab:
- in case of errors string starts with "[<name of command>]",
so '[' and ']' can NOT be used in normal string results
- "{xxx us} is append for timing information,
so '{' and '}' can NOT be used in normal string results
*/

/* conversion routines */

/* single channel to RGB */
template<typename itype, typename rgbchantype, int channels>
static void VL_SCtoRGB(const void* const in, void* const out, int pixels)
{
itype* in_p = (itype*)in;
rgbchantype* out_p = (rgbchantype*)out;

for (int i = 0; i < pixels; i++)
{
int ixc = i * channels;
rgbchantype in_pixel = static_cast<rgbchantype>(in_p[i]);
out_p[ixc] = in_pixel;
out_p[ixc + 1] = in_pixel;
out_p[ixc + 2] = in_pixel;
if (channels > 3)
{
out_p[ixc + 3] = std::numeric_limits<rgbchantype>::max(); //set alpha to highest possible value
}
}
}

/* conversion from RGB to RGB with different channel type*/
template<typename itype, typename otype, int in_channels, int out_channels>
static void VL_MCtoRGB(const void* const in, void* const out, int pixels)
{
itype* in_p = (itype*)in;
otype* out_p = (otype*)out;

for (int i = 0; i < pixels; i++)
{
int ixci = i * in_channels;
int ixco = i * out_channels;
out_p[ixco] = static_cast<otype>(in_p[ixci]);
out_p[ixco + 1] = static_cast<otype>(in_p[ixci + 1]);
out_p[ixco + 2] = static_cast<otype>(in_p[ixci + 2]);
if (out_channels > 3)
{
out_p[ixco + 3] = std::numeric_limits<otype>::max(); //set alpha to highest possible value
}
}
}

/* conversion from multichannel to same-typed multichannel */
template<typename itype, typename otype, int in_channels, int out_channels>
static void VL_MCtoMC(const void* const in, void* const out, int pixels)
{
itype* in_p = (itype*)in;
otype* out_p = (otype*)out;

for (int i = 0; i < pixels; i++)
{
int ixci = i * in_channels;
int ixco = i * out_channels;
out_p[ixco] = static_cast<otype>(in_p[ixci]);
out_p[ixco + 1] = static_cast<otype>(in_p[ixci + 1]);
out_p[ixco + 2] = static_cast<otype>(in_p[ixci + 2]);
}
}

template<typename itype, typename otype>
static void VL_SCtoSC(const void* const in, void* const out, int pixels)
{
itype* in_p = (itype*)in;
otype* out_p = (otype*)out;

for (int i = 0; i < pixels; i++)
{
out_p[i] = static_cast<otype>(in_p[i]);
}
}

template<typename itype, typename otype, int channels>
static void VL_RGBtoSC(const void* const in, void* const out, int pixels)
{
itype* in_p = (itype*)in;
otype* out_p = (otype*)out;

for (int i = 0; i < pixels; i++)
{
int ixc = i * channels;
double B = static_cast<double>(in_p[ixc]);
double G = static_cast<double>(in_p[ixc + 1]);
double R = static_cast<double>(in_p[ixc + 2]);
out_p[i] = static_cast<otype>(0.299 * R + 0.587 * G + 0.114 * B);
}
}

template<typename itype, typename otype, int channels>
static void VL_YUVtoSC(const void* const in, void* const out, int pixels)
{
itype* in_p = (itype*)in;
otype* out_p = (otype*)out;

for (int i = 0; i < pixels; i++)
{
int ixc = i * channels;

out_p[i] = static_cast<otype>(in_p[ixc + 2]);
}
}

template<typename itype, typename otype, int channels>
static void VL_SCtoYUV(const void* const in, void* const out, int pixels)
{
itype* in_p = (itype*)in;
otype* out_p = (otype*)out;

double tmax = std::numeric_limits<otype>::max();
double tmin = std::numeric_limits<otype>::min();

otype center = static_cast<otype>((tmax + tmin) / 2.0);

for (int i = 0; i < pixels; i++)
{
int ixc = i * channels;

out_p[ixc] = center;
out_p[ixc + 1] = center;
out_p[ixc + 2] = static_cast<otype>(in_p[i]);
}
}

template<typename itype, typename otype, int in_channels, int out_channels>
static void VL_YUVtoRGB(const void* const in, void* const out, int pixels)
{
itype* in_p = (itype*)in;
otype* out_p = (otype*)out;

double tmax = std::numeric_limits<otype>::max();
double tmin = std::numeric_limits<otype>::min();

double center = (tmax + tmin) / 2.0;

for (int i = 0; i < pixels; i++)
{
int ixci = i * in_channels;
int ixco = i * out_channels;

double V = static_cast<double>(in_p[ixci]) + center;
double U = static_cast<double>(in_p[ixci + 1]) + center;
double Y = static_cast<double>(in_p[ixci + 2]);

out_p[ixco] = static_cast<otype>(Y + 1.770 * U);
out_p[ixco + 1] = static_cast<otype>(Y - (0.344 * U) - (0.714 * V));
out_p[ixco + 2] = static_cast<otype>(Y + 1.403 * V);
if (out_channels > 3)
{
out_p[ixco + 3] = std::numeric_limits<otype>::max(); //set alpha to highest possible value
}
}
}

template<typename itype, typename otype, int in_channels, int out_channels>
static void VL_RGBtoYUV(const void* const in, void* const out, int pixels)
{
itype* in_p = (itype*)in;
otype* out_p = (otype*)out;

double tmax = std::numeric_limits<otype>::max();
double tmin = std::numeric_limits<otype>::min();

double center = (tmax + tmin) / 2.0;

for (int i = 0; i < pixels; i++)
{
int ixci = i * in_channels;
int ixco = i * out_channels;

double B = static_cast<double>(in_p[ixci]);
double G = static_cast<double>(in_p[ixci + 1]);
double R = static_cast<double>(in_p[ixci + 2]);

out_p[ixco] = static_cast<otype>((-0.169 * R - 0.331 * G + 0.500 * B) + center);
out_p[ixco + 1] = static_cast<otype>((0.500 * R - 0.419 * G - 0.081 * B) + center);
out_p[ixco + 2] = static_cast<otype>(0.299 * R + 0.587 * G + 0.114 * B);
}
}

template<typename ctype, int channels>
static void VL_convert_toRGB(const void* const in, void* const out, const JL_ImageType inType, const int pixels)
{
switch (inType)
{
case BYTEIMAGE:
VL_SCtoRGB<uint8_t, ctype, channels>(in, out, pixels);
break;
case INT8IMAGE:
VL_SCtoRGB<int8_t, ctype, channels>(in, out, pixels);
break;
case INT16IMAGE:
VL_SCtoRGB<int16_t, ctype, channels>(in, out, pixels);
break;
case INT32IMAGE:
VL_SCtoRGB<int32_t, ctype, channels>(in, out, pixels);
break;
case FLOATIMAGE:
VL_SCtoRGB<float, ctype, channels>(in, out, pixels);
break;
case DOUBLEIMAGE:
VL_SCtoRGB<double, ctype, channels>(in, out, pixels);
break;
case RGB888IMAGE:
VL_MCtoRGB<uint8_t, ctype, 4, channels>(in, out, pixels);
break;
case RGB161616IMAGE:
VL_MCtoRGB<int16_t, ctype, 3, channels>(in, out, pixels);
break;
case YUV888IMAGE:
VL_YUVtoRGB<uint8_t, ctype, 4, channels>(in, out, pixels);
break;
case YUV161616IMAGE:
VL_YUVtoRGB<int16_t, ctype, 3, channels>(in, out, pixels);
break;
default:
std::cerr << "Unsupported conversion: " << inType << "to RGB" << std::endl;
break;
}
}

template<typename ctype>
static void VL_convert_toSC(const void* const in, void* const out, const JL_ImageType inType, const int pixels)
{
switch (inType)
{
case BYTEIMAGE:
VL_SCtoSC<uint8_t, ctype>(in, out, pixels);
break;
case INT8IMAGE:
VL_SCtoSC<int8_t, ctype>(in, out, pixels);
break;
case INT16IMAGE:
VL_SCtoSC<int16_t, ctype>(in, out, pixels);
break;
case INT32IMAGE:
VL_SCtoSC<int32_t, ctype>(in, out, pixels);
break;
case FLOATIMAGE:
VL_SCtoSC<float, ctype>(in, out, pixels);
break;
case DOUBLEIMAGE:
VL_SCtoSC<double, ctype>(in, out, pixels);
break;
case RGB888IMAGE:
VL_RGBtoSC<uint8_t, ctype, 4>(in, out, pixels);
break;
case RGB161616IMAGE:
VL_RGBtoSC<int16_t, ctype, 3>(in, out, pixels);
break;
case YUV888IMAGE:
VL_YUVtoSC<uint8_t, ctype, 4>(in, out, pixels);
break;
case YUV161616IMAGE:
VL_YUVtoSC<int16_t, ctype, 3>(in, out, pixels);
break;
default:
std::cerr << "Unsupported conversion: " << inType << "to SC" << std::endl;
break;
}
}

template<typename ctype, int out_channels>
static void VL_convert_toYUV(const void* const in, void* const out, const JL_ImageType inType, const int pixels)
{
switch (inType)
{
case BYTEIMAGE:
VL_SCtoYUV<uint8_t, ctype, out_channels>(in, out, pixels);
break;
case INT8IMAGE:
VL_SCtoYUV<int8_t, ctype, out_channels>(in, out, pixels);
break;
case INT16IMAGE:
VL_SCtoYUV<int16_t, ctype, out_channels>(in, out, pixels);
break;
case INT32IMAGE:
VL_SCtoYUV<int32_t, ctype, out_channels>(in, out, pixels);
break;
case FLOATIMAGE:
VL_SCtoYUV<float, ctype, out_channels>(in, out, pixels);
break;
case DOUBLEIMAGE:
VL_SCtoYUV<double, ctype, out_channels>(in, out, pixels);
break;
case YUV888IMAGE:
VL_MCtoMC<uint8_t, ctype, 4, out_channels>(in, out, pixels);
break;
case YUV161616IMAGE:
VL_MCtoMC<int16_t, ctype, 3, out_channels>(in, out, pixels);
break;
case RGB888IMAGE:
VL_RGBtoYUV<uint8_t, ctype, 4, out_channels>(in, out, pixels);
break;
case RGB161616IMAGE:
VL_RGBtoYUV<int16_t, ctype, 3, out_channels>(in, out, pixels);
break;
default:
std::cerr << "Unsupported conversion: " << inType << "to YUV" << std::endl;
break;
}
}

void* VL_convert(const void* const in, const JL_ImageType inType, const JL_ImageType outType, const int width, const int height)
{
int pixels = width * height;
void* output = malloc(pixels * JL_BytesPerPixelTab[outType]);

if (inType != outType)
{
switch (outType)
{
case RGB888IMAGE:
VL_convert_toRGB<uint8_t, 4>(in, output, inType, pixels);
break;
case RGB161616IMAGE:
VL_convert_toRGB<int16_t, 3>(in, output, inType, pixels);
break;
case YUV888IMAGE:
VL_convert_toYUV<uint8_t, 4>(in, output, inType, pixels);
break;
case YUV161616IMAGE:
VL_convert_toYUV<int16_t, 3>(in, output, inType, pixels);
break;
case BYTEIMAGE:
VL_convert_toSC<uint8_t>(in, output, inType, pixels);
break;
case INT8IMAGE:
VL_convert_toSC<int8_t>(in, output, inType, pixels);
break;
case INT16IMAGE:
VL_convert_toSC<int16_t>(in, output, inType, pixels);
break;
case INT32IMAGE:
VL_convert_toSC<int32_t>(in, output, inType, pixels);
break;
case FLOATIMAGE:
VL_convert_toSC<float>(in, output, inType, pixels);
break;
case DOUBLEIMAGE:
VL_convert_toSC<double>(in, output, inType, pixels);
break;
default:
std::cerr << "Unsupported conversion: " << inType << " to " << outType << std::endl;
break;
}
}
else
{
switch (outType)
{
case RGB888IMAGE:
{
//need to set alpha channel to 0xFF
const uint32_t* inputPx = reinterpret_cast<const uint32_t*>(in);
uint32_t* outputPx = reinterpret_cast<uint32_t*>(output);
for (int i = 0; i < pixels; i++)
{
uint32_t inPixel = inputPx[i];
outputPx[i] = inPixel | 0xFF;
}
break;
}
default:
memcpy(output, in, pixels * JL_BytesPerPixelTab[outType]);
break;
}
}

return output;
}

#endif // ifndef JL_VISIONLIB_PLUGIN



Back to Contents

osspecif.h

/* File : osspecif.h
* Project : visionlib V3.0
* Author : Jaap van de Loosdrecht
* Van de Loosdrecht Machine Vision BV
* www.vdlmv.nl
* Date : 8-2-2017
*
* Copyright (c) 1993-2017, Van de Loosdrecht Machine Vision BV,
* all rights reserved.
*/

#ifndef JL_VIS_LIB_OS_SPECIFIC
#define JL_VIS_LIB_OS_SPECIFIC

#include <string>
#include <vector>
#include "qstring.h"
#include "rgbimage.h"

namespace JL_OS_Specific {

void InitOsSpecific ();
std::string ShowHeapInfo ();

void MicroDelay (const int us);
void MilliDelay (const int ms);
void Delay (const int secs);

bool IsKeyboardHit();

bool ChDir (const std::string &dir);
std::string CurrDir();
void SystemMsg (const std::string &msg);
std::string FindSysFile (const std::string &fileName);
void SplitFilePath (const std::string &path, std::string &drive, std::string &dir,
std::string &fName, std::string &ext);
int FileSize (const std::string &fileName);
int FileNamesInDir (const std::string &fileSpec, std::vector<std::string> &tab);

bool SystemCmd (const std::string cmd);
std::string GetHostName ();

enum ProcessPriority {RealTime, High, AboveNormal, Normal, BelowNormal, Low, NrProcessPriorities};
ProcessPriority GetProcessPriority();
ProcessPriority SetProcessPriority(ProcessPriority p);
int NrOfPhysicalCores();
JL_Word::Word64 GetAffinityMask ();
JL_Word::Word64 SetAffinityMask (JL_Word::Word64 mask);

std::string OSExceptionStr (const unsigned int code);

#define Catch_OS_Exception() \
catch (...) { \
RETHROW; \
}

#ifdef _MSC_VER
bool ReadRGB888FromBitmap(JL_VisionLib_V3::RGB888Image &Image, const QString &fileName);
bool WriteRGB888ToBitmap(JL_VisionLib_V3::RGB888Image &Image, const QString &fileName);
JL_VisionLib_V3::Image* ReadPNG (const QString fileName);
void WritePNG (JL_VisionLib_V3::Image &image, const QString &fileName);
#endif

EnumStrIODeclaration(ProcessPriority)

} // namespace JL_OS_Specific

#endif



Back to Contents

util.h

/* File : util.h
* Project : visionlib V3.0
* Author : Jaap van de Loosdrecht
* Van de Loosdrecht Machine Vision BV
* www.vdlmv.nl
* Date : 9-7-2016
*
* Copyright (c) 1993-2017, Van de Loosdrecht Machine Vision BV,
* all rights reserved.
*/

#ifndef JL_UTIL
#define JL_UTIL

#include "compiler.h"
#include "word.h"
#include <string>
#include <sstream>
#include <map>
#include <vector>
#include <stdexcept>
#include <limits>


namespace JL_Util {

class Error: public std::exception {
public:
Error (const std::string& msg);
virtual const char *what() const throw();
virtual ~Error() throw() {}
protected:
std::string msg;
};

template <class Type>
inline double Square (const Type x) { return x * x; }

inline JL_Word::Byte ClipByte (const int value) {
if (value > 255)
return JL_Word::Byte(255);
else if (value < 0)
return JL_Word::Byte(0);
else
return JL_Word::Byte(value);
} // ClipByte

inline JL_Word::Byte ModuloByte (const int value) {
return JL_Word::Byte(value % 256);
} // ModuloByte

inline double sgn (const double &v) {
if (v > 0) {
return 1.0;
} else if (v < 0) {
return -1.0;
} else {
return 0;
}
} // sgn

void Randomize (void);
void InitRandom (const unsigned int seed);
double RandomDouble (const double low, const double high);
float RandomFloat (const float low, const float high);
int RandomInt (const int low, const int high);
inline int Round (const float f) { return (int)(f + 0.5); }
inline int Round (const double f) { return (int)(f + 0.5); }

extern unsigned long fastRandX, fastRandY, fastRandZ;
inline unsigned long FastRandom(void) {
unsigned long t;
fastRandX ^= fastRandX << 16;
fastRandX ^= fastRandX >> 5;
fastRandX ^= fastRandX << 1;
t = fastRandX;
fastRandX = fastRandY;
fastRandY = fastRandZ;
return (fastRandZ = t ^ fastRandX ^ fastRandY);
} // FastRandom

std::string IntToStr (const int i);
std::string Int64ToStr (const JL_Word::Int64 i);
std::string FloatToStr (const double f);
std::string FloatToExactStr (const double f);
std::string BoolToStr (const bool b);
int StrToInt (const std::string &str);
JL_Word::Int64 StrToInt64 (const std::string &str);
double StrToFloat (const std::string &str);
bool IsTheSameFloat (const double &d1, const double &d2, const double dev);

bool StrToBool (const std::string &str);
std::string EXORString(const std::string &str, const std::string &key);
std::string StringToHex (const std::string &str);
std::string HexToString (const std::string &hexStr);
void StringToVectorString (const std::string &src, std::vector<std::string> &dest);
void StringLinesToVectorString (const std::string &src, std::vector<std::string> &dest);
std::vector<int> StrToVectorofInts(const std::string &str);

std::string StringToCSV (const std::string &str);

std::string ReplaceAll (const std::string &str, const std::string &from, const std::string &to);
std::string StripTypeName (const std::string &name);
std::string Strip (const std::string &str);
std::string StripTimeMsg (const std::string &str);
std::string StripErrorMsg (const std::string &str);
std::string RemoveLastCRLF (const std::string &str);
std::string GetRefVarName (const std::string &str, const std::string &opName);

std::string GetFirstWord (const std::string &str);
std::string GetNthWord (const std::string &str, const int n);
int GetSizeOfVector (const std::string &str);
std::string GetNthFromVector (const std::string &str, const int n);
std::string GetUntilWord (const std::string &str, const std::string &word);
std::string RemoveFirstWord (std::string &str);
std::string RemoveFirstNWords (std::string &str, const int n);
std::string RemoveUntilWord (std::string &str, const std::string &word);
std::string RemoveUntilCaseInsensitiveWord (std::string &str, const std::string &word);
std::string ToLowerCase (const std::string &str);

void HitAKey ();


// ---------- Enum conversion ---------

// Note if export template is available, next 2 lines can go to util.cpp

template <class EnumType> class RegEnumConv {
public:
RegEnumConv (const std::string &convStr);
};

typedef std::map <std::string, std::vector<std::string>, std::less<std::string> > EnumConvMap;
EnumConvMap& TheEnumConvMap ();

template <class EnumType>
std::string EnumToStr (const EnumType enumVal);

template <class EnumType>
EnumType StrToEnum(const std::string &str);

template <class EnumType>
bool ValidEnumStr(const std::string &str);

template <class EnumType>
std::istream& EnumFromStream (std::istream &is, EnumType &enumVal);

#define EnumStrIODeclaration(EnumType) \
string EnumType ## ToStr (const EnumType type); \
EnumType StrTo ## EnumType(const string &str); \
istream& operator>> (istream& is, EnumType &type); \
ostream& operator<< (ostream& os, const EnumType type);

#define EnumStrIODefinition(EnumType) \
string EnumType ## ToStr (const EnumType type) { \
return EnumToStr(type); \
} \
EnumType StrTo ## EnumType(const string &str) { \
return StrToEnum<EnumType>(str); \
} \
istream& operator>> (istream& is, EnumType &type) { \
return EnumFromStream (is, type); \
} \
ostream& operator<< (ostream& os, const EnumType type) { \
os << EnumType ## ToStr (type); \
return os; \
}

} // JL_Util

#include "util.cxx"

#endif



Back to Contents