wireshark-filter

title: wireshark-filter(4)

text:
# wireshark-filter(4)

## NAME
wireshark-filter - Wireshark display filter syntax and reference

## SYNOPSIS
wireshark [other options] [ -Y "display filter expression" | --display-filter "display filter expression" ]

tshark [other options] [ -Y "display filter expression" | --display-filter "display filter expression" ]

## DESCRIPTION
Wireshark and TShark share a powerful filter engine that helps remove the noise from a packet trace and lets you see only the packets that interest you. If a packet meets the requirements expressed in your filter, then it is displayed in the list of packets. Display filters let you compare the fields within a protocol against a specific value, compare fields against fields, and check the existence of specified fields or protocols.

Filters are also used by other features such as statistics generation and packet list colorization (the latter is only available to Wireshark). This manual page describes their syntax. A comprehensive reference of filter fields can be found within Wireshark and in the display filter reference at <https://www.wireshark.org/docs/dfref/>.

## FILTER SYNTAX

### Check whether a field or protocol exists
The simplest filter allows you to check for the existence of a protocol or field. If you want to see all packets which contain the IP protocol, the filter would be "ip" (without the quotation marks). To see all packets that contain a Token-Ring RIF field, use "tr.rif".

Whenever a protocol or field appears as the argument of a function in a filter, an exists operator for that protocol or field implicitly appears.

### Values and operators
Each field has a value, and that value can be used in operations with comparable values (which may be literals, other fields, or function results). The value of a field is not necessarily what appears in the Wireshark display or TShark output. For example, a protocol is semantically equivalent to the sequence of bytes that it spans, not its displayed text in the protocol tree.

### Comparison operators
The comparison operators can be expressed either through English-like abbreviations or through C-like symbols:

```
eq, ==    Equal
ne, !=    Not Equal
gt, >     Greater Than
lt, <     Less Than
ge, >=    Greater than or Equal to
le, <=    Less than or Equal to
```

The ordering depends on the value type in the usual way (e.g., lexicographic for strings and arithmetic for integers.) A field may appear more than once in a given frame. In that case equality can be strict (all fields must match the condition) or not (any field must match the condition). The inequality is the logical negation of equality. The following table contains all equality operators, their aliases and meaning:

```
eq, any_eq, ==    Any field must be equal
ne, all_ne, !=    All fields must be not equal

    all_eq, ===   All fields must be equal

    any_ne, !==   Any fields must be not equal
```

The operators "any" or "all" can be used with any comparison operator to make the test match any or all fields:

```
all tcp.port > 1024
```

```
any ip.addr != 1.1.1.1
```

The "any" and "all" modifiers take precedence over comparison operators such as "===" and "any_eq".

### Search and match operators
Additional operators exist expressed only in English, not C-like syntax:

```
contains     Does the protocol, field or slice contain a value
matches, ~   Does the string match the given case-insensitive

             Perl-compatible regular expression
```

The "contains" operator allows a filter to search for a sequence of characters, expressed as a string, or bytes, expressed as a byte array. The type of the left hand side of the "contains" operator must be comparable to that of the right hand side after any implicit or explicit conversions.

For example, to search for a given HTTP URL in a capture, the following filter can be used:

```
http contains "https://www.wireshark.org"
```

The "contains" operator cannot be used on atomic fields, such as numbers or IP addresses.

The "matches" or "~" operator allows a filter to apply to a specified Perl-compatible regular expression (PCRE2). The regular expression must be a double quoted string. The left hand side of the "matches" operator must be a string, which can be a non-stringlike field implicitly or explicitly converted to a string. Matches are case-insensitive by default. For example, to search for a given WAP WSP User-Agent, you can write:

```
wsp.header.user_agent matches "cldc"
```

This would match "cldc", "CLDC", "cLdC" or any other combination of upper and lower case letters.

You can force case sensitivity using

```
wsp.header.user_agent matches "(?-i)cldc"
```

This is an example of PCRE2’s (?option) construct. (?-i) performs a case-sensitive pattern match but other options can be specified as well. More information can be found in the pcre2pattern(3)|https://www.pcre.org/current/doc/html/pcre2pattern.html man page.

### Functions
The filter language has the following functions:

```
upper(string-field) - converts a string field to uppercase
lower(string-field) - converts a string field to lowercase
len(field)          - returns the byte length of a string or bytes field
count(field)        - returns the number of field occurrences in a frame
string(field)       - converts a non-string field to string
vals(field)         - converts a field value to its value string
dec(field)          - converts an unsigned integer to a decimal string
hex(field)          - converts an unsigned integer to a hexadecimal string
float(field)        - converts a field to single precision floating point
double(field)       - converts a field to double precision floating point
max(f1,...,fn)      - return the maximum value
min(f1,...,fn)      - return the minimum value
abs(field)          - return the absolute value of numeric fields
```

upper() and lower() are useful for performing case-insensitive string comparisons. For example:

```
upper(ncp.nds_stream_name) contains "MACRO"
lower(mount.dump.hostname) == "angel"
```

string() converts a field value to a string, suitable for use with operators like "matches" or "contains". Integer fields are converted to their decimal representation. It can be used with IP/Ethernet addresses (as well as others), but not with string or byte fields. For example:

```
string(frame.number) matches "[13579]$"
```

gives you all the odd packets. Note that the "matches" operator implicitly converts types of their value string representation; to match against the decimal representation of an integer field use string().

vals() converts an integer or boolean field value to a string using the field’s associated value string, if it has one. This produces strings similar to those seen in custom columns. The resultant string can also be used with other operators. E.g.:

```
vals(pfcp.msg_type) contains "Request"
```

would match all packets which have a PFCP request, even if that request is not matched with a response.

dec() and hex() convert unsigned integer fields to decimal or hexadecimal representation. Currently dec() and string() give same result for an unsigned integer, but it is possible that in the future string() will use the native base of the field.

max() and min() take any number of arguments and returns one value, respectively the largest/smallest. The arguments must all have the same type.

There is also a set of functions to test IP addresses:

```
ip_special_name(ip)       - Returns the IP special-purpose block name as a string
ip_special_mask(ip)       - Returns the IP special-purpose block flags as a mask. The bits are:

                                4 3 2 1 0

                                ---------

                                S D F G R

                            S = Source, D = Destination, F = Forwardable, G = Globally-reachable, R = Reserved-by-protocol
```

```
ip_linklocal(ip)          - true if the IPv4 or IPv6 address is link-local
ip_multicast(ip)          - true if the IPv4 or IPv6 address is multicast
ip_rfc1918(ipv4)          - true if the IPv4 address is private-use (from the allocation in RFC 1918)
ip_ula(ipv6)              - true if the IPv6 address is unique-local (ULA) as in RFC 4193
```

### Macros
It is possible to define display filter macros. Macro are names that are replaced with the associated expression, possibly performing argument substitution. Macro expansions are purely textual replacements and performed recursively before compilation. They allow replacing long and often used expressions with easy to use names.

Macros are defined using the GUI or directly in the "dmacros" configuration file. For example the definition

```
"addplusone" {$1 + $2 + 1}
```

creates a macro called addplusone that takes two arguments and expands to the given expression. Arguments in the replacement expression are given using the dollar sign.

Macros are invoked like function but preceded with a dollar sign (sometimes also called a sigil):

```
$addplusone(udp.src_port,udp.dst_port)
```

results in the expression

```
{udp.src_port + udp.dst_port + 1}
```

after argument substitution. There is an older alternative notation to invoke macros:

```
${addplusone:udp.src_port;udp.dst_port}
```

or

```
${addplusone;udp.src_port;udp.dst_port}
```

Both forms are equivalent and can be used interchangibly as a matter of preference.

### Protocol field types
Each protocol field is typed. The types are:

