001    /*----------------------------------------------------------------------------*/
002    /* Copyright (c) FIRST 2008-2012. All Rights Reserved.                        */
003    /* Open Source Software - may be modified and shared by FRC teams. The code   */
004    /* must be accompanied by the FIRST BSD license file in the root directory of */
005    /* the project.                                                               */
006    /*----------------------------------------------------------------------------*/
007    package edu.wpi.first.wpilibj.image;
008    
009    import com.sun.cldc.jna.BlockingFunction;
010    import com.sun.cldc.jna.Function;
011    import com.sun.cldc.jna.NativeLibrary;
012    import com.sun.cldc.jna.Pointer;
013    import com.sun.cldc.jna.Structure;
014    import com.sun.cldc.jna.TaskExecutor;
015    import com.sun.cldc.jna.ptr.IntByReference;
016    import com.sun.squawk.microedition.io.FileConnection;
017    import edu.wpi.first.wpilibj.util.BoundaryException;
018    import java.util.Vector;
019    
020    /**
021     * Class for interfacing with the NIVision libraries
022     * @author dtjones
023     */
024    public class NIVision {
025    
026        private NIVision() {
027        }
028    
029        private static final TaskExecutor taskExecutor = new TaskExecutor("nivision task");
030    
031        /**
032         * Enumeration representing the possible types of imaq images
033         */
034        public static class ImageType {
035    
036            public final int value;
037            /** The image type is 8-bit unsigned integer grayscale. */
038            public static final ImageType imaqImageU8 = new ImageType(0);
039            /** The image type is 16-bit unsigned integer grayscale. */
040            public static final ImageType imaqImageU16 = new ImageType(7);
041            /** The image type is 16-bit signed integer grayscale. */
042            public static final ImageType imaqImageI16 = new ImageType(1);
043            /** The image type is 32-bit floating-point grayscale. */
044            public static final ImageType imaqImageSGL = new ImageType(2);
045            /** The image type is complex. */
046            public static final ImageType imaqImageComplex = new ImageType(3);
047            /** The image type is RGB color. */
048            public static final ImageType imaqImageRGB = new ImageType(4);
049            /** The image type is HSL color. */
050            public static final ImageType imaqImageHSL = new ImageType(5);
051            /** The image type is 64-bit unsigned RGB color. */
052            public static final ImageType imaqImageRGBU64 = new ImageType(6);
053            /** Reserved */
054            public static final ImageType imaqImageTypeSizeGuard = new ImageType(0xFFFFFFFF);
055    
056            private ImageType(int value) {
057                this.value = value;
058            }
059        }
060    
061        /**
062         * Enumerations representing the possible color spaces to operate in
063         */
064        public static class ColorMode {
065    
066            public final int value;
067            /** The function operates in the RGB (Red, Blue, Green) color space. */
068            public static final ColorMode IMAQ_RGB = new ColorMode(0);
069            /** The function operates in the HSL (Hue, Saturation, Luminance) color space. */
070            public static final ColorMode IMAQ_HSL = new ColorMode(1);
071            /** The function operates in the HSV (Hue, Saturation, Value) color space. */
072            public static final ColorMode IMAQ_HSV = new ColorMode(2);
073            /** The function operates in the HSI (Hue, Saturation, Intensity) color space. */
074            public static final ColorMode IMAQ_HSI = new ColorMode(3);
075            /** The function operates in the CIE L*a*b* color space. */
076            public static final ColorMode IMAQ_CIE = new ColorMode(4);
077            /** The function operates in the CIE XYZ color space. */
078            public static final ColorMode IMAQ_CIEXYZ = new ColorMode(5);
079            public static final ColorMode IMAQ_COLOR_MODE_SIZE_GUARD = new ColorMode(0xFFFFFFFF);
080    
081            private ColorMode(int value) {
082                this.value = value;
083            }
084        }
085    
086        public static class MeasurementType {
087    
088            public final int value;
089            /** X-coordinate of the point representing the average position of the total particle mass, assuming every point in the particle has a constant density. */
090            public static final MeasurementType IMAQ_MT_CENTER_OF_MASS_X = new MeasurementType(0);
091            /** Y-coordinate of the point representing the average position of the total particle mass, assuming every point in the particle has a constant density. */
092            public static final MeasurementType IMAQ_MT_CENTER_OF_MASS_Y = new MeasurementType(1);
093            /** X-coordinate of the highest, leftmost particle pixel. */
094            public static final MeasurementType IMAQ_MT_FIRST_PIXEL_X = new MeasurementType(2);
095            /** Y-coordinate of the highest, leftmost particle pixel. */
096            public static final MeasurementType IMAQ_MT_FIRST_PIXEL_Y = new MeasurementType(3);
097            /** X-coordinate of the leftmost particle point. */
098            public static final MeasurementType IMAQ_MT_BOUNDING_RECT_LEFT = new MeasurementType(4);
099            /** Y-coordinate of highest particle point. */
100            public static final MeasurementType IMAQ_MT_BOUNDING_RECT_TOP = new MeasurementType(5);
101            /** X-coordinate of the rightmost particle point. */
102            public static final MeasurementType IMAQ_MT_BOUNDING_RECT_RIGHT = new MeasurementType(6);
103            /** Y-coordinate of the lowest particle point. */
104            public static final MeasurementType IMAQ_MT_BOUNDING_RECT_BOTTOM = new MeasurementType(7);
105            /** X-coordinate of the start of the line segment connecting the two perimeter points that are the furthest apart. */
106            public static final MeasurementType IMAQ_MT_MAX_FERET_DIAMETER_START_X = new MeasurementType(8);
107            /** Y-coordinate of the start of the line segment connecting the two perimeter points that are the furthest apart. */
108            public static final MeasurementType IMAQ_MT_MAX_FERET_DIAMETER_START_Y = new MeasurementType(9);
109            /** X-coordinate of the end of the line segment connecting the two perimeter points that are the furthest apart. */
110            public static final MeasurementType IMAQ_MT_MAX_FERET_DIAMETER_END_X = new MeasurementType(10);
111            /** Y-coordinate of the end of the line segment connecting the two perimeter points that are the furthest apart. */
112            public static final MeasurementType IMAQ_MT_MAX_FERET_DIAMETER_END_Y = new MeasurementType(11);
113            /** X-coordinate of the leftmost pixel in the longest row of contiguous pixels in the particle. */
114            public static final MeasurementType IMAQ_MT_MAX_HORIZ_SEGMENT_LENGTH_LEFT = new MeasurementType(12);
115            /** X-coordinate of the rightmost pixel in the longest row of contiguous pixels in the particle. */
116            public static final MeasurementType IMAQ_MT_MAX_HORIZ_SEGMENT_LENGTH_RIGHT = new MeasurementType(13);
117            /** Y-coordinate of all of the pixels in the longest row of contiguous pixels in the particle. */
118            public static final MeasurementType IMAQ_MT_MAX_HORIZ_SEGMENT_LENGTH_ROW = new MeasurementType(14);
119            /** Distance between the x-coordinate of the leftmost particle point and the x-coordinate of the rightmost particle point. */
120            public static final MeasurementType IMAQ_MT_BOUNDING_RECT_WIDTH = new MeasurementType(16);
121            /** Distance between the y-coordinate of highest particle point and the y-coordinate of the lowest particle point. */
122            public static final MeasurementType IMAQ_MT_BOUNDING_RECT_HEIGHT = new MeasurementType(17);
123            /** Distance between opposite corners of the bounding rectangle. */
124            public static final MeasurementType IMAQ_MT_BOUNDING_RECT_DIAGONAL = new MeasurementType(18);
125            /** Length of the outer boundary of the particle. */
126            public static final MeasurementType IMAQ_MT_PERIMETER = new MeasurementType(19);
127            /** Perimeter of the smallest convex polygon containing all points in the particle. */
128            public static final MeasurementType IMAQ_MT_CONVEX_HULL_PERIMETER = new MeasurementType(20);
129            /** Sum of the perimeters of each hole in the particle. */
130            public static final MeasurementType IMAQ_MT_HOLES_PERIMETER = new MeasurementType(21);
131            /** Distance between the start and end of the line segment connecting the two perimeter points that are the furthest apart. */
132            public static final MeasurementType IMAQ_MT_MAX_FERET_DIAMETER = new MeasurementType(22);
133            /** Length of the major axis of the ellipse with the same perimeter and area as the particle. */
134            public static final MeasurementType IMAQ_MT_EQUIVALENT_ELLIPSE_MAJOR_AXIS = new MeasurementType(23);
135            /** Length of the minor axis of the ellipse with the same perimeter and area as the particle. */
136            public static final MeasurementType IMAQ_MT_EQUIVALENT_ELLIPSE_MINOR_AXIS = new MeasurementType(24);
137            /** Length of the minor axis of the ellipse with the same area as the particle, and Major Axis equal in length to the Max Feret Diameter. */
138            public static final MeasurementType IMAQ_MT_EQUIVALENT_ELLIPSE_MINOR_AXIS_FERET = new MeasurementType(25);
139            /** Longest side of the rectangle with the same perimeter and area as the particle. */
140            public static final MeasurementType IMAQ_MT_EQUIVALENT_RECT_LONG_SIDE = new MeasurementType(26);
141            /** Shortest side of the rectangle with the same perimeter and area as the particle. */
142            public static final MeasurementType IMAQ_MT_EQUIVALENT_RECT_SHORT_SIDE = new MeasurementType(27);
143            /** Distance between opposite corners of the rectangle with the same perimeter and area as the particle. */
144            public static final MeasurementType IMAQ_MT_EQUIVALENT_RECT_DIAGONAL = new MeasurementType(28);
145            /** Shortest side of the rectangle with the same area as the particle, and longest side equal in length to the Max Feret Diameter. */
146            public static final MeasurementType IMAQ_MT_EQUIVALENT_RECT_SHORT_SIDE_FERET = new MeasurementType(29);
147            /** Average length of a horizontal segment in the particle. */
148            public static final MeasurementType IMAQ_MT_AVERAGE_HORIZ_SEGMENT_LENGTH = new MeasurementType(30);
149            /** Average length of a vertical segment in the particle. */
150            public static final MeasurementType IMAQ_MT_AVERAGE_VERT_SEGMENT_LENGTH = new MeasurementType(31);
151            /** The particle area divided by the particle perimeter. */
152            public static final MeasurementType IMAQ_MT_HYDRAULIC_RADIUS = new MeasurementType(32);
153            /** Diameter of a disk with the same area as the particle. */
154            public static final MeasurementType IMAQ_MT_WADDEL_DISK_DIAMETER = new MeasurementType(33);
155            /** Area of the particle. */
156            public static final MeasurementType IMAQ_MT_AREA = new MeasurementType(35);
157            /** Sum of the areas of each hole in the particle. */
158            public static final MeasurementType IMAQ_MT_HOLES_AREA = new MeasurementType(36);
159            /** Area of a particle that completely covers the image. */
160            public static final MeasurementType IMAQ_MT_PARTICLE_AND_HOLES_AREA = new MeasurementType(37);
161            /** Area of the smallest convex polygon containing all points in the particle. */
162            public static final MeasurementType IMAQ_MT_CONVEX_HULL_AREA = new MeasurementType(38);
163            /** Area of the image. */
164            public static final MeasurementType IMAQ_MT_IMAGE_AREA = new MeasurementType(39);
165            /** Number of holes in the particle. */
166            public static final MeasurementType IMAQ_MT_NUMBER_OF_HOLES = new MeasurementType(41);
167            /** Number of horizontal segments in the particle. */
168            public static final MeasurementType IMAQ_MT_NUMBER_OF_HORIZ_SEGMENTS = new MeasurementType(42);
169            /** Number of vertical segments in the particle. */
170            public static final MeasurementType IMAQ_MT_NUMBER_OF_VERT_SEGMENTS = new MeasurementType(43);
171            /** The angle of the line that passes through the particle Center of Mass about which the particle has the lowest moment of inertia. */
172            public static final MeasurementType IMAQ_MT_ORIENTATION = new MeasurementType(45);
173            /** The angle of the line segment connecting the two perimeter points that are the furthest apart. */
174            public static final MeasurementType IMAQ_MT_MAX_FERET_DIAMETER_ORIENTATION = new MeasurementType(46);
175            /** Percentage of the particle Area covering the Image Area. */
176            public static final MeasurementType IMAQ_MT_AREA_BY_IMAGE_AREA = new MeasurementType(48);
177            /** Percentage of the particle Area in relation to its Particle and Holes Area. */
178            public static final MeasurementType IMAQ_MT_AREA_BY_PARTICLE_AND_HOLES_AREA = new MeasurementType(49);
179            /** Equivalent Ellipse Major Axis divided by Equivalent Ellipse Minor Axis. */
180            public static final MeasurementType IMAQ_MT_RATIO_OF_EQUIVALENT_ELLIPSE_AXES = new MeasurementType(50);
181            /** Equivalent Rect Long Side divided by Equivalent Rect Short Side. */
182            public static final MeasurementType IMAQ_MT_RATIO_OF_EQUIVALENT_RECT_SIDES = new MeasurementType(51);
183            /** Max Feret Diameter divided by Equivalent Rect Short Side (Feret). */
184            public static final MeasurementType IMAQ_MT_ELONGATION_FACTOR = new MeasurementType(53);
185            /** Area divided by the product of Bounding Rect Width and Bounding Rect Height. */
186            public static final MeasurementType IMAQ_MT_COMPACTNESS_FACTOR = new MeasurementType(54);
187            /** Perimeter divided by the circumference of a circle with the same area. */
188            public static final MeasurementType IMAQ_MT_HEYWOOD_CIRCULARITY_FACTOR = new MeasurementType(55);
189            /** Factor relating area to moment of inertia. */
190            public static final MeasurementType IMAQ_MT_TYPE_FACTOR = new MeasurementType(56);
191            /** The sum of all x-coordinates in the particle. */
192            public static final MeasurementType IMAQ_MT_SUM_X = new MeasurementType(58);
193            /** The sum of all y-coordinates in the particle. */
194            public static final MeasurementType IMAQ_MT_SUM_Y = new MeasurementType(59);
195            /** The sum of all x-coordinates squared in the particle. */
196            public static final MeasurementType IMAQ_MT_SUM_XX = new MeasurementType(60);
197            /** The sum of all x-coordinates times y-coordinates in the particle. */
198            public static final MeasurementType IMAQ_MT_SUM_XY = new MeasurementType(61);
199            /** The sum of all y-coordinates squared in the particle. */
200            public static final MeasurementType IMAQ_MT_SUM_YY = new MeasurementType(62);
201            /** The sum of all x-coordinates cubed in the particle. */
202            public static final MeasurementType IMAQ_MT_SUM_XXX = new MeasurementType(63);
203            /** The sum of all x-coordinates squared times y-coordinates in the particle. */
204            public static final MeasurementType IMAQ_MT_SUM_XXY = new MeasurementType(64);
205            /** The sum of all x-coordinates times y-coordinates squared in the particle. */
206            public static final MeasurementType IMAQ_MT_SUM_XYY = new MeasurementType(65);
207            /** The sum of all y-coordinates cubed in the particle. */
208            public static final MeasurementType IMAQ_MT_SUM_YYY = new MeasurementType(66);
209            /** The moment of inertia in the x-direction twice. */
210            public static final MeasurementType IMAQ_MT_MOMENT_OF_INERTIA_XX = new MeasurementType(68);
211            /** The moment of inertia in the x and y directions. */
212            public static final MeasurementType IMAQ_MT_MOMENT_OF_INERTIA_XY = new MeasurementType(69);
213            /** The moment of inertia in the y-direction twice. */
214            public static final MeasurementType IMAQ_MT_MOMENT_OF_INERTIA_YY = new MeasurementType(70);
215            /** The moment of inertia in the x-direction three times. */
216            public static final MeasurementType IMAQ_MT_MOMENT_OF_INERTIA_XXX = new MeasurementType(71);
217            /** The moment of inertia in the x-direction twice and the y-direction once. */
218            public static final MeasurementType IMAQ_MT_MOMENT_OF_INERTIA_XXY = new MeasurementType(72);
219            /** The moment of inertia in the x-direction once and the y-direction twice. */
220            public static final MeasurementType IMAQ_MT_MOMENT_OF_INERTIA_XYY = new MeasurementType(73);
221            /** The moment of inertia in the y-direction three times. */
222            public static final MeasurementType IMAQ_MT_MOMENT_OF_INERTIA_YYY = new MeasurementType(74);
223            /** The normalized moment of inertia in the x-direction twice. */
224            public static final MeasurementType IMAQ_MT_NORM_MOMENT_OF_INERTIA_XX = new MeasurementType(75);
225            /** The normalized moment of inertia in the x- and y-directions. */
226            public static final MeasurementType IMAQ_MT_NORM_MOMENT_OF_INERTIA_XY = new MeasurementType(76);
227            /** The normalized moment of inertia in the y-direction twice. */
228            public static final MeasurementType IMAQ_MT_NORM_MOMENT_OF_INERTIA_YY = new MeasurementType(77);
229            /** The normalized moment of inertia in the x-direction three times. */
230            public static final MeasurementType IMAQ_MT_NORM_MOMENT_OF_INERTIA_XXX = new MeasurementType(78);
231            /** The normalized moment of inertia in the x-direction twice and the y-direction once. */
232            public static final MeasurementType IMAQ_MT_NORM_MOMENT_OF_INERTIA_XXY = new MeasurementType(79);
233            /** The normalized moment of inertia in the x-direction once and the y-direction twice. */
234            public static final MeasurementType IMAQ_MT_NORM_MOMENT_OF_INERTIA_XYY = new MeasurementType(80);
235            /** The normalized moment of inertia in the y-direction three times. */
236            public static final MeasurementType IMAQ_MT_NORM_MOMENT_OF_INERTIA_YYY = new MeasurementType(81);
237            /** The first Hu moment. */
238            public static final MeasurementType IMAQ_MT_HU_MOMENT_1 = new MeasurementType(82);
239            /** The second Hu moment. */
240            public static final MeasurementType IMAQ_MT_HU_MOMENT_2 = new MeasurementType(83);
241            /** The third Hu moment. */
242            public static final MeasurementType IMAQ_MT_HU_MOMENT_3 = new MeasurementType(84);
243            /** The fourth Hu moment. */
244            public static final MeasurementType IMAQ_MT_HU_MOMENT_4 = new MeasurementType(85);
245            /** The fifth Hu moment. */
246            public static final MeasurementType IMAQ_MT_HU_MOMENT_5 = new MeasurementType(86);
247            /** The sixth Hu moment. */
248            public static final MeasurementType IMAQ_MT_HU_MOMENT_6 = new MeasurementType(87);
249            /** The seventh Hu moment. */
250            public static final MeasurementType IMAQ_MT_HU_MOMENT_7 = new MeasurementType(88);
251    
252            public static final MeasurementType IMAQ_MEASUREMENT_TYPE_SIZE_GUARD = new MeasurementType(0xFFFFFFFF);
253    
254            private MeasurementType(int value) {
255                this.value = value;
256            }
257        }
258        
259        public static class Range extends Structure {
260    
261            int lower;
262            int upper;
263    
264            public void read() {
265                lower = backingNativeMemory.getInt(0);
266                upper = backingNativeMemory.getInt(4);
267            }
268    
269            public void write() {
270                backingNativeMemory.setInt(0, lower);
271                backingNativeMemory.setInt(4, upper);
272            }
273    
274            public int size() {
275                return 8;
276            }
277    
278            /**
279             * Free the memory used by this range
280             */
281            public void free() {
282                release();
283            }
284    
285            /**
286             * Create a new range with the specified upper and lower boundaries
287             * @param lower The lower limit
288             * @param upper The upper limit
289             */
290            public Range(final int lower, final int upper) {
291                allocateMemory();
292                set(lower, upper);
293            }
294    
295            /**
296             * Set the upper and lower boundaries
297             * @param lower The lower limit
298             * @param upper The upper limit
299             */
300            public void set(final int lower, final int upper) {
301                if (lower > upper) {
302                    throw new BoundaryException("Lower boundary is greater than upper");
303                }
304                this.lower = lower;
305                this.upper = upper;
306                write();
307            }
308    
309            /**
310             * Get the lower boundary
311             * @return The lower boundary.
312             */
313            public int getLower() {
314                read();
315                return lower;
316            }
317    
318            /**
319             * Get the upper boundary
320             * @return The upper boundary.
321             */
322            public int getUpper() {
323                read();
324                return upper;
325            }
326        }
327        
328        public static class Rect extends Structure {
329    
330            int top;
331            int left;
332            int height;
333            int width;
334    
335            public void read() {
336                top = backingNativeMemory.getInt(0);
337                left = backingNativeMemory.getInt(4);
338                height = backingNativeMemory.getInt(8);
339                width = backingNativeMemory.getInt(12);
340            }
341    
342            public void write() {
343                backingNativeMemory.setInt(0, top);
344                backingNativeMemory.setInt(4, left);
345                backingNativeMemory.setInt(8, height);
346                backingNativeMemory.setInt(12, width);
347            }
348    
349            public int size() {
350                return 16;
351            }
352    
353            /**
354             * Free the memory used by this range
355             */
356            public void free() {
357                release();
358            }
359    
360            /**
361             * Create a new Rect with the specified dimensions
362             * @param top  The top of the rectangle
363             * @param left The left edge of the rectangle
364             * @param height The height of the rectangle
365             * @param width The width of the rectangle
366             */
367            public Rect(final int top, final int left, final int height, final int width) {
368                allocateMemory();
369                set(top, left, height, width);
370            }
371    
372            /**
373             * Set the Rect dimensions
374             * @param top  The top of the rectangle
375             * @param left The left edge of the rectangle
376             * @param height The height of the rectangle
377             * @param width The width of the rectangle
378             */
379            public void set(final int top, final int left, final int height, final int width) {
380                this.top = top;
381                this.left = left;
382                this.height = height;
383                this.width = width;
384                write();
385            }
386    
387            /**
388             * Get the top of the rectangle
389             * @return The top edge of the rectangle in pixels, measured from the top of the image
390             */
391            public int getTop() {
392                read();
393                return top;
394            }
395    
396            /**
397             * Get the left edge of the rectangle
398             * @return The left edge of the rectangle in pixels measured from the left of the image
399             */
400            public int getLeft() {
401                read();
402                return left;
403            }
404    
405            /**
406             * Get the width of the rectangle
407             * @return The width of the rectangle in pixels
408             */
409            public int getWidth() {
410                read();
411                return width;
412            }
413    
414            /**
415             * Get the height of the rectangle
416             * @return The height edge of the rectangle in pixels
417             */
418            public int getHeight() {
419                read();
420                return height;
421            }
422    
423        }
424        
425        //============================================================================
426        //  Value Type handling
427        // Parameters of "type" PixelValue, RGBValue, HSLValue, etc, are passed as an encoded int from Java code.
428        //============================================================================
429        public int encodeRGBValue(int r, int g, int b, int a) {
430            return (a & 0xff << 24) | (r & 0xff << 16) | (g & 0xff << 8) | (b & 0xff);
431        }
432    
433        public int rgbGetR(int rgbvalue) {
434            return (rgbvalue >>> 16) & 0xFF;
435        }
436    
437        public int rgbGetG(int rgbvalue) {
438            return (rgbvalue >>> 8) & 0xFF;
439        }
440    
441        public int rgbGetB(int rgbvalue) {
442            return (rgbvalue >>> 0) & 0xFF;
443        }
444    
445        public int rgbGetA(int rgbvalue) {
446            return (rgbvalue >>> 24) & 0xFF;
447        }
448    
449        public int encodeHSLValue(int h, int s, int l, int a) {
450            return (a & 0xff << 24) | (h & 0xff << 16) | (s & 0xff << 8) | (l & 0xff);
451        }
452    
453        public int hslGetH(int hslvalue) {
454            return (hslvalue >>> 16) & 0xFF;
455        }
456    
457        public int hslGetS(int hslvalue) {
458            return (hslvalue >>> 8) & 0xFF;
459        }
460    
461        public int hslGetL(int hslvalue) {
462            return (hslvalue >>> 0) & 0xFF;
463        }
464    
465        public int hslGetA(int hslvalue) {
466            return (hslvalue >>> 24) & 0xFF;
467        }
468    
469        public int encodeHSVValue(int h, int s, int v, int a) {
470            return (a & 0xff << 24) | (h & 0xff << 16) | (s & 0xff << 8) | (v & 0xff);
471        }
472    
473        public int hsvGetH(int hsvvalue) {
474            return (hsvvalue >>> 16) & 0xFF;
475        }
476    
477        public int hsvGetS(int hsvvalue) {
478            return (hsvvalue >>> 8) & 0xFF;
479        }
480    
481        public int hsvGetV(int hsvvalue) {
482            return (hsvvalue >>> 0) & 0xFF;
483        }
484    
485        public int hsvGetA(int hsvvalue) {
486            return (hsvvalue >>> 24) & 0xFF;
487        }
488    
489        public int encodeGreyscaleValue(float greyscale) {
490            return Float.floatToIntBits(greyscale);
491        }
492    
493        public float decodeGreyscaleValue(int pixelValue) {
494            return Float.intBitsToFloat(pixelValue);
495        }
496    
497        //============================================================================
498        //  Acquisition functions
499        //============================================================================
500        //IMAQ_FUNC Image* IMAQ_STDCALL imaqCopyFromRing(SESSION_ID sessionID, Image* image, int imageToCopy, int* imageNumber, Rect rect);
501        //IMAQ_FUNC Image* IMAQ_STDCALL imaqEasyAcquire(const char* interfaceName);
502        //IMAQ_FUNC Image* IMAQ_STDCALL imaqExtractFromRing(SESSION_ID sessionID, int imageToExtract, int* imageNumber);
503        //IMAQ_FUNC Image* IMAQ_STDCALL imaqGrab(SESSION_ID sessionID, Image* image, int immediate);
504        //IMAQ_FUNC int    IMAQ_STDCALL imaqReleaseImage(SESSION_ID sessionID);
505        //IMAQ_FUNC int    IMAQ_STDCALL imaqSetupGrab(SESSION_ID sessionID, Rect rect);
506        //IMAQ_FUNC int    IMAQ_STDCALL imaqSetupRing(SESSION_ID sessionID, Image** images, int numImages, int skipCount, Rect rect);
507        //IMAQ_FUNC int    IMAQ_STDCALL imaqSetupSequence(SESSION_ID sessionID, Image** images, int numImages, int skipCount, Rect rect);
508        //IMAQ_FUNC Image* IMAQ_STDCALL imaqSnap(SESSION_ID sessionID, Image* image, Rect rect);
509        //IMAQ_FUNC int    IMAQ_STDCALL imaqStartAcquisition(SESSION_ID sessionID);
510        //IMAQ_FUNC int    IMAQ_STDCALL imaqStopAcquisition(SESSION_ID sessionID);
511    
512        //============================================================================
513        //  Arithmetic functions
514        //============================================================================
515        //IMAQ_FUNC int IMAQ_STDCALL imaqAbsoluteDifference(Image* dest, const Image* sourceA, const Image* sourceB);
516        //IMAQ_FUNC int IMAQ_STDCALL imaqAbsoluteDifferenceConstant(Image* dest, const Image* source, PixelValue value);
517        //IMAQ_FUNC int IMAQ_STDCALL imaqAdd(Image* dest, const Image* sourceA, const Image* sourceB);
518        //IMAQ_FUNC int IMAQ_STDCALL imaqAddConstant(Image* dest, const Image* source, PixelValue value);
519        //IMAQ_FUNC int IMAQ_STDCALL imaqAverage(Image* dest, const Image* sourceA, const Image* sourceB);
520        //IMAQ_FUNC int IMAQ_STDCALL imaqAverageConstant(Image* dest, const Image* source, PixelValue value);
521        //IMAQ_FUNC int IMAQ_STDCALL imaqDivide2(Image* dest, const Image* sourceA, const Image* sourceB, RoundingMode roundingMode);
522        //IMAQ_FUNC int IMAQ_STDCALL imaqDivideConstant2(Image* dest, const Image* source, PixelValue value, RoundingMode roundingMode);
523        //IMAQ_FUNC int IMAQ_STDCALL imaqMax(Image* dest, const Image* sourceA, const Image* sourceB);
524        //IMAQ_FUNC int IMAQ_STDCALL imaqMaxConstant(Image* dest, const Image* source, PixelValue value);
525        //IMAQ_FUNC int IMAQ_STDCALL imaqMin(Image* dest, const Image* sourceA, const Image* sourceB);
526        //IMAQ_FUNC int IMAQ_STDCALL imaqMinConstant(Image* dest, const Image* source, PixelValue value);
527        //IMAQ_FUNC int IMAQ_STDCALL imaqModulo(Image* dest, const Image* sourceA, const Image* sourceB);
528        //IMAQ_FUNC int IMAQ_STDCALL imaqModuloConstant(Image* dest, const Image* source, PixelValue value);
529        //IMAQ_FUNC int IMAQ_STDCALL imaqMulDiv(Image* dest, const Image* sourceA, const Image* sourceB, float value);
530        //IMAQ_FUNC int IMAQ_STDCALL imaqMultiply(Image* dest, const Image* sourceA, const Image* sourceB);
531        //IMAQ_FUNC int IMAQ_STDCALL imaqMultiplyConstant(Image* dest, const Image* source, PixelValue value);
532        //IMAQ_FUNC int IMAQ_STDCALL imaqSubtract(Image* dest, const Image* sourceA, const Image* sourceB);
533        //IMAQ_FUNC int IMAQ_STDCALL imaqSubtractConstant(Image* dest, const Image* source, PixelValue value);
534    
535        //============================================================================
536        //  Spatial Filters functions
537        //============================================================================
538        //IMAQ_FUNC int IMAQ_STDCALL imaqCannyEdgeFilter(Image* dest, const Image* source, const CannyOptions* options);
539        //IMAQ_FUNC int IMAQ_STDCALL imaqConvolve2(Image* dest, Image* source, float* kernel, int matrixRows, int matrixCols, float normalize, Image* mask, RoundingMode roundingMode);
540        //IMAQ_FUNC int IMAQ_STDCALL imaqCorrelate(Image* dest, Image* source, const Image* templateImage, Rect rect);
541        //IMAQ_FUNC int IMAQ_STDCALL imaqEdgeFilter(Image* dest, Image* source, OutlineMethod method, const Image* mask);
542        //IMAQ_FUNC int IMAQ_STDCALL imaqLowPass(Image* dest, Image* source, int width, int height, float tolerance, const Image* mask);
543        //IMAQ_FUNC int IMAQ_STDCALL imaqMedianFilter(Image* dest, Image* source, int width, int height, const Image* mask);
544        //IMAQ_FUNC int IMAQ_STDCALL imaqNthOrderFilter(Image* dest, Image* source, int width, int height, int n, const Image* mask);
545    
546        //============================================================================
547        //  Drawing functions
548        //============================================================================
549        //IMAQ_FUNC int IMAQ_STDCALL imaqDrawLineOnImage(Image* dest, const Image* source, DrawMode mode, Point start, Point end, float newPixelValue);
550        //IMAQ_FUNC int IMAQ_STDCALL imaqDrawShapeOnImage(Image* dest, const Image* source, Rect rect, DrawMode mode, ShapeMode shape, float newPixelValue);
551        //IMAQ_FUNC int IMAQ_STDCALL imaqDrawTextOnImage(Image* dest, const Image* source, Point coord, const char* text, const DrawTextOptions* options, int* fontNameUsed);
552    
553        //============================================================================
554        //  Interlacing functions
555        //============================================================================
556        //IMAQ_FUNC int IMAQ_STDCALL imaqInterlaceCombine(Image* frame, const Image* odd, const Image* even);
557        //IMAQ_FUNC int IMAQ_STDCALL imaqInterlaceSeparate(const Image* frame, Image* odd, Image* even);
558    
559        //============================================================================
560        //  Image Information functions
561        //============================================================================
562        //IMAQ_FUNC char** IMAQ_STDCALL imaqEnumerateCustomKeys(const Image* image, unsigned int* size);
563        //IMAQ_FUNC int    IMAQ_STDCALL imaqGetBitDepth(const Image* image, unsigned int* bitDepth);
564        //IMAQ_FUNC int    IMAQ_STDCALL imaqGetBytesPerPixel(const Image* image, int* byteCount);
565        //IMAQ_FUNC int    IMAQ_STDCALL imaqGetImageInfo(const Image* image, ImageInfo* info);
566        //IMAQ_FUNC int    IMAQ_STDCALL imaqGetImageType(const Image* image, ImageType* type);
567        //IMAQ_FUNC int    IMAQ_STDCALL imaqGetMaskOffset(const Image* image, Point* offset);
568        //IMAQ_FUNC void*  IMAQ_STDCALL imaqGetPixelAddress(const Image* image, Point pixel);
569        //IMAQ_FUNC int    IMAQ_STDCALL imaqGetVisionInfoTypes(const Image* image, unsigned int* present);
570        //IMAQ_FUNC int    IMAQ_STDCALL imaqIsImageEmpty(const Image* image, int* empty);
571        //IMAQ_FUNC void*  IMAQ_STDCALL imaqReadCustomData(const Image* image, const char* key, unsigned int* size);
572        //IMAQ_FUNC int    IMAQ_STDCALL imaqRemoveCustomData(Image* image, const char* key);
573        //IMAQ_FUNC int    IMAQ_STDCALL imaqRemoveVisionInfo2(const Image* image, unsigned int info);
574        //IMAQ_FUNC int    IMAQ_STDCALL imaqSetBitDepth(Image* image, unsigned int bitDepth);
575        //IMAQ_FUNC int    IMAQ_STDCALL imaqSetImageSize(Image* image, int width, int height);
576        //IMAQ_FUNC int    IMAQ_STDCALL imaqSetMaskOffset(Image* image, Point offset);
577        //IMAQ_FUNC int    IMAQ_STDCALL imaqWriteCustomData(Image* image, const char* key, const void* data, unsigned int size);
578    
579        // TODO: Make non-blocking...
580        private static final BlockingFunction imaqGetImageSizeFn = NativeLibrary.getDefaultInstance().getBlockingFunction("imaqGetImageSize");
581        static { imaqGetImageSizeFn.setTaskExecutor(taskExecutor); }
582    
583        /**
584         * Get the height of an image.
585         * @param image The image to get the height of.
586         * @return The height of the image.
587         */
588        public static int getHeight(Pointer image)  throws NIVisionException{
589            Pointer i = new Pointer(4);
590            int val;
591            try {
592                assertCleanStatus(imaqGetImageSizeFn.call3(image, 0, i));
593            } finally {
594                val = i.getInt(0);
595                i.free();
596            }
597            return val;
598        }
599    
600        /**
601         * Get the width of an image.
602         * @param image The image to get the width of.
603         * @return The width of the image.
604         */
605        public static int getWidth(Pointer image)  throws NIVisionException{
606            Pointer i = new Pointer(4);
607            int val;
608            try {
609                assertCleanStatus(imaqGetImageSizeFn.call3(image, i, 0));
610            } finally {
611                val = i.getInt(0);
612                i.free();
613            }
614            return val;
615        }
616    
617        //============================================================================
618        //  Morphology functions
619        //============================================================================
620        //IMAQ_FUNC int           IMAQ_STDCALL imaqConvexHull(Image* dest, Image* source, int connectivity8);
621        //IMAQ_FUNC int           IMAQ_STDCALL imaqDanielssonDistance(Image* dest, Image* source);
622        //IMAQ_FUNC int           IMAQ_STDCALL imaqFillHoles(Image* dest, const Image* source, int connectivity8);
623        //IMAQ_FUNC CircleReport* IMAQ_STDCALL imaqFindCircles(Image* dest, Image* source, float minRadius, float maxRadius, int* numCircles);
624        //IMAQ_FUNC int           IMAQ_STDCALL imaqLabel2(Image* dest, Image* source, int connectivity8, int* particleCount);
625        //IMAQ_FUNC int           IMAQ_STDCALL imaqMorphology(Image* dest, Image* source, MorphologyMethod method, const StructuringElement* structuringElement);
626        //IMAQ_FUNC int           IMAQ_STDCALL imaqRejectBorder(Image* dest, Image* source, int connectivity8);
627        //IMAQ_FUNC int           IMAQ_STDCALL imaqSegmentation(Image* dest, Image* source);
628        //IMAQ_FUNC int           IMAQ_STDCALL imaqSeparation(Image* dest, Image* source, int erosions, const StructuringElement* structuringElement);
629        //IMAQ_FUNC int           IMAQ_STDCALL imaqSimpleDistance(Image* dest, Image* source, const StructuringElement* structuringElement);
630        //IMAQ_FUNC int           IMAQ_STDCALL imaqSizeFilter(Image* dest, Image* source, int connectivity8, int erosions, SizeType keepSize, const StructuringElement* structuringElement);
631        //IMAQ_FUNC int           IMAQ_STDCALL imaqSkeleton(Image* dest, Image* source, SkeletonMethod method);
632            
633            
634        /**
635         * Convex hull operation
636         */
637        private static final BlockingFunction imaqConvexHullFn = NativeLibrary.getDefaultInstance().getBlockingFunction("imaqConvexHull");
638        static { imaqConvexHullFn.setTaskExecutor(taskExecutor); }
639        
640        public static void convexHull(Pointer dest, Pointer source, int connectivity8) throws NIVisionException {
641            assertCleanStatus(imaqConvexHullFn.call3(dest.address().toUWord().toPrimitive(),
642                                                    source.address().toUWord().toPrimitive(),
643                                                    connectivity8));
644        }
645        
646        /**
647         * size filter function
648         */
649        private static final BlockingFunction imaqSizeFilterFn = NativeLibrary.getDefaultInstance().getBlockingFunction("imaqSizeFilter");
650        static { imaqSizeFilterFn.setTaskExecutor(taskExecutor); }
651        
652        public static void sizeFilter(Pointer dest, Pointer source, boolean connectivity8, int erosions, boolean keepLarger) throws NIVisionException {
653            assertCleanStatus(imaqSizeFilterFn.call6(dest.address().toUWord().toPrimitive(),
654                                                    source.address().toUWord().toPrimitive(),
655                                                    connectivity8 ? 1 : 0, erosions, keepLarger ? 0 : 1, 0));
656        }
657        
658        //============================================================================
659        //  Logical functions
660        //============================================================================
661        //IMAQ_FUNC int IMAQ_STDCALL imaqAnd(Image* dest, const Image* sourceA, const Image* sourceB);
662        //IMAQ_FUNC int IMAQ_STDCALL imaqAndConstant(Image* dest, const Image* source, PixelValue value);
663        //IMAQ_FUNC int IMAQ_STDCALL imaqCompare(Image* dest, const Image* source, const Image* compareImage, ComparisonFunction compare);
664        //IMAQ_FUNC int IMAQ_STDCALL imaqCompareConstant(Image* dest, const Image* source, PixelValue value, ComparisonFunction compare);
665        //IMAQ_FUNC int IMAQ_STDCALL imaqLogicalDifference(Image* dest, const Image* sourceA, const Image* sourceB);
666        //IMAQ_FUNC int IMAQ_STDCALL imaqLogicalDifferenceConstant(Image* dest, const Image* source, PixelValue value);
667        //IMAQ_FUNC int IMAQ_STDCALL imaqNand(Image* dest, const Image* sourceA, const Image* sourceB);
668        //IMAQ_FUNC int IMAQ_STDCALL imaqNandConstant(Image* dest, const Image* source, PixelValue value);
669        //IMAQ_FUNC int IMAQ_STDCALL imaqNor(Image* dest, const Image* sourceA, const Image* sourceB);
670        //IMAQ_FUNC int IMAQ_STDCALL imaqNorConstant(Image* dest, const Image* source, PixelValue value);
671        //IMAQ_FUNC int IMAQ_STDCALL imaqOr(Image* dest, const Image* sourceA, const Image* sourceB);
672        //IMAQ_FUNC int IMAQ_STDCALL imaqOrConstant(Image* dest, const Image* source, PixelValue value);
673        //IMAQ_FUNC int IMAQ_STDCALL imaqXnor(Image* dest, const Image* sourceA, const Image* sourceB);
674        //IMAQ_FUNC int IMAQ_STDCALL imaqXnorConstant(Image* dest, const Image* source, PixelValue value);
675        //IMAQ_FUNC int IMAQ_STDCALL imaqXor(Image* dest, const Image* sourceA, const Image* sourceB);
676        //IMAQ_FUNC int IMAQ_STDCALL imaqXorConstant(Image* dest, const Image* source, PixelValue value);
677    
678        //============================================================================
679        //  Particle Analysis functions
680        //============================================================================
681    
682        private static final BlockingFunction imaqCountParticlesFn = NativeLibrary.getDefaultInstance().getBlockingFunction("imaqCountParticles");
683        static { imaqCountParticlesFn.setTaskExecutor(taskExecutor); }
684    
685        /**
686         * Counts the number of particles in a binary image.
687         * @param image The image to count the particles in
688         * @return The number of particles
689         */
690        public static int countParticles(Pointer image)  throws NIVisionException{
691            IntByReference i = new IntByReference(0);
692            int val;
693            try {
694                assertCleanStatus(imaqCountParticlesFn.call3(image, 1, i.getPointer()));
695            } finally {
696                val = i.getValue();
697                i.free();
698            }
699            return val;
700        }
701    
702        private static final BlockingFunction imaqMeasureParticleFn = NativeLibrary.getDefaultInstance().getBlockingFunction("imaqMeasureParticle");
703        static { imaqMeasureParticleFn.setTaskExecutor(taskExecutor); }
704    
705        /**
706         * Returns a measurement associated with a particle
707         * @param image The image containing the particle to get information about.
708         * @param particleNum The number of the particle to get information about.
709         * @param calibrated Specifies whether to return the measurement as a real-world value.
710         * @param type The measurement to make on the particle.
711         * @return The value of the requested measurement.
712         */
713        public static double MeasureParticle (Pointer image, int particleNum, boolean calibrated, MeasurementType type)  throws NIVisionException{
714            Pointer l = new Pointer(8);
715            double val;
716            try {
717                assertCleanStatus(imaqMeasureParticleFn.call5(image, particleNum, calibrated?1:0, type.value, l));
718            } finally {
719                val = l.getDouble(0);
720                l.free();
721            }
722            return val;
723        }
724    
725        //IMAQ_FUNC int IMAQ_STDCALL imaqParticleFilter4(Image* dest, Image* source, const ParticleFilterCriteria2* criteria, int criteriaCount, const ParticleFilterOptions2* options, const ROI* roi, int* numParticles);
726    
727        private static final BlockingFunction imaqParticleFilter4Fn = NativeLibrary.getDefaultInstance().getBlockingFunction("imaqParticleFilter4");
728        
729        public static int particleFilter(Pointer dest, Pointer source, CriteriaCollection collection) throws NIVisionException {
730            Pointer particleFilterOptions = new Pointer(16);
731            particleFilterOptions.setInt(0, 0);
732            particleFilterOptions.setInt(4, 0);
733            particleFilterOptions.setInt(8, 0);
734            particleFilterOptions.setInt(12, 1);
735            IntByReference i = new IntByReference(0);
736            Pointer criteriaArray = collection.getCriteriaArray();
737            assertCleanStatus(imaqParticleFilter4Fn.call7(dest.address().toUWord().toPrimitive(),   // dest image
738                                                        source.address().toUWord().toPrimitive(),   // source image
739                                                        criteriaArray.address().toUWord().toPrimitive(),  // array of criteria
740                                                        collection.getNumberOfCriteria(),           // number of criteria in the array
741                                                        particleFilterOptions.address().toUWord().toPrimitive(),  // particle filter options
742                                                        0,                                          // Region of interest
743                                                        i.getPointer().address().toUWord().toPrimitive()));  // returned number of particles
744            int numberOfParticles = i.getValue();
745            i.free();
746            criteriaArray.free();
747            particleFilterOptions.free();
748            return numberOfParticles;
749        }
750    
751        //============================================================================
752        //  Analytic Geometry functions
753        //============================================================================
754        //IMAQ_FUNC int           IMAQ_STDCALL imaqBuildCoordinateSystem(const Point* points, ReferenceMode mode, AxisOrientation orientation, CoordinateSystem* system);
755        //IMAQ_FUNC BestCircle2*  IMAQ_STDCALL imaqFitCircle2(const PointFloat* points, int numPoints, const FitCircleOptions* options);
756        //IMAQ_FUNC BestEllipse2* IMAQ_STDCALL imaqFitEllipse2(const PointFloat* points, int numPoints, const FitEllipseOptions* options);
757        //IMAQ_FUNC BestLine*     IMAQ_STDCALL imaqFitLine(const PointFloat* points, int numPoints, const FitLineOptions* options);
758        //IMAQ_FUNC int           IMAQ_STDCALL imaqGetAngle(PointFloat start1, PointFloat end1, PointFloat start2, PointFloat end2, float* angle);
759        //IMAQ_FUNC int           IMAQ_STDCALL imaqGetBisectingLine(PointFloat start1, PointFloat end1, PointFloat start2, PointFloat end2, PointFloat* bisectStart, PointFloat* bisectEnd);
760        //IMAQ_FUNC int           IMAQ_STDCALL imaqGetDistance(PointFloat point1, PointFloat point2, float* distance);
761        //IMAQ_FUNC int           IMAQ_STDCALL imaqGetIntersection(PointFloat start1, PointFloat end1, PointFloat start2, PointFloat end2, PointFloat* intersection);
762        //IMAQ_FUNC int           IMAQ_STDCALL imaqGetMidLine(PointFloat refLineStart, PointFloat refLineEnd, PointFloat point, PointFloat* midLineStart, PointFloat* midLineEnd);
763        //IMAQ_FUNC int           IMAQ_STDCALL imaqGetPerpendicularLine(PointFloat refLineStart, PointFloat refLineEnd, PointFloat point, PointFloat* perpLineStart, PointFloat* perpLineEnd, double* distance);
764        //IMAQ_FUNC SegmentInfo*  IMAQ_STDCALL imaqGetPointsOnContour(const Image* image, int* numSegments);
765        //IMAQ_FUNC Point*        IMAQ_STDCALL imaqGetPointsOnLine(Point start, Point end, int* numPoints);
766        //IMAQ_FUNC int           IMAQ_STDCALL imaqGetPolygonArea(const PointFloat* points, int numPoints, float* area);
767        //IMAQ_FUNC float*        IMAQ_STDCALL imaqInterpolatePoints(const Image* image, const Point* points, int numPoints, InterpolationMethod method, int subpixel, int* interpCount);
768    
769        //============================================================================
770        //  Border functions
771        //============================================================================
772        //IMAQ_FUNC int IMAQ_STDCALL imaqFillBorder(Image* image, BorderMethod method);
773        //IMAQ_FUNC int IMAQ_STDCALL imaqGetBorderSize(const Image* image, int* borderSize);
774        //IMAQ_FUNC int IMAQ_STDCALL imaqSetBorderSize(Image* image, int size);
775    
776        //============================================================================
777        //  Image Management functions
778        //============================================================================
779        protected static final BlockingFunction imaqCreateImageFn = NativeLibrary.getDefaultInstance().getBlockingFunction("imaqCreateImage");
780        static { imaqCreateImageFn.setTaskExecutor(taskExecutor); }
781    
782        /**
783         * Allocates space for and creates a new imaq image
784         * @param type the imaq encoding to use for the image
785         * @param borderSize the size of border to use for the image
786         * @return a newly allocated pointer to an imaqImage
787         */
788        public static Pointer imaqCreateImage(ImageType type, int borderSize) throws NIVisionException{
789            int toReturn = imaqCreateImageFn.call2(type.value, borderSize);
790            assertCleanStatus(toReturn);
791            return new Pointer(toReturn, 0);
792        }
793        //IMAQ_FUNC int    IMAQ_STDCALL imaqArrayToImage(Image* image, const void* array, int numCols, int numRows);
794        //IMAQ_FUNC void*  IMAQ_STDCALL imaqImageToArray(const Image* image, Rect rect, int* columns, int* rows);
795    
796        //============================================================================
797        //  Color Processing functions
798        //============================================================================
799    
800        private static final BlockingFunction imaqColorThresholdFn = NativeLibrary.getDefaultInstance().getBlockingFunction("imaqColorThreshold");
801        static { imaqColorThresholdFn.setTaskExecutor(taskExecutor); }
802    
803        /**
804         * Convert the given image into a binary image true where the colors match the given thresholds
805         * @param dest the 8 bit monocolor image to store the result in
806         * @param source the color image source
807         * @param mode The mode of color to use
808         * @param plane1Range First color range
809         * @param plane2Range Second color range
810         * @param plane3Range Third color range
811         */
812        public static void colorThreshold(Pointer dest, Pointer source, ColorMode mode,
813                Pointer plane1Range, Pointer plane2Range, Pointer plane3Range)  throws NIVisionException{
814            int replaceValue = 1;
815            assertCleanStatus(imaqColorThresholdFn.call7(dest.address().toUWord().toPrimitive(),
816                    source.address().toUWord().toPrimitive(),
817                    replaceValue, mode.value,
818                    plane1Range.address().toUWord().toPrimitive(),
819                    plane2Range.address().toUWord().toPrimitive(),
820                    plane3Range.address().toUWord().toPrimitive()));
821        }
822    
823        private static final BlockingFunction imaqColorEqualizeFn = NativeLibrary.getDefaultInstance().getBlockingFunction("imaqColorEqualize");
824        static { imaqColorEqualizeFn.setTaskExecutor(taskExecutor); }
825    
826        /**
827         * Calculates the histogram of each plane of a color image and redistributes
828         * pixel values across the desired range while maintaining pixel value
829         * groupings.
830         * @param destination The destination image.
831         * @param source The image to equalize.
832         * @param all Set this parameter to TRUE to equalize all three planes of the
833         * image. Set this parameter to FALSE to equalize only the luminance plane.
834         */
835        public static void colorEqualize(Pointer destination, Pointer source, boolean all)  throws NIVisionException{
836            assertCleanStatus(imaqColorEqualizeFn.call3(destination, source,all?1:0));
837        }
838    
839        //IMAQ_FUNC Color2                IMAQ_STDCALL imaqChangeColorSpace2(const Color2* sourceColor, ColorMode sourceSpace, ColorMode destSpace, double offset, const CIEXYZValue* whiteReference);
840        //IMAQ_FUNC int                   IMAQ_STDCALL imaqColorBCGTransform(Image* dest, const Image* source, const BCGOptions* redOptions, const BCGOptions* greenOptions, const BCGOptions* blueOptions, const Image* mask);
841        //IMAQ_FUNC ColorHistogramReport* IMAQ_STDCALL imaqColorHistogram2(Image* image, int numClasses, ColorMode mode, const CIEXYZValue* whiteReference, Image* mask);
842        //IMAQ_FUNC int                   IMAQ_STDCALL imaqColorLookup(Image* dest, const Image* source, ColorMode mode, const Image* mask, const short* plane1, const short* plane2, const short* plane3);
843    
844        //============================================================================
845        //  Transform functions
846        //============================================================================
847        //IMAQ_FUNC int IMAQ_STDCALL imaqBCGTransform(Image* dest, const Image* source, const BCGOptions* options, const Image* mask);
848        //IMAQ_FUNC int IMAQ_STDCALL imaqEqualize(Image* dest, const Image* source, float min, float max, const Image* mask);
849        //IMAQ_FUNC int IMAQ_STDCALL imaqInverse(Image* dest, const Image* source, const Image* mask);
850        //IMAQ_FUNC int IMAQ_STDCALL imaqLookup(Image* dest, const Image* source, const short* table, const Image* mask);
851        //IMAQ_FUNC int IMAQ_STDCALL imaqMathTransform(Image* dest, const Image* source, MathTransformMethod method, float rangeMin, float rangeMax, float power, const Image* mask);
852        //IMAQ_FUNC int IMAQ_STDCALL imaqWatershedTransform(Image* dest, const Image* source, int connectivity8, int* zoneCount);
853    
854    
855        //============================================================================
856        //  Utilities functions
857        //============================================================================
858        //IMAQ_FUNC const float* IMAQ_STDCALL imaqGetKernel(KernelFamily family, int size, int number);
859        //IMAQ_FUNC Annulus      IMAQ_STDCALL imaqMakeAnnulus(Point center, int innerRadius, int outerRadius, double startAngle, double endAngle);
860        //IMAQ_FUNC Point        IMAQ_STDCALL imaqMakePoint(int xCoordinate, int yCoordinate);
861        //IMAQ_FUNC PointFloat   IMAQ_STDCALL imaqMakePointFloat(float xCoordinate, float yCoordinate);
862        //IMAQ_FUNC Rect         IMAQ_STDCALL imaqMakeRect(int top, int left, int height, int width);
863        //IMAQ_FUNC Rect         IMAQ_STDCALL imaqMakeRectFromRotatedRect(RotatedRect rotatedRect);
864        //IMAQ_FUNC RotatedRect  IMAQ_STDCALL imaqMakeRotatedRect(int top, int left, int height, int width, double angle);
865        //IMAQ_FUNC RotatedRect  IMAQ_STDCALL imaqMakeRotatedRectFromRect(Rect rect);
866        //IMAQ_FUNC int          IMAQ_STDCALL imaqMulticoreOptions(MulticoreOperation operation, unsigned int* customNumCores);
867    
868        //============================================================================
869        //  Image Manipulation functions
870        //============================================================================
871        //IMAQ_FUNC int   IMAQ_STDCALL imaqCast(Image* dest, const Image* source, ImageType type, const float* lookup, int shift);
872        //IMAQ_FUNC int   IMAQ_STDCALL imaqCopyRect(Image* dest, const Image* source, Rect rect, Point destLoc);
873        //IMAQ_FUNC int   IMAQ_STDCALL imaqDuplicate(Image* dest, const Image* source);
874        //IMAQ_FUNC void* IMAQ_STDCALL imaqFlatten(const Image* image, FlattenType type, CompressionType compression, int quality, unsigned int* size);
875        //IMAQ_FUNC int   IMAQ_STDCALL imaqFlip(Image* dest, const Image* source, FlipAxis axis);
876        //IMAQ_FUNC int   IMAQ_STDCALL imaqMask(Image* dest, const Image* source, const Image* mask);
877        //IMAQ_FUNC int   IMAQ_STDCALL imaqResample(Image* dest, const Image* source, int newWidth, int newHeight, InterpolationMethod method, Rect rect);
878        //IMAQ_FUNC int   IMAQ_STDCALL imaqRotate2(Image* dest, const Image* source, float angle, PixelValue fill, InterpolationMethod method, int maintainSize);
879        //IMAQ_FUNC int   IMAQ_STDCALL imaqScale(Image* dest, const Image* source, int xScale, int yScale, ScalingMode scaleMode, Rect rect);
880        //IMAQ_FUNC int   IMAQ_STDCALL imaqShift(Image* dest, const Image* source, int shiftX, int shiftY, PixelValue fill);
881        //IMAQ_FUNC int   IMAQ_STDCALL imaqTranspose(Image* dest, const Image* source);
882        //IMAQ_FUNC int   IMAQ_STDCALL imaqUnflatten(Image* image, const void* data, unsigned int size);
883        //IMAQ_FUNC int   IMAQ_STDCALL imaqUnwrapImage(Image* dest, const Image* source, Annulus annulus, RectOrientation orientation, InterpolationMethod method);
884        //IMAQ_FUNC int   IMAQ_STDCALL imaqView3D(Image* dest, Image* source, const View3DOptions* options);
885    
886        //============================================================================
887        //  Pattern Matching functions
888        //============================================================================
889    
890        private static final BlockingFunction imaqDetectEllipsesFn =
891                NativeLibrary.getDefaultInstance().getBlockingFunction("imaqDetectEllipses");
892        static { imaqDetectEllipsesFn.setTaskExecutor(NIVision.taskExecutor); }
893        private static Pointer numberOfEllipsesDetected = new Pointer(4);
894    
895    
896        public static EllipseMatch[] detectEllipses(MonoImage image, EllipseDescriptor ellipseDescriptor,
897                CurveOptions curveOptions, ShapeDetectionOptions shapeDetectionOptions,
898                RegionOfInterest roi) throws NIVisionException {
899    
900            int curveOptionsPointer = 0;
901            if (curveOptions != null)
902                curveOptionsPointer = curveOptions.getPointer().address().toUWord().toPrimitive();
903            int shapeDetectionOptionsPointer = 0;
904            if (shapeDetectionOptions != null)
905                shapeDetectionOptionsPointer = shapeDetectionOptions.getPointer().address().toUWord().toPrimitive();
906            int roiPointer = 0;
907            if (roi != null)
908                roiPointer = roi.getPointer().address().toUWord().toPrimitive();
909    
910            int returnedAddress =
911                    imaqDetectEllipsesFn.call6(
912                    image.image.address().toUWord().toPrimitive(),
913                    ellipseDescriptor.getPointer().address().toUWord().toPrimitive(),
914                    curveOptionsPointer, shapeDetectionOptionsPointer,
915                    roiPointer,
916                    numberOfEllipsesDetected.address().toUWord().toPrimitive());
917    
918            try {
919                NIVision.assertCleanStatus(returnedAddress);
920            } catch (NIVisionException ex) {
921                if (!ex.getMessage().equals("No error."))
922                    throw ex;
923            }
924    
925            EllipseMatch[] matches = EllipseMatch.getMatchesFromMemory(returnedAddress, numberOfEllipsesDetected.getInt(0));
926            NIVision.dispose(new Pointer(returnedAddress,0));
927            return matches;
928        }
929        //IMAQ_FUNC CircleMatch*              IMAQ_STDCALL imaqDetectCircles(const Image* image, const CircleDescriptor* circleDescriptor, const CurveOptions* curveOptions, const ShapeDetectionOptions* shapeDetectionOptions, const ROI* roi, int* numMatchesReturned);
930        //IMAQ_FUNC LineMatch*                IMAQ_STDCALL imaqDetectLines(const Image* image, const LineDescriptor* lineDescriptor, const CurveOptions* curveOptions, const ShapeDetectionOptions* shapeDetectionOptions, const ROI* roi, int* numMatchesReturned);
931        //IMAQ_FUNC RectangleMatch*           IMAQ_STDCALL imaqDetectRectangles(const Image* image, const RectangleDescriptor* rectangleDescriptor, const CurveOptions* curveOptions, const ShapeDetectionOptions* shapeDetectionOptions, const ROI* roi, int* numMatchesReturned);
932        //IMAQ_FUNC FeatureData*              IMAQ_STDCALL imaqGetGeometricFeaturesFromCurves(const Curve* curves, unsigned int numCurves, const FeatureType* featureTypes, unsigned int numFeatureTypes, unsigned int* numFeatures);
933        //IMAQ_FUNC FeatureData*              IMAQ_STDCALL imaqGetGeometricTemplateFeatureInfo(const Image* pattern, unsigned int* numFeatures);
934        //IMAQ_FUNC int                       IMAQ_STDCALL imaqLearnColorPattern(Image* image, const LearnColorPatternOptions* options);
935        //IMAQ_FUNC int                       IMAQ_STDCALL imaqLearnGeometricPattern(Image* image, PointFloat originOffset, const CurveOptions* curveOptions, const LearnGeometricPatternAdvancedOptions* advancedLearnOptions, const Image* mask);
936        //IMAQ_FUNC MultipleGeometricPattern* IMAQ_STDCALL imaqLearnMultipleGeometricPatterns(const Image** patterns, unsigned int numberOfPatterns, const String255* labels);
937        //IMAQ_FUNC int                       IMAQ_STDCALL imaqLearnPattern3(Image* image, LearningMode learningMode, LearnPatternAdvancedOptions* advancedOptions, const Image* mask);
938        //IMAQ_FUNC PatternMatch*             IMAQ_STDCALL imaqMatchColorPattern(const Image* image, Image* pattern, const MatchColorPatternOptions* options, Rect searchRect, int* numMatches);
939        //IMAQ_FUNC GeometricPatternMatch2*   IMAQ_STDCALL imaqMatchGeometricPattern2(const Image* image, const Image* pattern, const CurveOptions* curveOptions, const MatchGeometricPatternOptions* matchOptions, const MatchGeometricPatternAdvancedOptions2* advancedMatchOptions, const ROI* roi, int* numMatches);
940        //IMAQ_FUNC GeometricPatternMatch2*   IMAQ_STDCALL imaqMatchMultipleGeometricPatterns(const Image* image, const MultipleGeometricPattern* multiplePattern, const ROI* roi, int* numMatches);
941        //IMAQ_FUNC PatternMatch*             IMAQ_STDCALL imaqMatchPattern2(const Image* image, const Image* pattern, const MatchPatternOptions* options, const MatchPatternOptions* advancedOptions, Rect searchRect, int* numMatches);
942        //IMAQ_FUNC MultipleGeometricPattern* IMAQ_STDCALL imaqReadMultipleGeometricPatternFile(const char* fileName, String255 description);
943        //IMAQ_FUNC PatternMatch*             IMAQ_STDCALL imaqRefineMatches(const Image* image, const Image* pattern, const PatternMatch* candidatesIn, int numCandidatesIn, MatchPatternOptions* options, MatchPatternAdvancedOptions* advancedOptions, int* numCandidatesOut);
944        //IMAQ_FUNC int                       IMAQ_STDCALL imaqSetMultipleGeometricPatternsOptions(MultipleGeometricPattern* multiplePattern, const char* label, const CurveOptions* curveOptions, const MatchGeometricPatternOptions* matchOptions, const MatchGeometricPatternAdvancedOptions2* advancedMatchOptions);
945        //IMAQ_FUNC int                       IMAQ_STDCALL imaqWriteMultipleGeometricPatternFile(const MultipleGeometricPattern* multiplePattern, const char* fileName, const char* description);
946    
947        //============================================================================
948        //  Calibration functions
949        //============================================================================
950        //IMAQ_FUNC int              IMAQ_STDCALL imaqCopyCalibrationInfo2(Image* dest, Image* source, Point offset);
951        //IMAQ_FUNC int              IMAQ_STDCALL imaqCorrectCalibratedImage(Image* dest, const Image* source, PixelValue fill, InterpolationMethod method, const ROI* roi);
952        //IMAQ_FUNC CalibrationInfo* IMAQ_STDCALL imaqGetCalibrationInfo2(const Image* image);
953        //IMAQ_FUNC int              IMAQ_STDCALL imaqLearnCalibrationGrid(Image* image, const ROI* roi, const LearnCalibrationOptions* options, const GridDescriptor* grid, const CoordinateSystem* system, const RangeFloat* range, float* quality);
954        //IMAQ_FUNC int              IMAQ_STDCALL imaqLearnCalibrationPoints(Image* image, const CalibrationPoints* points, const ROI* roi, const LearnCalibrationOptions* options, const GridDescriptor* grid, const CoordinateSystem* system, float* quality);
955        //IMAQ_FUNC int              IMAQ_STDCALL imaqSetCoordinateSystem(Image* image, const CoordinateSystem* system);
956        //IMAQ_FUNC int              IMAQ_STDCALL imaqSetSimpleCalibration(Image* image, ScalingMethod method, int learnTable, const GridDescriptor* grid, const CoordinateSystem* system);
957        //IMAQ_FUNC TransformReport* IMAQ_STDCALL imaqTransformPixelToRealWorld(const Image* image, const PointFloat* pixelCoordinates, int numCoordinates);
958        //IMAQ_FUNC TransformReport* IMAQ_STDCALL imaqTransformRealWorldToPixel(const Image* image, const PointFloat* realWorldCoordinates, int numCoordinates);
959    
960        //============================================================================
961        //  Overlay functions
962        //============================================================================
963        //IMAQ_FUNC int IMAQ_STDCALL imaqClearOverlay(Image* image, const char* group);
964        //IMAQ_FUNC int IMAQ_STDCALL imaqCopyOverlay(Image* dest, const Image* source, const char* group);
965        //IMAQ_FUNC int IMAQ_STDCALL imaqGetOverlayProperties(Image* image, const char* group, TransformBehaviors* transformBehaviors);
966        //IMAQ_FUNC int IMAQ_STDCALL imaqMergeOverlay(Image* dest, const Image* source, const RGBValue* palette, unsigned int numColors, const char* group);
967        //IMAQ_FUNC int IMAQ_STDCALL imaqOverlayArc(Image* image, const ArcInfo* arc, const RGBValue* color, DrawMode drawMode, const char* group);
968        //IMAQ_FUNC int IMAQ_STDCALL imaqOverlayBitmap(Image* image, Point destLoc, const RGBValue* bitmap, unsigned int numCols, unsigned int numRows, const char* group);
969        //IMAQ_FUNC int IMAQ_STDCALL imaqOverlayClosedContour(Image* image, const Point* points, int numPoints, const RGBValue* color, DrawMode drawMode, const char* group);
970        //IMAQ_FUNC int IMAQ_STDCALL imaqOverlayLine(Image* image, Point start, Point end, const RGBValue* color, const char* group);
971        //IMAQ_FUNC int IMAQ_STDCALL imaqOverlayMetafile(Image* image, const void* metafile, Rect rect, const char* group);
972        //IMAQ_FUNC int IMAQ_STDCALL imaqOverlayOpenContour(Image* image, const Point* points, int numPoints, const RGBValue* color, const char* group);
973        //IMAQ_FUNC int IMAQ_STDCALL imaqOverlayOval(Image* image, Rect boundingBox, const RGBValue* color, DrawMode drawMode, char* group);
974        //IMAQ_FUNC int IMAQ_STDCALL imaqOverlayPoints(Image* image, const Point* points, int numPoints, const RGBValue* colors, int numColors, PointSymbol symbol, const UserPointSymbol* userSymbol, const char* group);
975        //IMAQ_FUNC int IMAQ_STDCALL imaqOverlayRect(Image* image, Rect rect, const RGBValue* color, DrawMode drawMode, const char* group);
976        //IMAQ_FUNC int IMAQ_STDCALL imaqOverlayROI(Image* image, const ROI* roi, PointSymbol symbol, const UserPointSymbol* userSymbol, const char* group);
977        //IMAQ_FUNC int IMAQ_STDCALL imaqOverlayText(Image* image, Point origin, const char* text, const RGBValue* color, const OverlayTextOptions* options, const char* group);
978        //IMAQ_FUNC int IMAQ_STDCALL imaqSetOverlayProperties(Image* image, const char* group, TransformBehaviors* transformBehaviors);
979    
980        //============================================================================
981        //  Color Matching functions
982        //============================================================================
983        //IMAQ_FUNC ColorInformation* IMAQ_STDCALL imaqLearnColor(const Image* image, const ROI* roi, ColorSensitivity sensitivity, int saturation);
984        //IMAQ_FUNC int*              IMAQ_STDCALL imaqMatchColor(const Image* image, const ColorInformation* info, const ROI* roi, int* numScores);
985    
986        //============================================================================
987        //  Meter functions
988        //============================================================================
989        //IMAQ_FUNC MeterArc* IMAQ_STDCALL imaqGetMeterArc(int lightNeedle, MeterArcMode mode, const ROI* roi, PointFloat base, PointFloat start, PointFloat end);
990        //IMAQ_FUNC int       IMAQ_STDCALL imaqReadMeter(const Image* image, const MeterArc* arcInfo, double* percentage, PointFloat* endOfNeedle);
991    
992        //============================================================================
993        //  Barcode I/O functions
994        //============================================================================
995        //IMAQ_FUNC int               IMAQ_STDCALL imaqGradeDataMatrixBarcodeAIM(const Image* image, AIMGradeReport* report);
996        //IMAQ_FUNC BarcodeInfo*      IMAQ_STDCALL imaqReadBarcode(const Image* image, BarcodeType type, const ROI* roi, int validate);
997        //IMAQ_FUNC DataMatrixReport* IMAQ_STDCALL imaqReadDataMatrixBarcode2(Image* image, const ROI* roi, DataMatrixGradingMode prepareForGrading, const DataMatrixDescriptionOptions* descriptionOptions, const DataMatrixSizeOptions* sizeOptions, const DataMatrixSearchOptions* searchOptions);
998        //IMAQ_FUNC Barcode2DInfo*    IMAQ_STDCALL imaqReadPDF417Barcode(const Image* image, const ROI* roi, Barcode2DSearchMode searchMode, unsigned int* numBarcodes);
999        //IMAQ_FUNC QRCodeReport*     IMAQ_STDCALL imaqReadQRCode(Image* image, const ROI* roi, QRGradingMode reserved, const QRCodeDescriptionOptions* descriptionOptions, const QRCodeSizeOptions* sizeOptions, const QRCodeSearchOptions* searchOptions);
1000    
1001        //============================================================================
1002        //  Shape Matching functions
1003        //============================================================================
1004        //IMAQ_FUNC ShapeReport* IMAQ_STDCALL imaqMatchShape(Image* dest, Image* source, const Image* templateImage, int scaleInvariant, int connectivity8, double tolerance, int* numMatches);
1005    
1006        //============================================================================
1007        //  Contours functions
1008        //============================================================================
1009        //IMAQ_FUNC ContourID     IMAQ_STDCALL imaqAddAnnulusContour(ROI* roi, Annulus annulus);
1010        //IMAQ_FUNC ContourID     IMAQ_STDCALL imaqAddClosedContour(ROI* roi, const Point* points, int numPoints);
1011        //IMAQ_FUNC ContourID     IMAQ_STDCALL imaqAddLineContour(ROI* roi, Point start, Point end);
1012        //IMAQ_FUNC ContourID     IMAQ_STDCALL imaqAddOpenContour(ROI* roi, const Point* points, int numPoints);
1013        //IMAQ_FUNC ContourID     IMAQ_STDCALL imaqAddOvalContour(ROI* roi, Rect boundingBox);
1014        //IMAQ_FUNC ContourID     IMAQ_STDCALL imaqAddPointContour(ROI* roi, Point point);
1015        //IMAQ_FUNC ContourID     IMAQ_STDCALL imaqAddRectContour(ROI* roi, Rect rect);
1016        //IMAQ_FUNC ContourID     IMAQ_STDCALL imaqAddRotatedRectContour2(ROI* roi, RotatedRect rect);
1017        //IMAQ_FUNC ContourID     IMAQ_STDCALL imaqCopyContour(ROI* destRoi, const ROI* sourceRoi, ContourID id);
1018        //IMAQ_FUNC ContourID     IMAQ_STDCALL imaqGetContour(const ROI* roi, unsigned int index);
1019        //IMAQ_FUNC int           IMAQ_STDCALL imaqGetContourColor(const ROI* roi, ContourID id, RGBValue* contourColor);
1020        //IMAQ_FUNC int           IMAQ_STDCALL imaqGetContourCount(const ROI* roi);
1021        //IMAQ_FUNC ContourInfo2* IMAQ_STDCALL imaqGetContourInfo2(const ROI* roi, ContourID id);
1022        //IMAQ_FUNC int           IMAQ_STDCALL imaqMoveContour(ROI* roi, ContourID id, int deltaX, int deltaY);
1023        //IMAQ_FUNC int           IMAQ_STDCALL imaqRemoveContour(ROI* roi, ContourID id);
1024        //IMAQ_FUNC int           IMAQ_STDCALL imaqSetContourColor(ROI* roi, ContourID id, const RGBValue* color);
1025    
1026        //============================================================================
1027        //  Regions of Interest functions
1028        //============================================================================
1029        //IMAQ_FUNC int  IMAQ_STDCALL imaqConstructROI2(const Image* image, ROI* roi, Tool initialTool, const ToolWindowOptions* tools, const ConstructROIOptions2* options, int* okay);
1030        //IMAQ_FUNC ROI* IMAQ_STDCALL imaqCreateROI();
1031        //IMAQ_FUNC int  IMAQ_STDCALL imaqGetROIBoundingBox(const ROI* roi, Rect* boundingBox);
1032        //IMAQ_FUNC int  IMAQ_STDCALL imaqGetROIColor(const ROI* roi, RGBValue* roiColor);
1033        //IMAQ_FUNC ROI* IMAQ_STDCALL imaqGetWindowROI(int windowNumber);
1034        //IMAQ_FUNC int  IMAQ_STDCALL imaqSetROIColor(ROI* roi, const RGBValue* color);
1035        //IMAQ_FUNC int  IMAQ_STDCALL imaqSetWindowROI(int windowNumber, const ROI* roi);
1036    
1037        //============================================================================
1038        //  Image Analysis functions
1039        //============================================================================
1040        //IMAQ_FUNC int              IMAQ_STDCALL imaqCentroid(const Image* image, PointFloat* centroid, const Image* mask);
1041        //IMAQ_FUNC Curve*           IMAQ_STDCALL imaqExtractCurves(const Image* image, const ROI* roi, const CurveOptions* curveOptions, unsigned int* numCurves);
1042        //IMAQ_FUNC HistogramReport* IMAQ_STDCALL imaqHistogram(const Image* image, int numClasses, float min, float max, const Image* mask);
1043        
1044        private static final BlockingFunction imaqLinearAverages2Fn = NativeLibrary.getDefaultInstance().getBlockingFunction("imaqLinearAverages2");
1045        
1046        public static LinearAverages getLinearAverages(Pointer image, LinearAverages.LinearAveragesMode mode, Rect rect) throws NIVisionException
1047        { 
1048           int returnedAddress = imaqLinearAverages2Fn.call3(image, mode.value, rect.getPointer());
1049           
1050           try {
1051                NIVision.assertCleanStatus(returnedAddress);
1052           } catch (NIVisionException ex) {
1053                if (!ex.getMessage().equals("No error."))
1054                    throw ex;
1055           }
1056           
1057           LinearAverages averages = new LinearAverages(returnedAddress);
1058           NIVision.dispose(new Pointer(returnedAddress,0));
1059           return averages;
1060        }
1061        
1062        //IMAQ_FUNC LineProfile*     IMAQ_STDCALL imaqLineProfile(const Image* image, Point start, Point end);
1063        //IMAQ_FUNC QuantifyReport*  IMAQ_STDCALL imaqQuantify(const Image* image, const Image* mask);
1064    
1065        //============================================================================
1066        //  Error Management functions
1067        //============================================================================
1068        private static final BlockingFunction imaqGetLastErrorFn = NativeLibrary.getDefaultInstance().getBlockingFunction("imaqGetLastError");
1069        static { imaqGetLastErrorFn.setTaskExecutor(taskExecutor);  }
1070    
1071        public static int getLastError(){
1072            return imaqGetLastErrorFn.call0();
1073        }
1074        protected static void assertCleanStatus (int code) throws NIVisionException {
1075            if (code == 0) {
1076                throw new NIVisionException(imaqGetLastErrorFn.call0());
1077            }
1078        }
1079    
1080        //IMAQ_FUNC int         IMAQ_STDCALL imaqClearError();
1081        //IMAQ_FUNC char*       IMAQ_STDCALL imaqGetErrorText(int errorCode);
1082        //IMAQ_FUNC const char* IMAQ_STDCALL imaqGetLastErrorFunc();
1083        //IMAQ_FUNC int         IMAQ_STDCALL imaqSetError(int errorCode, const char* function);
1084    
1085        //============================================================================
1086        //  Threshold functions
1087        //============================================================================
1088        //IMAQ_FUNC ThresholdData* IMAQ_STDCALL imaqAutoThreshold2(Image* dest, const Image* source, int numClasses, ThresholdMethod method, const Image* mask);
1089        //IMAQ_FUNC int            IMAQ_STDCALL imaqLocalThreshold(Image* dest, const Image* source, unsigned int windowWidth, unsigned int windowHeight, LocalThresholdMethod method, double deviationWeight, ObjectType type, float replaceValue);
1090        //IMAQ_FUNC int            IMAQ_STDCALL imaqMagicWand(Image* dest, const Image* source, Point coord, float tolerance, int connectivity8, float replaceValue);
1091        //IMAQ_FUNC int            IMAQ_STDCALL imaqMultithreshold(Image* dest, const Image* source, const ThresholdData* ranges, int numRanges);
1092        //IMAQ_FUNC int            IMAQ_STDCALL imaqThreshold(Image* dest, const Image* source, float rangeMin, float rangeMax, int useNewValue, float newValue);
1093    
1094        //============================================================================
1095        //  Memory Management functions
1096        //============================================================================
1097    
1098        private static final BlockingFunction imaqDisposeFn = NativeLibrary.getDefaultInstance().getBlockingFunction("imaqDispose");
1099        static { imaqDisposeFn.setTaskExecutor(taskExecutor); }
1100    
1101        /**
1102         * Cleans up resources associated with images, regions of interest (ROIs),
1103         * arrays, and reports that you no longer need.
1104         * After you dispose of something, you can no longer use it.
1105         * @param item The image, ROI, array, or report whose memory you want to free.
1106         */
1107        public static void dispose (Pointer item)  throws NIVisionException{
1108            assertCleanStatus(imaqDisposeFn.call1(item));
1109        }
1110    
1111        //============================================================================
1112        //  File I/O functions
1113        //============================================================================
1114    
1115        private static final BlockingFunction Priv_ReadJPEGString_CFn = NativeLibrary.getDefaultInstance().getBlockingFunction("Priv_ReadJPEGString_C");
1116        static { Priv_ReadJPEGString_CFn.setTaskExecutor(taskExecutor); }
1117    
1118        /**
1119         * Read a pointer to a byte array into the given image
1120         * @param image pointer to an imaq image object
1121         * @param p pointer to a byte array holding image data
1122         */
1123        public static void readJpegString(Pointer image, Pointer p) {
1124            Priv_ReadJPEGString_CFn.call3(image, p, p.getSize());
1125        }
1126    
1127        private static final BlockingFunction Priv_SetWriteFileAllowedFn = NativeLibrary.getDefaultInstance().getBlockingFunction("Priv_SetWriteFileAllowed");
1128        static { Priv_SetWriteFileAllowedFn.setTaskExecutor(taskExecutor); }
1129    
1130        /**
1131         * Set true to be able to create files on cRio
1132         * @param val true allows files to be created
1133         */
1134        public static void setWriteFileAllowed(boolean val) {
1135            Priv_SetWriteFileAllowedFn.call1(val ? 1 : 0);
1136        }
1137    
1138        private static final Function imaqWriteFileFn = NativeLibrary.getDefaultInstance().getFunction("imaqWriteFile");
1139    //    static { imaqWriteFileFn.setTaskExecutor(taskExecutor); }
1140    
1141        /**
1142         * Write an image to the given file.
1143         *
1144         * Supported extensions:
1145         * .aipd or .apd AIPD
1146         * .bmp BMP
1147         * .jpg or .jpeg JPEG
1148         * .jp2 JPEG2000
1149         * .png PNG
1150         * .tif or .tiff TIFF
1151         *
1152         * @param image The image to write to a file.
1153         * @param fileName The name of the destination file.
1154         */
1155        public static void writeFile(Pointer image, String fileName) throws NIVisionException {
1156            Pointer p = new Pointer(fileName.length() + 1);
1157            p.setString(0, fileName);
1158            setWriteFileAllowed(true);
1159            try {
1160                assertCleanStatus(imaqWriteFileFn.call3(image, p, 0)); //zero is unused color table
1161            } finally {
1162                p.free();
1163            }
1164        }
1165    
1166        /**
1167         * Write an image to the given file.
1168         *
1169         * Supported extensions:
1170         * .aipd or .apd AIPD
1171         * .bmp BMP
1172         * .jpg or .jpeg JPEG
1173         * .jp2 JPEG2000
1174         * .png PNG
1175         * .tif or .tiff TIFF
1176         *
1177         * @param image The image to write to a file.
1178         * @param fileName The name of the destination file.
1179         * @param colorTable The color table to use for 8-bit images
1180         */
1181        public static void writeFile(Pointer image, String fileName, Pointer colorTable)  throws NIVisionException{
1182            Pointer p = new Pointer(fileName.length() + 1);
1183            p.setString(0, fileName);
1184            setWriteFileAllowed(true);
1185            try {
1186                assertCleanStatus(imaqWriteFileFn.call3(image, p, colorTable)); //zero is unused color table
1187            } finally {
1188                p.free();
1189            }
1190        }
1191    
1192        private static final BlockingFunction imaqReadFileFn = NativeLibrary.getDefaultInstance().getBlockingFunction("imaqReadFile");
1193        static { imaqReadFileFn.setTaskExecutor(taskExecutor); }
1194    
1195        /**
1196         * Read an image from to the given image from the given filename
1197         * @param image The image to store the data in.
1198         * @param fileName The name of the file to load.
1199         */
1200        public static void readFile(Pointer image, String fileName)  throws NIVisionException{
1201            Pointer p = new Pointer(fileName.length() + 1);
1202            p.setString(0, fileName);
1203            try {
1204                assertCleanStatus(imaqReadFileFn.call4(image, p, 0, 0)); //zeros are unused color table and num colors
1205            } finally {
1206                p.free();
1207            }
1208        }
1209    
1210        //IMAQ_FUNC int         IMAQ_STDCALL imaqCloseAVI(AVISession session);
1211        //IMAQ_FUNC AVISession  IMAQ_STDCALL imaqCreateAVI(const char* fileName, const char* compressionFilter, int quality, unsigned int framesPerSecond, unsigned int maxDataSize);
1212        //IMAQ_FUNC int         IMAQ_STDCALL imaqGetAVIInfo(AVISession session, AVIInfo* info);
1213        //IMAQ_FUNC int         IMAQ_STDCALL imaqGetFileInfo(const char* fileName, CalibrationUnit* calibrationUnit, float* calibrationX, float* calibrationY, int* width, int* height, ImageType* imageType);
1214        //IMAQ_FUNC FilterName* IMAQ_STDCALL imaqGetFilterNames(int* numFilters);
1215        //IMAQ_FUNC char**      IMAQ_STDCALL imaqLoadImagePopup(const char* defaultDirectory, const char* defaultFileSpec, const char* fileTypeList, const char* title, int allowMultiplePaths, ButtonLabel buttonLabel, int restrictDirectory, int restrictExtension, int allowCancel, int allowMakeDirectory, int* cancelled, int* numPaths);
1216        //IMAQ_FUNC AVISession  IMAQ_STDCALL imaqOpenAVI(const char* fileName);
1217        //IMAQ_FUNC int         IMAQ_STDCALL imaqReadAVIFrame(Image* image, AVISession session, unsigned int frameNum, void* data, unsigned int* dataSize);
1218        //IMAQ_FUNC int         IMAQ_STDCALL imaqReadVisionFile(Image* image, const char* fileName, RGBValue* colorTable, int* numColors);
1219        //IMAQ_FUNC int         IMAQ_STDCALL imaqWriteAVIFrame(Image* image, AVISession session, const void* data, unsigned int dataLength);
1220        //IMAQ_FUNC int         IMAQ_STDCALL imaqWriteBMPFile(const Image* image, const char* fileName, int compress, const RGBValue* colorTable);
1221        //IMAQ_FUNC int         IMAQ_STDCALL imaqWriteJPEGFile(const Image* image, const char* fileName, unsigned int quality, void* colorTable);
1222        //IMAQ_FUNC int         IMAQ_STDCALL imaqWriteJPEG2000File(const Image* image, const char* fileName, int lossless, float compressionRatio, const JPEG2000FileAdvancedOptions* advancedOptions, const RGBValue* colorTable);
1223        //IMAQ_FUNC int         IMAQ_STDCALL imaqWritePNGFile2(const Image* image, const char* fileName, unsigned int compressionSpeed, const RGBValue* colorTable, int useBitDepth);
1224        //IMAQ_FUNC int         IMAQ_STDCALL imaqWriteTIFFFile(const Image* image, const char* fileName, const TIFFFileOptions* options, const RGBValue* colorTable);
1225        //IMAQ_FUNC int         IMAQ_STDCALL imaqWriteVisionFile(const Image* image, const char* fileName, const RGBValue* colorTable);
1226    
1227    
1228        //============================================================================
1229        //  Frequency Domain Analysis functions
1230        //============================================================================
1231        //IMAQ_FUNC int IMAQ_STDCALL imaqAttenuate(Image* dest, const Image* source, AttenuateMode highlow);
1232        //IMAQ_FUNC int IMAQ_STDCALL imaqConjugate(Image* dest, const Image* source);
1233        //IMAQ_FUNC int IMAQ_STDCALL imaqFFT(Image* dest, const Image* source);
1234        //IMAQ_FUNC int IMAQ_STDCALL imaqFlipFrequencies(Image* dest, const Image* source);
1235        //IMAQ_FUNC int IMAQ_STDCALL imaqInverseFFT(Image* dest, const Image* source);
1236        //IMAQ_FUNC int IMAQ_STDCALL imaqTruncate(Image* dest, const Image* source, TruncateMode highlow, float ratioToKeep);
1237    
1238        //============================================================================
1239        //  Pixel Manipulation functions
1240        //============================================================================
1241    
1242        private static final BlockingFunction imaqExtractColorPlanesFn = NativeLibrary.getDefaultInstance().getBlockingFunction("imaqExtractColorPlanes");
1243        static { imaqExtractColorPlanesFn.setTaskExecutor(taskExecutor); }
1244    
1245        /**
1246         * Extract the color planes from the given source image into the given planes
1247         * @param source The color source image.
1248         * @param mode The color space to extract the planes of.
1249         * @param plane1 MonoImage destination for the first plane.
1250         * @param plane2 MonoImage destination for the first plane.
1251         * @param plane3 MonoImage destination for the first plane.
1252         */
1253        public static void extractColorPlanes(Pointer source, ColorMode mode, Pointer plane1, Pointer plane2, Pointer plane3)  throws NIVisionException{
1254            int plane_1 = 0;
1255            int plane_2 = 0;
1256            int plane_3 = 0;
1257            if (plane1 != null)
1258                plane_1 = plane1.address().toUWord().toPrimitive();
1259            if (plane2 != null)
1260                plane_2 = plane2.address().toUWord().toPrimitive();
1261            if (plane3 != null)
1262                plane_3 = plane3.address().toUWord().toPrimitive();
1263            assertCleanStatus(imaqExtractColorPlanesFn.call5(source, mode.value, plane_1, plane_2, plane_3));
1264        }
1265    
1266        private static final BlockingFunction imaqReplaceColorPlanesFn = NativeLibrary.getDefaultInstance().getBlockingFunction("imaqReplaceColorPlanes");
1267        static { imaqReplaceColorPlanesFn.setTaskExecutor(taskExecutor); }
1268    
1269        /**
1270         * Replaces one or more of the color planes of a color image. The plane you
1271         * replace may be independent of the image type. For example, you can
1272         * replace the green plane of an RGB image or the hue plane of an HSL image.
1273         * @param dest The destination image.
1274         * @param source The source image.
1275         * @param mode The color space in which the function replaces planes.
1276         * @param plane1 The first plane of replacement data. Set this parameter to null if you do not want to change the first plane of the source image.
1277         * @param plane2 The second plane of replacement data. Set this parameter to null if you do not want to change the second plane of the source image.
1278         * @param plane3 The third plane of replacement data. Set this parameter to null if you do not want to change the third plane of the source image.
1279         */
1280        public static void replaceColorPlanes(Pointer dest, Pointer source,
1281                ColorMode mode, Pointer plane1, Pointer plane2, Pointer plane3)  throws NIVisionException{
1282            int plane_1 = 0;
1283            int plane_2 = 0;
1284            int plane_3 = 0;
1285            if (plane1 != null)
1286                plane_1 = plane1.address().toUWord().toPrimitive();
1287            if (plane2 != null)
1288                plane_2 = plane2.address().toUWord().toPrimitive();
1289            if (plane3 != null)
1290                plane_3 = plane3.address().toUWord().toPrimitive();
1291            assertCleanStatus(imaqReplaceColorPlanesFn.call6(
1292                    dest.address().toUWord().toPrimitive(),
1293                    source.address().toUWord().toPrimitive(),
1294                    mode.value,
1295                    plane_1,
1296                    plane_2,
1297                    plane_3));
1298        }
1299    
1300        //IMAQ_FUNC int    IMAQ_STDCALL imaqArrayToComplexPlane(Image* dest, const Image* source, const float* newPixels, ComplexPlane plane);
1301        //IMAQ_FUNC float* IMAQ_STDCALL imaqComplexPlaneToArray(const Image* image, ComplexPlane plane, Rect rect, int* columns, int* rows);
1302        //IMAQ_FUNC int    IMAQ_STDCALL imaqExtractComplexPlane(Image* dest, const Image* source, ComplexPlane plane);
1303        //IMAQ_FUNC int    IMAQ_STDCALL imaqFillImage(Image* image, PixelValue value, const Image* mask);
1304        //IMAQ_FUNC void*  IMAQ_STDCALL imaqGetLine(const Image* image, Point start, Point end, int* numPoints);
1305        //IMAQ_FUNC int    IMAQ_STDCALL imaqGetPixel(const Image* image, Point pixel, PixelValue* value);
1306        //IMAQ_FUNC int    IMAQ_STDCALL imaqReplaceComplexPlane(Image* dest, const Image* source, const Image* newValues, ComplexPlane plane);
1307        //IMAQ_FUNC int    IMAQ_STDCALL imaqSetLine(Image* image, const void* array, int arraySize, Point start, Point end);
1308        //IMAQ_FUNC int    IMAQ_STDCALL imaqSetPixel(Image* image, Point coord, PixelValue value);
1309    
1310        //============================================================================
1311        //  LCD functions
1312        //============================================================================
1313        //IMAQ_FUNC int        IMAQ_STDCALL imaqFindLCDSegments(ROI* roi, const Image* image, const LCDOptions* options);
1314        //IMAQ_FUNC LCDReport* IMAQ_STDCALL imaqReadLCD(const Image* image, const ROI* roi, const LCDOptions* options);
1315    
1316        //============================================================================
1317        //  Regions of Interest Manipulation functions
1318        //============================================================================
1319        //IMAQ_FUNC ROI*        IMAQ_STDCALL imaqMaskToROI(const Image* mask, int* withinLimit);
1320        //IMAQ_FUNC ROIProfile* IMAQ_STDCALL imaqROIProfile(const Image* image, const ROI* roi);
1321        //IMAQ_FUNC int         IMAQ_STDCALL imaqROIToMask(Image* mask, const ROI* roi, int fillValue, const Image* imageModel, int* inSpace);
1322        //IMAQ_FUNC int         IMAQ_STDCALL imaqTransformROI2(ROI* roi, const CoordinateSystem* baseSystem, const CoordinateSystem* newSystem);
1323    
1324        //============================================================================
1325        //  OCR functions
1326        //============================================================================
1327        //IMAQ_FUNC CharSet*         IMAQ_STDCALL imaqCreateCharSet();
1328        //IMAQ_FUNC int              IMAQ_STDCALL imaqDeleteChar(CharSet* set, int index);
1329        //IMAQ_FUNC int              IMAQ_STDCALL imaqGetCharCount(const CharSet* set);
1330        //IMAQ_FUNC CharInfo2*       IMAQ_STDCALL imaqGetCharInfo2(const CharSet* set, int index);
1331        //IMAQ_FUNC int              IMAQ_STDCALL imaqReadOCRFile(const char* fileName, CharSet* set, String255 setDescription, ReadTextOptions* readOptions, OCRProcessingOptions* processingOptions, OCRSpacingOptions* spacingOptions);
1332        //IMAQ_FUNC ReadTextReport3* IMAQ_STDCALL imaqReadText3(const Image* image, const CharSet* set, const ROI* roi, const ReadTextOptions* readOptions, const OCRProcessingOptions* processingOptions, const OCRSpacingOptions* spacingOptions);
1333        //IMAQ_FUNC int              IMAQ_STDCALL imaqRenameChar(CharSet* set, int index, const char* newCharValue);
1334        //IMAQ_FUNC int              IMAQ_STDCALL imaqSetReferenceChar(const CharSet* set, int index, int isReferenceChar);
1335        //IMAQ_FUNC int              IMAQ_STDCALL imaqTrainChars(const Image* image, CharSet* set, int index, const char* charValue, const ROI* roi, const OCRProcessingOptions* processingOptions, const OCRSpacingOptions* spacingOptions);
1336        //IMAQ_FUNC int*             IMAQ_STDCALL imaqVerifyPatterns(const Image* image, const CharSet* set, const String255* expectedPatterns, int patternCount, const ROI* roi, int* numScores);
1337        //IMAQ_FUNC int*             IMAQ_STDCALL imaqVerifyText(const Image* image, const CharSet* set, const char* expectedString, const ROI* roi, int* numScores);
1338        //IMAQ_FUNC int              IMAQ_STDCALL imaqWriteOCRFile(const char* fileName, const CharSet* set, const char* setDescription, const ReadTextOptions* readOptions, const OCRProcessingOptions* processingOptions, const OCRSpacingOptions* spacingOptions);
1339    
1340        //============================================================================
1341        //  Classification functions
1342        //============================================================================
1343        //IMAQ_FUNC int                            IMAQ_STDCALL imaqAddClassifierSample(Image* image, ClassifierSession* session, const ROI* roi, const char* sampleClass, double* featureVector, unsigned int vectorSize);
1344        //IMAQ_FUNC ClassifierReport*              IMAQ_STDCALL imaqClassify(Image* image, const ClassifierSession* session, const ROI* roi, double* featureVector, unsigned int vectorSize);
1345        //IMAQ_FUNC ClassifierSession*             IMAQ_STDCALL imaqCreateClassifier(ClassifierType type);
1346        //IMAQ_FUNC int                            IMAQ_STDCALL imaqDeleteClassifierSample(ClassifierSession* session, int index);
1347        //IMAQ_FUNC ClassifierAccuracyReport*      IMAQ_STDCALL imaqGetClassifierAccuracy(const ClassifierSession* session);
1348        //IMAQ_FUNC ClassifierSampleInfo*          IMAQ_STDCALL imaqGetClassifierSampleInfo(const ClassifierSession* session, int index, int* numSamples);
1349        //IMAQ_FUNC int                            IMAQ_STDCALL imaqGetNearestNeighborOptions(const ClassifierSession* session, NearestNeighborOptions* options);
1350        //IMAQ_FUNC int                            IMAQ_STDCALL imaqGetParticleClassifierOptions(const ClassifierSession* session, ParticleClassifierPreprocessingOptions* preprocessingOptions, ParticleClassifierOptions* options);
1351        //IMAQ_FUNC ClassifierSession*             IMAQ_STDCALL imaqReadClassifierFile(ClassifierSession* session, const char* fileName, ReadClassifierFileMode mode, ClassifierType* type, ClassifierEngineType* engine, String255 description);
1352        //IMAQ_FUNC int                            IMAQ_STDCALL imaqRelabelClassifierSample(ClassifierSession* session, int index, const char* newClass);
1353        //IMAQ_FUNC int                            IMAQ_STDCALL imaqSetParticleClassifierOptions(ClassifierSession* session, const ParticleClassifierPreprocessingOptions* preprocessingOptions, const ParticleClassifierOptions* options);
1354        //IMAQ_FUNC NearestNeighborTrainingReport* IMAQ_STDCALL imaqTrainNearestNeighborClassifier(ClassifierSession* session, const NearestNeighborOptions* options);
1355        //IMAQ_FUNC int                            IMAQ_STDCALL imaqWriteClassifierFile(const ClassifierSession* session, const char* fileName, WriteClassifierFileMode mode, const String255 description);
1356    
1357        //============================================================================
1358        //  Inspection functions
1359        //============================================================================
1360        //IMAQ_FUNC int IMAQ_STDCALL imaqCompareGoldenTemplate(const Image* image, Image* goldenTemplate, Image* brightDefects, Image* darkDefects, const InspectionAlignment* alignment, const InspectionOptions* options);
1361        //IMAQ_FUNC int IMAQ_STDCALL imaqLearnGoldenTemplate(Image* goldenTemplate, PointFloat originOffset, const Image* mask);
1362    
1363        //============================================================================
1364        //  Morphology functions
1365        //============================================================================
1366        //IMAQ_FUNC int IMAQ_STDCALL imaqGrayMorphology(Image* dest, Image* source, MorphologyMethod method, const StructuringElement* structuringElement);
1367    
1368    }