UNIVERSIDAD CATÓLICA DE  VALPARAÍSO - FUNDACIÓN ISABEL CACES DE BROWN
Portada
Intro
home
Temas
Charlas
Publicaciones
Heteroestructuras
Oleds
Linux
Simulaciones
Experimentos
svg
fotos
Logo

Crecimiento de dominios en metales y espumas

PC+Escaner

Sistema de adquisición de imágenes basado en una máquina linux y uno o varios escaners.


Objetivos


Se pretende entender la dinámica del crecimiento de granos en metales, mediante el estudio experimental del crecimiento de burbujas en espumas.

Este sistema presenta una dinámica similar al crecimiento de granos en metales, pero tiene la ventaja de que las burbujas crecen a una rapidez razonable y además es muy fácil obtener imágenes de éstas.

Luego de analizar este proceso de crecimiento, se obtienen datos reales con los cuales es posible el estudio teórico usando modelos matemáticos.

El experimento consiste en un sistema bidimensional formado por dos placas de vidrio que contienen en su interior una espuma jabonosa.

Descripción del sistema


  • obtención de las imágenes desde un escaner

  • preprocesar las imágenes en una máquina linux

  • procesar la imágenes automáticamente en la misma máquina usando un software de análisis de imágenes, aplicando diversos filtros para entregar finalmente estadísticas de número de burbujas, tamaños, etc.

  • Presentación de los resultados en línea usando Scalable Vector Graphics, que permite presentar en una página web gráficos, animaciones, imágenes, etc.

    Específicamente se entregará:
  • imagen original en formato jpg
  • imagen procesada en formato jpg
  • imagen con granos encerrados en rectángulos.
  • gráfico de Nº de granos vs área.
  • Automatizar este proceso para que se repita cada cierto intervalo es muy fácil en el sistema operativo linux usando el programa cron. El problema principal es tener imágenes nítidas para que el procesamiento de la imagen sea confiable.

    Ejemplos de implementaciones similares:

    Medición del nivel de cobre en un convertidor el teniente usando imágenes termográficas.

    diagrama

    Software de procesamiento de imágenes



    Image Measurement and Analysis Lab tnimage

    ftp://entropy.brni-jhu.org/pub/unix (all Unix versions)
    http://entropy.brni-jhu.org/tnimage.html (all versions)
    ftp://entropy.brni-jhu.org/pub/dos/ (DOS version)

    Ejemplo de filtros en burbujas pequeñas

    Original original alicia alicia
    Max. contr. maxcontr gray Color -> gris
    Pasabajos pasabajos eros Erosión
    Inv. color inv grains Granos

    Ejemplo de filtros en burbujas grandes

    Original original alicia alicia
    filtrada inv grains Granos

    Conteo de granos

    Tnimage puede usar un algoritmo de segmentación rápida, un algoritmo de red neuronal, o un algoritmo de diferencia espacial para identificar y contar objetos en una imagen. La elección del algoritmo a usar depende del tipo de objeto a contar.

    Redes neuronales son preferibles para estructuras complejas, debido a que toman en consideración la estructura interna del objeto. Sin embargo éstas requieren el ajuste de tres parámetros (threshold, match weight, y mismatch weight) en vez de uno, de manera que puede ser difícil encontrar la mejor combinación de parámetros para discriminar en forma óptima entre estructuras similares.

    Segmentación rápida es muy eficiente y rápida, pero es sólo adecuada para contar granos negros en un fondo claro. Los granos necesitan ser separados uno de otro en forma previa.

    El algoritmo de diferencia espacial es también adecuado principalmente para pequeños objetos oscuros como granos, pero es mejor separando objetos que se tocan entre ellos.

    Comparación de Métodos de Conteo de Granos

    Feature Neural Network Differencing Quick Segmentation
    Speed slow medium fast
    No. of params 3 2 1
    Works with color images yes no no
    Ability to separate good medium poor
    closely-spaced patterns
    Requires selecting yes no no
    representative pattern
    Provides graphs of no yes yes
    size distribution and
    signal distribution
    Type of pattern Any Grains/spheres Grains

    Procesamiento en modo Batch

    Tnimage puede también ser usado en modo "batch" para operar en forma automática. Esto es útil para operaciones que consumen mucho tiempo o necesitan ser hechas en forma reiterada.

    Procedimiento: Crear primero una macro en tnimage y guardarla en disco duro. El último comando en la macro debiera ser "quit" para asegurar que tnimage salga al finalizar. El comando ``messages(0)'' puede también ser usado para asegurar que cualquier mensaje de error sea ignorado en vez de que el programa se quede esperando por una respuesta, hay que asegurarse de que la macro funcione bien primero. La manera de ejecutar una macro es la siguiente:
    $tnimage -macro mi-primer-macro.macro&

    Interfaz de línea de comandos

    El editor de macros en tnimage puede también actuar como una interfaz de línea de comandos. Moviendo el cursor al final de la línea y presionando Shift-Enter o bien la tecla Ctrl-M causa que la línea sea ejecutada. Esto tiene la ventaja adicional de que una lista de comandos puede ser guardada en un archivo, para servir como documentación y para permitir que los mismos comandos sean ejecutados posteriormente. La ventana principal puede también ser iconificada y las imágenes pueden ser cargadas en ventanas individuales, de manera que la funcionalidad completa del programa puede ser obtenida sin el uso del ratón si se desea

    Interfaz SVG


    Filtros

    Performs a convolution filter on the currently-selected image, or the selected screen region. The original image should be backed up before filtering it, in case you don't like the results.

    For images greater than 8 bits/pixel, only the selected color planes are filtered. Color planes can be selected in the ``Config'' dialog box. Indexed-color images are temporarily converted to 24 bits/pixel before filtering, then converted back using the quantization method selected in the "Configure..." dialog.

    In general, the kernel size should be close to the size of the features of interest. In particular, with Laplace edge enhancement, if the features are larger than 3 pixels across, a 3x3 or 9x9 kernel may actually make the image appear fuzzier, while a 5x5 kernel might dramatically sharpen the image. The amount of filtering can be adjusted from 1 to 100.

    8.1.1   High-pass filter (Sharpening)

    Extracts only the highest spatial frequencies in the image. More low frequency components are saved if a larger 'kernel' is selected. If the image contains few high-frequency components, and too much sharpening was selected, the result may appear dark or black. This can be corrected by increasing the contrast of the image after filtering it.

    8.1.2   Low-pass filtering

    Low-pass filtering eliminates sharp edges from the image, causing a blurring effect. The total intensity is unchanged, but is spread throughout the neighboring pixels.

    8.1.3   Background subtract

    This is similar to high-pass filtering except it removes only the lowest frequencies. This has the effect of removing uneven background in the image. As with high-pass filtering, it can make the image appear darker. Selecting a larger kernel removes less of the low frequencies, but will require much more processing time. A preferred method is to use the ``kernel multiplier''. Selecting a multiplier of 5 with a 3x3 kernel produces results similar to using a multiplier of 1 with a 15x15 kernel, but is many times faster. For this reason, it is recommended to set the kernel to 3x3 for background subtract.

    It is possible to specify whether ``black'' or ``white'' pixels should be considered as the background. If it is set to ``white'', the image will generally get lighter in regions of unvarying pixel intensity. If the background value is ``black'', the image will get darker wherever the pixel intensity does not vary. This can be compensated for by increasing the contrast.

    Background subtraction will also trash any text in the image.

    See also Background flatten, remove low frequencies, and Rank leveling.

    8.1.4   Background Flatten (de-trending)

    This filter removes the largest-scale gradients from the image or selected region by measuring the average pixel value in each corner and then adding or subtracting a value to equalize the overall intensity. This could also be done manually, by creating a gradient region on the screen and adding the image to it (see Gradient fill ). However, the manual method is not 2-dimensional.

    In contrast to Background Subtraction, this filter does not trash text. It differs from remove low frequencies in that it only removes large-scale gradients from the image.

    See also Background subtract, remove low frequencies, Force background, Rank leveling.

    8.1.5   Force background to fixed value

    This filter is similar to the ``Remove low frequencies'' filter, except that instead of adding and subtracting values to remove gradients in the image, it multiplies dark and light areas by some factor to make the low-frequency background constant. This constant value can be adjusted by clicking on the ``Background value'' box.

    The difference between this filter and removing low frequencies is that, with this filter, the intensity of any information hidden in a dark area will be more accurately preserved. This filter can be thought of as a cross between the ``maximize local contrast'' and ``Remove low frequencies'' filters.

    Forcing the background to the 50% intensity value (e.g., 128 for 8-bit images) gives the best retention of the original intensity variation. Setting it to 100% (i.e., 255) would be useful if the high-frequency features (such as grains or spots) were of interest.

    See also Background subtract, remove low frequencies, and Rank leveling.


    Picture 12

    Comparison of different methods of compensating for uneven background.
    A Original image
    B Conventional contrast increase.
    C Background subtract (bkg=white).
    D Background flattening
    E Remove low frequencies
    F Maximize local contrast
    G Force background to fixed value (191).

    8.1.6   Noise filtering (median filtering)

    Median filtering removes extraneous pixels from the image. This is useful if the image contains noise which consists of little dots that are clearly outside the range of the other pixels. If a given pixel varies by more than a certain amount from the pixels around it, median filtering substitutes the median of the neighboring pixels, thereby eliminating noise from the image. The image is otherwise unaffected. The range in ± pixel value units, outside of which a value is to be considered noise, can be changed. A higher value results in less noise removal. Excessive noise filtering can make an image appear posterized. A setting of 0 will create a smoothing effect.

    8.1.7   Laplace edge enhancement

    This filter finds any edges in the image whose length is equal or greater than the kernel size. The edges are then increased in intensity while non-edge regions are eliminated. The effect on text is to create an outline of the text.

    8.1.8   Detección de bordes usando el filtro Sobel

    Este filtro es similar a la detección de bordes por Laplace pero los efectos son mas suaves. El filtro Sobel incrementa el color o gradiente de intensidad de manera simétrica, de manera que áreas de color constante quedan negras. Nota:La función de Sobel usada aquí es levemente diferente a la usada en otras implementaciones, de manera que el término `Sobel' puede no ser estrictamente exacto.
    Original original lowpass pasabajos 3x3 100%
    Sobel núcleo 3x3 50% sobel sobel Sobel núcleo 5x5 50%
    Sobel núcleo 3x3 100% sobel sobel Sobel núcleo 5x5 100%

    8.1.9   Edge detect | , -

    Detects and enhances edges in the image preferentially in the horizontal or vertical direction.

    8.1.10   Sharpen | / - \

    Sharpens the selected region or image preferentially in the indicated direction, creating a `freeze-fracture' 3-D effect. This is particularly useful for images of biological specimens that have low contrast, since it highlights the overall shape of the cells.

    8.1.11   Remove low frequencies

    This filter uses a combination of operations to subtract a blurred copy of the image from itself, thereby making the background perfectly flat. The effect is about halfway between Background Subtract, which only removes the very low spatial frequencies, and High Pass, which enhances the high frequencies. Selecting a 3x3 kernel removes all but the highest frequencies, while a 15x15 kernel has a less harsh effect. The effect can be made even more gentle by specifying a kernel multiplier of 2 or more.

    See also Background flatten, Background subtract, Force background, and Rank leveling.

    8.1.12   Background subtraction by rank leveling

    Rank leveling subtracts background gradients rapidly by assuming that the features of interest are small in size (less than 10×10 pixels). Subtracting nearby background pixels from the feature pixels achieves a very localized background flattening. Features larger than 10x10 will also be attenuated.

    ``Background level'' must be set correctly, otherwise the result will be garbage. For example, if the features are dark on a light background, background level must be set to ``white''.

    This filter only works for grayscale images. Other settings including kernel size, range, and amount of filtering, are ignored.

    As with ``background subtract'', it is usually necessary to adjust the contrast after filtering with rank level filter, because the image will get lighter or darker depending on the setting of ``background level''.

    See also Background flatten, Background subtract, Force background, and Remove Low Frequencies.

    8.1.13   User-defined

    Performs a convolution filtering using a user-defined filter. This filter should be a text file with the folowing characteristics:

    1. First line is a single odd number indicating the number (n) of rows.
    2. The no. of rows must equal the no. of columns.
    3. The first line is followed by n rows of n numbers separated by whitespace. The numbers can be positive or negative, and need not be integers.
    4. The total of all elements should equal 0, otherwise an error message is printed. If the total is not 0, the filter will make the image lighter or darker. The center element, which represents the pixel under consideration by the filter, should be increased or decreased to make the total equal to 0.
    5. The ``Kernel'' setting is ignored for user-defined filters.
    6. Size of filter is not limited.

    Example This 5×5 filter will enhance vertical edges.

    5
    -1-101 1
    -1-101 1
    -1-101 1
    -1-101 1
    -1-101 1

    8.1.14   Engrave

    Filters the image by converting edges to shadows so that the image resembles an engraved outline. Uses a threshold value to determine the pixel intensity value at which the outline is to be drawn.

    8.1.15   Spatial difference

    Filters image using a spatial differencing filter. This has the effect of separating closely-spaced objects so that there is a clear boundary between them. This is useful in preprocessing images before performing densitometry or grain counting. Uses a `size' parameter which determines the area over which the differencing will be performed for each pixel. A larger size will accentuate larger objects, and will have more noise immunity, but takes more processing time. Currently only works on monochrome images.

    8.1.16   Multiplicative Sobel

    This experimental filter is similar to the Sobel filter (Sec.8.1.8) except that the differences are multiplied to each pixel rather than added. It produces a strongly non-linear effect of enhancing details in the image. Only works on monochrome images.

    8.1.17   Maximize local contrast

    This filter increases the contrast at each point in the image to the maximum possible value with respect to its neighbors. This is useful for images in which details are obscured in large dark or light areas. Increasing the contrast in the overall image would make these faint features visible, but at the expense of washing out all detail in other areas. Maximizing the contrast locally allows details in both light and dark areas to be viewed simultaneously. See Sec.

    For example, in the mammogram shown below, in the left panel (A), some of the details in the mammogram are visible, while others are obscured in a dark area. After maximizing the local contrast, the details of the vascularization are easily discernable, and even the subtle gradations in the white background area are also clearly visible (B).


    Picture 13

    Maximizing local contrast.

    The degree of contrast enhancement can be selected in the clickbox labeled ``Local contrast scale''. This value is the area over which the contrast will be measured for each pixel. A smaller value gives greater enhancement of fine details, while a large value only removes gentle background gradients. An excessively large value, however, can create artifacts. See sec. 9.12 for another example.

    8.1.18   Adaptive maximize local contrast

    This filter is similar to the ``Maximize local contrast'' filter, except that the contrast factor is calculated ``adaptively''. This makes it much faster. However, the results are sometimes not as good. The adaptation or ``decay factor'' can be adjusted.

    8.1.19   Adjustable parameters

    8.1.20   Kernel

    The kernel is the number of pixels used in calculating a pixel in the new image. The processing time needed increases with the square of the kernel size.

    8.1.21   Kernel multiply factor

    A kernel multiply factor permits arbitrarily large kernel without an increase in computation time. This is possible because usually only a small sample of the surrounding pixels are really needed to calculate the new pixel value. For most types of filters, a 3x3 kernel with a kernel multiplier of 3 gives the same results as a 9x9 kernel, but is 3 times faster. For sharpening and blurring, this doesn't work, and the factor is automatically set to 1.

    8.1.22   Amount of filtering

    The amount of filtering applied to the image, from 1 to 100 (maximal filtering).


    Picture 14

    Effect of some different filters. The original is an image of the Horsehead Nebula.
    A. Original
    B. Background subtract, background level=white
    C. Background flatten
    D. Sobel edge detection
    E. Background subtract, background level=black
    F. Sharpen

    Grain counting and pattern recognition

    Tnimage can use the quick segmentation algorithm, a neural network algorithm, or a spatial differencing algorithm to identify and count objects in an image. The choice of which algorithm to use will depend on the pattern to be counted. Neural networks are preferable for complex patterns, since they take the internal structure of the pattern into account. However, neural networks require the adjustment of 3 parameters (threshold, match weight, and mismatch weight) instead of one, so it can be tricky to find the best combination of parameters to optimally discriminate between similar patterns.

    Quick segmentation is extremely efficient and fast, but is only suitable for counting black grains on a light background. The grains need to be already separated from each other.

    The differencing algorithm is also suitable mainly for small dark objects like grains, but is better at separating objects that touch each other.

    Comparison of Grain Counting Methods

    Feature Neural Network Differencing Quick Segmentation
    Speed slow medium fast
    No. of params 3 2 1
    Works with color images yes no no
    Ability to separate good medium poor
    closely-spaced patterns
    Requires selecting yes no no
    representative pattern
    Provides graphs of no yes yes
    size distribution and
    signal distribution
    Type of pattern Any Grains/spheres Grains

    The neural network algorithm is a modified and greatly simplified version of a hierarchical neural network[6]. With appropriate threshold values, it is possible to count grains or any other pattern such as cells, faces, etc., in the presence of other potentially-interfering objects. To illustrate, we will count occurrences of the letter ``x'' in a simplified image.

    The left panel below shows the original image, a combination of x's, y's and z's. The pattern recognition process subtracts pixels that are part of the pattern (in this case the `x's), while tye `y' and `z' are unaffected. This subtraction also allows any patterns obscured by the pattern to be identified on a subsequent pass.


    Picture 22

    Pattern recognition in tnimage.

    Counting patterns with neural network method

    1. Select ``Process..Grain/pattern counting''.
    2. Click on ``Select pattern''
    3. With the mouse, click and drag on the image such that the crawling box circumscribes an ``x''.
    4. Set Threshold to 0.5.
    5. Set Match weight to 1 and Mismatch weight to -0.1.
    6. Use the mouse to select a region to count, or do nothing to count the entire image.
    7. Click on ``Count patterns''.
    8. The x's will be indicated by a red cross as they are counted, leaving only the y's and z's (right panel). If the threshold is too low, the y's and z's will also be counted.
    9. The count is displayed in a message box.

    Options:

    • Select pattern: defines the pattern to search for.
    • Read pattern from disk: Define a pattern based on a disk file. (not currently implemented)
    • Save pattern to disk: Save current pattern to a file. (not currently implemented)
    • Count patterns: Count the occurrences of current pattern in currently-selected region or image, making no assumptions about the prototype pattern. It is necessary to select a pattern before using this option.
    • Count grains: Counts occurrences of current pattern, making the assumption that the pattern is supposed to be a dark grain on a light background. It is necessary to select a pattern before using this option.
    • Count std. size grains: Uses a pre-defined ``grain'' pattern to count grains. It is not necessary to select a pattern before using this option.
    • Enhance grains: Performs a Sobel filtering to improve contrast for grain counting.
    • Filename: file name for pattern if saving the pattern to disk file.
    • Threshold: Determines the sensitivity to variations in the candidate patterns. A higher threshold means greater selectivity. Too low a threshold will result in extraneous items being counted as patterns, while too high a threshold will cause some patterns to be missed.
    • Match Weight: Adjusts the relative weight given to a pixel which is part of a pattern.
    • Mismatch Weight: Adjusts the relative weight given to a pixel which is not part of a pattern. This parameter is the penalty for an mismatched pixel, thus it is usually between 0 and -1.

    8.12.1   Grain counting using neural network method

    • After you click ``Count patterns'', the program will pause for several seconds while it searches for candidate patterns in the image or selected region. This may be a long time if the template pattern or the image is large. Color images (including indexed-color images) take considerably longer than grayscale images. It is recommended to test the threshold values on a small part of the image before counting a large image.
    • After counting, each occurrence of the pattern that is found is indicated by a red crosshair. If desired, the original image can be restored by clicking ``Restore original''. The program will repeatedly make passes through the image, until no additional matching patterns are found.
    • In most cases, the Match Weight should be kept at 1.0. Setting the value lower would cause the area around the pattern (i.e., the mismatched pixels) to have proportionately more influence on whether the pattern is identified.
    • Setting the Mismatch Weight to a more negative value may improve the selectivity in some cases, by increasing the penalty for a mismatched pixel. More negative values are needed for complex patterns such as faces.
    • When counting grains, the grains must be black on a light background. Use ``Color..Invert colors'' if necessary to achieve this.
    • When counting grains, especially on color images, it is recommended to click ``Enhance grains'' before starting. Otherwise, extraneous dark areas (such as cells) may be misidentified as large clumps of grains.
    • During the counting, the patterns the most closely match the prototype pattern are recognized first. The counting can be interrupted at any time by clicking on ``Cancel'', pressing Esc, or clicking the main Cancel button.
    • When selecting the prototype pattern, select an area of average size and intensity, surrounded by a small region of background. Omitting the background region, or selecting a pattern that is too small, will increase the likelihood that a large dark clump will be identified as several grains that are overlapping.

    8.12.2   Grain counting using segmentation and differencing methods

    • When counting grains, the grains must be black on a light background. Use ``Color..Invert colors'' if necessary to achieve this.
    • Maximize contrast in image before starting. Ideally, all the grain pixels should be below 127 and all background pixels should be above 127 (assuming an 8-bit image and a threshold of 0.5).
    • Any large dark objects in the image, such as labels or borders, must be removed before starting. Large areas of uneven background can be removed using ``Filter..Remove Low Frequencies'' and setting kernel to 3×3 or 15×15 and `Amount of filtering' to 100.
    • If extraneous items are misidentified as occurrences of the pattern, the threshold should be increased to improve specificity.
    • If noise pixels are counted as grains, filter the image with a low-pass filter or noise removal filter before starting.
    • ``Min size'' discards any spots containing fewer than the specified total number of pixels. ``Min size'' and ``threshold'' can be adjusted to give a more accurate grain count without counting stray dots.
    • If the `labels' box is set, the following marks will be added to the image:

      • A number indicating the measured size of the spot. Clicking on ``Show size'' opens a menu allowing you to specify what is printed on the labels. This can be size, spot number, signal, or no label.
      • An arrow pointing to the center of the spot
      • A rectangle indicating the bounding box of the spot. Note: the box only indicates the maximum x and y range of the spot. Calculations are done on the subset of pixels within this range that exceed the threshold value.

      Be sure to back up the original image (Ctrl-B) before using this feature. The marks can be removed by clicking ``Undo'' (or Ctrl-U). If `labels' is not checked, the spots will be marked with a small cross which will disappear when the mouse is clicked on the image.

    • `Label color' sets the color for the labels.
    • If any single grain contains more than 10,000 pixels, the counting is automatically aborted.
    • If the image contains more than 10,000 grains, tnimage will need to be recompiled with a larger value for MAXGRAINS.
    • The size distribution data can be saved to disk by clicking on the ``Save'' button in the Size Distribution graph.
    • The differencing algorithm uses the ``Size'' parameter which determines the area over which differencing is to be performed. A larger value will difference over a larger area, which would be suitable for larger grains, but will take longer. Using too small a value will increase the chance that noise pixels will be counted as grains. The differencing method is also more sensitive than quick segmentation, so the threshold should be increased to compensate.
    • If ``Sz Graph'' is checked, a graph of size distributions will be created.
    • Checking ``Dens Graph'' creates a graph of signal distributions, i.e., the number of spots vs. densitometrically measured signal per spot. This is useful, for example, in analyzing spot sizes on 2D gels.
    • If ``Save Data'' is checked, a list of all spots, together with their x and y coordinates, sizes, and signal per spot, will be saved into a disk file. This will be followed by the size distribution and the signal distribution data.
    • On large images, if counting grains using the differencing method is too slow, the same effect can be achieved by filtering the image, setting ``Difference filter size'' to 10 in the Filter dialog, then counting grains using the Quick Segmentation method. This allows different thresholds and filter sizes to be more rapidly tested.

    8.12.3   Notes on Pattern counting

    • It is usually necessary to clean up the image before counting grains, for example to remove dark areas around the edge and other artifacts in the image, and to maximize the contrast before starting. You should also back up the image (Ctrl-B) before starting.
    • Both the threshold and mismatch weight should be increased when counting patterns, compared to counting grains. For example, if the threshold is 0.9, a pixel will match if the average of the red, green, and blue values in a pixel deviate from the pattern by less than (1-0.9)× 255, or 25.5. If the sum of the signals from each pixel is higher than a minimum signal (defined as pattern area × threshold), the neuron will register a match.
    • Increased speed can be obtained by converting color images to grayscale before starting. Note that just because an image appears to contain only shades of gray, this does not necessarily mean it is a grayscale image.
    • Image contrast should be maximized before starting (``Color..Contrast.. Maximize Value''). Increasing the image contrast has an effect similar to increasing the threshold.
    • Clicking on ``Enhance grains'' often improves the accuracy of pattern counting as well as the accuracy of grain counting. (sobel 5x5 100 + invert colors)
    • The pattern detection algorithm is currently unable to recognize patterns that are rotated or of different sizes. Often, patterns of different sizes can be recognized by selecting only one edge as the model pattern, e.g. if the desired pattern is a symmetrical round object, drawing the box around the left half of the object instead of the entire object will cause the algorithm to recognize objects of a broad range of sizes.

    8.12.4   Possible problems with Grain and Pattern counting

    • No patterns detected Threshold is too high, mismatch weight is too negative, or match weight is too low; or, contrast is too low in image.
    • Too many patterns detected Threshold is too low, mismatch weight is not negative enough, or match weight is too high. The optimum threshold is different for each type of image. The ideal threshold can be estimated visually by watching the numbers in the information box, and determining the signal at the point at which non-patterns begin to be detected. Interrupt the counting at this point and set the threshold to the value of the signal shown in the information box.
    • Same pattern counted more than once; or, algorithm gets stuck on one pattern (coordinates don't change). This is a bug; please report it.
    • Processing is too slow. Convert image to grayscale. This will increase speed at least 2.8 fold. Converting image to 8 bits will also help.
    • Message box says ``0 Patterns found'', even though it found patterns on the same image earlier. You may have accidentally clicked on the background or menu bar, deselecting the image. Click on image and repeat.
    • Message box says ``Neuron count mismatch''. This message occurs when you click on a different image while the algorithm is counting. The buffers are incorrect for the new image, so the algorithm aborts.
    • Small red box indicating location of pattern is off-center. This occurs when defining the pattern, if the region selected for the pattern is not centered on the pattern (i.e., too much background is included in the pattern on one side).
    • Large areas with shading similar to the pattern are identified as numerous instances of the pattern. This is caused by selecting an insufficient amount of background around the prototype pattern; or the mismatch weight is too low.

    WARNING: Measured grain sizes will be different depending on the method and parameters used. Users should verify that the results obtained are consistent with their expectations.

    8.12.5   Examples

    Size distribution using quick segmentation

    Here is an example of an astronomical image after analysis by the quick segmentation algorithm. The threshold was set to 0.8 so that only the larger stars are counted. Each star that was counted is automatically labeled with its relative size. The size of a given object depends on the threshold and will be larger if the threshold is smaller, because more pixels are present in the distance matrix which is used to find grains. The grain counting dialog box is shown at right.


    Picture 23

    The size distribution graph (not shown) usually follows
    a Poisson distribution.

    Recommended Threshold and Weight values for neural network method

    Type of pattern Threshold Match Wt. Mismatch Wt.
    Grains (monochrome) 0.50 1.0 -0.05
    Grains (color) 0.45 1.0 -0.10
    Grains (enhanced) 0.55 1.0 -0.15
    Faces 0.60 1.0 -0.15
    Faces (color) 0.95 1.0 -1.00
    Patterns 0.90 1.0 -0.50

    Note: These values should be considered as starting points only. Different images will need different thresholds and mismatch weights.

    Example of neural network grain counting:

    Below is an example of neural network grain-counting of a moderately-difficult image illustrating some of the steps that may be necessary to obtain the most accurate counts. Panel A shows the original image, which contains several grains that are out of focus or clumped together, as well as some grains that are sharply focused, and a darker, out-of-focus blue cell in the center, which could be difficult to distinguish from the two faint grains on top of it. Under some conditions, the cell could even be misidentified as a large clump of grains. The image was converted to grayscale (B) and the grains were enhanced (by clicking on ``Enhance grains''), producing C, which is more easily analyzed. Using the default threshold value of 0.5 and Match and Mismatch weights of 1 and -0.05, however, caused a number of extraneous points to be counted as grains (D). This occurred because the filtering process also increased the noise slightly. Changing the mismatch weight to -0.15 solved the problem, and the program counted the number of grains as 64, the correct number (E).

    Batch mode processing

    Tnimage can also be run in ``batch'' mode for unattended operation. This is useful for operations that are time-consuming or need to be done every day. A cron-like utility or (for the DOS version) a DOS command scheduler such as tnshell (available from the author) can be used to automatically carry out any sequence of operations at (for example) 3 a.m. on Thursdays or to automatically load a series of images before you come to work.

    Procedure: Create a macro in tnimage and save it to disk. The last command in the macro should be ``exit'' to ensure tnimage quits when finished. The command ``messages 0'' can also be used to ensure that any error messages are ignored instead of causing the program to wait for an acknowledgment (Make sure the macro works before using this).

    Command line interface

    Some users find it more convenient to type commands than select items from the mouse. The macro editor in tnimage doubles as a command-line interface. Moving the cursor to the end of a line and hitting < Shift-Enter > or the < Ctrl-M > key causes a single line to be executed. This has the additional advantage that a list of commands can be saved in a file, providing documentation and enabling the same commands to be executed later. The main window can also be iconified and images loaded into individual windows, so that complete functionality is obtained without use of a mouse if desired. For a complete list of commands, see Macro Commands (Sec. 14).

    14.3   Macro Programming Guide

    Here is a brief tutorial on some of the finer points on creating useful macros. In general a macro should reset the program to its original state. If a macro does something different the second time it is executed, the cause is almost always a failure to reset the original conditions. In a real macro, you should also always execute ``select_image'' or ``open'' first to make sure the operation is performed on the correct image.



    Example macro #1. Nested macros
    Macro ``beep.macro''

    ¯ Line # ¯ Command
     1  beep;
     2  beep;
     3  beep;

    Note: the words ``Line #'' and ``Command'' and the numbers 1,2, and 3 are not part of the macro. In this example, the macro would consist of only 3 words (``beep''), one on each line.


    Macro ``test.macro''

    ¯ Line # ¯ Command
     1  macro(beep.macro);
     2  beep;

    Executing ``test.macro'' should cause a total of 4 beeps. A macro must never call itself - this would cause an infinite loop.




    Example macro #2. Converting GIF image to TIFF format interactively

    ¯ Line # ¯ Command
     1  a=getstring("What is the filename?");
     2  messages(0);
     3  fileformat(0);
     4  save(a);
     5  messages(1);
     6  goto(1);

    Line 1 - Prompts you for a filename each time

    Line 2 - Resets default file format to 0 (TIF). If this line is omitted, the file format would default to the original format of each image.

    Line 4 - Saves the image in TIFF format. Don't forget to rename the file extension to TIFF later.

    Line 5 - Resume error messages

    Line 6 - Unconditional loop back to line 1. Press ESC to stop.



    Example macro #3. Converting GIF image to TIFF format in batch mode

    ¯ Line # ¯ Command
     1  messages(0);
     2  load(*.gif);
     3  file_format(0);
     4  save;


    In the DOS version, this macro could be executed at 3 a.m. by setting the following timed events in tnshell or other command scheduler: ¯ Line # ¯ Command
     Event 1:  cd c:\ tnimage 3:00am
     Event 2:  tnimage -macro convert.macro 3:01am
     Event 3:  ren *.gif *.tif 4:00am
     Event 4:  cd c:\ 4:01am


    Event 3 could also be replaced by a new line in the macro:

    dos ren *.gif *.tif
    Make sure there is enough free disk space before starting this macro.



    Example macro #4. Subtracting two images


    ¯ Line # ¯ Command
     1  pixel_interact_mode(1);
     2  load cells.tif(0,0,1,1);
     3  pixel_interact_mode(5);
     4  load cells.tif(1,1,1,1);
     5  pixel_interact_mode(1);
     6  intensity(185);


    This macro loads an image, then subtracts the same image after offsetting it by (1,1), then increases the intensity. All 6 lines are essential for a good macro.

    Line 1: The pixel interaction mode is set to 1 (overwrite) in case a previous operation changed it.

    Line 2: All 4 parameters (x offset, y offset, x size, and y size) must be given. Otherwise, if the macro was executed again, the default parameters would be 1,1,1,1 because of line 4. This would cause the image to be placed at (1,1) and then subtracted from itself, giving solid black.

    Line 3: The pixel interaction mode is set to 5 (subtract). It is usually helpful to change the screen background color to 0 (black) before doing this.

    Line 4: Load the image to subtract.

    Line 5: Reset the pixel interaction mode to overwrite.

    Line 6: Increase the intensity by a factor of 1.85.


    Be careful using ``DOS command'' in combination with ``messages 0''. If there is insufficient low DOS memory to execute the command, ``messages 0'' may cause you to miss the fact that the command was not executed.



    Example macro #5. Multiple image math formulas


    ¯ Line # ¯ Command
     1  selectregion(50,50,100,100);
     2  i=i+5;
     3  i=i+image[2][0][x][y];
     4  r=r*1.23;
     5  i=i-5;


    Line 1: Select a region to modify. If this line is omitted, it would modify the entire image.

    Line 2: Lighten the image by 5 intensity units.

    Line 3: Add the corresponding region from image #2.

    Line 4: Increase the red contrast by 1.23 fold.

    Line 5: Subtract 5 intensity units from the selected region.