```
ASN.1 object identifier, plain or relative
AX.25 address
Boolean
Byte sequence
Character string
Character, 1 byte
Date and time
Ethernet or other MAC address
EUI64 address
Fibre Channel WWN
Floating point, single or double precision
Frame number
Globally Unique Identifier
IEEE-11073 floating point, 16 or 32 bits
IPv4 address
IPv6 address
IPX network number
Label
OSI System-ID
Protocol
Signed integer, 1, 2, 3, 4, or 8 bytes
Time offset
Unsigned integer, 1, 2, 3, 4, or 8 bytes
VINES address
```

An integer may be expressed in decimal, octal, hexadecimal or binary notation, or as a C-style character constant. The following seven display filters are equivalent:

```
frame.len > 10
frame.len > 012
frame.len > 0xa
frame.len > 0b1010
frame.len > '\n'
frame.len > '\x0a'
frame.len > '\012'
```

Boolean values are either true or false. In a display filter expression testing the value of a Boolean field, true is expressed as the word true (case-insensitive) or any non-zero number. False is expressed as false (case-insensitive) or the number zero. For example, a token-ring packet’s source route field is Boolean. To find any source-routed packets, a display filter would be any of the following:

```
tr.sr == 1
tr.sr == true
tr.sr == TRUE
```

Non source-routed packets can be found with:

```
tr.sr == 0
tr.sr == false
tr.sr == FALSE
```

Ethernet addresses and byte arrays are represented by hex digits. The hex digits may be separated by colons, periods, or hyphens:

```
eth.dst eq ff:ff:ff:ff:ff:ff
aim.data == 0.1.0.d
fddi.src == aa-aa-aa-aa-aa-aa
echo.data == 7a
```

IPv4 addresses can be represented in either dotted decimal notation or by using the hostname:

```
ip.src == 192.168.1.1
ip.dst eq www.mit.edu
```

IPv4 addresses can be compared with the same logical relations as numbers: eq, ne, gt, ge, lt, and le. The IPv4 address is stored in host order, so you do not have to worry about the endianness of an IPv4 address when using it in a display filter.

Classless Inter-Domain Routing (CIDR) notation can be used to test if an IPv4 address is in a certain subnet. For example, this display filter will find all packets in the 129.111 network:

```
ip.addr == 129.111.0.0/16
```

Remember, the number after the slash represents the number of bits used to represent the network. CIDR notation can also be used with hostnames, as in this example of finding IP addresses on the same network as 'sneezy' (requires that 'sneezy' resolve to an IP address for filter to be valid):

```
ip.addr eq sneezy/24
```

The CIDR notation can only be used on IP addresses or hostnames, not in variable names. So, a display filter like "ip.src/24 == ip.dst/24" is not valid (yet).

Transaction and other IDs are often represented by unsigned 16 or 32 bit integers and formatted as a hexadecimal string with "0x" prefix:

```
(dhcp.id == 0xfe089c15) || (ip.id == 0x0373)
```

Strings are enclosed in double quotes:

```
http.request.method == "POST"
```

Inside double quotes, you may use a backslash to embed a double quote or an arbitrary byte represented in either octal or hexadecimal.

```
browser.comment == "An embedded \" double-quote"
```

Use of hexadecimal to look for "HEAD":

```
http.request.method == "\x48EAD"
```

Use of octal to look for "HEAD":

```
http.request.method == "\110EAD"
```

This means that you must escape backslashes with backslashes inside double quotes.

```
smb.path contains "\\\\SERVER\\SHARE"
```

looks for \\SERVER\SHARE in "smb.path". This may be more conveniently written as

```
smb.path contains r"\\SERVER\SHARE"
```

String literals prefixed with 'r' are called "raw strings". Such strings treat backslash as a literal character. Double quotes may still be escaped with backslash but note that backslashes are always preserved in the result.

The following table lists all escape sequences supported with strings and character constants:

```
\'          single quote
\"          double quote
\\          backslash
\a          audible bell
\b          backspace
\f          form feed
\n          line feed
\r          carriage return
\t          horizontal tab
\v          vertical tab
\NNN        arbitrary octal value
\xNN        arbitrary hexadecimal value
\uNNNN      Unicode codepoint U+NNNN
\UNNNNNNNN  Unicode codepoint U+NNNNNNNN
```

Date and time values can be given in ISO 8601 format or using a legacy month-year-time format:

```
"2020-07-04T12:34:56"
"Sep 26, 2004 23:18:04.954975"
```

The 'T' separator in ISO 8601 can be omitted. The timezone can be given as "Z" or an offset from UTC.

When not using ISO 8601 the timezone can be given as the strings "UTC", "GMT" or "UT" for UTC or also given as an offset from UTC, plus some North American and Nautical/Military designations (see the specification for %z in strptime(3) <https://man.netbsd.org/strptime.3>). Note that arbitrary timezone names are not supported however.

If the timezone is omitted then date and time values are interpreted as local time.

### The slice operator
You can take a slice of a field if the field base type is a text string or a byte array (the base type of most network address fields is bytes). For example, you can filter on the vendor portion of an ethernet address (the first three bytes) like this:

```
eth.src[0:3] == 00:00:83
```

Another example is:

```
http.content_type[0:4] == "text"
```

You can use the slice operator on a protocol name, too. The "frame" protocol can be useful, encompassing all the data captured by Wireshark or TShark.

```
token[0:5] ne 0.0.0.1.1
llc[0] eq aa
frame[100-199] contains "wireshark"
```

The following syntax governs slices:

```
[i:j]    i = start_offset, j = length
[i-j]    i = start_offset, j = end_offset, inclusive.
[i]      i = start_offset, length = 1
[:j]     start_offset = 0, length = j
[i:]     start_offset = i, end_offset = end_of_field
```

Slice indexes are zero-based. Offsets can be negative, in which case they indicate the offset from the end of the field. The last byte of the field is at offset -1, the last but one byte is at offset -2, and so on. Here’s how to check the last four bytes of a frame:

```
frame[-4:4] == 0.1.2.3
```

or

```
frame[-4:] == 0.1.2.3
```

As mentioned above the slice operator can be used on string and byte fields and will respectively produce string or byte slices. String slices are indexed on UTF-8 codepoint boundaries (i.e: internationalized characters), so the following comparison is true:

```
"touché"[5] == "é"
```

The example above generates an error because the compiler rejects constant expressions but is otherwise syntactically correct and exemplifies the behaviour of string slices.

To obtain a byte slice of the same string the raw (@) operator can be used:

```
@"touché"[5-6] == c3:a9
```

A slice can always be compared against either a string or a byte sequence.

Slices can be combined. You can concatenate them using the comma operator:

```
ftp[1,3-5,9:] == 01:03:04:05:09:0a:0b
```

This concatenates offset 1, offsets 3-5, and offset 9 to the end of the ftp data.

### The layer operator
A field can be restricted to a certain layer in the protocol stack using the layer operator (#), followed by a decimal number:

```
ip.addr#2 == 192.168.30.40
```

matches only the inner (second) layer in the packet. Layers use simple stacking semantics and protocol layers are counted sequentially starting from 1. For example, in a packet that contains two IPv4 headers, the outer (first) source address can be matched with "ip.src#1" and the inner (second) source address can be matched with "ip.src#2".

For more complicated ranges the same syntax used with slices is valid:

```
tcp.port#[2-4]
```

means layers number 2, 3 or 4 inclusive. The hash symbol is required to distinguish a layer range from a slice.

### The at operator
By prefixing the field name with an at sign (@) the comparison is done against the raw packet data for the field.

A character string must be decoded from a source encoding during dissection. If there are decoding errors the resulting string will usually contain replacement characters:

```
browser.comment == "string is ����"
```

The at operator allows testing the raw undecoded data:

```
@browser.comment == 73:74:72:69:6e:67:20:69:73:20:aa:aa:aa:aa
```

The syntactical rules for a bytes field type apply to the second example.

### The membership operator
A field may be checked for matches against a set of values simply with the membership operator. For instance, you may find traffic on common HTTP/HTTPS ports with the following filter:

```
tcp.port in {80,443,8080}
```

as opposed to the more verbose:

```
tcp.port == 80 or tcp.port == 443 or tcp.port == 8080
```

To find HTTP requests using the HEAD or GET methods:

```
http.request.method in {"HEAD", "GET"}
```

The set of values can also contain ranges:

```
tcp.port in {443, 4430..4434}
ip.addr in {10.0.0.5 .. 10.0.0.9, 192.168.1.1..192.168.1.9}
frame.time_delta in {10 .. 10.5}
```

### Implicit type conversions
When fields which are sequences of bytes, including protocols, are compared with (double quoted) literal strings and raw strings, the literals are converted to their byte representation using the UTF-8 encoding. (To be precise, the original byte sequence is used, not the canonical normalized forms, so the precomposed é (U+00E9) and decomposed é (U+0065 U+0301) can match differently.)

So, for instance, the following filters are equivalent:

```
tcp.payload contains "GET"
tcp.payload contains 47.45.54
```

As noted above, a slice can also be compared in either way:

```
frame[60:2] gt 50.51
frame[60:2] gt "PQ"
```

The inverse does not occur; stringlike fields are not implicitly converted to byte arrays. (Some operators allow stringlike fields to be compared with unquoted literals, which are then treated as strings; this is deprecated in general and specifically disallowed by the "matches" operator. Literal strings should be double quoted for clarity.)

A hex integer that is 0xff or less (which means it fits inside one byte) can be implicitly converted to a byte string. This is not allowed for hex integers greater than one byte, because then one would need to specify the endianness of the multi-byte integer. Also, this is not allowed for decimal or octal numbers, since they would be confused with the hex numbers that make up byte string literals. Nevertheless, single-byte hex integers can be convenient:

```
frame[4] == 0xff
frame[1:4] contains 0x02
```

An integer or boolean field that has a value string can be compared to to one of the strings that corresponds with a value. As with stringlike fields and comparisons, it is possible to perform the comparison with an unquoted literal, though this is deprecated and will not work if the literal contains a space (as with "Modify Bearer Response" above). Double quotes are recommended.

If there is a unique reverse mapping from the string literal into a numeric value, the string is converted into that number and the comparison function is applied using arithmetic rules. If the mapping is not unique, then equality and inequality can be tested, but not the ordered comparisons.

This is in contrast with the string() and vals() functions, which convert the field value to a string and applies string (lexicographic) comparisons, as well as work with all operators that take strings. Therefore the following two filters give the same result:

```
gtpv2.message_type <= 35
gtpv2.message_type <= "Modify Bearer Response"
```

whereas

```
vals(gtpv2.message_type) <= "Modify Bearer Response"
```

matches all messages whose value string precedes "Modify Bearer Response" in lexicographical order, and

```
string(gtpv2.message_type) <= "35"
```

matches all messages such that the message type comes before "35" in lexicographical order, i.e. would also match "170" (the message type for "Release Access Bearers Request.")

For the "contains" and "matches" operators, which operate on strings (or byte arrays in the case of "contains"), fields on the left hand side are implicitly converted to their value strings for comparison. (To compare a field with a byte array, use the raw/at (@) operator.)

### Bitwise operators
It is also possible to define tests with bitwise operations. Currently the following bitwise operator is supported:

```
bitand, bitwise_and, &        Bitwise AND
```

The bitwise AND operation allows masking bits and testing to see if one or more bits are set. Bitwise AND operates on integer protocol fields and slices.

When testing for TCP SYN packets, you can write:

```
tcp.flags & 0x02
```

That expression will match all packets that contain a "tcp.flags" field with the 0x02 bit, i.e. the SYN bit, set.

To match locally administered unicast ethernet addresses you can use:

```
eth.addr[0] & 0x0f == 2
```

When using slices, the bit mask must be specified as a byte string, and it must have the same number of bytes as the slice itself, as in:

```
ip[42:2] & 40:ff
```

### Arithmetic operators
Arithmetic expressions are supported with the usual operators:

```
+   Addition
-   Subtraction
*   Multiplication
/   Division
%   Modulo (integer remainder)
```

Arithmetic operations can be performed on numeric types. Numeric types are integers, floating point numbers and date and time values.

Date and time values can only be multiplied by integers or floating point numbers (i.e: scalars) and furthermore the scalar multiplier must appear on the right-hand side of the arithmetic operation.

For example it is possible to filter for UDP destination ports greater or equal by one to the source port with the expression:

```
udp.dstport >= udp.srcport + 1
```

It is possible to group arithmetic expressions using curly brackets (parenthesis will not work for this):

```
tcp.dstport >= 4 * {tcp.srcport + 3}
```

Do not confuse this usage of curly brackets with set membership.

An unfortunate quirk in the filter syntax is that the subtraction operator must be preceded by a space character, so "A-B" must be written as "A -B" or "A - B".

### Protocol field references
A variable using a sigil with the form $some.proto.field or ${some.proto.field} is called a field reference. A field reference is a field value read from the currently selected frame in the GUI. This is useful to build dynamic filters such as, frames since the last five minutes to the selected frame:

```
frame.time_relative >= ${frame.time_relative} - 300
```

or more simply

```
frame.time_relative >= $frame.time_relative - 300
```

Field references share a similar notation to macros but are distinct syntactical elements in the filter language.

### Logical expressions
Tests can be combined using logical expressions. These too are expressible in C-like syntax or with English-like abbreviations. The following table lists the logical operators from highest to lowest precedence:

```
not, !    Logical NOT   (right-associative)
and, &&   Logical AND   (left-associative)
xor, ^^   Logical XOR   (left-associative)
or,  ||   Logical OR    (left-associative)
```

The evaluation is always performed left to right. Expressions can be grouped by parentheses as well. The expression "A and B or not C or D and not E or F" is read:

```
(A and B) or (not C) or (D and (not E)) or F
```

It’s usually better to be explicit about grouping using parenthesis. The following are all valid display filter expressions:

```
tcp.port == 80 and ip.src == 192.168.2.1
not llc
http and frame[100-199] contains "wireshark"
(ipx.src.net == 0xbad && ipx.src.node == 0.0.0.0.0.1) || ip
```

Remember that whenever a protocol or field name occurs in an expression, the "exists" operator is implicitly called. The "exists" operator has the highest priority. This means that the first filter expression must be read as "show me the packets for which tcp.port exists and equals 80, and ip.src exists and equals 192.168.2.1". The second filter expression means "show me the packets where not exists llc", or in other words "where llc does not exist" and hence will match all packets that do not contain the llc protocol. The third filter expression includes the constraint that offset 199 in the frame exists, in other words the length of the frame is at least 200.

Because each comparison has an implicit exists test for field values care must be taken when using the display filter to remove noise from the packet trace. If, for example, you want to filter out all IP multicast packets to address 224.1.2.3, then using:

```
ip.dst ne 224.1.2.3
```

may be too restrictive. This is the same as writing:

```
ip.dst and ip.dst ne 224.1.2.3
```

The filter selects only frames that have the "ip.dst" field. Any other frames, including all non-IP packets, will not be displayed. To display the non-IP packets as well, you can use one of the following two expressions:

```
not ip.dst or ip.dst ne 224.1.2.3
not ip.dst eq 224.1.2.3
```

The first filter uses "not ip.dst" to include all non-IP packets and then lets "ip.dst ne 224.1.2.3" filter out the unwanted IP packets. The second filter also negates the implicit existence test and so is a shorter way to write the first.

## FILTER FIELD REFERENCE
The entire list of display filters is too large to list here. You can can find references and examples at the following locations:

•The online Display Filter Reference: <https://www.wireshark.org/docs/dfref/>

•View:Internals:Supported Protocols in Wireshark

•tshark -G fields on the command line

•The Wireshark wiki: <https://wiki.wireshark.org/DisplayFilters>

## NOTES
The wireshark-filter(4) manpage is part of the Wireshark distribution. The latest version of Wireshark can be found at <https://www.wireshark.org>.

Regular expressions in the "matches" operator are provided by the PCRE2 library. See <https://www.pcre.org/> for more information.

This manpage does not describe the capture filter syntax, which is different. See the manual page of pcap-filter(7) or, if that doesn’t exist, tcpdump(8), or, if that doesn’t exist, <https://wiki.wireshark.org/CaptureFilters> for a description of capture filters.

Display Filters are also described in the Wireshark User’s Guide <https://www.wireshark.org/docs/wsug_html_chunked/ChWorkBuildDisplayFilterSection.html>.

## SEE ALSO
wireshark(1), tshark(1), editcap(1), pcap(3), pcap-filter(7) or tcpdump(8) if it doesn’t exist.

## AUTHORS
See the list of authors in the Wireshark man page for a list of authors of that code.


m-acr

package: xmedcon-devel

title: m-acr(4)

text:
# m-acr(4)

## NAME
m-acr - ACR/NEMA medical image format (MedCon)

## DESCRIPTION

We are absolutely lost in standards, versions and ACR/NEMA dialects. Here you can only read how we handle this format. The format is written in one file with extension `.ima'.

The format consists of a group of fields with different elements, in a serie of tags. Does that explain you something? The image data is stored from left to right and from top to bottom.

The basic defines for the format:

```
---------------------------------------------------------------------------
#define MDC_ACR_TAG_SIZE 8    /* size of group+element+length */
typedef struct {

  Uint16 group;           /* the kind of group   */

  Uint16 element;         /* the kind of element */

  Uint32  length;         /* the length of data  */

  Uint8   *data;          /* pointer to the data */
} MDC_ACR_TAG;
---------------------------------------------------------------------------

What does the format support or not support:
```

```
===========================================================================
Item            Supported                             Not Supported
===========================================================================
Color Map     : grayscale                                   -
File Endian   : little & big                                -
Pixeltypes    : all integers (signed/unsigned)        float & double
===========================================================================
Scaling factors  : quantify & calibrate factors/image  are NOT supported,

                   unless you define your own tags
---------------------------------------------------------------------------
Dimensions/Image : different dimensions for each image are supported
---------------------------------------------------------------------------
Pixeltypes/Image : different pixeltypes for each image are supported
===========================================================================
```

An ACR/NEMA file could look like this, in fact it is the kind we write:

```
===========================================================================
GROUP 0x0008		Identifying information
===========================================================================
Uint16  Group   number                : 0x0008
Uint16  Element number                : 0x0000 (first element of any group)
Uint32  Element length  in bytes      : (4)
Int32   Length of group in bytes      : (X)    (143)
X = [total length of this group] - [total bytes of this first tag (12)]
---------------------------------------------------------------------------
Uint16  Group   number                : 0x0008
Uint16  Element number                : 0x0001
Uint32  Element length  in bytes      : (4)
Int32   Total bytes to end of file    : Y
Y = [filesize] - [total bytes of first two tags]
---------------------------------------------------------------------------
Uint16  Group   number                : 0x0008
Uint16  Element number                : 0x0010
Uint32  Element length  in bytes      : (12)
char *  Recognition Code              : (ACR-NEMA 2.0)
---------------------------------------------------------------------------
Uint16  Group   number                : 0x0008
Uint16  Element number                : 0x0020
Uint32  Element length  in bytes      : (10)
char *  Study Date                    : yyyy.mm.dd
---------------------------------------------------------------------------
Uint16 Group    number                : 0x0008
Uint16 Element  number                : 0x0030
Uint32 Element length   in bytes      : (14)
char *  Study Time                    : hh.mm.ss.frac_
---------------------------------------------------------------------------
Uint16  Group   number                : 0x0008
Uint16  Element number                : 0x0040
Uint32  Element length  in bytes      : (2)
Int16   Data Set Type                 :   0 = Images

                                        256 = Raw data
---------------------------------------------------------------------------
Uint16  Group   number                : 0x0008
Uint16  Element number                : 0x0060
Uint32  Element length  in bytes      : (2)
char *  Image Modality                : (NM)
---------------------------------------------------------------------------
Uint16  Group   number                : 0x0008
Uint16  Element number                : 0x0070
Uint32  Element length  in bytes      : (24)
char *  Manufacturer                  : (MedCon v?.?? - Erik Nolf)
---------------------------------------------------------------------------
Uint16  Group   number                : 0x0008
Uint16  Element number                : 0x0080
Uint32  Element length  in bytes      : (11)
char *  Institution ID                : (NucMed)
===========================================================================
GROUP 0x0010		Patient Information
===========================================================================
Uint16  Group   number                : 0x0010
Uint16  Element number                : 0x0000
Uint32  Element length  in bytes      : (4)
Int32   Length of group in bytes      : (96)
---------------------------------------------------------------------------
Uint16  Group   number                : 0x0010
Uint16  Element number                : 0x0010
Uint32  Element length  in bytes      : (35)
char *  Patient Name                  :
---------------------------------------------------------------------------
Uint16  Group   number                : 0x0010
Uint16  Element number                : 0x0020
Uint32  Element length  in bytes      : (35)
char *  Patient ID                    :
---------------------------------------------------------------------------
Uint16  Group   number                : 0x0010
Uint16  Element number                : 0x0040
Uint32  Element length  in bytes      : (2)
char *  Patient Sex                   : M_ = male

                                        F_ = female

                                        O_ = others
===========================================================================
GROUP 0x0018		Acquisition Information
===========================================================================
Uint16  Group   number                : 0x0018
Uint16  Element number                : 0x0000
Uint32  Element length  in bytes      : (4)
Int32   Length of group in bytes      : (122)
---------------------------------------------------------------------------
Uint16  Group   number                : 0x0018
Uint16  Element number                : 0x0030
Uint32  Element length  in bytes      : 32
char *  Radionuclide                  :
---------------------------------------------------------------------------
Uint16  Group   number                : 0x0018
Uint16  Element number                : 0x0050
Uint32  Element length  in bytes      : (13)
char *  Slice Thickness in mm         : (+0.000000e+00)
---------------------------------------------------------------------------
Uint16  Group   number                : 0x0018
Uint16  Element number                : 0x0088
Uint32  Element length  in bytes      : (13)
char *  Slice Spacing   in mm         : (+0.000000e+00)
---------------------------------------------------------------------------
Uint16  Group   number                : 0x0018
Uint16  Element number                : 0x1120
Uint32  Element length  in bytes      : (13)
float   Gantry Tilt     in degrees    : (+0.000000e+00)
---------------------------------------------------------------------------
Uint16  Group   number                : 0x0018
Uint16  Element number                : 0x1160
Uint32  Element length  in bytes      : (32)
char *  Filter Type                   :
---------------------------------------------------------------------------
Uint16  Group   number                : 0x0018
Uint16  Element number                : 0x5100
Uint32  Element length  in bytes      : (32)
char *  Patient Position              : (supine)

                                        supine = face-up     on    the table

                                        prone  = face-down towards the table

                                        other?
===========================================================================
GROUP 0x0020 Relationship Information
===========================================================================
Uint16  Group   number                : 0x0020
Uint16  Element number                : 0x0000
Uint32  Element length  in bytes      : (4)
Int32   Length of group in bytes      : (352)
---------------------------------------------------------------------------
Uint16  Group   number                : 0x0020
Uint16  Element number                : 0x0010
Uint32  Element length  in bytes      : (10)
char *  Study ID                      :
---------------------------------------------------------------------------
Uint16  Group   number                : 0x0020
Uint16  Element number                : 0x0013
Uint32  Element length  in bytes      : (6)
char *  Image Number                  :
---------------------------------------------------------------------------
Uint16  Group   number                : 0x0020
Uint16  Element number                : 0x0020
Uint32  Element length  in bytes      : (32)
char *  Patient Orientation           : (L\P)

 (direction of image row in patient\direction of image column in patient)

   'L' = Left  (hand)   'A' = Anterior  (to front)   'H' = Head

   'R' = Right (hand)   'P' = Posterior (to back)    'F' = Feet
---------------------------------------------------------------------------
Uint16  Group   number                : 0x0020
Uint16  Element number                : 0x0030
Uint32  Element length  in bytes      : (41)
char *  Image Position  in mm         :

                        * * * * * * * * * * * * *
Gives the 3D equipment based coordinates of the upper left hand corner
in the image. Example: (+0.000000e+00\+0.000000e+00\+0.000000e+00)

                         =X-axis         =Y-axis       =Z-axis
"When facing the front of the gantry (equipment device), and with the

 gantry in a neutral (untilted) position, the x-axis is increasing to the

 right; the y-axis is increasing down (gravitational attraction); and the

 z-axis is defined as the line orthogonal to x and y, with increasing

 values from the front to the back of the gantry."

 (From a Papyrus 2.3 document: UIN/HCUG 1990, 91)

My note: where is its origin? For an ECAT 931 scanner we choose the origin
in the right/back/down point of the gantry

      A

   ______H

  |\______\F    Looking to the scanner, this is a representation of the
R |.|.... |  L  volume our scanner detects. My origin is in the point we

   \|_____|     can't see ;-) Our images are transversal slices, beginning

                at the head towards the feet (so patient orientation = L\P)

      P         and the patient position is supine.
Therefore, the coordinates of the first pixel in our images is:
Image 0:

 -(PIXEL_X_SIZE*PIXELS_IN_X);-(PIXEL_Y_SIZE*PIXELS_IN_Y);-0
Image 1:

 -(PIXEL_X_SIZE*PIXELS_IN_X);-(PIXEL_Y_SIZE*PIXELS_IN_Y);-(SLICE_WIDTH*1)
Image n:

 -(PIXEL_X_SIZE*PIXELS_IN_X);-(PIXEL_Y_SIZE*PIXELS_IN_Y);-(SLICE_WIDTH*N)

                     |                           |

                image width                 image height
A view of the coordinate system you can see in 0x0020;0x0035.
However, it could all be wrong too! By the way, for DICOM it's retired stuff.

                        * * * * * * * * * * * * *
---------------------------------------------------------------------------
Uint16  Group   number                : 0x0020
Uint16  Element number                : 0x0032
Uint32  Element length  in bytes      : (41)
char *  Image Position (Patient) in mm:

                        * * * * * * * * * * * * *
The same as above but know based on the coordinate system of the patient.
A DICOM replacement for the above values:
"The direction of the axes is defined fully by the patient's orientation.
The x-axis is increasing to the left hand side of the patient. The y-axis
is increasing to the posterior side of the patient. The z-axis is increasing
toward the head of the patient.
The patient based coordinate system is a right handed system, i.e. the vector
cross product of a unit vector along the positive x-axis and a unit vector
along the positive y-axis is equal to a unit vector along the positive z-axis.
NOTE: If a patient lies parallel to the ground, face-up on the table, with

      his feet-to-head direction the same as front-to-back direction of the

      imaging equipment, the direction of the axes of the patient based

      coordinate system and equipment based coordinate system in previous

      versions of the DICOM Standard will coincide"
(From the NEMA Standards Publication PS3.3(199X)

                        * * * * * * * * * * * * *
---------------------------------------------------------------------------
Uint16  Group   number                : 0x0020
Uint16  Element number                : 0x0032
Uint32  Element length  in bytes      : (83)
char *  Image Orientation             :

                        * * * * * * * * * * * * *
Based on 0x0020;0x0030 these are the direction cosines of a unit vector
on the first row and on the first column based on the equipment coordinate
system (or our patient coordinate system, because they coincide as we
described above).

                       (to back of the scanner)

                    +Z (or head of the patient)

                    \

                     \  coordinate system

                      \

                       \_ _ _ _ _ _ _ +X (to right of the scanner)

                        |                 (or left  of the patient)

                        |

                        |

                        |

                       +Y (to the ground)

                          (or back of the patient)

                        * * * * * * * * * * * * *
Remember we take transversal slices (Right to Left of patient, Anterior to
Posterior) while the patient is supine with head first in gantry.
Then the images are in the plane XY and the unit vectors are

   upper left

   corner of image         (X)

                   + - - - - > (x1,y1,z1 = 1,0,0)

                   |               unit vector on row

                   |

                   |

              (Y)  V (x2,y2,z2 = 0,1,0)

                         unit vector on column
In this case: a) in point (x1,y1,z1)

                   X direction cosinus = +1

                   Y direction cosinus = -0

                   Z direction cosinus = -0

              b) in point (x2,y2,z2)

                   X direction cosinus = +0

                   Y direction cosinus = +1

                   Z direction cosinus = +0

How about the signs and values?

                     cos(0 or 360) = +1

                     cos(90)       = +0

                     cos(180)      = -1

                     cos(270)      = -0
The angle between an axis and the vector, you determine with a so called
"corkscrew-rule": You must turn from THE AXIS towards THE VECTOR (=angle)
the same direction so a corkscrew should proceed in the direction
of an axis orthogonal on the plane formed by THE AXIS and THE VECTOR.
Well, thats what it should be I think. If your images are tilted, it
will be a bit harder, isn't it?
For the above ECAT 931 acquisition an example value should be:
	(+1.000000e+00\-0.000000e+00\+0.000000e+00\
	 +0.000000e+00\+1.000000e+00\-0.000000e+00)
Again, this tag is retired for DICOM ...

                        * * * * * * * * * * * * *
---------------------------------------------------------------------------
Uint16  Group   number                : 0x0020
Uint16  Element number                : 0x0037
Uint32  Element length  in bytes      : (83)
char *  Image Orientation Patient     :
The same as for tag 0x0020;0x0032 but now considered for the patient
coordinate system ...
===========================================================================
GROUP 0x0028		Image Presentation
===========================================================================
Uint16  Group   number                : 0x0028
Uint16  Element number                : 0x0000
Uint32  Element length  in bytes      : (4)
Int32   Length of group in bytes      : (127)
---------------------------------------------------------------------------
Uint16  Group   number                : 0x0028
Uint16  Element number                : 0x0005
Uint32  Element length  in bytes      : (2)
Int16   Image Dimensions              : (2)
---------------------------------------------------------------------------
Uint16  Group   number                : 0x0028
Uint16  Element number                : 0x0010
Uint32  Element length  in bytes      : (2)
Int16   Rows                          :
---------------------------------------------------------------------------
Uint16  Group   number                : 0x0028
Uint16  Element number                : 0x0011
Uint32  Element length  in bytes      : (2)
Int16   Columns                       :
---------------------------------------------------------------------------
Uint16  Group   number                : 0x0028
Uint16  Element number                : 0x0030
Uint32  Element length  in bytes      : (27)
char *  Pixel Size      in mm         : (+0.000000e+00\+0.000000e+00)
---------------------------------------------------------------------------
Uint16  Group   number                : 0x0028
Uint16  Element number                : 0x0060
Uint32  Element length  in bytes      : (4)
char *  Compression code              : (NONE)
---------------------------------------------------------------------------
Uint16  Group   number                : 0x0028
Uint16  Element number                : 0x0100
Uint32  Element length  in bytes      : (2)
Int16   Bits Allocated                :
---------------------------------------------------------------------------
Uint16  Group   number                : 0x0028
Uint16  Element number                : 0x0101
Uint32  Element length  in bytes      : (2)
Int16   Bits per Pixel                :
---------------------------------------------------------------------------
Uint16  Group   number                : 0x0028
Uint16  Element number                : 0x0102
Uint32  Element length  in bytes      : (2)
Int16   High Bit                      :
---------------------------------------------------------------------------
Uint16  Group   number                : 0x0028
Uint16  Element number                : 0x0103
Uint32  Element length  in bytes      : (2)
Int16   Pixel Representation          : 0 = unsigned

                                        1 = signed
---------------------------------------------------------------------------
Uint16  Group   number                : 0x0028
Uint16  Element number                : 0x0200
Uint32  Element length  in bytes      : (2)
Int16   Image Location                : (7fe0)
===========================================================================
GROUP 0x7fe0		Pixel Information
===========================================================================
Uint16  Group   number                : 0x7fe0
Uint16  Element number                : 0x0000
Uint32  Element length  in bytes      : (4)
Int32   Length of group in bytes      : Z
Z = [imagesize] + 8
---------------------------------------------------------------------------
Uint16  Group   number                : 0x7fe0
Uint16  Element number                : 0x0010
Uint32  Element length  in bytes      : (imagesize)
Uint8 * Image Data                    :
---------------------------------------------------------------------------
```

This was an example of an ACR/NEMA file holding one image, as normal ACR/NEMA files do. However, as we are interested in multiple images, we use an ACR/NEMA dialect such as Papyrus. In this case we sequentially concatenate different ACR/NEMA files into one single large file!

## NOTES

Because of the previous remark, we must notify that in the Element 0x0001 of Group 0x0008, the [filesize] means the filesize in case of this one ACR/NEMA file and NOT the real filesize!

For the Group 0x0028, Element 0x0100: `Bits Allocated'

We only support a multiple of 8.

For the Group 0x0028, Element 0x0102: `High Bit'

We only support `High Bit' = [`Bits per Pixel'] - 1,

so we only accept images stored in the file endian type.

## FILES

```
/usr/local/xmedcon/source/m-acr.h       The header file.
/usr/local/xmedcon/source/m-acr.c       The source file.
```

## SEE ALSO

medcon(1), xmedcon(1), xmedcon-config(1)

m-anlz(4), m-gif(4), m-inw(4), m-intf(4), m-ecat(4)

medcon(3)

## AUTHOR

(X)MedCon project was originally written by Erik Nolf (eNlf) for the former PET-Centre at Ghent University (Belgium).

e-mail:

enlf-at-users.sourceforge.net

www:

http://xmedcon.sourceforge.net


m-anlz

title: m-anlz(4)

text:
# m-anlz(4)

## NAME
m-anlz - Analyze (SPM) medical image format (MedCon)

## DESCRIPTION

This is a very simple format. The basic headers are written in one file with extension `.hdr', the image data in another file with extension `.img'.

The basic defines for the format:

```
---------------------------------------------------------------------------
typedef struct Header_Key_t{

        Int32  sizeof_hdr;               /* 348 or 148                 */

        char data_type[10];              /* "dsr"                      */

        char db_name[18];                /* filename without extension */

        Int32 extents;                   /* 16384                      */

        Int16 session_error;

        char regular;                    /* 'r'                        */

        char hkey_un0;
} MDC_ANLZ_HEADER_KEY;
#define MDC_ANLZ_HK_SIZE 40
typedef struct Image_Dimensions_t{

        Int16 dim[8];                    /* [0] = # of dimensions      */

                                         /* [1] = X-dim                */

                                         /* [2] = Y-dim                */

                                         /* [3] = Z-dim                */

                                         /* [4] = t-dim                */

                                         /* ...                        */

        Int16 unused[7];

        Int16 datatype;                  /* pixel type                 */

                                         /*  0 = Unknown   1 = one-bit */

                                         /*  2 = Uint8     4 = Int16   */

                                         /*  8 = Int32    16 = float   */

                                         /* 32 = complex  64 = double  */

                                         /*128 = RGB     255 = all     */

        Int16 bitpix;                    /* bits per pixel             */

        Int16 dim_un0;

        float pixdim[8];                 /* [0] = # of dimensions      */

                                         /* [1] = X-dim (mm)           */

                                         /* [2] = Y-dim (mm)           */

                                         /* [3] = Z-dim (mm)           */

                                         /* [4] = t-dim (ms)           */

                                         /* ...                        */

        float funused[6];

        float compressed;

        float verified;

        Int32 glmax,glmin;
} MDC_ANLZ_IMAGE_DIMS;
#define MDC_ANLZ_IMD_SIZE 108
typedef struct Data_History_t{

        char descrip[80];

        char aux_file[24];

        char orient;                     /* patient orientation        */

                                         /* 0 = transverse unflipped   */

                                         /* 1 = coronal unflipped      */

                                         /* 2 = sagittal unflipped     */

                                         /* 3 = transverse flipped     */

                                         /* 4 = coronal flipped        */

                                         /* 5 = sagittal flipped       */

        char originator[10];

        char generated[10];

        char scannum[10];

        char patient_id[10];

        char exp_date[10];

        char exp_time[10];

        char hist_un0[3];

        Int32 views;

        Int32 vols_added;

        Int32 start_field;

        Int32 field_skip;

        Int32 omax, omin;

        Int32 smax, smin;
} MDC_ANLZ_DATA_HIST;
#define MDC_ANLZ_DH_SIZE 200
---------------------------------------------------------------------------
```

The structures are defined in the order as they should be found in the file. The Data_History header is not obliged. The SPM Analyze format, intended for the SPM software, differs a little from the normal Analyze format.

What does the format support or not support:

```
===========================================================================
Item            Supported                             Not Supported
===========================================================================
Color Map     : grayscale                                   -
File Endian   : little & big                                -
Pixeltypes    : 1-bit, Uint8, Int16, Int32           Int8,Uint16,Uint32

                float, double, (complex)               Int64,Uint64
===========================================================================
Scaling factors  : quantify & calibrate factors/image  are NOT supported
---------------------------------------------------------------------------
Dimensions/Image : different dimensions for each image are NOT supported
---------------------------------------------------------------------------
Pixeltypes/Image : different pixeltypes for each image are NOT supported
---------------------------------------------------------------------------
SPM remarks      : 1) imd.funused[0] = the offset

                   2) imd.funused[1] = one global scaling factor

                   3) (Int16)dh.originator[0...1] \

                      (Int16)dh.originator[2...3]  } =  origin (X, Y, Z)

                      (Int16)dh.originator[4...5] /
===========================================================================
```

## NOTES

A note about the image (patient) orientation in SPM:

X-axis

increases from leftside (hand) to rightside (hand).

Y-axis

increases from posterior (back) to anterior (front).

Z-axis

increases from inferior (feet) to superior (head).

## FILES

```
/usr/local/xmedcon/source/m-anlz.h      The header file.
/usr/local/xmedcon/source/m-anlz.c      The source file.
```

## SEE ALSO

medcon(1), xmedcon(1), xmedcon-config(1)

m-acr(4), m-gif(4), m-inw(4), m-intf(4), m-ecat(4)

medcon(3)

## AUTHOR

(X)MedCon project was originally written by Erik Nolf (eNlf) for the former PET-Centre at Ghent University (Belgium).

e-mail:

enlf-at-users.sourceforge.net

www:

http://xmedcon.sourceforge.net


m-ecat

title: m-ecat(4)

text:
# m-ecat(4)

## NAME
m-ecat - CTI ECAT 6/7 medical image format (MedCon)

## DESCRIPTION

This is a painful format. You should check the source code for more info. There is only read support for ECAT 7. Below you will find the specs for the ECAT 6 format. The ECAT 7 format differs a little in header definitions and there is only one matrix entry per volume, while for ECAT 6 files there is one matrix entry per plane. All ECAT 6 image data is written in one file with `.img' extension.

-----------------------------------------------------------------------

Important Definitions

-----------------------------------------------------------------------

```
typedef struct mat_main_header {

        char            original_file_name[20];

        Int16           sw_version;

        Int16           data_type;

        Int16           system_type;

        Int16           file_type;

        char            node_id[10];

        Int16           scan_start_day,

                        scan_start_month,

                        scan_start_year,

                        scan_start_hour,

                        scan_start_minute,

                        scan_start_second;

        char            isotope_code[8];

        float           isotope_halflife;

        char            radiopharmaceutical[32];

        float           gantry_tilt,

                        gantry_rotation,

                        bed_elevation;

        Int16           rot_source_speed,

                        wobble_speed,

                        transm_source_type;

        float           axial_fov,

                        transaxial_fov;

        Int16           transaxial_samp_mode,

                        coin_samp_mode,

                        axial_samp_mode;

        float           calibration_factor;

        Int16           calibration_units,

                        compression_code;

        char            study_name[12],

                        patient_id[16],

                        patient_name[32],

                        patient_sex,

                        patient_age[10],

                        patient_height[10],

                        patient_weight[10],

                        patient_dexterity,

                        physician_name[32],

                        operator_name[32],

                        study_description[32];

        Int16           acquisition_type,

                        bed_type,

                        septa_type;

        char            facility_name[20];

        Int16           num_planes,

                        num_frames,

                        num_gates,

                        num_bed_pos;

        float           init_bed_position,

                        bed_offset[15],

                        plane_separation;

        Int16           lwr_sctr_thres,

                        lwr_true_thres,

                        upr_true_thres;

        float           collimator;

        char            user_process_code[10];

        Int16           acquisition_mode;
} Main_header;
#define MH_64_SIZE 446
typedef struct mat_scan_subheader {

        Int16           data_type,

                        dimension_1,

                        dimension_2,

                        smoothing,

                        processing_code;

        float           sample_distance,

                        isotope_halflife;

        Int16           frame_duration_sec;

        Int32           gate_duration,

                        r_wave_offset;

        float           scale_factor;

        Int16           scan_min,

                        scan_max;

        Int32           prompts,

                        delayed,

                        multiples,

                        net_trues;

        float           cor_singles[16],

                        uncor_singles[16],

                        tot_avg_cor,

                        tot_avg_uncor;

        Int32           total_coin_rate,

                        frame_start_time,

                        frame_duration;

        float           loss_correction_fctr;

        Int32           phy_planes[8];
} Scan_subheader;
#define SSH_64_SIZE 236
typedef struct mat_image_subheader {

        Int16           data_type,

                        num_dimensions,

                        dimension_1,

                        dimension_2;

        float           x_origin,

                        y_origin,

                        recon_scale,    /* Image ZOOM from reconstruction */

                        quant_scale;    /* Scale Factor */

        Int16           image_min,

                        image_max;

        float           pixel_size,

                        slice_width;

        Int32           frame_duration,

                        frame_start_time;

        Int16           slice_location,

                        recon_start_hour,

                        recon_start_minute,

                        recon_start_sec;

        Int32           gate_duration;

        Int16           filter_code;

        Int32           scan_matrix_num,

                        norm_matrix_num,

                        atten_cor_matrix_num;

        float           image_rotation,

                        plane_eff_corr_fctr,

                        decay_corr_fctr,

                        loss_corr_fctr,

                        intrinsic_tilt ;

        Int16           processing_code,

                        quant_units,

                        recon_start_day,

                        recon_start_month,

                        recon_start_year;

        float           ecat_calibration_fctr,

                        well_counter_cal_fctr,

                        filter_params[6];

        char            annotation[40];
} Image_subheader;
#define ISH_64_SIZE 172
typedef struct mat_norm_subheader {

        Int16           data_type,

                        dimension_1,

                        dimension_2;

        float           scale_factor;

        Int16           norm_hour,

                        norm_minute,

                        norm_second,

                        norm_day,

                        norm_month,

                        norm_year;

        float           fov_source_width;

        float           ecat_calib_factor;
} Norm_subheader;
#define NSH_64_SIZE 30
typedef struct mat_attn_subheader {

        Int16           data_type,

                        attenuation_type,

                        dimension_1,

                        dimension_2;

        float           scale_factor,

                        x_origin,

                        y_origin,

                        x_radius,

                        y_radius,

                        tilt_angle,

                        attenuation_coeff,

                        sample_distance;
} Attn_subheader;
#define ASH_64_SIZE 40
-----------------------------------------------------------------------
```

```
What does the format support or not support:
```

```
===========================================================================
Item            Supported                             Not Supported
===========================================================================
Color Map     : grayscale                                   -
File Endian   : big                                       little
Pixeltypes    : VAX Int16 (write)  | All (read)             -
===========================================================================
Scaling factors  : quantify & calibrate factors/image  are supported
---------------------------------------------------------------------------
Dimensions/Image : different dimensions for each image are NOT supported
---------------------------------------------------------------------------
Pixeltypes/Image : different pixeltypes for each image are NOT supported
===========================================================================
```

## NOTES

The MedCon program also supports the reading of sinogram, attenuation and normalization files for conversion purposes but it does not support writing those file types. In fact, they will be considered as reconstructed data!

The format supports more pixeltypes. The reason for our restriction of writing only the Int16 type was our ECAT software that only supports the Int16 type.

We consider three kinds of images (planes) in an ECAT file:

(1) plain pixel values [no unit] (ppv = ppv)

- the planes/images are NOT normalized

(2) quantified values [counts/second/pixel] (qpv = ppv * quant_scale)

- the planes/images are normalized

(3) calibrated values [uCi/ml] (cpv = qpv * calibr_fctr)

- the planes/images are normalized

The float values in the header are stored as VAX format.

## FILES

```
/usr/local/xmedcon/source/m-ecat64.h      The header file.
/usr/local/xmedcon/source/m-ecat64.c      The source file.
/usr/local/xmedcon/source/m-matrix64.h    CTI header file.
/usr/local/xmedcon/source/m-matrix64.c    CTI source file.
```

## SEE ALSO

medcon(1), xmedcon(1), xmedcon-config(1)

m-acr(4), m-anlz(4), m-gif(4), m-inw(4), m-intf(4)

medcon(3)

## AUTHOR

(X)MedCon project was originally written by Erik Nolf (eNlf) for the former PET-Centre at Ghent University (Belgium).

e-mail:

enlf-at-users.sourceforge.net

www:

http://xmedcon.sourceforge.net


m-gif

title: m-gif(4)

text:
# m-gif(4)

## NAME
m-gif - GIF87a and annimated GIF89a format (MedCon)

## DESCRIPTION

The Graphics Interchange Format from CompuServe allows between 1 and 8 bits of color information with an RGB color palette. The image arrays are compressed with an LZW coding. The extension of the file is `.gif'.

The basic defines for the format:

```
---------------------------------------------------------------------------
typedef struct {

        char sig[6];                       /* GIF87a or GIF89a         */

        Uint16 screenwidth,screenheight;   /* screen dimensions        */

        Uint8  flags,background,aspect;    /* background color, ratio  */
} MDC_GIFHEADER;
#define MDC_GIF_GH_SIZE 13
typedef struct {

        Uint16 left,top,width,height;       /* image dimensions         */

        Uint8  flags;
} MDC_GIFIMAGEBLOCK;
#define MDC_GIF_IBLK_SIZE  9
typedef struct {                           /* display information      */

        Uint8 blocksize;

        Uint8 flags;

        Uint16 delay;

        Uint8 transparent_colour;

        Uint8 terminator;
} MDC_GIFCONTROLBLOCK;
#define MDC_GIF_CBLK_SIZE 6
typedef struct {                           /* plain text block         */

        Uint8 blocksize;

        Uint16 left,top;

        Uint16 gridwidth,gridheight;

        Uint8 cellwidth,cellheight;

        Uint8 forecolour,backcolour;
} MDC_GIFPLAINTEXT;
#define MDC_GIF_TBLK_SIZE 13
typedef struct {                           /* application block        */

        Uint8 blocksize;

        char applstring[8];

        char authentication[3];
} MDC_GIFAPPLICATION;
#define MDC_GIF_ABLK_SIZE 12
---------------------------------------------------------------------------
```

What does the format support or not support:

```
===========================================================================
Item            Supported                             Not Supported
===========================================================================
Color Map     : max 256 RGB colors                          -
File Endian   : little                                     big
Pixeltypes    : Uint8                                       -
===========================================================================
Scaling factors  : quantify & calibrate factors/image  are NOT supported
---------------------------------------------------------------------------
Dimensions/Image : different dimensions for each image are supported
---------------------------------------------------------------------------
Pixeltypes/Image : different pixeltypes for each image are NOT supported
===========================================================================
```

Because of the flexible nature of the GIF format it could be possible to include scaling factors per image with the GIF extension blocks, but more about this later. The image is stored from left to right and from top to bottom, unless the images are interlaced.

First some explanation on the GIF format and its different structures.

=======================

The GIFHEADER structure

=======================

This data structure is the very first information in a GIF file:

sig[6]

Holds the signature of the file "GIF87a" or "GIF89a".

screenwidth, screenheight

The required screen dimensions in pixels to display the images.

background

This represents the background color. It is in fact an index entry in the color palette.

aspect

The aspect ratio of the pixels in the image. If this field is not 0 the aspect ratio is: ((gh.aspect + 15) / 64). This entry is always 0 for the GIF87a format.

flags

This fields contains a number of bits of information.

if (gh.flags & 0x0080) is true, a global color map will follow.

```
     The number of color bits: ((gh.flags & 0x0007) + 1)

     The number of colors    : (1 << ((gh.flags & 0x0007) + 1)
```

if (gh.flags > 0x0008) is true, the color palette is sorted with the most important colors first. This bit is low in GIF87a.

Finally (1 << ((gh.flags >> 4) + 1) represents the number of color bits in the original image. This bit is low in GIF87a.

After reading the GIFHEADER and any global colormap, there should be a `block separator' which introduce the following block of GIF information. There are three kind of `block separators' : a comma, an exclamation mark and a semicolon.

```
                     ','  =>  the next block will be an image

                     '!'  =>  the next block will be an extension

                     ';'  =>  the end of the GIF file
```

The image block after a comma consists of the IMAGEBLOCK structure and the compressed image. The IMAGEBLOCK structure defines the nature of the image and supersedes the global definitions.

========================

The IMAGEBLOCK extension

========================

left, top

The upper left coordinate of the image relative to the screen.

width, height

The image dimensions. Width is the number of pixels in a line. Depth represents the number of rows.

flags

This field is similar to the global flags in the GIFHEADER structure. Number of colors in the image is ((iblk.flags & 0x0007) + 1).

If (iblk.flags & 0x0040) is true, the image is interlaced. In this case the image is split into four passes instead of sequential lines:

1st pass: lines 0 8 16 24 ... (+8)

2nd pass: lines 4 12 20 28 ... (+8)

3rd pass: lines 2 6 10 14 ... (+4)

4th pass: lines 1 3 5 7 ... (+2)

If (iblk.flags & 0x0080) is true, there is a local color map.

If (iblk.flags & 0x0020) is true, the color map is sorted.

The next byte, after the IMAGEBLOCK should be the initial image code size The compressed image consists of subblocks of code, of which the first byte gives the amount of code bytes that follow. The last block is a zero-length block. This is how you could skip an image:

```
     FILE *fp;

     int i,n;

     do {

       n = fgetc(fp);                     /* get code size               */

       if (n != EOF) {

         for (i=0; i<n; i++) fgetc(fp);   /* skip the block              */

       }

     }while( (n != 0) && (n != EOF))      /* read the next block, if any */
```

After reading this hole image block, the next byte should be again a `block separator'. If this separator is an exclamation mark, the following block is an extension. The GIF extension blocks allow additional features.

=====================

The COMMENT extension

=====================

This is a very simple extension. The byte 0xfe after a block separator, introduces a comment block. It contains text that does not make part of the image. The comment block is stored as subblocks, ending with a zero-length subblock (or endblock).

=======================

The PLAINTEXT extension

=======================

This is identified by the byte 0x01 after the block separator. The data structure follows this byte.

left, top

The items give the starting position of the displayed text.

gridwidth, gridheight

Two elements that specify the distance in pixels from one character to the next.

cellwidth, cellheight

These fields represent the actual dimensions in pixels of the characters to be displayed.

forecolor, backcolor

Color map indices for the foreground and background respectively.

The next data after this structure is the text itself, stored in data subblocks just like the comment block is.

==========================

The CONTROLBLOCK extension

==========================

A GIF file with more then one picture also contains a CONTROLBLOCK extension. The byte 0xf9 after the block separator, represents this graphics control block. Following this byte is the data structure.

blocksize

This field always contains the value 0x04.

flags

if (cb.flags & 0x01) is true, cb.transparent_color will contain a valid transparent color index.

if (cb.flags & 0x02) is true, the viewing program should wait for user input before displaying the next image. if (cb.delay) is greater than zero, the viewer should at least wait for the number of seconds specified in the delay data field.

The value ((cb.flags >> 2) & 0x0007) tells the method to remove the present image from the screen:

```
          0 = do nothing

          1 = leave it

          2 = restore with the background color

          3 = restore with the previous graphic
```

delay

The delay in 1/100ths of a second to dispose the present graphic.

transparant_color

This fields represents the color index of the transparant color.

terminator

Any clues on this?

=========================

The APPLICATION extension

=========================

The final extension is the APPLICATION block. The application data structure is identified by the byte 0xff just after the block separator.

blocksize

This contains the value 0x0b.

applstring

An 8-byte string that specifies the creator software.

authentication

This field should contain 3 bytes based on the applstring field to check the integrity of the applstring field.

The APPLICATION block extension can be followed by subblocks, ending with a zero-length subblock.

A special kind of APPLICATION block extension is the LOOPBLOCK extension used for annimated GIF files in concern to Netscape Navigator. This block comes between the GIFHEADER and IMAGEBLOCK data structures. It contains the following items:

```
       1. An application block

                ap.blocksize      = 0x0b;

                ap.applstring     = "NETSCAPE";

                ap.authentication = "2.0";

       2. subblock of 3 bytes: 0x03

                0x01,0xe8,0x03

       3. endblock of 0 bytes: 0x00
```

## NOTES
For complete information on the GIF format, we liked reading this book:

``Supercharged Bitmapped Graphics''

written by Steve Rimmer

published by Windcrest/McGraw-Hill

ISBN: 0-8306-3788-5

## FILES

```
/usr/local/xmedcon/source/m-gif.h     The header file.
/usr/local/xmedcon/source/m-gif.c     The source file.
```

## SEE ALSO

medcon(1), xmedcon(1), xmedcon-config(1)

m-acr(4), m-anlz(4), m-inw(4), m-intf(4), m-ecat(4)

medcon(3)

## AUTHOR

(X)MedCon project was originally written by Erik Nolf (eNlf) for the former PET-Centre at Ghent University (Belgium).

e-mail:

enlf-at-users.sourceforge.net

www:

http://xmedcon.sourceforge.net