code
stringlengths
2.5k
150k
kind
stringclasses
1 value
bash Modifiers Modifiers ========= After the optional word designator, you can add a sequence of one or more of the following modifiers, each preceded by a β€˜`:`’. These modify, or edit, the word or words selected from the history event. `h` Remove a trailing pathname component, leaving only the head. `t` Remove all leading pathname components, leaving the tail. `r` Remove a trailing suffix of the form β€˜`.suffix`’, leaving the basename. `e` Remove all but the trailing suffix. `p` Print the new command but do not execute it. `q` Quote the substituted words, escaping further substitutions. `x` Quote the substituted words as with β€˜`q`’, but break into words at spaces, tabs, and newlines. The β€˜`q`’ and β€˜`x`’ modifiers are mutually exclusive; the last one supplied is used. `s/old/new/` Substitute new for the first occurrence of old in the event line. Any character may be used as the delimiter in place of β€˜`/`’. The delimiter may be quoted in old and new with a single backslash. If β€˜`&`’ appears in new, it is replaced by old. A single backslash will quote the β€˜`&`’. If old is null, it is set to the last old substituted, or, if no previous history substitutions took place, the last string in a !?string`[?]` search. If new is null, each matching old is deleted. The final delimiter is optional if it is the last character on the input line. `&` Repeat the previous substitution. `g` `a` Cause changes to be applied over the entire event line. Used in conjunction with β€˜`s`’, as in `gs/old/new/`, or with β€˜`&`’. `G` Apply the following β€˜`s`’ or β€˜`&`’ modifier once to each word in the event. bash Special Builtins Special Builtins ================ For historical reasons, the POSIX standard has classified several builtin commands as *special*. When Bash is executing in POSIX mode, the special builtins differ from other builtin commands in three respects: 1. Special builtins are found before shell functions during command lookup. 2. If a special builtin returns an error status, a non-interactive shell exits. 3. Assignment statements preceding the command stay in effect in the shell environment after the command completes. When Bash is not executing in POSIX mode, these builtins behave no differently than the rest of the Bash builtin commands. The Bash POSIX mode is described in [Bash POSIX Mode](bash-posix-mode). These are the POSIX special builtins: ``` break : . continue eval exec exit export readonly return set shift trap unset ``` bash Commands For Moving Commands For Moving =================== `beginning-of-line (C-a)` Move to the start of the current line. `end-of-line (C-e)` Move to the end of the line. `forward-char (C-f)` Move forward a character. `backward-char (C-b)` Move back a character. `forward-word (M-f)` Move forward to the end of the next word. Words are composed of letters and digits. `backward-word (M-b)` Move back to the start of the current or previous word. Words are composed of letters and digits. `shell-forward-word (M-C-f)` Move forward to the end of the next word. Words are delimited by non-quoted shell metacharacters. `shell-backward-word (M-C-b)` Move back to the start of the current or previous word. Words are delimited by non-quoted shell metacharacters. `previous-screen-line ()` Attempt to move point to the same physical screen column on the previous physical screen line. This will not have the desired effect if the current Readline line does not take up more than one physical line or if point is not greater than the length of the prompt plus the screen width. `next-screen-line ()` Attempt to move point to the same physical screen column on the next physical screen line. This will not have the desired effect if the current Readline line does not take up more than one physical line or if the length of the current Readline line is not greater than the length of the prompt plus the screen width. `clear-display (M-C-l)` Clear the screen and, if possible, the terminal’s scrollback buffer, then redraw the current line, leaving the current line at the top of the screen. `clear-screen (C-l)` Clear the screen, then redraw the current line, leaving the current line at the top of the screen. `redraw-current-line ()` Refresh the current line. By default, this is unbound. bash Installing Bash Installing Bash =============== This chapter provides basic instructions for installing Bash on the various supported platforms. The distribution supports the GNU operating systems, nearly every version of Unix, and several non-Unix systems such as BeOS and Interix. Other independent ports exist for MS-DOS, OS/2, and Windows platforms. * [Basic Installation](basic-installation) * [Compilers and Options](compilers-and-options) * [Compiling For Multiple Architectures](compiling-for-multiple-architectures) * [Installation Names](installation-names) * [Specifying the System Type](specifying-the-system-type) * [Sharing Defaults](sharing-defaults) * [Operation Controls](operation-controls) * [Optional Features](optional-features) bash Controlling the Prompt Controlling the Prompt ====================== Bash examines the value of the array variable `PROMPT_COMMAND` just before printing each primary prompt. If any elements in `PROMPT_COMMAND` are set and non-null, Bash executes each value, in numeric order, just as if it had been typed on the command line. In addition, the following table describes the special characters which can appear in the prompt variables `PS0`, `PS1`, `PS2`, and `PS4`: `\a` A bell character. `\d` The date, in "Weekday Month Date" format (e.g., "Tue May 26"). `\D{format}` The format is passed to `strftime`(3) and the result is inserted into the prompt string; an empty format results in a locale-specific time representation. The braces are required. `\e` An escape character. `\h` The hostname, up to the first β€˜.’. `\H` The hostname. `\j` The number of jobs currently managed by the shell. `\l` The basename of the shell’s terminal device name. `\n` A newline. `\r` A carriage return. `\s` The name of the shell, the basename of `$0` (the portion following the final slash). `\t` The time, in 24-hour HH:MM:SS format. `\T` The time, in 12-hour HH:MM:SS format. `\@` The time, in 12-hour am/pm format. `\A` The time, in 24-hour HH:MM format. `\u` The username of the current user. `\v` The version of Bash (e.g., 2.00) `\V` The release of Bash, version + patchlevel (e.g., 2.00.0) `\w` The value of the `PWD` shell variable (`$PWD`), with `$HOME` abbreviated with a tilde (uses the `$PROMPT_DIRTRIM` variable). `\W` The basename of `$PWD`, with `$HOME` abbreviated with a tilde. `\!` The history number of this command. `\#` The command number of this command. `\$` If the effective uid is 0, `#`, otherwise `$`. `\nnn` The character whose ASCII code is the octal value nnn. `\\` A backslash. `\[` Begin a sequence of non-printing characters. This could be used to embed a terminal control sequence into the prompt. `\]` End a sequence of non-printing characters. The command number and the history number are usually different: the history number of a command is its position in the history list, which may include commands restored from the history file (see [Bash History Facilities](bash-history-facilities)), while the command number is the position in the sequence of commands executed during the current shell session. After the string is decoded, it is expanded via parameter expansion, command substitution, arithmetic expansion, and quote removal, subject to the value of the `promptvars` shell option (see [The Shopt Builtin](the-shopt-builtin)). This can have unwanted side effects if escaped portions of the string appear within command substitution or contain characters special to word expansion. bash Definitions Definitions =========== These definitions are used throughout the remainder of this manual. `POSIX` A family of open system standards based on Unix. Bash is primarily concerned with the Shell and Utilities portion of the POSIX 1003.1 standard. `blank` A space or tab character. `builtin` A command that is implemented internally by the shell itself, rather than by an executable program somewhere in the file system. `control operator` A `token` that performs a control function. It is a `newline` or one of the following: β€˜`||`’, β€˜`&&`’, β€˜`&`’, β€˜`;`’, β€˜`;;`’, β€˜`;&`’, β€˜`;;&`’, β€˜`|`’, β€˜`|&`’, β€˜`(`’, or β€˜`)`’. `exit status` The value returned by a command to its caller. The value is restricted to eight bits, so the maximum value is 255. `field` A unit of text that is the result of one of the shell expansions. After expansion, when executing a command, the resulting fields are used as the command name and arguments. `filename` A string of characters used to identify a file. `job` A set of processes comprising a pipeline, and any processes descended from it, that are all in the same process group. `job control` A mechanism by which users can selectively stop (suspend) and restart (resume) execution of processes. `metacharacter` A character that, when unquoted, separates words. A metacharacter is a `space`, `tab`, `newline`, or one of the following characters: β€˜`|`’, β€˜`&`’, β€˜`;`’, β€˜`(`’, β€˜`)`’, β€˜`<`’, or β€˜`>`’. `name` A `word` consisting solely of letters, numbers, and underscores, and beginning with a letter or underscore. `Name`s are used as shell variable and function names. Also referred to as an `identifier`. `operator` A `control operator` or a `redirection operator`. See [Redirections](redirections), for a list of redirection operators. Operators contain at least one unquoted `metacharacter`. `process group` A collection of related processes each having the same process group ID. `process group ID` A unique identifier that represents a `process group` during its lifetime. `reserved word` A `word` that has a special meaning to the shell. Most reserved words introduce shell flow control constructs, such as `for` and `while`. `return status` A synonym for `exit status`. `signal` A mechanism by which a process may be notified by the kernel of an event occurring in the system. `special builtin` A shell builtin command that has been classified as special by the POSIX standard. `token` A sequence of characters considered a single unit by the shell. It is either a `word` or an `operator`. `word` A sequence of characters treated as a unit by the shell. Words may not include unquoted `metacharacters`. bash Directory Stack Builtins Directory Stack Builtins ======================== `dirs` ``` dirs [-clpv] [+N | -N] ``` Display the list of currently remembered directories. Directories are added to the list with the `pushd` command; the `popd` command removes directories from the list. The current directory is always the first directory in the stack. `-c` Clears the directory stack by deleting all of the elements. `-l` Produces a listing using full pathnames; the default listing format uses a tilde to denote the home directory. `-p` Causes `dirs` to print the directory stack with one entry per line. `-v` Causes `dirs` to print the directory stack with one entry per line, prefixing each entry with its index in the stack. `+N` Displays the Nth directory (counting from the left of the list printed by `dirs` when invoked without options), starting with zero. `-N` Displays the Nth directory (counting from the right of the list printed by `dirs` when invoked without options), starting with zero. `popd` ``` popd [-n] [+N | -N] ``` Removes elements from the directory stack. The elements are numbered from 0 starting at the first directory listed by `dirs`; that is, `popd` is equivalent to `popd +0`. When no arguments are given, `popd` removes the top directory from the stack and changes to the new top directory. Arguments, if supplied, have the following meanings: `-n` Suppresses the normal change of directory when removing directories from the stack, so that only the stack is manipulated. `+N` Removes the Nth directory (counting from the left of the list printed by `dirs`), starting with zero, from the stack. `-N` Removes the Nth directory (counting from the right of the list printed by `dirs`), starting with zero, from the stack. If the top element of the directory stack is modified, and the `-n` option was not supplied, `popd` uses the `cd` builtin to change to the directory at the top of the stack. If the `cd` fails, `popd` returns a non-zero value. Otherwise, `popd` returns an unsuccessful status if an invalid option is encountered, the directory stack is empty, or a non-existent directory stack entry is specified. If the `popd` command is successful, Bash runs `dirs` to show the final contents of the directory stack, and the return status is 0. `pushd` ``` pushd [-n] [+N | -N | dir] ``` Adds a directory to the top of the directory stack, or rotates the stack, making the new top of the stack the current working directory. With no arguments, `pushd` exchanges the top two elements of the directory stack. Arguments, if supplied, have the following meanings: `-n` Suppresses the normal change of directory when rotating or adding directories to the stack, so that only the stack is manipulated. `+N` Brings the Nth directory (counting from the left of the list printed by `dirs`, starting with zero) to the top of the list by rotating the stack. `-N` Brings the Nth directory (counting from the right of the list printed by `dirs`, starting with zero) to the top of the list by rotating the stack. `dir` Makes dir be the top of the stack. After the stack has been modified, if the `-n` option was not supplied, `pushd` uses the `cd` builtin to change to the directory at the top of the stack. If the `cd` fails, `pushd` returns a non-zero value. Otherwise, if no arguments are supplied, `pushd` returns 0 unless the directory stack is empty. When rotating the directory stack, `pushd` returns 0 unless the directory stack is empty or a non-existent directory stack element is specified. If the `pushd` command is successful, Bash runs `dirs` to show the final contents of the directory stack. bash Shell Compatibility Mode Shell Compatibility Mode ======================== Bash-4.0 introduced the concept of a *shell compatibility level*, specified as a set of options to the shopt builtin (`compat31`, `compat32`, `compat40`, `compat41`, and so on). There is only one current compatibility level – each option is mutually exclusive. The compatibility level is intended to allow users to select behavior from previous versions that is incompatible with newer versions while they migrate scripts to use current features and behavior. It’s intended to be a temporary solution. This section does not mention behavior that is standard for a particular version (e.g., setting `compat32` means that quoting the rhs of the regexp matching operator quotes special regexp characters in the word, which is default behavior in bash-3.2 and subsequent versions). If a user enables, say, `compat32`, it may affect the behavior of other compatibility levels up to and including the current compatibility level. The idea is that each compatibility level controls behavior that changed in that version of Bash, but that behavior may have been present in earlier versions. For instance, the change to use locale-based comparisons with the `[[` command came in bash-4.1, and earlier versions used ASCII-based comparisons, so enabling `compat32` will enable ASCII-based comparisons as well. That granularity may not be sufficient for all uses, and as a result users should employ compatibility levels carefully. Read the documentation for a particular feature to find out the current behavior. Bash-4.3 introduced a new shell variable: `BASH_COMPAT`. The value assigned to this variable (a decimal version number like 4.2, or an integer corresponding to the `compat`NN option, like 42) determines the compatibility level. Starting with bash-4.4, Bash has begun deprecating older compatibility levels. Eventually, the options will be removed in favor of `BASH_COMPAT`. Bash-5.0 is the final version for which there will be an individual shopt option for the previous version. Users should use `BASH_COMPAT` on bash-5.0 and later versions. The following table describes the behavior changes controlled by each compatibility level setting. The `compat`NN tag is used as shorthand for setting the compatibility level to NN using one of the following mechanisms. For versions prior to bash-5.0, the compatibility level may be set using the corresponding `compat`NN shopt option. For bash-4.3 and later versions, the `BASH_COMPAT` variable is preferred, and it is required for bash-5.1 and later versions. `compat31` * quoting the rhs of the `[[` command’s regexp matching operator (=~) has no special effect `compat32` * interrupting a command list such as "a ; b ; c" causes the execution of the next command in the list (in bash-4.0 and later versions, the shell acts as if it received the interrupt, so interrupting one command in a list aborts the execution of the entire list) `compat40` * the β€˜`<`’ and β€˜`>`’ operators to the `[[` command do not consider the current locale when comparing strings; they use ASCII ordering. Bash versions prior to bash-4.1 use ASCII collation and strcmp(3); bash-4.1 and later use the current locale’s collation sequence and strcoll(3). `compat41` * in posix mode, `time` may be followed by options and still be recognized as a reserved word (this is POSIX interpretation 267) * in posix mode, the parser requires that an even number of single quotes occur in the word portion of a double-quoted ${…} parameter expansion and treats them specially, so that characters within the single quotes are considered quoted (this is POSIX interpretation 221) `compat42` * the replacement string in double-quoted pattern substitution does not undergo quote removal, as it does in versions after bash-4.2 * in posix mode, single quotes are considered special when expanding the word portion of a double-quoted ${…} parameter expansion and can be used to quote a closing brace or other special character (this is part of POSIX interpretation 221); in later versions, single quotes are not special within double-quoted word expansions `compat43` * the shell does not print a warning message if an attempt is made to use a quoted compound assignment as an argument to declare (e.g., declare -a foo=’(1 2)’). Later versions warn that this usage is deprecated * word expansion errors are considered non-fatal errors that cause the current command to fail, even in posix mode (the default behavior is to make them fatal errors that cause the shell to exit) * when executing a shell function, the loop state (while/until/etc.) is not reset, so `break` or `continue` in that function will break or continue loops in the calling context. Bash-4.4 and later reset the loop state to prevent this `compat44` * the shell sets up the values used by `BASH_ARGV` and `BASH_ARGC` so they can expand to the shell’s positional parameters even if extended debugging mode is not enabled * a subshell inherits loops from its parent context, so `break` or `continue` will cause the subshell to exit. Bash-5.0 and later reset the loop state to prevent the exit * variable assignments preceding builtins like `export` and `readonly` that set attributes continue to affect variables with the same name in the calling environment even if the shell is not in posix mode `compat50 (set using BASH_COMPAT)` * Bash-5.1 changed the way `$RANDOM` is generated to introduce slightly more randomness. If the shell compatibility level is set to 50 or lower, it reverts to the method from bash-5.0 and previous versions, so seeding the random number generator by assigning a value to `RANDOM` will produce the same sequence as in bash-5.0 * If the command hash table is empty, Bash versions prior to bash-5.1 printed an informational message to that effect, even when producing output that can be reused as input. Bash-5.1 suppresses that message when the `-l` option is supplied. `compat51 (set using BASH_COMPAT)` * The `unset` builtin will unset the array `a` given an argument like β€˜`a[@]`’. Bash-5.2 will unset an element with key β€˜`@`’ (associative arrays) or remove all the elements without unsetting the array (indexed arrays) * arithmetic commands ( ((...)) ) and the expressions in an arithmetic for statement can be expanded more than once * expressions used as arguments to arithmetic operators in the `[[` conditional command can be expanded more than once * the expressions in substring parameter brace expansion can be expanded more than once * the expressions in the $(( ... )) word expansion can be expanded more than once * arithmetic expressions used as indexed array subscripts can be expanded more than once * `test -v`, when given an argument of β€˜`A[@]`’, where A is an existing associative array, will return true if the array has any set elements. Bash-5.2 will look for and report on a key named β€˜`@`’ * the ${parameter[:]=value} word expansion will return value, before any variable-specific transformations have been performed (e.g., converting to lowercase). Bash-5.2 will return the final value assigned to the variable. * Parsing command substitutions will behave as if extended glob (see [The Shopt Builtin](the-shopt-builtin)) is enabled, so that parsing a command substitution containing an extglob pattern (say, as part of a shell function) will not fail. This assumes the intent is to enable extglob before the command is executed and word expansions are performed. It will fail at word expansion time if extglob hasn’t been enabled by the time the command is executed.
programming_docs
bash Readline Movement Commands Readline Movement Commands ========================== The above table describes the most basic keystrokes that you need in order to do editing of the input line. For your convenience, many other commands have been added in addition to `C-b`, `C-f`, `C-d`, and `DEL`. Here are some commands for moving more rapidly about the line. `C-a` Move to the start of the line. `C-e` Move to the end of the line. `M-f` Move forward a word, where a word is composed of letters and digits. `M-b` Move backward a word. `C-l` Clear the screen, reprinting the current line at the top. Notice how `C-f` moves forward a character, while `M-f` moves forward a word. It is a loose convention that control keystrokes operate on characters while meta keystrokes operate on words. bash Shell Commands Shell Commands ============== A simple shell command such as `echo a b c` consists of the command itself followed by arguments, separated by spaces. More complex shell commands are composed of simple commands arranged together in a variety of ways: in a pipeline in which the output of one command becomes the input of a second, in a loop or conditional construct, or in some other grouping. * [Reserved Words](reserved-words) * [Simple Commands](simple-commands) * [Pipelines](pipelines) * [Lists of Commands](lists) * [Compound Commands](compound-commands) * [Coprocesses](coprocesses) * [GNU Parallel](gnu-parallel) bash GNU Parallel GNU Parallel ============ There are ways to run commands in parallel that are not built into Bash. GNU Parallel is a tool to do just that. GNU Parallel, as its name suggests, can be used to build and run commands in parallel. You may run the same command with different arguments, whether they are filenames, usernames, hostnames, or lines read from files. GNU Parallel provides shorthand references to many of the most common operations (input lines, various portions of the input line, different ways to specify the input source, and so on). Parallel can replace `xargs` or feed commands from its input sources to several different instances of Bash. For a complete description, refer to the GNU Parallel documentation, which is available at <https://www.gnu.org/software/parallel/parallel_tutorial.html>. bash Word Designators Word Designators ================ Word designators are used to select desired words from the event. A β€˜`:`’ separates the event specification from the word designator. It may be omitted if the word designator begins with a β€˜`^`’, β€˜`$`’, β€˜`\*`’, β€˜`-`’, or β€˜`%`’. Words are numbered from the beginning of the line, with the first word being denoted by 0 (zero). Words are inserted into the current line separated by single spaces. For example, `!!` designates the preceding command. When you type this, the preceding command is repeated in toto. `!!:$` designates the last argument of the preceding command. This may be shortened to `!$`. `!fi:2` designates the second argument of the most recent command starting with the letters `fi`. Here are the word designators: `0 (zero)` The `0`th word. For many applications, this is the command word. `n` The nth word. `^` The first argument; that is, word 1. `$` The last argument. `%` The first word matched by the most recent β€˜`?string?`’ search, if the search string begins with a character that is part of a word. `x-y` A range of words; β€˜`-y`’ abbreviates β€˜`0-y`’. `*` All of the words, except the `0`th. This is a synonym for β€˜`1-$`’. It is not an error to use β€˜`\*`’ if there is just one word in the event; the empty string is returned in that case. `x*` Abbreviates β€˜`x-$`’ `x-` Abbreviates β€˜`x-$`’ like β€˜`x\*`’, but omits the last word. If β€˜`x`’ is missing, it defaults to 0. If a word designator is supplied without an event specification, the previous command is used as the event. bash Using History Interactively Using History Interactively =========================== This chapter describes how to use the GNU History Library interactively, from a user’s standpoint. It should be considered a user’s guide. For information on using the GNU History Library in other programs, see the GNU Readline Library Manual. * [Bash History Facilities](bash-history-facilities) * [Bash History Builtins](bash-history-builtins) * [History Expansion](history-interaction) bash Bash POSIX Mode Bash POSIX Mode =============== Starting Bash with the `--posix` command-line option or executing β€˜`set -o posix`’ while Bash is running will cause Bash to conform more closely to the POSIX standard by changing the behavior to match that specified by POSIX in areas where the Bash default differs. When invoked as `sh`, Bash enters POSIX mode after reading the startup files. The following list is what’s changed when β€˜POSIX mode’ is in effect: 1. Bash ensures that the `POSIXLY_CORRECT` variable is set. 2. When a command in the hash table no longer exists, Bash will re-search `$PATH` to find the new location. This is also available with β€˜`shopt -s checkhash`’. 3. Bash will not insert a command without the execute bit set into the command hash table, even if it returns it as a (last-ditch) result from a `$PATH` search. 4. The message printed by the job control code and builtins when a job exits with a non-zero status is β€˜Done(status)’. 5. The message printed by the job control code and builtins when a job is stopped is β€˜Stopped(signame)’, where signame is, for example, `SIGTSTP`. 6. Alias expansion is always enabled, even in non-interactive shells. 7. Reserved words appearing in a context where reserved words are recognized do not undergo alias expansion. 8. Alias expansion is performed when initially parsing a command substitution. The default mode generally defers it, when enabled, until the command substitution is executed. This means that command substitution will not expand aliases that are defined after the command substitution is initially parsed (e.g., as part of a function definition). 9. The POSIX `PS1` and `PS2` expansions of β€˜`!`’ to the history number and β€˜`!!`’ to β€˜`!`’ are enabled, and parameter expansion is performed on the values of `PS1` and `PS2` regardless of the setting of the `promptvars` option. 10. The POSIX startup files are executed (`$ENV`) rather than the normal Bash files. 11. Tilde expansion is only performed on assignments preceding a command name, rather than on all assignment statements on the line. 12. The default history file is `~/.sh\_history` (this is the default value of `$HISTFILE`). 13. Redirection operators do not perform filename expansion on the word in the redirection unless the shell is interactive. 14. Redirection operators do not perform word splitting on the word in the redirection. 15. Function names must be valid shell `name`s. That is, they may not contain characters other than letters, digits, and underscores, and may not start with a digit. Declaring a function with an invalid name causes a fatal syntax error in non-interactive shells. 16. Function names may not be the same as one of the POSIX special builtins. 17. POSIX special builtins are found before shell functions during command lookup. 18. When printing shell function definitions (e.g., by `type`), Bash does not print the `function` keyword. 19. Literal tildes that appear as the first character in elements of the `PATH` variable are not expanded as described above under [Tilde Expansion](tilde-expansion). 20. The `time` reserved word may be used by itself as a command. When used in this way, it displays timing statistics for the shell and its completed children. The `TIMEFORMAT` variable controls the format of the timing information. 21. When parsing and expanding a ${…} expansion that appears within double quotes, single quotes are no longer special and cannot be used to quote a closing brace or other special character, unless the operator is one of those defined to perform pattern removal. In this case, they do not have to appear as matched pairs. 22. The parser does not recognize `time` as a reserved word if the next token begins with a β€˜`-`’. 23. The β€˜`!`’ character does not introduce history expansion within a double-quoted string, even if the `histexpand` option is enabled. 24. If a POSIX special builtin returns an error status, a non-interactive shell exits. The fatal errors are those listed in the POSIX standard, and include things like passing incorrect options, redirection errors, variable assignment errors for assignments preceding the command name, and so on. 25. A non-interactive shell exits with an error status if a variable assignment error occurs when no command name follows the assignment statements. A variable assignment error occurs, for example, when trying to assign a value to a readonly variable. 26. A non-interactive shell exits with an error status if a variable assignment error occurs in an assignment statement preceding a special builtin, but not with any other simple command. For any other simple command, the shell aborts execution of that command, and execution continues at the top level ("the shell shall not perform any further processing of the command in which the error occurred"). 27. A non-interactive shell exits with an error status if the iteration variable in a `for` statement or the selection variable in a `select` statement is a readonly variable. 28. Non-interactive shells exit if filename in `.` filename is not found. 29. Non-interactive shells exit if a syntax error in an arithmetic expansion results in an invalid expression. 30. Non-interactive shells exit if a parameter expansion error occurs. 31. Non-interactive shells exit if there is a syntax error in a script read with the `.` or `source` builtins, or in a string processed by the `eval` builtin. 32. While variable indirection is available, it may not be applied to the β€˜`#`’ and β€˜`?`’ special parameters. 33. Expanding the β€˜`\*`’ special parameter in a pattern context where the expansion is double-quoted does not treat the `$*` as if it were double-quoted. 34. Assignment statements preceding POSIX special builtins persist in the shell environment after the builtin completes. 35. The `command` builtin does not prevent builtins that take assignment statements as arguments from expanding them as assignment statements; when not in POSIX mode, assignment builtins lose their assignment statement expansion properties when preceded by `command`. 36. The `bg` builtin uses the required format to describe each job placed in the background, which does not include an indication of whether the job is the current or previous job. 37. The output of β€˜`kill -l`’ prints all the signal names on a single line, separated by spaces, without the β€˜`SIG`’ prefix. 38. The `kill` builtin does not accept signal names with a β€˜`SIG`’ prefix. 39. The `export` and `readonly` builtin commands display their output in the format required by POSIX. 40. The `trap` builtin displays signal names without the leading `SIG`. 41. The `trap` builtin doesn’t check the first argument for a possible signal specification and revert the signal handling to the original disposition if it is, unless that argument consists solely of digits and is a valid signal number. If users want to reset the handler for a given signal to the original disposition, they should use β€˜`-`’ as the first argument. 42. `trap -p` displays signals whose dispositions are set to SIG\_DFL and those that were ignored when the shell started. 43. The `.` and `source` builtins do not search the current directory for the filename argument if it is not found by searching `PATH`. 44. Enabling POSIX mode has the effect of setting the `inherit_errexit` option, so subshells spawned to execute command substitutions inherit the value of the `-e` option from the parent shell. When the `inherit_errexit` option is not enabled, Bash clears the `-e` option in such subshells. 45. Enabling POSIX mode has the effect of setting the `shift_verbose` option, so numeric arguments to `shift` that exceed the number of positional parameters will result in an error message. 46. When the `alias` builtin displays alias definitions, it does not display them with a leading β€˜`alias` ’ unless the `-p` option is supplied. 47. When the `set` builtin is invoked without options, it does not display shell function names and definitions. 48. When the `set` builtin is invoked without options, it displays variable values without quotes, unless they contain shell metacharacters, even if the result contains nonprinting characters. 49. When the `cd` builtin is invoked in logical mode, and the pathname constructed from `$PWD` and the directory name supplied as an argument does not refer to an existing directory, `cd` will fail instead of falling back to physical mode. 50. When the `cd` builtin cannot change a directory because the length of the pathname constructed from `$PWD` and the directory name supplied as an argument exceeds `PATH_MAX` when all symbolic links are expanded, `cd` will fail instead of attempting to use only the supplied directory name. 51. The `pwd` builtin verifies that the value it prints is the same as the current directory, even if it is not asked to check the file system with the `-P` option. 52. When listing the history, the `fc` builtin does not include an indication of whether or not a history entry has been modified. 53. The default editor used by `fc` is `ed`. 54. The `type` and `command` builtins will not report a non-executable file as having been found, though the shell will attempt to execute such a file if it is the only so-named file found in `$PATH`. 55. The `vi` editing mode will invoke the `vi` editor directly when the β€˜`v`’ command is run, instead of checking `$VISUAL` and `$EDITOR`. 56. When the `xpg_echo` option is enabled, Bash does not attempt to interpret any arguments to `echo` as options. Each argument is displayed, after escape characters are converted. 57. The `ulimit` builtin uses a block size of 512 bytes for the `-c` and `-f` options. 58. The arrival of `SIGCHLD` when a trap is set on `SIGCHLD` does not interrupt the `wait` builtin and cause it to return immediately. The trap command is run once for each child that exits. 59. The `read` builtin may be interrupted by a signal for which a trap has been set. If Bash receives a trapped signal while executing `read`, the trap handler executes and `read` returns an exit status greater than 128. 60. The `printf` builtin uses `double` (via `strtod`) to convert arguments corresponding to floating point conversion specifiers, instead of `long double` if it’s available. The β€˜`L`’ length modifier forces `printf` to use `long double` if it’s available. 61. Bash removes an exited background process’s status from the list of such statuses after the `wait` builtin is used to obtain it. There is other POSIX behavior that Bash does not implement by default even when in POSIX mode. Specifically: 1. The `fc` builtin checks `$EDITOR` as a program to edit history entries if `FCEDIT` is unset, rather than defaulting directly to `ed`. `fc` uses `ed` if `EDITOR` is unset. 2. As noted above, Bash requires the `xpg_echo` option to be enabled for the `echo` builtin to be fully conformant. Bash can be configured to be POSIX-conformant by default, by specifying the `--enable-strict-posix-default` to `configure` when building (see [Optional Features](optional-features)). bash Readline Arguments Readline Arguments ================== You can pass numeric arguments to Readline commands. Sometimes the argument acts as a repeat count, other times it is the *sign* of the argument that is significant. If you pass a negative argument to a command which normally acts in a forward direction, that command will act in a backward direction. For example, to kill text back to the start of the line, you might type β€˜`M-- C-k`’. The general way to pass numeric arguments to a command is to type meta digits before the command. If the first β€˜digit’ typed is a minus sign (β€˜`-`’), then the sign of the argument will be negative. Once you have typed one meta digit to get the argument started, you can type the remainder of the digits, and then the command. For example, to give the `C-d` command an argument of 10, you could type β€˜`M-1 0 C-d`’, which will delete the next ten characters on the input line. bash Escape Character Escape Character ================ A non-quoted backslash β€˜`\`’ is the Bash escape character. It preserves the literal value of the next character that follows, with the exception of `newline`. If a `\newline` pair appears, and the backslash itself is not quoted, the `\newline` is treated as a line continuation (that is, it is removed from the input stream and effectively ignored). bash Conditional Constructs Conditional Constructs ====================== `if` The syntax of the `if` command is: ``` if test-commands; then consequent-commands; [elif more-test-commands; then more-consequents;] [else alternate-consequents;] fi ``` The test-commands list is executed, and if its return status is zero, the consequent-commands list is executed. If test-commands returns a non-zero status, each `elif` list is executed in turn, and if its exit status is zero, the corresponding more-consequents is executed and the command completes. If β€˜`else alternate-consequents`’ is present, and the final command in the final `if` or `elif` clause has a non-zero exit status, then alternate-consequents is executed. The return status is the exit status of the last command executed, or zero if no condition tested true. `case` The syntax of the `case` command is: ``` case word in [ [(] pattern [| pattern]…) command-list ;;]… esac ``` `case` will selectively execute the command-list corresponding to the first pattern that matches word. The match is performed according to the rules described below in [Pattern Matching](pattern-matching). If the `nocasematch` shell option (see the description of `shopt` in [The Shopt Builtin](the-shopt-builtin)) is enabled, the match is performed without regard to the case of alphabetic characters. The β€˜`|`’ is used to separate multiple patterns, and the β€˜`)`’ operator terminates a pattern list. A list of patterns and an associated command-list is known as a clause. Each clause must be terminated with β€˜`;;`’, β€˜`;&`’, or β€˜`;;&`’. The word undergoes tilde expansion, parameter expansion, command substitution, arithmetic expansion, and quote removal (see [Shell Parameter Expansion](shell-parameter-expansion)) before matching is attempted. Each pattern undergoes tilde expansion, parameter expansion, command substitution, arithmetic expansion, process substitution, and quote removal. There may be an arbitrary number of `case` clauses, each terminated by a β€˜`;;`’, β€˜`;&`’, or β€˜`;;&`’. The first pattern that matches determines the command-list that is executed. It’s a common idiom to use β€˜`\*`’ as the final pattern to define the default case, since that pattern will always match. Here is an example using `case` in a script that could be used to describe one interesting feature of an animal: ``` echo -n "Enter the name of an animal: " read ANIMAL echo -n "The $ANIMAL has " case $ANIMAL in horse | dog | cat) echo -n "four";; man | kangaroo ) echo -n "two";; *) echo -n "an unknown number of";; esac echo " legs." ``` If the β€˜`;;`’ operator is used, no subsequent matches are attempted after the first pattern match. Using β€˜`;&`’ in place of β€˜`;;`’ causes execution to continue with the command-list associated with the next clause, if any. Using β€˜`;;&`’ in place of β€˜`;;`’ causes the shell to test the patterns in the next clause, if any, and execute any associated command-list on a successful match, continuing the case statement execution as if the pattern list had not matched. The return status is zero if no pattern is matched. Otherwise, the return status is the exit status of the command-list executed. `select` The `select` construct allows the easy generation of menus. It has almost the same syntax as the `for` command: ``` select name [in words …]; do commands; done ``` The list of words following `in` is expanded, generating a list of items, and the set of expanded words is printed on the standard error output stream, each preceded by a number. If the β€˜`in words`’ is omitted, the positional parameters are printed, as if β€˜`in "$@"`’ had been specified. `select` then displays the `PS3` prompt and reads a line from the standard input. If the line consists of a number corresponding to one of the displayed words, then the value of name is set to that word. If the line is empty, the words and prompt are displayed again. If `EOF` is read, the `select` command completes and returns 1. Any other value read causes name to be set to null. The line read is saved in the variable `REPLY`. The commands are executed after each selection until a `break` command is executed, at which point the `select` command completes. Here is an example that allows the user to pick a filename from the current directory, and displays the name and index of the file selected. ``` select fname in *; do echo you picked $fname \($REPLY\) break; done ``` `((…))` ``` (( expression )) ``` The arithmetic expression is evaluated according to the rules described below (see [Shell Arithmetic](shell-arithmetic)). The expression undergoes the same expansions as if it were within double quotes, but double quote characters in expression are not treated specially are removed. If the value of the expression is non-zero, the return status is 0; otherwise the return status is 1. `[[…]]` ``` [[ expression ]] ``` Return a status of 0 or 1 depending on the evaluation of the conditional expression expression. Expressions are composed of the primaries described below in [Bash Conditional Expressions](bash-conditional-expressions). The words between the `[[` and `]]` do not undergo word splitting and filename expansion. The shell performs tilde expansion, parameter and variable expansion, arithmetic expansion, command substitution, process substitution, and quote removal on those words (the expansions that would occur if the words were enclosed in double quotes). Conditional operators such as β€˜`-f`’ must be unquoted to be recognized as primaries. When used with `[[`, the β€˜`<`’ and β€˜`>`’ operators sort lexicographically using the current locale. When the β€˜`==`’ and β€˜`!=`’ operators are used, the string to the right of the operator is considered a pattern and matched according to the rules described below in [Pattern Matching](pattern-matching), as if the `extglob` shell option were enabled. The β€˜`=`’ operator is identical to β€˜`==`’. If the `nocasematch` shell option (see the description of `shopt` in [The Shopt Builtin](the-shopt-builtin)) is enabled, the match is performed without regard to the case of alphabetic characters. The return value is 0 if the string matches (β€˜`==`’) or does not match (β€˜`!=`’) the pattern, and 1 otherwise. If you quote any part of the pattern, using any of the shell’s quoting mechanisms, the quoted portion is matched literally. This means every character in the quoted portion matches itself, instead of having any special pattern matching meaning. An additional binary operator, β€˜`=~`’, is available, with the same precedence as β€˜`==`’ and β€˜`!=`’. When you use β€˜`=~`’, the string to the right of the operator is considered a POSIX extended regular expression pattern and matched accordingly (using the POSIX `regcomp` and `regexec` interfaces usually described in *regex*(3)). The return value is 0 if the string matches the pattern, and 1 if it does not. If the regular expression is syntactically incorrect, the conditional expression returns 2. If the `nocasematch` shell option (see the description of `shopt` in [The Shopt Builtin](the-shopt-builtin)) is enabled, the match is performed without regard to the case of alphabetic characters. You can quote any part of the pattern to force the quoted portion to be matched literally instead of as a regular expression (see above). If the pattern is stored in a shell variable, quoting the variable expansion forces the entire pattern to be matched literally. The pattern will match if it matches any part of the string. If you want to force the pattern to match the entire string, anchor the pattern using the β€˜`^`’ and β€˜`$`’ regular expression operators. For example, the following will match a line (stored in the shell variable `line`) if there is a sequence of characters anywhere in the value consisting of any number, including zero, of characters in the `space` character class, immediately followed by zero or one instances of β€˜`a`’, then a β€˜`b`’: ``` [[ $line =~ [[:space:]]*(a)?b ]] ``` That means values for `line` like β€˜`aab`’, β€˜ `aaaaaab`’, β€˜`xaby`’, and β€˜ `ab`’ will all match, as will a line containing a β€˜`b`’ anywhere in its value. If you want to match a character that’s special to the regular expression grammar (β€˜`^$|[]()\.\*+?`’), it has to be quoted to remove its special meaning. This means that in the pattern β€˜`xxx.txt`’, the β€˜`.`’ matches any character in the string (its usual regular expression meaning), but in the pattern β€˜`"xxx.txt"`’, it can only match a literal β€˜`.`’. Likewise, if you want to include a character in your pattern that has a special meaning to the regular expression grammar, you must make sure it’s not quoted. If you want to anchor a pattern at the beginning or end of the string, for instance, you cannot quote the β€˜`^`’ or β€˜`$`’ characters using any form of shell quoting. If you want to match β€˜`initial string`’ at the start of a line, the following will work: ``` [[ $line =~ ^"initial string" ]] ``` but this will not: ``` [[ $line =~ "^initial string" ]] ``` because in the second example the β€˜`^`’ is quoted and doesn’t have its usual special meaning. It is sometimes difficult to specify a regular expression properly without using quotes, or to keep track of the quoting used by regular expressions while paying attention to shell quoting and the shell’s quote removal. Storing the regular expression in a shell variable is often a useful way to avoid problems with quoting characters that are special to the shell. For example, the following is equivalent to the pattern used above: ``` pattern='[[:space:]]*(a)?b' [[ $line =~ $pattern ]] ``` Shell programmers should take special care with backslashes, since backslashes are used by both the shell and regular expressions to remove the special meaning from the following character. This means that after the shell’s word expansions complete (see [Shell Expansions](shell-expansions)), any backslashes remaining in parts of the pattern that were originally not quoted can remove the special meaning of pattern characters. If any part of the pattern is quoted, the shell does its best to ensure that the regular expression treats those remaining backslashes as literal, if they appeared in a quoted portion. The following two sets of commands are *not* equivalent: ``` pattern='\.' [[ . =~ $pattern ]] [[ . =~ \. ]] [[ . =~ "$pattern" ]] [[ . =~ '\.' ]] ``` The first two matches will succeed, but the second two will not, because in the second two the backslash will be part of the pattern to be matched. In the first two examples, the pattern passed to the regular expression parser is β€˜`\.`’. The backslash removes the special meaning from β€˜`.`’, so the literal β€˜`.`’ matches. In the second two examples, the pattern passed to the regular expression parser has the backslash quoted (e.g., β€˜`\\\.`’), which will not match the string, since it does not contain a backslash. If the string in the first examples were anything other than β€˜`.`’, say β€˜`a`’, the pattern would not match, because the quoted β€˜`.`’ in the pattern loses its special meaning of matching any single character. Bracket expressions in regular expressions can be sources of errors as well, since characters that are normally special in regular expressions lose their special meanings between brackets. However, you can use bracket expressions to match special pattern characters without quoting them, so they are sometimes useful for this purpose. Though it might seem like a strange way to write it, the following pattern will match a β€˜`.`’ in the string: ``` [[ . =~ [.] ]] ``` The shell performs any word expansions before passing the pattern to the regular expression functions, so you can assume that the shell’s quoting takes precedence. As noted above, the regular expression parser will interpret any unquoted backslashes remaining in the pattern after shell expansion according to its own rules. The intention is to avoid making shell programmers quote things twice as much as possible, so shell quoting should be sufficient to quote special pattern characters where that’s necessary. The array variable `BASH_REMATCH` records which parts of the string matched the pattern. The element of `BASH_REMATCH` with index 0 contains the portion of the string matching the entire regular expression. Substrings matched by parenthesized subexpressions within the regular expression are saved in the remaining `BASH_REMATCH` indices. The element of `BASH_REMATCH` with index n is the portion of the string matching the nth parenthesized subexpression. Bash sets `BASH_REMATCH` in the global scope; declaring it as a local variable will lead to unexpected results. Expressions may be combined using the following operators, listed in decreasing order of precedence: `( expression )` Returns the value of expression. This may be used to override the normal precedence of operators. `! expression` True if expression is false. `expression1 && expression2` True if both expression1 and expression2 are true. `expression1 || expression2` True if either expression1 or expression2 is true. The `&&` and `||` operators do not evaluate expression2 if the value of expression1 is sufficient to determine the return value of the entire conditional expression.
programming_docs
bash Index of Shell Reserved Words Index of Shell Reserved Words ============================= | | | | --- | --- | | Jump to: | [**!**](#Reserved-Word-Index_rw_symbol-1) [**[**](#Reserved-Word-Index_rw_symbol-2) [**]**](#Reserved-Word-Index_rw_symbol-3) [**{**](#Reserved-Word-Index_rw_symbol-4) [**}**](#Reserved-Word-Index_rw_symbol-5) [**C**](#Reserved-Word-Index_rw_letter-C) [**D**](#Reserved-Word-Index_rw_letter-D) [**E**](#Reserved-Word-Index_rw_letter-E) [**F**](#Reserved-Word-Index_rw_letter-F) [**I**](#Reserved-Word-Index_rw_letter-I) [**S**](#Reserved-Word-Index_rw_letter-S) [**T**](#Reserved-Word-Index_rw_letter-T) [**U**](#Reserved-Word-Index_rw_letter-U) [**W**](#Reserved-Word-Index_rw_letter-W) | | | | | | --- | --- | --- | | | Index Entry | Section | | ! | | | | | [`!`](pipelines#!) | [Pipelines](pipelines#Pipelines) | | [ | | | | | [`[[`](conditional-constructs#%5B%5B) | [Conditional Constructs](conditional-constructs#Conditional%20Constructs) | | ] | | | | | [`]]`](conditional-constructs#%5D%5D) | [Conditional Constructs](conditional-constructs#Conditional%20Constructs) | | { | | | | | [`{`](command-grouping#%7B) | [Command Grouping](command-grouping#Command%20Grouping) | | } | | | | | [`}`](command-grouping#%7D) | [Command Grouping](command-grouping#Command%20Grouping) | | C | | | | | [`case`](conditional-constructs#case) | [Conditional Constructs](conditional-constructs#Conditional%20Constructs) | | D | | | | | [`do`](looping-constructs#do) | [Looping Constructs](looping-constructs#Looping%20Constructs) | | | [`done`](looping-constructs#done) | [Looping Constructs](looping-constructs#Looping%20Constructs) | | E | | | | | [`elif`](conditional-constructs#elif) | [Conditional Constructs](conditional-constructs#Conditional%20Constructs) | | | [`else`](conditional-constructs#else) | [Conditional Constructs](conditional-constructs#Conditional%20Constructs) | | | [`esac`](conditional-constructs#esac) | [Conditional Constructs](conditional-constructs#Conditional%20Constructs) | | F | | | | | [`fi`](conditional-constructs#fi) | [Conditional Constructs](conditional-constructs#Conditional%20Constructs) | | | [`for`](looping-constructs#for) | [Looping Constructs](looping-constructs#Looping%20Constructs) | | | [`function`](shell-functions#function) | [Shell Functions](shell-functions#Shell%20Functions) | | I | | | | | [`if`](conditional-constructs#if) | [Conditional Constructs](conditional-constructs#Conditional%20Constructs) | | | [`in`](conditional-constructs#in) | [Conditional Constructs](conditional-constructs#Conditional%20Constructs) | | S | | | | | [`select`](conditional-constructs#select) | [Conditional Constructs](conditional-constructs#Conditional%20Constructs) | | T | | | | | [`then`](conditional-constructs#then) | [Conditional Constructs](conditional-constructs#Conditional%20Constructs) | | | [`time`](pipelines#time) | [Pipelines](pipelines#Pipelines) | | U | | | | | [`until`](looping-constructs#until) | [Looping Constructs](looping-constructs#Looping%20Constructs) | | W | | | | | [`while`](looping-constructs#while) | [Looping Constructs](looping-constructs#Looping%20Constructs) | | | | | --- | --- | | Jump to: | [**!**](#Reserved-Word-Index_rw_symbol-1) [**[**](#Reserved-Word-Index_rw_symbol-2) [**]**](#Reserved-Word-Index_rw_symbol-3) [**{**](#Reserved-Word-Index_rw_symbol-4) [**}**](#Reserved-Word-Index_rw_symbol-5) [**C**](#Reserved-Word-Index_rw_letter-C) [**D**](#Reserved-Word-Index_rw_letter-D) [**E**](#Reserved-Word-Index_rw_letter-E) [**F**](#Reserved-Word-Index_rw_letter-F) [**I**](#Reserved-Word-Index_rw_letter-I) [**S**](#Reserved-Word-Index_rw_letter-S) [**T**](#Reserved-Word-Index_rw_letter-T) [**U**](#Reserved-Word-Index_rw_letter-U) [**W**](#Reserved-Word-Index_rw_letter-W) | bash Simple Commands Simple Commands =============== A simple command is the kind of command encountered most often. It’s just a sequence of words separated by `blank`s, terminated by one of the shell’s control operators (see [Definitions](definitions)). The first word generally specifies a command to be executed, with the rest of the words being that command’s arguments. The return status (see [Exit Status](exit-status)) of a simple command is its exit status as provided by the POSIX 1003.1 `waitpid` function, or 128+n if the command was terminated by signal n. bash Compilers and Options Compilers and Options ===================== Some systems require unusual options for compilation or linking that the `configure` script does not know about. You can give `configure` initial values for variables by setting them in the environment. Using a Bourne-compatible shell, you can do that on the command line like this: ``` CC=c89 CFLAGS=-O2 LIBS=-lposix ./configure ``` On systems that have the `env` program, you can do it like this: ``` env CPPFLAGS=-I/usr/local/include LDFLAGS=-s ./configure ``` The configuration process uses GCC to build Bash if it is available. bash Exit Status Exit Status =========== The exit status of an executed command is the value returned by the `waitpid` system call or equivalent function. Exit statuses fall between 0 and 255, though, as explained below, the shell may use values above 125 specially. Exit statuses from shell builtins and compound commands are also limited to this range. Under certain circumstances, the shell will use special values to indicate specific failure modes. For the shell’s purposes, a command which exits with a zero exit status has succeeded. A non-zero exit status indicates failure. This seemingly counter-intuitive scheme is used so there is one well-defined way to indicate success and a variety of ways to indicate various failure modes. When a command terminates on a fatal signal whose number is N, Bash uses the value 128+N as the exit status. If a command is not found, the child process created to execute it returns a status of 127. If a command is found but is not executable, the return status is 126. If a command fails because of an error during expansion or redirection, the exit status is greater than zero. The exit status is used by the Bash conditional commands (see [Conditional Constructs](conditional-constructs)) and some of the list constructs (see [Lists of Commands](lists)). All of the Bash builtins return an exit status of zero if they succeed and a non-zero status on failure, so they may be used by the conditional and list constructs. All builtins return an exit status of 2 to indicate incorrect usage, generally invalid options or missing arguments. The exit status of the last command is available in the special parameter $? (see [Special Parameters](special-parameters)). bash Shell Expansions Shell Expansions ================ Expansion is performed on the command line after it has been split into `token`s. There are seven kinds of expansion performed: * brace expansion * tilde expansion * parameter and variable expansion * command substitution * arithmetic expansion * word splitting * filename expansion The order of expansions is: brace expansion; tilde expansion, parameter and variable expansion, arithmetic expansion, and command substitution (done in a left-to-right fashion); word splitting; and filename expansion. On systems that can support it, there is an additional expansion available: *process substitution*. This is performed at the same time as tilde, parameter, variable, and arithmetic expansion and command substitution. After these expansions are performed, quote characters present in the original word are removed unless they have been quoted themselves (*quote removal*). Only brace expansion, word splitting, and filename expansion can increase the number of words of the expansion; other expansions expand a single word to a single word. The only exceptions to this are the expansions of `"$@"` and `$*` (see [Special Parameters](special-parameters)), and `"${name[@]}"` and `${name[*]}` (see [Arrays](arrays)). After all expansions, `quote removal` (see [Quote Removal](quote-removal)) is performed. * [Brace Expansion](brace-expansion) * [Tilde Expansion](tilde-expansion) * [Shell Parameter Expansion](shell-parameter-expansion) * [Command Substitution](command-substitution) * [Arithmetic Expansion](arithmetic-expansion) * [Process Substitution](process-substitution) * [Word Splitting](word-splitting) * [Filename Expansion](filename-expansion) * [Quote Removal](quote-removal) bash What is a shell? What is a shell? ================ At its base, a shell is simply a macro processor that executes commands. The term macro processor means functionality where text and symbols are expanded to create larger expressions. A Unix shell is both a command interpreter and a programming language. As a command interpreter, the shell provides the user interface to the rich set of GNU utilities. The programming language features allow these utilities to be combined. Files containing commands can be created, and become commands themselves. These new commands have the same status as system commands in directories such as `/bin`, allowing users or groups to establish custom environments to automate their common tasks. Shells may be used interactively or non-interactively. In interactive mode, they accept input typed from the keyboard. When executing non-interactively, shells execute commands read from a file. A shell allows execution of GNU commands, both synchronously and asynchronously. The shell waits for synchronous commands to complete before accepting more input; asynchronous commands continue to execute in parallel with the shell while it reads and executes additional commands. The *redirection* constructs permit fine-grained control of the input and output of those commands. Moreover, the shell allows control over the contents of commands’ environments. Shells also provide a small set of built-in commands (*builtins*) implementing functionality impossible or inconvenient to obtain via separate utilities. For example, `cd`, `break`, `continue`, and `exec` cannot be implemented outside of the shell because they directly manipulate the shell itself. The `history`, `getopts`, `kill`, or `pwd` builtins, among others, could be implemented in separate utilities, but they are more convenient to use as builtin commands. All of the shell builtins are described in subsequent sections. While executing commands is essential, most of the power (and complexity) of shells is due to their embedded programming languages. Like any high-level language, the shell provides variables, flow control constructs, quoting, and functions. Shells offer features geared specifically for interactive use rather than to augment the programming language. These interactive features include job control, command line editing, command history and aliases. Each of these features is described in this manual. bash Process Substitution Process Substitution ==================== Process substitution allows a process’s input or output to be referred to using a filename. It takes the form of ``` <(list) ``` or ``` >(list) ``` The process list is run asynchronously, and its input or output appears as a filename. This filename is passed as an argument to the current command as the result of the expansion. If the `>(list)` form is used, writing to the file will provide input for list. If the `<(list)` form is used, the file passed as an argument should be read to obtain the output of list. Note that no space may appear between the `<` or `>` and the left parenthesis, otherwise the construct would be interpreted as a redirection. Process substitution is supported on systems that support named pipes (FIFOs) or the `/dev/fd` method of naming open files. When available, process substitution is performed simultaneously with parameter and variable expansion, command substitution, and arithmetic expansion. bash Double Quotes Double Quotes ============= Enclosing characters in double quotes (β€˜`"`’) preserves the literal value of all characters within the quotes, with the exception of β€˜`$`’, β€˜```’, β€˜`\`’, and, when history expansion is enabled, β€˜`!`’. When the shell is in POSIX mode (see [Bash POSIX Mode](bash-posix-mode)), the β€˜`!`’ has no special meaning within double quotes, even when history expansion is enabled. The characters β€˜`$`’ and β€˜```’ retain their special meaning within double quotes (see [Shell Expansions](shell-expansions)). The backslash retains its special meaning only when followed by one of the following characters: β€˜`$`’, β€˜```’, β€˜`"`’, β€˜`\`’, or `newline`. Within double quotes, backslashes that are followed by one of these characters are removed. Backslashes preceding characters without a special meaning are left unmodified. A double quote may be quoted within double quotes by preceding it with a backslash. If enabled, history expansion will be performed unless an β€˜`!`’ appearing in double quotes is escaped using a backslash. The backslash preceding the β€˜`!`’ is not removed. The special parameters β€˜`\*`’ and β€˜`@`’ have special meaning when in double quotes (see [Shell Parameter Expansion](shell-parameter-expansion)). bash Compound Commands Compound Commands ================= Compound commands are the shell programming language constructs. Each construct begins with a reserved word or control operator and is terminated by a corresponding reserved word or operator. Any redirections (see [Redirections](redirections)) associated with a compound command apply to all commands within that compound command unless explicitly overridden. In most cases a list of commands in a compound command’s description may be separated from the rest of the command by one or more newlines, and may be followed by a newline in place of a semicolon. Bash provides looping constructs, conditional commands, and mechanisms to group commands and execute them as a unit. * [Looping Constructs](looping-constructs) * [Conditional Constructs](conditional-constructs) * [Grouping Commands](command-grouping) bash Bash Features Bash Features ============= This chapter describes features unique to Bash. * [Invoking Bash](invoking-bash) * [Bash Startup Files](bash-startup-files) * [Interactive Shells](interactive-shells) * [Bash Conditional Expressions](bash-conditional-expressions) * [Shell Arithmetic](shell-arithmetic) * [Aliases](aliases) * [Arrays](arrays) * [The Directory Stack](the-directory-stack) * [Controlling the Prompt](controlling-the-prompt) * [The Restricted Shell](the-restricted-shell) * [Bash POSIX Mode](bash-posix-mode) * [Shell Compatibility Mode](shell-compatibility-mode) bash Lists of Commands Lists of Commands ================= A `list` is a sequence of one or more pipelines separated by one of the operators β€˜`;`’, β€˜`&`’, β€˜`&&`’, or β€˜`||`’, and optionally terminated by one of β€˜`;`’, β€˜`&`’, or a `newline`. Of these list operators, β€˜`&&`’ and β€˜`||`’ have equal precedence, followed by β€˜`;`’ and β€˜`&`’, which have equal precedence. A sequence of one or more newlines may appear in a `list` to delimit commands, equivalent to a semicolon. If a command is terminated by the control operator β€˜`&`’, the shell executes the command asynchronously in a subshell. This is known as executing the command in the *background*, and these are referred to as *asynchronous* commands. The shell does not wait for the command to finish, and the return status is 0 (true). When job control is not active (see [Job Control](job-control)), the standard input for asynchronous commands, in the absence of any explicit redirections, is redirected from `/dev/null`. Commands separated by a β€˜`;`’ are executed sequentially; the shell waits for each command to terminate in turn. The return status is the exit status of the last command executed. AND and OR lists are sequences of one or more pipelines separated by the control operators β€˜`&&`’ and β€˜`||`’, respectively. AND and OR lists are executed with left associativity. An AND list has the form ``` command1 && command2 ``` command2 is executed if, and only if, command1 returns an exit status of zero (success). An OR list has the form ``` command1 || command2 ``` command2 is executed if, and only if, command1 returns a non-zero exit status. The return status of AND and OR lists is the exit status of the last command executed in the list. bash Redirections Redirections ============ Before a command is executed, its input and output may be *redirected* using a special notation interpreted by the shell. *Redirection* allows commands’ file handles to be duplicated, opened, closed, made to refer to different files, and can change the files the command reads from and writes to. Redirection may also be used to modify file handles in the current shell execution environment. The following redirection operators may precede or appear anywhere within a simple command or may follow a command. Redirections are processed in the order they appear, from left to right. Each redirection that may be preceded by a file descriptor number may instead be preceded by a word of the form {varname}. In this case, for each redirection operator except >&- and <&-, the shell will allocate a file descriptor greater than 10 and assign it to {varname}. If >&- or <&- is preceded by {varname}, the value of varname defines the file descriptor to close. If {varname} is supplied, the redirection persists beyond the scope of the command, allowing the shell programmer to manage the file descriptor’s lifetime manually. The `varredir_close` shell option manages this behavior (see [The Shopt Builtin](the-shopt-builtin)). In the following descriptions, if the file descriptor number is omitted, and the first character of the redirection operator is β€˜`<`’, the redirection refers to the standard input (file descriptor 0). If the first character of the redirection operator is β€˜`>`’, the redirection refers to the standard output (file descriptor 1). The word following the redirection operator in the following descriptions, unless otherwise noted, is subjected to brace expansion, tilde expansion, parameter expansion, command substitution, arithmetic expansion, quote removal, filename expansion, and word splitting. If it expands to more than one word, Bash reports an error. Note that the order of redirections is significant. For example, the command ``` ls > dirlist 2>&1 ``` directs both standard output (file descriptor 1) and standard error (file descriptor 2) to the file dirlist, while the command ``` ls 2>&1 > dirlist ``` directs only the standard output to file dirlist, because the standard error was made a copy of the standard output before the standard output was redirected to dirlist. Bash handles several filenames specially when they are used in redirections, as described in the following table. If the operating system on which Bash is running provides these special files, bash will use them; otherwise it will emulate them internally with the behavior described below. `/dev/fd/fd` If fd is a valid integer, file descriptor fd is duplicated. `/dev/stdin` File descriptor 0 is duplicated. `/dev/stdout` File descriptor 1 is duplicated. `/dev/stderr` File descriptor 2 is duplicated. `/dev/tcp/host/port` If host is a valid hostname or Internet address, and port is an integer port number or service name, Bash attempts to open the corresponding TCP socket. `/dev/udp/host/port` If host is a valid hostname or Internet address, and port is an integer port number or service name, Bash attempts to open the corresponding UDP socket. A failure to open or create a file causes the redirection to fail. Redirections using file descriptors greater than 9 should be used with care, as they may conflict with file descriptors the shell uses internally. * [Redirecting Input](#Redirecting-Input) * [Redirecting Output](#Redirecting-Output) * [Appending Redirected Output](#Appending-Redirected-Output) * [Redirecting Standard Output and Standard Error](#Redirecting-Standard-Output-and-Standard-Error) * [Appending Standard Output and Standard Error](#Appending-Standard-Output-and-Standard-Error) * [Here Documents](#Here-Documents) * [Here Strings](#Here-Strings) * [Duplicating File Descriptors](#Duplicating-File-Descriptors) * [Moving File Descriptors](#Moving-File-Descriptors) * [Opening File Descriptors for Reading and Writing](#Opening-File-Descriptors-for-Reading-and-Writing) #### 3.6.1 Redirecting Input Redirection of input causes the file whose name results from the expansion of word to be opened for reading on file descriptor `n`, or the standard input (file descriptor 0) if `n` is not specified. The general format for redirecting input is: ``` [n]<word ``` #### 3.6.2 Redirecting Output Redirection of output causes the file whose name results from the expansion of word to be opened for writing on file descriptor n, or the standard output (file descriptor 1) if n is not specified. If the file does not exist it is created; if it does exist it is truncated to zero size. The general format for redirecting output is: ``` [n]>[|]word ``` If the redirection operator is β€˜`>`’, and the `noclobber` option to the `set` builtin has been enabled, the redirection will fail if the file whose name results from the expansion of word exists and is a regular file. If the redirection operator is β€˜`>|`’, or the redirection operator is β€˜`>`’ and the `noclobber` option is not enabled, the redirection is attempted even if the file named by word exists. #### 3.6.3 Appending Redirected Output Redirection of output in this fashion causes the file whose name results from the expansion of word to be opened for appending on file descriptor n, or the standard output (file descriptor 1) if n is not specified. If the file does not exist it is created. The general format for appending output is: ``` [n]>>word ``` #### 3.6.4 Redirecting Standard Output and Standard Error This construct allows both the standard output (file descriptor 1) and the standard error output (file descriptor 2) to be redirected to the file whose name is the expansion of word. There are two formats for redirecting standard output and standard error: ``` &>word ``` and ``` >&word ``` Of the two forms, the first is preferred. This is semantically equivalent to ``` >word 2>&1 ``` When using the second form, word may not expand to a number or β€˜`-`’. If it does, other redirection operators apply (see Duplicating File Descriptors below) for compatibility reasons. #### 3.6.5 Appending Standard Output and Standard Error This construct allows both the standard output (file descriptor 1) and the standard error output (file descriptor 2) to be appended to the file whose name is the expansion of word. The format for appending standard output and standard error is: ``` &>>word ``` This is semantically equivalent to ``` >>word 2>&1 ``` (see Duplicating File Descriptors below). #### 3.6.6 Here Documents This type of redirection instructs the shell to read input from the current source until a line containing only word (with no trailing blanks) is seen. All of the lines read up to that point are then used as the standard input (or file descriptor n if n is specified) for a command. The format of here-documents is: ``` [n]<<[-]word here-document delimiter ``` No parameter and variable expansion, command substitution, arithmetic expansion, or filename expansion is performed on word. If any part of word is quoted, the delimiter is the result of quote removal on word, and the lines in the here-document are not expanded. If word is unquoted, all lines of the here-document are subjected to parameter expansion, command substitution, and arithmetic expansion, the character sequence `\newline` is ignored, and β€˜`\`’ must be used to quote the characters β€˜`\`’, β€˜`$`’, and β€˜```’. If the redirection operator is β€˜`<<-`’, then all leading tab characters are stripped from input lines and the line containing delimiter. This allows here-documents within shell scripts to be indented in a natural fashion. #### 3.6.7 Here Strings A variant of here documents, the format is: ``` [n]<<< word ``` The word undergoes tilde expansion, parameter and variable expansion, command substitution, arithmetic expansion, and quote removal. Filename expansion and word splitting are not performed. The result is supplied as a single string, with a newline appended, to the command on its standard input (or file descriptor n if n is specified). #### 3.6.8 Duplicating File Descriptors The redirection operator ``` [n]<&word ``` is used to duplicate input file descriptors. If word expands to one or more digits, the file descriptor denoted by n is made to be a copy of that file descriptor. If the digits in word do not specify a file descriptor open for input, a redirection error occurs. If word evaluates to β€˜`-`’, file descriptor n is closed. If n is not specified, the standard input (file descriptor 0) is used. The operator ``` [n]>&word ``` is used similarly to duplicate output file descriptors. If n is not specified, the standard output (file descriptor 1) is used. If the digits in word do not specify a file descriptor open for output, a redirection error occurs. If word evaluates to β€˜`-`’, file descriptor n is closed. As a special case, if n is omitted, and word does not expand to one or more digits or β€˜`-`’, the standard output and standard error are redirected as described previously. #### 3.6.9 Moving File Descriptors The redirection operator ``` [n]<&digit- ``` moves the file descriptor digit to file descriptor n, or the standard input (file descriptor 0) if n is not specified. digit is closed after being duplicated to n. Similarly, the redirection operator ``` [n]>&digit- ``` moves the file descriptor digit to file descriptor n, or the standard output (file descriptor 1) if n is not specified. #### 3.6.10 Opening File Descriptors for Reading and Writing The redirection operator ``` [n]<>word ``` causes the file whose name is the expansion of word to be opened for both reading and writing on file descriptor n, or on file descriptor 0 if n is not specified. If the file does not exist, it is created.
programming_docs
bash A Programmable Completion Example A Programmable Completion Example ================================= The most common way to obtain additional completion functionality beyond the default actions `complete` and `compgen` provide is to use a shell function and bind it to a particular command using `complete -F`. The following function provides completions for the `cd` builtin. It is a reasonably good example of what shell functions must do when used for completion. This function uses the word passed as `$2` to determine the directory name to complete. You can also use the `COMP_WORDS` array variable; the current word is indexed by the `COMP_CWORD` variable. The function relies on the `complete` and `compgen` builtins to do much of the work, adding only the things that the Bash `cd` does beyond accepting basic directory names: tilde expansion (see [Tilde Expansion](tilde-expansion)), searching directories in $CDPATH, which is described above (see [Bourne Shell Builtins](bourne-shell-builtins)), and basic support for the `cdable_vars` shell option (see [The Shopt Builtin](the-shopt-builtin)). `_comp_cd` modifies the value of IFS so that it contains only a newline to accommodate file names containing spaces and tabs – `compgen` prints the possible completions it generates one per line. Possible completions go into the COMPREPLY array variable, one completion per array element. The programmable completion system retrieves the completions from there when the function returns. ``` # A completion function for the cd builtin # based on the cd completion function from the bash_completion package _comp_cd() { local IFS=$' \t\n' # normalize IFS local cur _skipdot _cdpath local i j k # Tilde expansion, which also expands tilde to full pathname case "$2" in \~*) eval cur="$2" ;; *) cur=$2 ;; esac # no cdpath or absolute pathname -- straight directory completion if [[ -z "${CDPATH:-}" ]] || [[ "$cur" == @(./*|../*|/*) ]]; then # compgen prints paths one per line; could also use while loop IFS=$'\n' COMPREPLY=( $(compgen -d -- "$cur") ) IFS=$' \t\n' # CDPATH+directories in the current directory if not in CDPATH else IFS=$'\n' _skipdot=false # preprocess CDPATH to convert null directory names to . _cdpath=${CDPATH/#:/.:} _cdpath=${_cdpath//::/:.:} _cdpath=${_cdpath/%:/:.} for i in ${_cdpath//:/$'\n'}; do if [[ $i -ef . ]]; then _skipdot=true; fi k="${#COMPREPLY[@]}" for j in $( compgen -d -- "$i/$cur" ); do COMPREPLY[k++]=${j#$i/} # cut off directory done done $_skipdot || COMPREPLY+=( $(compgen -d -- "$cur") ) IFS=$' \t\n' fi # variable names if appropriate shell option set and no completions if shopt -q cdable_vars && [[ ${#COMPREPLY[@]} -eq 0 ]]; then COMPREPLY=( $(compgen -v -- "$cur") ) fi return 0 } ``` We install the completion function using the `-F` option to `complete`: ``` # Tell readline to quote appropriate and append slashes to directories; # use the bash default completion for other arguments complete -o filenames -o nospace -o bashdefault -F _comp_cd cd ``` Since we’d like Bash and Readline to take care of some of the other details for us, we use several other options to tell Bash and Readline what to do. The `-o filenames` option tells Readline that the possible completions should be treated as filenames, and quoted appropriately. That option will also cause Readline to append a slash to filenames it can determine are directories (which is why we might want to extend `_comp_cd` to append a slash if we’re using directories found via CDPATH: Readline can’t tell those completions are directories). The `-o nospace` option tells Readline to not append a space character to the directory name, in case we want to append to it. The `-o bashdefault` option brings in the rest of the "Bash default" completions – possible completions that Bash adds to the default Readline set. These include things like command name completion, variable completion for words beginning with β€˜`$`’ or β€˜`${`’, completions containing pathname expansion patterns (see [Filename Expansion](filename-expansion)), and so on. Once installed using `complete`, `_comp_cd` will be called every time we attempt word completion for a `cd` command. Many more examples – an extensive collection of completions for most of the common GNU, Unix, and Linux commands – are available as part of the bash\_completion project. This is installed by default on many GNU/Linux distributions. Originally written by Ian Macdonald, the project now lives at <https://github.com/scop/bash-completion/>. There are ports for other systems such as Solaris and Mac OS X. An older version of the bash\_completion package is distributed with bash in the `examples/complete` subdirectory. bash Readline Killing Commands Readline Killing Commands ========================= *Killing* text means to delete the text from the line, but to save it away for later use, usually by *yanking* (re-inserting) it back into the line. (β€˜Cut’ and β€˜paste’ are more recent jargon for β€˜kill’ and β€˜yank’.) If the description for a command says that it β€˜kills’ text, then you can be sure that you can get the text back in a different (or the same) place later. When you use a kill command, the text is saved in a *kill-ring*. Any number of consecutive kills save all of the killed text together, so that when you yank it back, you get it all. The kill ring is not line specific; the text that you killed on a previously typed line is available to be yanked back later, when you are typing another line. Here is the list of commands for killing text. `C-k` Kill the text from the current cursor position to the end of the line. `M-d` Kill from the cursor to the end of the current word, or, if between words, to the end of the next word. Word boundaries are the same as those used by `M-f`. `M-DEL` Kill from the cursor to the start of the current word, or, if between words, to the start of the previous word. Word boundaries are the same as those used by `M-b`. `C-w` Kill from the cursor to the previous whitespace. This is different than `M-DEL` because the word boundaries differ. Here is how to *yank* the text back into the line. Yanking means to copy the most-recently-killed text from the kill buffer. `C-y` Yank the most recently killed text back into the buffer at the cursor. `M-y` Rotate the kill-ring, and yank the new top. You can only do this if the prior command is `C-y` or `M-y`. bash Bash History Builtins Bash History Builtins ===================== Bash provides two builtin commands which manipulate the history list and history file. `fc` ``` fc [-e ename] [-lnr] [first] [last] fc -s [pat=rep] [command] ``` The first form selects a range of commands from first to last from the history list and displays or edits and re-executes them. Both first and last may be specified as a string (to locate the most recent command beginning with that string) or as a number (an index into the history list, where a negative number is used as an offset from the current command number). When listing, a first or last of 0 is equivalent to -1 and -0 is equivalent to the current command (usually the `fc` command); otherwise 0 is equivalent to -1 and -0 is invalid. If last is not specified, it is set to first. If first is not specified, it is set to the previous command for editing and -16 for listing. If the `-l` flag is given, the commands are listed on standard output. The `-n` flag suppresses the command numbers when listing. The `-r` flag reverses the order of the listing. Otherwise, the editor given by ename is invoked on a file containing those commands. If ename is not given, the value of the following variable expansion is used: `${FCEDIT:-${EDITOR:-vi}}`. This says to use the value of the `FCEDIT` variable if set, or the value of the `EDITOR` variable if that is set, or `vi` if neither is set. When editing is complete, the edited commands are echoed and executed. In the second form, command is re-executed after each instance of pat in the selected command is replaced by rep. command is interpreted the same as first above. A useful alias to use with the `fc` command is `r='fc -s'`, so that typing β€˜`r cc`’ runs the last command beginning with `cc` and typing β€˜`r`’ re-executes the last command (see [Aliases](aliases)). `history` ``` history [n] history -c history -d offset history -d start-end history [-anrw] [filename] history -ps arg ``` With no options, display the history list with line numbers. Lines prefixed with a β€˜`\*`’ have been modified. An argument of n lists only the last n lines. If the shell variable `HISTTIMEFORMAT` is set and not null, it is used as a format string for strftime to display the time stamp associated with each displayed history entry. No intervening blank is printed between the formatted time stamp and the history line. Options, if supplied, have the following meanings: `-c` Clear the history list. This may be combined with the other options to replace the history list completely. `-d offset` Delete the history entry at position offset. If offset is positive, it should be specified as it appears when the history is displayed. If offset is negative, it is interpreted as relative to one greater than the last history position, so negative indices count back from the end of the history, and an index of β€˜`-1`’ refers to the current `history -d` command. `-d start-end` Delete the range of history entries between positions start and end, inclusive. Positive and negative values for start and end are interpreted as described above. `-a` Append the new history lines to the history file. These are history lines entered since the beginning of the current Bash session, but not already appended to the history file. `-n` Append the history lines not already read from the history file to the current history list. These are lines appended to the history file since the beginning of the current Bash session. `-r` Read the history file and append its contents to the history list. `-w` Write out the current history list to the history file. `-p` Perform history substitution on the args and display the result on the standard output, without storing the results in the history list. `-s` The args are added to the end of the history list as a single entry. If a filename argument is supplied when any of the `-w`, `-r`, `-a`, or `-n` options is used, Bash uses filename as the history file. If not, then the value of the `HISTFILE` variable is used. The return value is 0 unless an invalid option is encountered, an error occurs while reading or writing the history file, an invalid offset or range is supplied as an argument to `-d`, or the history expansion supplied as an argument to `-p` fails. bash Appendix B Major Differences From The Bourne Shell Appendix B Major Differences From The Bourne Shell ================================================== Bash implements essentially the same grammar, parameter and variable expansion, redirection, and quoting as the Bourne Shell. Bash uses the POSIX standard as the specification of how these features are to be implemented. There are some differences between the traditional Bourne shell and Bash; this section quickly details the differences of significance. A number of these differences are explained in greater depth in previous sections. This section uses the version of `sh` included in SVR4.2 (the last version of the historical Bourne shell) as the baseline reference. * Bash is POSIX-conformant, even where the POSIX specification differs from traditional `sh` behavior (see [Bash POSIX Mode](bash-posix-mode)). * Bash has multi-character invocation options (see [Invoking Bash](invoking-bash)). * Bash has command-line editing (see [Command Line Editing](command-line-editing)) and the `bind` builtin. * Bash provides a programmable word completion mechanism (see [Programmable Completion](programmable-completion)), and builtin commands `complete`, `compgen`, and `compopt`, to manipulate it. * Bash has command history (see [Bash History Facilities](bash-history-facilities)) and the `history` and `fc` builtins to manipulate it. The Bash history list maintains timestamp information and uses the value of the `HISTTIMEFORMAT` variable to display it. * Bash implements `csh`-like history expansion (see [History Expansion](history-interaction)). * Bash has one-dimensional array variables (see [Arrays](arrays)), and the appropriate variable expansions and assignment syntax to use them. Several of the Bash builtins take options to act on arrays. Bash provides a number of built-in array variables. * The `$'…'` quoting syntax, which expands ANSI-C backslash-escaped characters in the text between the single quotes, is supported (see [ANSI-C Quoting](ansi_002dc-quoting)). * Bash supports the `$"…"` quoting syntax to do locale-specific translation of the characters between the double quotes. The `-D`, `--dump-strings`, and `--dump-po-strings` invocation options list the translatable strings found in a script (see [Locale-Specific Translation](locale-translation)). * Bash implements the `!` keyword to negate the return value of a pipeline (see [Pipelines](pipelines)). Very useful when an `if` statement needs to act only if a test fails. The Bash β€˜`-o pipefail`’ option to `set` will cause a pipeline to return a failure status if any command fails. * Bash has the `time` reserved word and command timing (see [Pipelines](pipelines)). The display of the timing statistics may be controlled with the `TIMEFORMAT` variable. * Bash implements the `for (( expr1 ; expr2 ; expr3 ))` arithmetic for command, similar to the C language (see [Looping Constructs](looping-constructs)). * Bash includes the `select` compound command, which allows the generation of simple menus (see [Conditional Constructs](conditional-constructs)). * Bash includes the `[[` compound command, which makes conditional testing part of the shell grammar (see [Conditional Constructs](conditional-constructs)), including optional regular expression matching. * Bash provides optional case-insensitive matching for the `case` and `[[` constructs. * Bash includes brace expansion (see [Brace Expansion](brace-expansion)) and tilde expansion (see [Tilde Expansion](tilde-expansion)). * Bash implements command aliases and the `alias` and `unalias` builtins (see [Aliases](aliases)). * Bash provides shell arithmetic, the `((` compound command (see [Conditional Constructs](conditional-constructs)), and arithmetic expansion (see [Shell Arithmetic](shell-arithmetic)). * Variables present in the shell’s initial environment are automatically exported to child processes. The Bourne shell does not normally do this unless the variables are explicitly marked using the `export` command. * Bash supports the β€˜`+=`’ assignment operator, which appends to the value of the variable named on the left hand side. * Bash includes the POSIX pattern removal β€˜`%`’, β€˜`#`’, β€˜`%%`’ and β€˜`##`’ expansions to remove leading or trailing substrings from variable values (see [Shell Parameter Expansion](shell-parameter-expansion)). * The expansion `${#xx}`, which returns the length of `${xx}`, is supported (see [Shell Parameter Expansion](shell-parameter-expansion)). * The expansion `${var:`offset`[:`length`]}`, which expands to the substring of `var`’s value of length length, beginning at offset, is present (see [Shell Parameter Expansion](shell-parameter-expansion)). * The expansion `${var/[/]`pattern`[/`replacement`]}`, which matches pattern and replaces it with replacement in the value of var, is available (see [Shell Parameter Expansion](shell-parameter-expansion)). * The expansion `${!prefix*}` expansion, which expands to the names of all shell variables whose names begin with prefix, is available (see [Shell Parameter Expansion](shell-parameter-expansion)). * Bash has indirect variable expansion using `${!word}` (see [Shell Parameter Expansion](shell-parameter-expansion)). * Bash can expand positional parameters beyond `$9` using `${num}`. * The POSIX `$()` form of command substitution is implemented (see [Command Substitution](command-substitution)), and preferred to the Bourne shell’s ```` (which is also implemented for backwards compatibility). * Bash has process substitution (see [Process Substitution](process-substitution)). * Bash automatically assigns variables that provide information about the current user (`UID`, `EUID`, and `GROUPS`), the current host (`HOSTTYPE`, `OSTYPE`, `MACHTYPE`, and `HOSTNAME`), and the instance of Bash that is running (`BASH`, `BASH_VERSION`, and `BASH_VERSINFO`). See [Bash Variables](bash-variables), for details. * The `IFS` variable is used to split only the results of expansion, not all words (see [Word Splitting](word-splitting)). This closes a longstanding shell security hole. * The filename expansion bracket expression code uses β€˜`!`’ and β€˜`^`’ to negate the set of characters between the brackets. The Bourne shell uses only β€˜`!`’. * Bash implements the full set of POSIX filename expansion operators, including character classes, equivalence classes, and collating symbols (see [Filename Expansion](filename-expansion)). * Bash implements extended pattern matching features when the `extglob` shell option is enabled (see [Pattern Matching](pattern-matching)). * It is possible to have a variable and a function with the same name; `sh` does not separate the two name spaces. * Bash functions are permitted to have local variables using the `local` builtin, and thus useful recursive functions may be written (see [Bash Builtin Commands](bash-builtins)). * Variable assignments preceding commands affect only that command, even builtins and functions (see [Environment](environment)). In `sh`, all variable assignments preceding commands are global unless the command is executed from the file system. * Bash performs filename expansion on filenames specified as operands to input and output redirection operators (see [Redirections](redirections)). * Bash contains the β€˜`<>`’ redirection operator, allowing a file to be opened for both reading and writing, and the β€˜`&>`’ redirection operator, for directing standard output and standard error to the same file (see [Redirections](redirections)). * Bash includes the β€˜`<<<`’ redirection operator, allowing a string to be used as the standard input to a command. * Bash implements the β€˜`[n]<&word`’ and β€˜`[n]>&word`’ redirection operators, which move one file descriptor to another. * Bash treats a number of filenames specially when they are used in redirection operators (see [Redirections](redirections)). * Bash can open network connections to arbitrary machines and services with the redirection operators (see [Redirections](redirections)). * The `noclobber` option is available to avoid overwriting existing files with output redirection (see [The Set Builtin](the-set-builtin)). The β€˜`>|`’ redirection operator may be used to override `noclobber`. * The Bash `cd` and `pwd` builtins (see [Bourne Shell Builtins](bourne-shell-builtins)) each take `-L` and `-P` options to switch between logical and physical modes. * Bash allows a function to override a builtin with the same name, and provides access to that builtin’s functionality within the function via the `builtin` and `command` builtins (see [Bash Builtin Commands](bash-builtins)). * The `command` builtin allows selective disabling of functions when command lookup is performed (see [Bash Builtin Commands](bash-builtins)). * Individual builtins may be enabled or disabled using the `enable` builtin (see [Bash Builtin Commands](bash-builtins)). * The Bash `exec` builtin takes additional options that allow users to control the contents of the environment passed to the executed command, and what the zeroth argument to the command is to be (see [Bourne Shell Builtins](bourne-shell-builtins)). * Shell functions may be exported to children via the environment using `export -f` (see [Shell Functions](shell-functions)). * The Bash `export`, `readonly`, and `declare` builtins can take a `-f` option to act on shell functions, a `-p` option to display variables with various attributes set in a format that can be used as shell input, a `-n` option to remove various variable attributes, and β€˜`name=value`’ arguments to set variable attributes and values simultaneously. * The Bash `hash` builtin allows a name to be associated with an arbitrary filename, even when that filename cannot be found by searching the `$PATH`, using β€˜`hash -p`’ (see [Bourne Shell Builtins](bourne-shell-builtins)). * Bash includes a `help` builtin for quick reference to shell facilities (see [Bash Builtin Commands](bash-builtins)). * The `printf` builtin is available to display formatted output (see [Bash Builtin Commands](bash-builtins)). * The Bash `read` builtin (see [Bash Builtin Commands](bash-builtins)) will read a line ending in β€˜`\`’ with the `-r` option, and will use the `REPLY` variable as a default if no non-option arguments are supplied. The Bash `read` builtin also accepts a prompt string with the `-p` option and will use Readline to obtain the line when given the `-e` option. The `read` builtin also has additional options to control input: the `-s` option will turn off echoing of input characters as they are read, the `-t` option will allow `read` to time out if input does not arrive within a specified number of seconds, the `-n` option will allow reading only a specified number of characters rather than a full line, and the `-d` option will read until a particular character rather than newline. * The `return` builtin may be used to abort execution of scripts executed with the `.` or `source` builtins (see [Bourne Shell Builtins](bourne-shell-builtins)). * Bash includes the `shopt` builtin, for finer control of shell optional capabilities (see [The Shopt Builtin](the-shopt-builtin)), and allows these options to be set and unset at shell invocation (see [Invoking Bash](invoking-bash)). * Bash has much more optional behavior controllable with the `set` builtin (see [The Set Builtin](the-set-builtin)). * The β€˜`-x`’ (`xtrace`) option displays commands other than simple commands when performing an execution trace (see [The Set Builtin](the-set-builtin)). * The `test` builtin (see [Bourne Shell Builtins](bourne-shell-builtins)) is slightly different, as it implements the POSIX algorithm, which specifies the behavior based on the number of arguments. * Bash includes the `caller` builtin, which displays the context of any active subroutine call (a shell function or a script executed with the `.` or `source` builtins). This supports the Bash debugger. * The `trap` builtin (see [Bourne Shell Builtins](bourne-shell-builtins)) allows a `DEBUG` pseudo-signal specification, similar to `EXIT`. Commands specified with a `DEBUG` trap are executed before every simple command, `for` command, `case` command, `select` command, every arithmetic `for` command, and before the first command executes in a shell function. The `DEBUG` trap is not inherited by shell functions unless the function has been given the `trace` attribute or the `functrace` option has been enabled using the `shopt` builtin. The `extdebug` shell option has additional effects on the `DEBUG` trap. The `trap` builtin (see [Bourne Shell Builtins](bourne-shell-builtins)) allows an `ERR` pseudo-signal specification, similar to `EXIT` and `DEBUG`. Commands specified with an `ERR` trap are executed after a simple command fails, with a few exceptions. The `ERR` trap is not inherited by shell functions unless the `-o errtrace` option to the `set` builtin is enabled. The `trap` builtin (see [Bourne Shell Builtins](bourne-shell-builtins)) allows a `RETURN` pseudo-signal specification, similar to `EXIT` and `DEBUG`. Commands specified with a `RETURN` trap are executed before execution resumes after a shell function or a shell script executed with `.` or `source` returns. The `RETURN` trap is not inherited by shell functions unless the function has been given the `trace` attribute or the `functrace` option has been enabled using the `shopt` builtin. * The Bash `type` builtin is more extensive and gives more information about the names it finds (see [Bash Builtin Commands](bash-builtins)). * The Bash `umask` builtin permits a `-p` option to cause the output to be displayed in the form of a `umask` command that may be reused as input (see [Bourne Shell Builtins](bourne-shell-builtins)). * Bash implements a `csh`-like directory stack, and provides the `pushd`, `popd`, and `dirs` builtins to manipulate it (see [The Directory Stack](the-directory-stack)). Bash also makes the directory stack visible as the value of the `DIRSTACK` shell variable. * Bash interprets special backslash-escaped characters in the prompt strings when interactive (see [Controlling the Prompt](controlling-the-prompt)). * The Bash restricted mode is more useful (see [The Restricted Shell](the-restricted-shell)); the SVR4.2 shell restricted mode is too limited. * The `disown` builtin can remove a job from the internal shell job table (see [Job Control Builtins](job-control-builtins)) or suppress the sending of `SIGHUP` to a job when the shell exits as the result of a `SIGHUP`. * Bash includes a number of features to support a separate debugger for shell scripts. * The SVR4.2 shell has two privilege-related builtins (`mldmode` and `priv`) not present in Bash. * Bash does not have the `stop` or `newgrp` builtins. * Bash does not use the `SHACCT` variable or perform shell accounting. * The SVR4.2 `sh` uses a `TIMEOUT` variable like Bash uses `TMOUT`. More features unique to Bash may be found in [Bash Features](bash-features). * [Implementation Differences From The SVR4.2 Shell](#Implementation-Differences-From-The-SVR4_002e2-Shell) ### B.1 Implementation Differences From The SVR4.2 Shell Since Bash is a completely new implementation, it does not suffer from many of the limitations of the SVR4.2 shell. For instance: * Bash does not fork a subshell when redirecting into or out of a shell control structure such as an `if` or `while` statement. * Bash does not allow unbalanced quotes. The SVR4.2 shell will silently insert a needed closing quote at `EOF` under certain circumstances. This can be the cause of some hard-to-find errors. * The SVR4.2 shell uses a baroque memory management scheme based on trapping `SIGSEGV`. If the shell is started from a process with `SIGSEGV` blocked (e.g., by using the `system()` C library function call), it misbehaves badly. * In a questionable attempt at security, the SVR4.2 shell, when invoked without the `-p` option, will alter its real and effective UID and GID if they are less than some magic threshold value, commonly 100. This can lead to unexpected results. * The SVR4.2 shell does not allow users to trap `SIGSEGV`, `SIGALRM`, or `SIGCHLD`. * The SVR4.2 shell does not allow the `IFS`, `MAILCHECK`, `PATH`, `PS1`, or `PS2` variables to be unset. * The SVR4.2 shell treats β€˜`^`’ as the undocumented equivalent of β€˜`|`’. * Bash allows multiple option arguments when it is invoked (`-x -v`); the SVR4.2 shell allows only one option argument (`-xv`). In fact, some versions of the shell dump core if the second argument begins with a β€˜`-`’. * The SVR4.2 shell exits a script if any builtin fails; Bash exits a script only if one of the POSIX special builtins fails, and only for certain failures, as enumerated in the POSIX standard. * The SVR4.2 shell behaves differently when invoked as `jsh` (it turns on job control).
programming_docs
bash Basic Shell Features Basic Shell Features ==================== Bash is an acronym for β€˜`Bourne-Again SHell`’. The Bourne shell is the traditional Unix shell originally written by Stephen Bourne. All of the Bourne shell builtin commands are available in Bash, The rules for evaluation and quoting are taken from the POSIX specification for the β€˜standard’ Unix shell. This chapter briefly summarizes the shell’s β€˜building blocks’: commands, control structures, shell functions, shell *parameters*, shell expansions, *redirections*, which are a way to direct input and output from and to named files, and how the shell executes commands. * [Shell Syntax](shell-syntax) * [Shell Commands](shell-commands) * [Shell Functions](shell-functions) * [Shell Parameters](shell-parameters) * [Shell Expansions](shell-expansions) * [Redirections](redirections) * [Executing Commands](executing-commands) * [Shell Scripts](shell-scripts) bash Coprocesses Coprocesses =========== A `coprocess` is a shell command preceded by the `coproc` reserved word. A coprocess is executed asynchronously in a subshell, as if the command had been terminated with the β€˜`&`’ control operator, with a two-way pipe established between the executing shell and the coprocess. The syntax for a coprocess is: ``` coproc [NAME] command [redirections] ``` This creates a coprocess named NAME. command may be either a simple command (see [Simple Commands](simple-commands)) or a compound command (see [Compound Commands](compound-commands)). NAME is a shell variable name. If NAME is not supplied, the default name is `COPROC`. The recommended form to use for a coprocess is ``` coproc NAME { command; } ``` This form is recommended because simple commands result in the coprocess always being named `COPROC`, and it is simpler to use and more complete than the other compound commands. There are other forms of coprocesses: ``` coproc NAME compound-command coproc compound-command coproc simple-command ``` If command is a compound command, NAME is optional. The word following `coproc` determines whether that word is interpreted as a variable name: it is interpreted as NAME if it is not a reserved word that introduces a compound command. If command is a simple command, NAME is not allowed; this is to avoid confusion between NAME and the first word of the simple command. When the coprocess is executed, the shell creates an array variable (see [Arrays](arrays)) named NAME in the context of the executing shell. The standard output of command is connected via a pipe to a file descriptor in the executing shell, and that file descriptor is assigned to NAME[0]. The standard input of command is connected via a pipe to a file descriptor in the executing shell, and that file descriptor is assigned to NAME[1]. This pipe is established before any redirections specified by the command (see [Redirections](redirections)). The file descriptors can be utilized as arguments to shell commands and redirections using standard word expansions. Other than those created to execute command and process substitutions, the file descriptors are not available in subshells. The process ID of the shell spawned to execute the coprocess is available as the value of the variable `NAME_PID`. The `wait` builtin command may be used to wait for the coprocess to terminate. Since the coprocess is created as an asynchronous command, the `coproc` command always returns success. The return status of a coprocess is the exit status of command. bash The Set Builtin The Set Builtin =============== This builtin is so complicated that it deserves its own section. `set` allows you to change the values of shell options and set the positional parameters, or to display the names and values of shell variables. `set` ``` set [-abefhkmnptuvxBCEHPT] [-o option-name] [--] [-] [argument …] set [+abefhkmnptuvxBCEHPT] [+o option-name] [--] [-] [argument …] ``` If no options or arguments are supplied, `set` displays the names and values of all shell variables and functions, sorted according to the current locale, in a format that may be reused as input for setting or resetting the currently-set variables. Read-only variables cannot be reset. In POSIX mode, only shell variables are listed. When options are supplied, they set or unset shell attributes. Options, if specified, have the following meanings: `-a` Each variable or function that is created or modified is given the export attribute and marked for export to the environment of subsequent commands. `-b` Cause the status of terminated background jobs to be reported immediately, rather than before printing the next primary prompt. `-e` Exit immediately if a pipeline (see [Pipelines](pipelines)), which may consist of a single simple command (see [Simple Commands](simple-commands)), a list (see [Lists of Commands](lists)), or a compound command (see [Compound Commands](compound-commands)) returns a non-zero status. The shell does not exit if the command that fails is part of the command list immediately following a `while` or `until` keyword, part of the test in an `if` statement, part of any command executed in a `&&` or `||` list except the command following the final `&&` or `||`, any command in a pipeline but the last, or if the command’s return status is being inverted with `!`. If a compound command other than a subshell returns a non-zero status because a command failed while `-e` was being ignored, the shell does not exit. A trap on `ERR`, if set, is executed before the shell exits. This option applies to the shell environment and each subshell environment separately (see [Command Execution Environment](command-execution-environment)), and may cause subshells to exit before executing all the commands in the subshell. If a compound command or shell function executes in a context where `-e` is being ignored, none of the commands executed within the compound command or function body will be affected by the `-e` setting, even if `-e` is set and a command returns a failure status. If a compound command or shell function sets `-e` while executing in a context where `-e` is ignored, that setting will not have any effect until the compound command or the command containing the function call completes. `-f` Disable filename expansion (globbing). `-h` Locate and remember (hash) commands as they are looked up for execution. This option is enabled by default. `-k` All arguments in the form of assignment statements are placed in the environment for a command, not just those that precede the command name. `-m` Job control is enabled (see [Job Control](job-control)). All processes run in a separate process group. When a background job completes, the shell prints a line containing its exit status. `-n` Read commands but do not execute them. This may be used to check a script for syntax errors. This option is ignored by interactive shells. `-o option-name` Set the option corresponding to option-name: `allexport` Same as `-a`. `braceexpand` Same as `-B`. `emacs` Use an `emacs`-style line editing interface (see [Command Line Editing](command-line-editing)). This also affects the editing interface used for `read -e`. `errexit` Same as `-e`. `errtrace` Same as `-E`. `functrace` Same as `-T`. `hashall` Same as `-h`. `histexpand` Same as `-H`. `history` Enable command history, as described in [Bash History Facilities](bash-history-facilities). This option is on by default in interactive shells. `ignoreeof` An interactive shell will not exit upon reading EOF. `keyword` Same as `-k`. `monitor` Same as `-m`. `noclobber` Same as `-C`. `noexec` Same as `-n`. `noglob` Same as `-f`. `nolog` Currently ignored. `notify` Same as `-b`. `nounset` Same as `-u`. `onecmd` Same as `-t`. `physical` Same as `-P`. `pipefail` If set, the return value of a pipeline is the value of the last (rightmost) command to exit with a non-zero status, or zero if all commands in the pipeline exit successfully. This option is disabled by default. `posix` Change the behavior of Bash where the default operation differs from the POSIX standard to match the standard (see [Bash POSIX Mode](bash-posix-mode)). This is intended to make Bash behave as a strict superset of that standard. `privileged` Same as `-p`. `verbose` Same as `-v`. `vi` Use a `vi`-style line editing interface. This also affects the editing interface used for `read -e`. `xtrace` Same as `-x`. `-p` Turn on privileged mode. In this mode, the `$BASH_ENV` and `$ENV` files are not processed, shell functions are not inherited from the environment, and the `SHELLOPTS`, `BASHOPTS`, `CDPATH` and `GLOBIGNORE` variables, if they appear in the environment, are ignored. If the shell is started with the effective user (group) id not equal to the real user (group) id, and the `-p` option is not supplied, these actions are taken and the effective user id is set to the real user id. If the `-p` option is supplied at startup, the effective user id is not reset. Turning this option off causes the effective user and group ids to be set to the real user and group ids. `-r` Enable restricted shell mode. This option cannot be unset once it has been set. `-t` Exit after reading and executing one command. `-u` Treat unset variables and parameters other than the special parameters β€˜`@`’ or β€˜`\*`’, or array variables subscripted with β€˜`@`’ or β€˜`\*`’, as an error when performing parameter expansion. An error message will be written to the standard error, and a non-interactive shell will exit. `-v` Print shell input lines as they are read. `-x` Print a trace of simple commands, `for` commands, `case` commands, `select` commands, and arithmetic `for` commands and their arguments or associated word lists after they are expanded and before they are executed. The value of the `PS4` variable is expanded and the resultant value is printed before the command and its expanded arguments. `-B` The shell will perform brace expansion (see [Brace Expansion](brace-expansion)). This option is on by default. `-C` Prevent output redirection using β€˜`>`’, β€˜`>&`’, and β€˜`<>`’ from overwriting existing files. `-E` If set, any trap on `ERR` is inherited by shell functions, command substitutions, and commands executed in a subshell environment. The `ERR` trap is normally not inherited in such cases. `-H` Enable β€˜`!`’ style history substitution (see [History Expansion](history-interaction)). This option is on by default for interactive shells. `-P` If set, do not resolve symbolic links when performing commands such as `cd` which change the current directory. The physical directory is used instead. By default, Bash follows the logical chain of directories when performing commands which change the current directory. For example, if `/usr/sys` is a symbolic link to `/usr/local/sys` then: ``` $ cd /usr/sys; echo $PWD /usr/sys $ cd ..; pwd /usr ``` If `set -P` is on, then: ``` $ cd /usr/sys; echo $PWD /usr/local/sys $ cd ..; pwd /usr/local ``` `-T` If set, any trap on `DEBUG` and `RETURN` are inherited by shell functions, command substitutions, and commands executed in a subshell environment. The `DEBUG` and `RETURN` traps are normally not inherited in such cases. `--` If no arguments follow this option, then the positional parameters are unset. Otherwise, the positional parameters are set to the arguments, even if some of them begin with a β€˜`-`’. `-` Signal the end of options, cause all remaining arguments to be assigned to the positional parameters. The `-x` and `-v` options are turned off. If there are no arguments, the positional parameters remain unchanged. Using β€˜`+`’ rather than β€˜`-`’ causes these options to be turned off. The options can also be used upon invocation of the shell. The current set of options may be found in `$-`. The remaining N arguments are positional parameters and are assigned, in order, to `$1`, `$2`, … `$N`. The special parameter `#` is set to N. The return status is always zero unless an invalid option is supplied. bash Killing And Yanking Killing And Yanking =================== `kill-line (C-k)` Kill the text from point to the end of the line. With a negative numeric argument, kill backward from the cursor to the beginning of the current line. `backward-kill-line (C-x Rubout)` Kill backward from the cursor to the beginning of the current line. With a negative numeric argument, kill forward from the cursor to the end of the current line. `unix-line-discard (C-u)` Kill backward from the cursor to the beginning of the current line. `kill-whole-line ()` Kill all characters on the current line, no matter where point is. By default, this is unbound. `kill-word (M-d)` Kill from point to the end of the current word, or if between words, to the end of the next word. Word boundaries are the same as `forward-word`. `backward-kill-word (M-DEL)` Kill the word behind point. Word boundaries are the same as `backward-word`. `shell-kill-word (M-C-d)` Kill from point to the end of the current word, or if between words, to the end of the next word. Word boundaries are the same as `shell-forward-word`. `shell-backward-kill-word ()` Kill the word behind point. Word boundaries are the same as `shell-backward-word`. `shell-transpose-words (M-C-t)` Drag the word before point past the word after point, moving point past that word as well. If the insertion point is at the end of the line, this transposes the last two words on the line. Word boundaries are the same as `shell-forward-word` and `shell-backward-word`. `unix-word-rubout (C-w)` Kill the word behind point, using white space as a word boundary. The killed text is saved on the kill-ring. `unix-filename-rubout ()` Kill the word behind point, using white space and the slash character as the word boundaries. The killed text is saved on the kill-ring. `delete-horizontal-space ()` Delete all spaces and tabs around point. By default, this is unbound. `kill-region ()` Kill the text in the current region. By default, this command is unbound. `copy-region-as-kill ()` Copy the text in the region to the kill buffer, so it can be yanked right away. By default, this command is unbound. `copy-backward-word ()` Copy the word before point to the kill buffer. The word boundaries are the same as `backward-word`. By default, this command is unbound. `copy-forward-word ()` Copy the word following point to the kill buffer. The word boundaries are the same as `forward-word`. By default, this command is unbound. `yank (C-y)` Yank the top of the kill ring into the buffer at point. `yank-pop (M-y)` Rotate the kill-ring, and yank the new top. You can only do this if the prior command is `yank` or `yank-pop`. bash Bindable Readline Commands Bindable Readline Commands ========================== This section describes Readline commands that may be bound to key sequences. You can list your key bindings by executing `bindΒ -P` or, for a more terse format, suitable for an inputrc file, `bindΒ -p`. (See [Bash Builtin Commands](bash-builtins).) Command names without an accompanying key sequence are unbound by default. In the following descriptions, *point* refers to the current cursor position, and *mark* refers to a cursor position saved by the `set-mark` command. The text between the point and mark is referred to as the *region*. * [Commands For Moving](commands-for-moving) * [Commands For Manipulating The History](commands-for-history) * [Commands For Changing Text](commands-for-text) * [Killing And Yanking](commands-for-killing) * [Specifying Numeric Arguments](numeric-arguments) * [Letting Readline Type For You](commands-for-completion) * [Keyboard Macros](keyboard-macros) * [Some Miscellaneous Commands](miscellaneous-commands) bash Operation Controls Operation Controls ================== `configure` recognizes the following options to control how it operates. `--cache-file=file` Use and save the results of the tests in file instead of `./config.cache`. Set file to `/dev/null` to disable caching, for debugging `configure`. `--help` Print a summary of the options to `configure`, and exit. `--quiet` `--silent` `-q` Do not print messages saying which checks are being made. `--srcdir=dir` Look for the Bash source code in directory dir. Usually `configure` can determine that directory automatically. `--version` Print the version of Autoconf used to generate the `configure` script, and exit. `configure` also accepts some other, not widely used, boilerplate options. β€˜`configure --help`’ prints the complete list. bash Programmable Completion Builtins Programmable Completion Builtins ================================ Three builtin commands are available to manipulate the programmable completion facilities: one to specify how the arguments to a particular command are to be completed, and two to modify the completion as it is happening. `compgen` ``` compgen [option] [word] ``` Generate possible completion matches for word according to the options, which may be any option accepted by the `complete` builtin with the exception of `-p` and `-r`, and write the matches to the standard output. When using the `-F` or `-C` options, the various shell variables set by the programmable completion facilities, while available, will not have useful values. The matches will be generated in the same way as if the programmable completion code had generated them directly from a completion specification with the same flags. If word is specified, only those completions matching word will be displayed. The return value is true unless an invalid option is supplied, or no matches were generated. `complete` ``` complete [-abcdefgjksuv] [-o comp-option] [-DEI] [-A action] [-G globpat] [-W wordlist] [-F function] [-C command] [-X filterpat] [-P prefix] [-S suffix] name [name …] complete -pr [-DEI] [name …] ``` Specify how arguments to each name should be completed. If the `-p` option is supplied, or if no options are supplied, existing completion specifications are printed in a way that allows them to be reused as input. The `-r` option removes a completion specification for each name, or, if no names are supplied, all completion specifications. The `-D` option indicates that other supplied options and actions should apply to the β€œdefault” command completion; that is, completion attempted on a command for which no completion has previously been defined. The `-E` option indicates that other supplied options and actions should apply to β€œempty” command completion; that is, completion attempted on a blank line. The `-I` option indicates that other supplied options and actions should apply to completion on the initial non-assignment word on the line, or after a command delimiter such as β€˜`;`’ or β€˜`|`’, which is usually command name completion. If multiple options are supplied, the `-D` option takes precedence over `-E`, and both take precedence over `-I`. If any of `-D`, `-E`, or `-I` are supplied, any other name arguments are ignored; these completions only apply to the case specified by the option. The process of applying these completion specifications when word completion is attempted is described above (see [Programmable Completion](programmable-completion)). Other options, if specified, have the following meanings. The arguments to the `-G`, `-W`, and `-X` options (and, if necessary, the `-P` and `-S` options) should be quoted to protect them from expansion before the `complete` builtin is invoked. `-o comp-option` The comp-option controls several aspects of the compspec’s behavior beyond the simple generation of completions. comp-option may be one of: `bashdefault` Perform the rest of the default Bash completions if the compspec generates no matches. `default` Use Readline’s default filename completion if the compspec generates no matches. `dirnames` Perform directory name completion if the compspec generates no matches. `filenames` Tell Readline that the compspec generates filenames, so it can perform any filename-specific processing (like adding a slash to directory names, quoting special characters, or suppressing trailing spaces). This option is intended to be used with shell functions specified with `-F`. `noquote` Tell Readline not to quote the completed words if they are filenames (quoting filenames is the default). `nosort` Tell Readline not to sort the list of possible completions alphabetically. `nospace` Tell Readline not to append a space (the default) to words completed at the end of the line. `plusdirs` After any matches defined by the compspec are generated, directory name completion is attempted and any matches are added to the results of the other actions. `-A action` The action may be one of the following to generate a list of possible completions: `alias` Alias names. May also be specified as `-a`. `arrayvar` Array variable names. `binding` Readline key binding names (see [Bindable Readline Commands](bindable-readline-commands)). `builtin` Names of shell builtin commands. May also be specified as `-b`. `command` Command names. May also be specified as `-c`. `directory` Directory names. May also be specified as `-d`. `disabled` Names of disabled shell builtins. `enabled` Names of enabled shell builtins. `export` Names of exported shell variables. May also be specified as `-e`. `file` File names. May also be specified as `-f`. `function` Names of shell functions. `group` Group names. May also be specified as `-g`. `helptopic` Help topics as accepted by the `help` builtin (see [Bash Builtin Commands](bash-builtins)). `hostname` Hostnames, as taken from the file specified by the `HOSTFILE` shell variable (see [Bash Variables](bash-variables)). `job` Job names, if job control is active. May also be specified as `-j`. `keyword` Shell reserved words. May also be specified as `-k`. `running` Names of running jobs, if job control is active. `service` Service names. May also be specified as `-s`. `setopt` Valid arguments for the `-o` option to the `set` builtin (see [The Set Builtin](the-set-builtin)). `shopt` Shell option names as accepted by the `shopt` builtin (see [Bash Builtin Commands](bash-builtins)). `signal` Signal names. `stopped` Names of stopped jobs, if job control is active. `user` User names. May also be specified as `-u`. `variable` Names of all shell variables. May also be specified as `-v`. `-C command` command is executed in a subshell environment, and its output is used as the possible completions. Arguments are passed as with the `-F` option. `-F function` The shell function function is executed in the current shell environment. When it is executed, $1 is the name of the command whose arguments are being completed, $2 is the word being completed, and $3 is the word preceding the word being completed, as described above (see [Programmable Completion](programmable-completion)). When it finishes, the possible completions are retrieved from the value of the `COMPREPLY` array variable. `-G globpat` The filename expansion pattern globpat is expanded to generate the possible completions. `-P prefix` prefix is added at the beginning of each possible completion after all other options have been applied. `-S suffix` suffix is appended to each possible completion after all other options have been applied. `-W wordlist` The wordlist is split using the characters in the `IFS` special variable as delimiters, and each resultant word is expanded. The possible completions are the members of the resultant list which match the word being completed. `-X filterpat` filterpat is a pattern as used for filename expansion. It is applied to the list of possible completions generated by the preceding options and arguments, and each completion matching filterpat is removed from the list. A leading β€˜`!`’ in filterpat negates the pattern; in this case, any completion not matching filterpat is removed. The return value is true unless an invalid option is supplied, an option other than `-p` or `-r` is supplied without a name argument, an attempt is made to remove a completion specification for a name for which no specification exists, or an error occurs adding a completion specification. `compopt` ``` compopt [-o option] [-DEI] [+o option] [name] ``` Modify completion options for each name according to the options, or for the currently-executing completion if no names are supplied. If no options are given, display the completion options for each name or the current completion. The possible values of option are those valid for the `complete` builtin described above. The `-D` option indicates that other supplied options should apply to the β€œdefault” command completion; that is, completion attempted on a command for which no completion has previously been defined. The `-E` option indicates that other supplied options should apply to β€œempty” command completion; that is, completion attempted on a blank line. The `-I` option indicates that other supplied options should apply to completion on the initial non-assignment word on the line, or after a command delimiter such as β€˜`;`’ or β€˜`|`’, which is usually command name completion. If multiple options are supplied, the `-D` option takes precedence over `-E`, and both take precedence over `-I` The return value is true unless an invalid option is supplied, an attempt is made to modify the options for a name for which no completion specification exists, or an output error occurs.
programming_docs
bash Locale-Specific Translation Locale-Specific Translation =========================== Prefixing a double-quoted string with a dollar sign (β€˜`$`’), such as `$"hello, world"`, will cause the string to be translated according to the current locale. The `gettext` infrastructure performs the lookup and translation, using the `LC_MESSAGES`, `TEXTDOMAINDIR`, and `TEXTDOMAIN` shell variables, as explained below. See the gettext documentation for additional details not covered here. If the current locale is `C` or `POSIX`, if there are no translations available, of if the string is not translated, the dollar sign is ignored. Since this is a form of double quoting, the string remains double-quoted by default, whether or not it is translated and replaced. If the `noexpand_translation` option is enabled using the `shopt` builtin (see [The Shopt Builtin](the-shopt-builtin)), translated strings are single-quoted instead of double-quoted. The rest of this section is a brief overview of how you use gettext to create translations for strings in a shell script named scriptname. There are more details in the gettext documentation. bash Readline vi Mode Readline vi Mode ================ While the Readline library does not have a full set of `vi` editing functions, it does contain enough to allow simple editing of the line. The Readline `vi` mode behaves as specified in the POSIX standard. In order to switch interactively between `emacs` and `vi` editing modes, use the β€˜`set -o emacs`’ and β€˜`set -o vi`’ commands (see [The Set Builtin](the-set-builtin)). The Readline default is `emacs` mode. When you enter a line in `vi` mode, you are already placed in β€˜insertion’ mode, as if you had typed an β€˜`i`’. Pressing `ESC` switches you into β€˜command’ mode, where you can edit the text of the line with the standard `vi` movement keys, move to previous history lines with β€˜`k`’ and subsequent lines with β€˜`j`’, and so forth. bash Brace Expansion Brace Expansion =============== Brace expansion is a mechanism by which arbitrary strings may be generated. This mechanism is similar to *filename expansion* (see [Filename Expansion](filename-expansion)), but the filenames generated need not exist. Patterns to be brace expanded take the form of an optional preamble, followed by either a series of comma-separated strings or a sequence expression between a pair of braces, followed by an optional postscript. The preamble is prefixed to each string contained within the braces, and the postscript is then appended to each resulting string, expanding left to right. Brace expansions may be nested. The results of each expanded string are not sorted; left to right order is preserved. For example, ``` bash$ echo a{d,c,b}e ade ace abe ``` A sequence expression takes the form `{x..y[..incr]}`, where x and y are either integers or letters, and incr, an optional increment, is an integer. When integers are supplied, the expression expands to each number between x and y, inclusive. Supplied integers may be prefixed with β€˜`0`’ to force each term to have the same width. When either x or y begins with a zero, the shell attempts to force all generated terms to contain the same number of digits, zero-padding where necessary. When letters are supplied, the expression expands to each character lexicographically between x and y, inclusive, using the default C locale. Note that both x and y must be of the same type (integer or letter). When the increment is supplied, it is used as the difference between each term. The default increment is 1 or -1 as appropriate. Brace expansion is performed before any other expansions, and any characters special to other expansions are preserved in the result. It is strictly textual. Bash does not apply any syntactic interpretation to the context of the expansion or the text between the braces. A correctly-formed brace expansion must contain unquoted opening and closing braces, and at least one unquoted comma or a valid sequence expression. Any incorrectly formed brace expansion is left unchanged. A { or β€˜`,`’ may be quoted with a backslash to prevent its being considered part of a brace expression. To avoid conflicts with parameter expansion, the string β€˜`${`’ is not considered eligible for brace expansion, and inhibits brace expansion until the closing β€˜`}`’. This construct is typically used as shorthand when the common prefix of the strings to be generated is longer than in the above example: ``` mkdir /usr/local/src/bash/{old,new,dist,bugs} ``` or ``` chown root /usr/{ucb/{ex,edit},lib/{ex?.?*,how_ex}} ``` bash Command Line Editing Command Line Editing ==================== This chapter describes the basic features of the GNU command line editing interface. Command line editing is provided by the Readline library, which is used by several different programs, including Bash. Command line editing is enabled by default when using an interactive shell, unless the `--noediting` option is supplied at shell invocation. Line editing is also used when using the `-e` option to the `read` builtin command (see [Bash Builtin Commands](bash-builtins)). By default, the line editing commands are similar to those of Emacs. A vi-style line editing interface is also available. Line editing can be enabled at any time using the `-o emacs` or `-o vi` options to the `set` builtin command (see [The Set Builtin](the-set-builtin)), or disabled using the `+o emacs` or `+o vi` options to `set`. * [Introduction to Line Editing](introduction-and-notation) * [Readline Interaction](readline-interaction) * [Readline Init File](readline-init-file) * [Bindable Readline Commands](bindable-readline-commands) * [Readline vi Mode](readline-vi-mode) * [Programmable Completion](programmable-completion) * [Programmable Completion Builtins](programmable-completion-builtins) * [A Programmable Completion Example](a-programmable-completion-example) bash Command Execution Environment Command Execution Environment ============================= The shell has an *execution environment*, which consists of the following: * open files inherited by the shell at invocation, as modified by redirections supplied to the `exec` builtin * the current working directory as set by `cd`, `pushd`, or `popd`, or inherited by the shell at invocation * the file creation mode mask as set by `umask` or inherited from the shell’s parent * current traps set by `trap` * shell parameters that are set by variable assignment or with `set` or inherited from the shell’s parent in the environment * shell functions defined during execution or inherited from the shell’s parent in the environment * options enabled at invocation (either by default or with command-line arguments) or by `set` * options enabled by `shopt` (see [The Shopt Builtin](the-shopt-builtin)) * shell aliases defined with `alias` (see [Aliases](aliases)) * various process IDs, including those of background jobs (see [Lists of Commands](lists)), the value of `$$`, and the value of `$PPID` When a simple command other than a builtin or shell function is to be executed, it is invoked in a separate execution environment that consists of the following. Unless otherwise noted, the values are inherited from the shell. * the shell’s open files, plus any modifications and additions specified by redirections to the command * the current working directory * the file creation mode mask * shell variables and functions marked for export, along with variables exported for the command, passed in the environment (see [Environment](environment)) * traps caught by the shell are reset to the values inherited from the shell’s parent, and traps ignored by the shell are ignored A command invoked in this separate environment cannot affect the shell’s execution environment. A *subshell* is a copy of the shell process. Command substitution, commands grouped with parentheses, and asynchronous commands are invoked in a subshell environment that is a duplicate of the shell environment, except that traps caught by the shell are reset to the values that the shell inherited from its parent at invocation. Builtin commands that are invoked as part of a pipeline are also executed in a subshell environment. Changes made to the subshell environment cannot affect the shell’s execution environment. Subshells spawned to execute command substitutions inherit the value of the `-e` option from the parent shell. When not in POSIX mode, Bash clears the `-e` option in such subshells. If a command is followed by a β€˜`&`’ and job control is not active, the default standard input for the command is the empty file `/dev/null`. Otherwise, the invoked command inherits the file descriptors of the calling shell as modified by redirections. bash Quoting Quoting ======= Quoting is used to remove the special meaning of certain characters or words to the shell. Quoting can be used to disable special treatment for special characters, to prevent reserved words from being recognized as such, and to prevent parameter expansion. Each of the shell metacharacters (see [Definitions](definitions)) has special meaning to the shell and must be quoted if it is to represent itself. When the command history expansion facilities are being used (see [History Expansion](history-interaction)), the *history expansion* character, usually β€˜`!`’, must be quoted to prevent history expansion. See [Bash History Facilities](bash-history-facilities), for more details concerning history expansion. There are three quoting mechanisms: the *escape character*, single quotes, and double quotes. * [Escape Character](escape-character) * [Single Quotes](single-quotes) * [Double Quotes](double-quotes) * [ANSI-C Quoting](ansi_002dc-quoting) * [Locale-Specific Translation](locale-translation) bash Keyboard Macros Keyboard Macros =============== `start-kbd-macro (C-x ()` Begin saving the characters typed into the current keyboard macro. `end-kbd-macro (C-x ))` Stop saving the characters typed into the current keyboard macro and save the definition. `call-last-kbd-macro (C-x e)` Re-execute the last keyboard macro defined, by making the characters in the macro appear as if typed at the keyboard. `print-last-kbd-macro ()` Print the last keyboard macro defined in a format suitable for the inputrc file. bash Concept Index Concept Index ============= | | | | --- | --- | | Jump to: | [**A**](#Concept-Index_cp_letter-A) [**B**](#Concept-Index_cp_letter-B) [**C**](#Concept-Index_cp_letter-C) [**D**](#Concept-Index_cp_letter-D) [**E**](#Concept-Index_cp_letter-E) [**F**](#Concept-Index_cp_letter-F) [**H**](#Concept-Index_cp_letter-H) [**I**](#Concept-Index_cp_letter-I) [**J**](#Concept-Index_cp_letter-J) [**K**](#Concept-Index_cp_letter-K) [**L**](#Concept-Index_cp_letter-L) [**M**](#Concept-Index_cp_letter-M) [**N**](#Concept-Index_cp_letter-N) [**O**](#Concept-Index_cp_letter-O) [**P**](#Concept-Index_cp_letter-P) [**Q**](#Concept-Index_cp_letter-Q) [**R**](#Concept-Index_cp_letter-R) [**S**](#Concept-Index_cp_letter-S) [**T**](#Concept-Index_cp_letter-T) [**V**](#Concept-Index_cp_letter-V) [**W**](#Concept-Index_cp_letter-W) [**Y**](#Concept-Index_cp_letter-Y) | | | | | | --- | --- | --- | | | Index Entry | Section | | A | | | | | [alias expansion](aliases#alias%20expansion) | [Aliases](aliases#Aliases) | | | [arithmetic evaluation](shell-arithmetic#arithmetic%20evaluation) | [Shell Arithmetic](shell-arithmetic#Shell%20Arithmetic) | | | [arithmetic expansion](arithmetic-expansion#arithmetic%20expansion) | [Arithmetic Expansion](arithmetic-expansion#Arithmetic%20Expansion) | | | [arithmetic, shell](shell-arithmetic#arithmetic,%20shell) | [Shell Arithmetic](shell-arithmetic#Shell%20Arithmetic) | | | [arrays](arrays#arrays) | [Arrays](arrays#Arrays) | | B | | | | | [background](job-control-basics#background) | [Job Control Basics](job-control-basics#Job%20Control%20Basics) | | | [Bash configuration](basic-installation#Bash%20configuration) | [Basic Installation](basic-installation#Basic%20Installation) | | | [Bash installation](basic-installation#Bash%20installation) | [Basic Installation](basic-installation#Basic%20Installation) | | | [Bourne shell](basic-shell-features#Bourne%20shell) | [Basic Shell Features](basic-shell-features#Basic%20Shell%20Features) | | | [brace expansion](brace-expansion#brace%20expansion) | [Brace Expansion](brace-expansion#Brace%20Expansion) | | | [builtin](definitions#builtin) | [Definitions](definitions#Definitions) | | C | | | | | [command editing](readline-bare-essentials#command%20editing) | [Readline Bare Essentials](readline-bare-essentials#Readline%20Bare%20Essentials) | | | [command execution](command-search-and-execution#command%20execution) | [Command Search and Execution](command-search-and-execution#Command%20Search%20and%20Execution) | | | [command expansion](simple-command-expansion#command%20expansion) | [Simple Command Expansion](simple-command-expansion#Simple%20Command%20Expansion) | | | [command history](bash-history-facilities#command%20history) | [Bash History Facilities](bash-history-facilities#Bash%20History%20Facilities) | | | [command search](command-search-and-execution#command%20search) | [Command Search and Execution](command-search-and-execution#Command%20Search%20and%20Execution) | | | [command substitution](command-substitution#command%20substitution) | [Command Substitution](command-substitution#Command%20Substitution) | | | [command timing](pipelines#command%20timing) | [Pipelines](pipelines#Pipelines) | | | [commands, compound](compound-commands#commands,%20compound) | [Compound Commands](compound-commands#Compound%20Commands) | | | [commands, conditional](conditional-constructs#commands,%20conditional) | [Conditional Constructs](conditional-constructs#Conditional%20Constructs) | | | [commands, grouping](command-grouping#commands,%20grouping) | [Command Grouping](command-grouping#Command%20Grouping) | | | [commands, lists](lists#commands,%20lists) | [Lists](lists#Lists) | | | [commands, looping](looping-constructs#commands,%20looping) | [Looping Constructs](looping-constructs#Looping%20Constructs) | | | [commands, pipelines](pipelines#commands,%20pipelines) | [Pipelines](pipelines#Pipelines) | | | [commands, shell](shell-commands#commands,%20shell) | [Shell Commands](shell-commands#Shell%20Commands) | | | [commands, simple](simple-commands#commands,%20simple) | [Simple Commands](simple-commands#Simple%20Commands) | | | [comments, shell](comments#comments,%20shell) | [Comments](comments#Comments) | | | [Compatibility Level](shell-compatibility-mode#Compatibility%20Level) | [Shell Compatibility Mode](shell-compatibility-mode#Shell%20Compatibility%20Mode) | | | [Compatibility Mode](shell-compatibility-mode#Compatibility%20Mode) | [Shell Compatibility Mode](shell-compatibility-mode#Shell%20Compatibility%20Mode) | | | [completion builtins](programmable-completion-builtins#completion%20builtins) | [Programmable Completion Builtins](programmable-completion-builtins#Programmable%20Completion%20Builtins) | | | [configuration](basic-installation#configuration) | [Basic Installation](basic-installation#Basic%20Installation) | | | [control operator](definitions#control%20operator) | [Definitions](definitions#Definitions) | | | [coprocess](coprocesses#coprocess) | [Coprocesses](coprocesses#Coprocesses) | | D | | | | | [directory stack](the-directory-stack#directory%20stack) | [The Directory Stack](the-directory-stack#The%20Directory%20Stack) | | E | | | | | [editing command lines](readline-bare-essentials#editing%20command%20lines) | [Readline Bare Essentials](readline-bare-essentials#Readline%20Bare%20Essentials) | | | [environment](environment#environment) | [Environment](environment#Environment) | | | [evaluation, arithmetic](shell-arithmetic#evaluation,%20arithmetic) | [Shell Arithmetic](shell-arithmetic#Shell%20Arithmetic) | | | [event designators](event-designators#event%20designators) | [Event Designators](event-designators#Event%20Designators) | | | [execution environment](command-execution-environment#execution%20environment) | [Command Execution Environment](command-execution-environment#Command%20Execution%20Environment) | | | [exit status](definitions#exit%20status) | [Definitions](definitions#Definitions) | | | [exit status](exit-status#exit%20status) | [Exit Status](exit-status#Exit%20Status) | | | [expansion](shell-expansions#expansion) | [Shell Expansions](shell-expansions#Shell%20Expansions) | | | [expansion, arithmetic](arithmetic-expansion#expansion,%20arithmetic) | [Arithmetic Expansion](arithmetic-expansion#Arithmetic%20Expansion) | | | [expansion, brace](brace-expansion#expansion,%20brace) | [Brace Expansion](brace-expansion#Brace%20Expansion) | | | [expansion, filename](filename-expansion#expansion,%20filename) | [Filename Expansion](filename-expansion#Filename%20Expansion) | | | [expansion, parameter](shell-parameter-expansion#expansion,%20parameter) | [Shell Parameter Expansion](shell-parameter-expansion#Shell%20Parameter%20Expansion) | | | [expansion, pathname](filename-expansion#expansion,%20pathname) | [Filename Expansion](filename-expansion#Filename%20Expansion) | | | [expansion, tilde](tilde-expansion#expansion,%20tilde) | [Tilde Expansion](tilde-expansion#Tilde%20Expansion) | | | [expressions, arithmetic](shell-arithmetic#expressions,%20arithmetic) | [Shell Arithmetic](shell-arithmetic#Shell%20Arithmetic) | | | [expressions, conditional](bash-conditional-expressions#expressions,%20conditional) | [Bash Conditional Expressions](bash-conditional-expressions#Bash%20Conditional%20Expressions) | | F | | | | | [field](definitions#field) | [Definitions](definitions#Definitions) | | | [filename](definitions#filename) | [Definitions](definitions#Definitions) | | | [filename expansion](filename-expansion#filename%20expansion) | [Filename Expansion](filename-expansion#Filename%20Expansion) | | | [foreground](job-control-basics#foreground) | [Job Control Basics](job-control-basics#Job%20Control%20Basics) | | | [functions, shell](shell-functions#functions,%20shell) | [Shell Functions](shell-functions#Shell%20Functions) | | H | | | | | [history builtins](bash-history-builtins#history%20builtins) | [Bash History Builtins](bash-history-builtins#Bash%20History%20Builtins) | | | [history events](event-designators#history%20events) | [Event Designators](event-designators#Event%20Designators) | | | [history expansion](history-interaction#history%20expansion) | [History Interaction](history-interaction#History%20Interaction) | | | [history list](bash-history-facilities#history%20list) | [Bash History Facilities](bash-history-facilities#Bash%20History%20Facilities) | | | [History, how to use](a-programmable-completion-example#History,%20how%20to%20use) | [A Programmable Completion Example](a-programmable-completion-example#A%20Programmable%20Completion%20Example) | | I | | | | | [identifier](definitions#identifier) | [Definitions](definitions#Definitions) | | | [initialization file, readline](readline-init-file#initialization%20file,%20readline) | [Readline Init File](readline-init-file#Readline%20Init%20File) | | | [installation](basic-installation#installation) | [Basic Installation](basic-installation#Basic%20Installation) | | | [interaction, readline](readline-interaction#interaction,%20readline) | [Readline Interaction](readline-interaction#Readline%20Interaction) | | | [interactive shell](invoking-bash#interactive%20shell) | [Invoking Bash](invoking-bash#Invoking%20Bash) | | | [interactive shell](interactive-shells#interactive%20shell) | [Interactive Shells](interactive-shells#Interactive%20Shells) | | | [internationalization](locale-translation#internationalization) | [Locale Translation](locale-translation#Locale%20Translation) | | | [internationalized scripts](creating-internationalized-scripts#internationalized%20scripts) | [Creating Internationalized Scripts](creating-internationalized-scripts#Creating%20Internationalized%20Scripts) | | J | | | | | [job](definitions#job) | [Definitions](definitions#Definitions) | | | [job control](definitions#job%20control) | [Definitions](definitions#Definitions) | | | [job control](job-control-basics#job%20control) | [Job Control Basics](job-control-basics#Job%20Control%20Basics) | | K | | | | | [kill ring](readline-killing-commands#kill%20ring) | [Readline Killing Commands](readline-killing-commands#Readline%20Killing%20Commands) | | | [killing text](readline-killing-commands#killing%20text) | [Readline Killing Commands](readline-killing-commands#Readline%20Killing%20Commands) | | L | | | | | [localization](locale-translation#localization) | [Locale Translation](locale-translation#Locale%20Translation) | | | [login shell](invoking-bash#login%20shell) | [Invoking Bash](invoking-bash#Invoking%20Bash) | | M | | | | | [matching, pattern](pattern-matching#matching,%20pattern) | [Pattern Matching](pattern-matching#Pattern%20Matching) | | | [metacharacter](definitions#metacharacter) | [Definitions](definitions#Definitions) | | N | | | | | [name](definitions#name) | [Definitions](definitions#Definitions) | | | [native languages](locale-translation#native%20languages) | [Locale Translation](locale-translation#Locale%20Translation) | | | [notation, readline](readline-bare-essentials#notation,%20readline) | [Readline Bare Essentials](readline-bare-essentials#Readline%20Bare%20Essentials) | | O | | | | | [operator, shell](definitions#operator,%20shell) | [Definitions](definitions#Definitions) | | P | | | | | [parameter expansion](shell-parameter-expansion#parameter%20expansion) | [Shell Parameter Expansion](shell-parameter-expansion#Shell%20Parameter%20Expansion) | | | [parameters](shell-parameters#parameters) | [Shell Parameters](shell-parameters#Shell%20Parameters) | | | [parameters, positional](positional-parameters#parameters,%20positional) | [Positional Parameters](positional-parameters#Positional%20Parameters) | | | [parameters, special](special-parameters#parameters,%20special) | [Special Parameters](special-parameters#Special%20Parameters) | | | [pathname expansion](filename-expansion#pathname%20expansion) | [Filename Expansion](filename-expansion#Filename%20Expansion) | | | [pattern matching](pattern-matching#pattern%20matching) | [Pattern Matching](pattern-matching#Pattern%20Matching) | | | [pipeline](pipelines#pipeline) | [Pipelines](pipelines#Pipelines) | | | [POSIX](definitions#POSIX) | [Definitions](definitions#Definitions) | | | [POSIX Mode](bash-posix-mode#POSIX%20Mode) | [Bash POSIX Mode](bash-posix-mode#Bash%20POSIX%20Mode) | | | [process group](definitions#process%20group) | [Definitions](definitions#Definitions) | | | [process group ID](definitions#process%20group%20ID) | [Definitions](definitions#Definitions) | | | [process substitution](process-substitution#process%20substitution) | [Process Substitution](process-substitution#Process%20Substitution) | | | [programmable completion](programmable-completion#programmable%20completion) | [Programmable Completion](programmable-completion#Programmable%20Completion) | | | [prompting](controlling-the-prompt#prompting) | [Controlling the Prompt](controlling-the-prompt#Controlling%20the%20Prompt) | | Q | | | | | [quoting](quoting#quoting) | [Quoting](quoting#Quoting) | | | [quoting, ANSI](ansi_002dc-quoting#quoting,%20ANSI) | [ANSI-C Quoting](ansi_002dc-quoting#ANSI-C%20Quoting) | | R | | | | | [Readline, how to use](job-control-variables#Readline,%20how%20to%20use) | [Job Control Variables](job-control-variables#Job%20Control%20Variables) | | | [redirection](redirections#redirection) | [Redirections](redirections#Redirections) | | | [reserved word](definitions#reserved%20word) | [Definitions](definitions#Definitions) | | | [reserved words](reserved-words#reserved%20words) | [Reserved Words](reserved-words#Reserved%20Words) | | | [restricted shell](the-restricted-shell#restricted%20shell) | [The Restricted Shell](the-restricted-shell#The%20Restricted%20Shell) | | | [return status](definitions#return%20status) | [Definitions](definitions#Definitions) | | S | | | | | [shell arithmetic](shell-arithmetic#shell%20arithmetic) | [Shell Arithmetic](shell-arithmetic#Shell%20Arithmetic) | | | [shell function](shell-functions#shell%20function) | [Shell Functions](shell-functions#Shell%20Functions) | | | [shell script](shell-scripts#shell%20script) | [Shell Scripts](shell-scripts#Shell%20Scripts) | | | [shell variable](shell-parameters#shell%20variable) | [Shell Parameters](shell-parameters#Shell%20Parameters) | | | [shell, interactive](interactive-shells#shell,%20interactive) | [Interactive Shells](interactive-shells#Interactive%20Shells) | | | [signal](definitions#signal) | [Definitions](definitions#Definitions) | | | [signal handling](signals#signal%20handling) | [Signals](signals#Signals) | | | [special builtin](definitions#special%20builtin) | [Definitions](definitions#Definitions) | | | [special builtin](special-builtins#special%20builtin) | [Special Builtins](special-builtins#Special%20Builtins) | | | [startup files](bash-startup-files#startup%20files) | [Bash Startup Files](bash-startup-files#Bash%20Startup%20Files) | | | [string translations](creating-internationalized-scripts#string%20translations) | [Creating Internationalized Scripts](creating-internationalized-scripts#Creating%20Internationalized%20Scripts) | | | [suspending jobs](job-control-basics#suspending%20jobs) | [Job Control Basics](job-control-basics#Job%20Control%20Basics) | | T | | | | | [tilde expansion](tilde-expansion#tilde%20expansion) | [Tilde Expansion](tilde-expansion#Tilde%20Expansion) | | | [token](definitions#token) | [Definitions](definitions#Definitions) | | | [translation, native languages](locale-translation#translation,%20native%20languages) | [Locale Translation](locale-translation#Locale%20Translation) | | V | | | | | [variable, shell](shell-parameters#variable,%20shell) | [Shell Parameters](shell-parameters#Shell%20Parameters) | | | [variables, readline](readline-init-file-syntax#variables,%20readline) | [Readline Init File Syntax](readline-init-file-syntax#Readline%20Init%20File%20Syntax) | | W | | | | | [word](definitions#word) | [Definitions](definitions#Definitions) | | | [word splitting](word-splitting#word%20splitting) | [Word Splitting](word-splitting#Word%20Splitting) | | Y | | | | | [yanking text](readline-killing-commands#yanking%20text) | [Readline Killing Commands](readline-killing-commands#Readline%20Killing%20Commands) | | | | | --- | --- | | Jump to: | [**A**](#Concept-Index_cp_letter-A) [**B**](#Concept-Index_cp_letter-B) [**C**](#Concept-Index_cp_letter-C) [**D**](#Concept-Index_cp_letter-D) [**E**](#Concept-Index_cp_letter-E) [**F**](#Concept-Index_cp_letter-F) [**H**](#Concept-Index_cp_letter-H) [**I**](#Concept-Index_cp_letter-I) [**J**](#Concept-Index_cp_letter-J) [**K**](#Concept-Index_cp_letter-K) [**L**](#Concept-Index_cp_letter-L) [**M**](#Concept-Index_cp_letter-M) [**N**](#Concept-Index_cp_letter-N) [**O**](#Concept-Index_cp_letter-O) [**P**](#Concept-Index_cp_letter-P) [**Q**](#Concept-Index_cp_letter-Q) [**R**](#Concept-Index_cp_letter-R) [**S**](#Concept-Index_cp_letter-S) [**T**](#Concept-Index_cp_letter-T) [**V**](#Concept-Index_cp_letter-V) [**W**](#Concept-Index_cp_letter-W) [**Y**](#Concept-Index_cp_letter-Y) |
programming_docs
bash Sample Init File Sample Init File ================ Here is an example of an inputrc file. This illustrates key binding, variable assignment, and conditional syntax. ``` # This file controls the behaviour of line input editing for # programs that use the GNU Readline library. Existing # programs include FTP, Bash, and GDB. # # You can re-read the inputrc file with C-x C-r. # Lines beginning with '#' are comments. # # First, include any system-wide bindings and variable # assignments from /etc/Inputrc $include /etc/Inputrc # # Set various bindings for emacs mode. set editing-mode emacs $if mode=emacs Meta-Control-h: backward-kill-word Text after the function name is ignored # # Arrow keys in keypad mode # #"\M-OD": backward-char #"\M-OC": forward-char #"\M-OA": previous-history #"\M-OB": next-history # # Arrow keys in ANSI mode # "\M-[D": backward-char "\M-[C": forward-char "\M-[A": previous-history "\M-[B": next-history # # Arrow keys in 8 bit keypad mode # #"\M-\C-OD": backward-char #"\M-\C-OC": forward-char #"\M-\C-OA": previous-history #"\M-\C-OB": next-history # # Arrow keys in 8 bit ANSI mode # #"\M-\C-[D": backward-char #"\M-\C-[C": forward-char #"\M-\C-[A": previous-history #"\M-\C-[B": next-history C-q: quoted-insert $endif # An old-style binding. This happens to be the default. TAB: complete # Macros that are convenient for shell interaction $if Bash # edit the path "\C-xp": "PATH=${PATH}\e\C-e\C-a\ef\C-f" # prepare to type a quoted word -- # insert open and close double quotes # and move to just after the open quote "\C-x\"": "\"\"\C-b" # insert a backslash (testing backslash escapes # in sequences and macros) "\C-x\\": "\\" # Quote the current or previous word "\C-xq": "\eb\"\ef\"" # Add a binding to refresh the line, which is unbound "\C-xr": redraw-current-line # Edit variable on current line. "\M-\C-v": "\C-a\C-k$\C-y\M-\C-e\C-a\C-y=" $endif # use a visible bell if one is available set bell-style visible # don't strip characters to 7 bits when reading set input-meta on # allow iso-latin1 characters to be inserted rather # than converted to prefix-meta sequences set convert-meta off # display characters with the eighth bit set directly # rather than as meta-prefixed characters set output-meta on # if there are 150 or more possible completions for a word, # ask whether or not the user wants to see all of them set completion-query-items 150 # For FTP $if Ftp "\C-xg": "get \M-?" "\C-xt": "put \M-?" "\M-.": yank-last-arg $endif ``` bash Readline Init File Syntax Readline Init File Syntax ========================= There are only a few basic constructs allowed in the Readline init file. Blank lines are ignored. Lines beginning with a β€˜`#`’ are comments. Lines beginning with a β€˜`$`’ indicate conditional constructs (see [Conditional Init Constructs](conditional-init-constructs)). Other lines denote variable settings and key bindings. Variable Settings You can modify the run-time behavior of Readline by altering the values of variables in Readline using the `set` command within the init file. The syntax is simple: ``` set variable value ``` Here, for example, is how to change from the default Emacs-like key binding to use `vi` line editing commands: ``` set editing-mode vi ``` Variable names and values, where appropriate, are recognized without regard to case. Unrecognized variable names are ignored. Boolean variables (those that can be set to on or off) are set to on if the value is null or empty, on (case-insensitive), or 1. Any other value results in the variable being set to off. The `bindΒ -V` command lists the current Readline variable names and values. See [Bash Builtin Commands](bash-builtins). A great deal of run-time behavior is changeable with the following variables. `active-region-start-color` A string variable that controls the text color and background when displaying the text in the active region (see the description of `enable-active-region` below). This string must not take up any physical character positions on the display, so it should consist only of terminal escape sequences. It is output to the terminal before displaying the text in the active region. This variable is reset to the default value whenever the terminal type changes. The default value is the string that puts the terminal in standout mode, as obtained from the terminal’s terminfo description. A sample value might be β€˜`\e[01;33m`’. `active-region-end-color` A string variable that "undoes" the effects of `active-region-start-color` and restores "normal" terminal display appearance after displaying text in the active region. This string must not take up any physical character positions on the display, so it should consist only of terminal escape sequences. It is output to the terminal after displaying the text in the active region. This variable is reset to the default value whenever the terminal type changes. The default value is the string that restores the terminal from standout mode, as obtained from the terminal’s terminfo description. A sample value might be β€˜`\e[0m`’. `bell-style` Controls what happens when Readline wants to ring the terminal bell. If set to β€˜`none`’, Readline never rings the bell. If set to β€˜`visible`’, Readline uses a visible bell if one is available. If set to β€˜`audible`’ (the default), Readline attempts to ring the terminal’s bell. `bind-tty-special-chars` If set to β€˜`on`’ (the default), Readline attempts to bind the control characters treated specially by the kernel’s terminal driver to their Readline equivalents. `blink-matching-paren` If set to β€˜`on`’, Readline attempts to briefly move the cursor to an opening parenthesis when a closing parenthesis is inserted. The default is β€˜`off`’. `colored-completion-prefix` If set to β€˜`on`’, when listing completions, Readline displays the common prefix of the set of possible completions using a different color. The color definitions are taken from the value of the `LS_COLORS` environment variable. If there is a color definition in `LS_COLORS` for the custom suffix β€˜`readline-colored-completion-prefix`’, Readline uses this color for the common prefix instead of its default. The default is β€˜`off`’. `colored-stats` If set to β€˜`on`’, Readline displays possible completions using different colors to indicate their file type. The color definitions are taken from the value of the `LS_COLORS` environment variable. The default is β€˜`off`’. `comment-begin` The string to insert at the beginning of the line when the `insert-comment` command is executed. The default value is `"#"`. `completion-display-width` The number of screen columns used to display possible matches when performing completion. The value is ignored if it is less than 0 or greater than the terminal screen width. A value of 0 will cause matches to be displayed one per line. The default value is -1. `completion-ignore-case` If set to β€˜`on`’, Readline performs filename matching and completion in a case-insensitive fashion. The default value is β€˜`off`’. `completion-map-case` If set to β€˜`on`’, and completion-ignore-case is enabled, Readline treats hyphens (β€˜`-`’) and underscores (β€˜`\_`’) as equivalent when performing case-insensitive filename matching and completion. The default value is β€˜`off`’. `completion-prefix-display-length` The length in characters of the common prefix of a list of possible completions that is displayed without modification. When set to a value greater than zero, common prefixes longer than this value are replaced with an ellipsis when displaying possible completions. `completion-query-items` The number of possible completions that determines when the user is asked whether the list of possibilities should be displayed. If the number of possible completions is greater than or equal to this value, Readline will ask whether or not the user wishes to view them; otherwise, they are simply listed. This variable must be set to an integer value greater than or equal to zero. A zero value means Readline should never ask; negative values are treated as zero. The default limit is `100`. `convert-meta` If set to β€˜`on`’, Readline will convert characters with the eighth bit set to an ASCII key sequence by stripping the eighth bit and prefixing an `ESC` character, converting them to a meta-prefixed key sequence. The default value is β€˜`on`’, but will be set to β€˜`off`’ if the locale is one that contains eight-bit characters. This variable is dependent on the `LC_CTYPE` locale category, and may change if the locale is changed. `disable-completion` If set to β€˜`On`’, Readline will inhibit word completion. Completion characters will be inserted into the line as if they had been mapped to `self-insert`. The default is β€˜`off`’. `echo-control-characters` When set to β€˜`on`’, on operating systems that indicate they support it, Readline echoes a character corresponding to a signal generated from the keyboard. The default is β€˜`on`’. `editing-mode` The `editing-mode` variable controls which default set of key bindings is used. By default, Readline starts up in Emacs editing mode, where the keystrokes are most similar to Emacs. This variable can be set to either β€˜`emacs`’ or β€˜`vi`’. `emacs-mode-string` If the show-mode-in-prompt variable is enabled, this string is displayed immediately before the last line of the primary prompt when emacs editing mode is active. The value is expanded like a key binding, so the standard set of meta- and control prefixes and backslash escape sequences is available. Use the β€˜`\1`’ and β€˜`\2`’ escapes to begin and end sequences of non-printing characters, which can be used to embed a terminal control sequence into the mode string. The default is β€˜`@`’. `enable-active-region` The *point* is the current cursor position, and *mark* refers to a saved cursor position (see [Commands For Moving](commands-for-moving)). The text between the point and mark is referred to as the *region*. When this variable is set to β€˜`On`’, Readline allows certain commands to designate the region as *active*. When the region is active, Readline highlights the text in the region using the value of the `active-region-start-color`, which defaults to the string that enables the terminal’s standout mode. The active region shows the text inserted by bracketed-paste and any matching text found by incremental and non-incremental history searches. The default is β€˜`On`’. `enable-bracketed-paste` When set to β€˜`On`’, Readline configures the terminal to insert each paste into the editing buffer as a single string of characters, instead of treating each character as if it had been read from the keyboard. This is called putting the terminal into *bracketed paste mode*; it prevents Readline from executing any editing commands bound to key sequences appearing in the pasted text. The default is β€˜`On`’. `enable-keypad` When set to β€˜`on`’, Readline will try to enable the application keypad when it is called. Some systems need this to enable the arrow keys. The default is β€˜`off`’. `enable-meta-key` When set to β€˜`on`’, Readline will try to enable any meta modifier key the terminal claims to support when it is called. On many terminals, the meta key is used to send eight-bit characters. The default is β€˜`on`’. `expand-tilde` If set to β€˜`on`’, tilde expansion is performed when Readline attempts word completion. The default is β€˜`off`’. `history-preserve-point` If set to β€˜`on`’, the history code attempts to place the point (the current cursor position) at the same location on each history line retrieved with `previous-history` or `next-history`. The default is β€˜`off`’. `history-size` Set the maximum number of history entries saved in the history list. If set to zero, any existing history entries are deleted and no new entries are saved. If set to a value less than zero, the number of history entries is not limited. By default, the number of history entries is not limited. If an attempt is made to set history-size to a non-numeric value, the maximum number of history entries will be set to 500. `horizontal-scroll-mode` This variable can be set to either β€˜`on`’ or β€˜`off`’. Setting it to β€˜`on`’ means that the text of the lines being edited will scroll horizontally on a single screen line when they are longer than the width of the screen, instead of wrapping onto a new screen line. This variable is automatically set to β€˜`on`’ for terminals of height 1. By default, this variable is set to β€˜`off`’. `input-meta` If set to β€˜`on`’, Readline will enable eight-bit input (it will not clear the eighth bit in the characters it reads), regardless of what the terminal claims it can support. The default value is β€˜`off`’, but Readline will set it to β€˜`on`’ if the locale contains eight-bit characters. The name `meta-flag` is a synonym for this variable. This variable is dependent on the `LC_CTYPE` locale category, and may change if the locale is changed. `isearch-terminators` The string of characters that should terminate an incremental search without subsequently executing the character as a command (see [Searching for Commands in the History](searching)). If this variable has not been given a value, the characters `ESC` and `C-J` will terminate an incremental search. `keymap` Sets Readline’s idea of the current keymap for key binding commands. Built-in `keymap` names are `emacs`, `emacs-standard`, `emacs-meta`, `emacs-ctlx`, `vi`, `vi-move`, `vi-command`, and `vi-insert`. `vi` is equivalent to `vi-command` (`vi-move` is also a synonym); `emacs` is equivalent to `emacs-standard`. Applications may add additional names. The default value is `emacs`. The value of the `editing-mode` variable also affects the default keymap. `keyseq-timeout` Specifies the duration Readline will wait for a character when reading an ambiguous key sequence (one that can form a complete key sequence using the input read so far, or can take additional input to complete a longer key sequence). If no input is received within the timeout, Readline will use the shorter but complete key sequence. Readline uses this value to determine whether or not input is available on the current input source (`rl_instream` by default). The value is specified in milliseconds, so a value of 1000 means that Readline will wait one second for additional input. If this variable is set to a value less than or equal to zero, or to a non-numeric value, Readline will wait until another key is pressed to decide which key sequence to complete. The default value is `500`. `mark-directories` If set to β€˜`on`’, completed directory names have a slash appended. The default is β€˜`on`’. `mark-modified-lines` This variable, when set to β€˜`on`’, causes Readline to display an asterisk (β€˜`\*`’) at the start of history lines which have been modified. This variable is β€˜`off`’ by default. `mark-symlinked-directories` If set to β€˜`on`’, completed names which are symbolic links to directories have a slash appended (subject to the value of `mark-directories`). The default is β€˜`off`’. `match-hidden-files` This variable, when set to β€˜`on`’, causes Readline to match files whose names begin with a β€˜`.`’ (hidden files) when performing filename completion. If set to β€˜`off`’, the leading β€˜`.`’ must be supplied by the user in the filename to be completed. This variable is β€˜`on`’ by default. `menu-complete-display-prefix` If set to β€˜`on`’, menu completion displays the common prefix of the list of possible completions (which may be empty) before cycling through the list. The default is β€˜`off`’. `output-meta` If set to β€˜`on`’, Readline will display characters with the eighth bit set directly rather than as a meta-prefixed escape sequence. The default is β€˜`off`’, but Readline will set it to β€˜`on`’ if the locale contains eight-bit characters. This variable is dependent on the `LC_CTYPE` locale category, and may change if the locale is changed. `page-completions` If set to β€˜`on`’, Readline uses an internal `more`-like pager to display a screenful of possible completions at a time. This variable is β€˜`on`’ by default. `print-completions-horizontally` If set to β€˜`on`’, Readline will display completions with matches sorted horizontally in alphabetical order, rather than down the screen. The default is β€˜`off`’. `revert-all-at-newline` If set to β€˜`on`’, Readline will undo all changes to history lines before returning when `accept-line` is executed. By default, history lines may be modified and retain individual undo lists across calls to `readline()`. The default is β€˜`off`’. `show-all-if-ambiguous` This alters the default behavior of the completion functions. If set to β€˜`on`’, words which have more than one possible completion cause the matches to be listed immediately instead of ringing the bell. The default value is β€˜`off`’. `show-all-if-unmodified` This alters the default behavior of the completion functions in a fashion similar to show-all-if-ambiguous. If set to β€˜`on`’, words which have more than one possible completion without any possible partial completion (the possible completions don’t share a common prefix) cause the matches to be listed immediately instead of ringing the bell. The default value is β€˜`off`’. `show-mode-in-prompt` If set to β€˜`on`’, add a string to the beginning of the prompt indicating the editing mode: emacs, vi command, or vi insertion. The mode strings are user-settable (e.g., emacs-mode-string). The default value is β€˜`off`’. `skip-completed-text` If set to β€˜`on`’, this alters the default completion behavior when inserting a single match into the line. It’s only active when performing completion in the middle of a word. If enabled, Readline does not insert characters from the completion that match characters after point in the word being completed, so portions of the word following the cursor are not duplicated. For instance, if this is enabled, attempting completion when the cursor is after the β€˜`e`’ in β€˜`Makefile`’ will result in β€˜`Makefile`’ rather than β€˜`Makefilefile`’, assuming there is a single possible completion. The default value is β€˜`off`’. `vi-cmd-mode-string` If the show-mode-in-prompt variable is enabled, this string is displayed immediately before the last line of the primary prompt when vi editing mode is active and in command mode. The value is expanded like a key binding, so the standard set of meta- and control prefixes and backslash escape sequences is available. Use the β€˜`\1`’ and β€˜`\2`’ escapes to begin and end sequences of non-printing characters, which can be used to embed a terminal control sequence into the mode string. The default is β€˜`(cmd)`’. `vi-ins-mode-string` If the show-mode-in-prompt variable is enabled, this string is displayed immediately before the last line of the primary prompt when vi editing mode is active and in insertion mode. The value is expanded like a key binding, so the standard set of meta- and control prefixes and backslash escape sequences is available. Use the β€˜`\1`’ and β€˜`\2`’ escapes to begin and end sequences of non-printing characters, which can be used to embed a terminal control sequence into the mode string. The default is β€˜`(ins)`’. `visible-stats` If set to β€˜`on`’, a character denoting a file’s type is appended to the filename when listing possible completions. The default is β€˜`off`’. Key Bindings The syntax for controlling key bindings in the init file is simple. First you need to find the name of the command that you want to change. The following sections contain tables of the command name, the default keybinding, if any, and a short description of what the command does. Once you know the name of the command, simply place on a line in the init file the name of the key you wish to bind the command to, a colon, and then the name of the command. There can be no space between the key name and the colon – that will be interpreted as part of the key name. The name of the key can be expressed in different ways, depending on what you find most comfortable. In addition to command names, Readline allows keys to be bound to a string that is inserted when the key is pressed (a macro). The `bindΒ -p` command displays Readline function names and bindings in a format that can be put directly into an initialization file. See [Bash Builtin Commands](bash-builtins). keyname: function-name or macro keyname is the name of a key spelled out in English. For example: ``` Control-u: universal-argument Meta-Rubout: backward-kill-word Control-o: "> output" ``` In the example above, `C-u` is bound to the function `universal-argument`, `M-DEL` is bound to the function `backward-kill-word`, and `C-o` is bound to run the macro expressed on the right hand side (that is, to insert the text β€˜`> output`’ into the line). A number of symbolic character names are recognized while processing this key binding syntax: DEL, ESC, ESCAPE, LFD, NEWLINE, RET, RETURN, RUBOUT, SPACE, SPC, and TAB. "keyseq": function-name or macro keyseq differs from keyname above in that strings denoting an entire key sequence can be specified, by placing the key sequence in double quotes. Some GNU Emacs style key escapes can be used, as in the following example, but the special character names are not recognized. ``` "\C-u": universal-argument "\C-x\C-r": re-read-init-file "\e[11~": "Function Key 1" ``` In the above example, `C-u` is again bound to the function `universal-argument` (just as it was in the first example), β€˜``C-x` `C-r``’ is bound to the function `re-read-init-file`, and β€˜`ESC [ 1 1 ~`’ is bound to insert the text β€˜`Function Key 1`’. The following GNU Emacs style escape sequences are available when specifying key sequences: ``\C-`` control prefix ``\M-`` meta prefix ``\e`` an escape character ``\\`` backslash ``\"`` `"`, a double quotation mark ``\'`` `'`, a single quote or apostrophe In addition to the GNU Emacs style escape sequences, a second set of backslash escapes is available: `\a` alert (bell) `\b` backspace `\d` delete `\f` form feed `\n` newline `\r` carriage return `\t` horizontal tab `\v` vertical tab `\nnn` the eight-bit character whose value is the octal value nnn (one to three digits) `\xHH` the eight-bit character whose value is the hexadecimal value HH (one or two hex digits) When entering the text of a macro, single or double quotes must be used to indicate a macro definition. Unquoted text is assumed to be a function name. In the macro body, the backslash escapes described above are expanded. Backslash will quote any other character in the macro text, including β€˜`"`’ and β€˜`'`’. For example, the following binding will make β€˜``C-x` \`’ insert a single β€˜`\`’ into the line: ``` "\C-x\\": "\\" ```
programming_docs
bash Simple Command Expansion Simple Command Expansion ======================== When a simple command is executed, the shell performs the following expansions, assignments, and redirections, from left to right, in the following order. 1. The words that the parser has marked as variable assignments (those preceding the command name) and redirections are saved for later processing. 2. The words that are not variable assignments or redirections are expanded (see [Shell Expansions](shell-expansions)). If any words remain after expansion, the first word is taken to be the name of the command and the remaining words are the arguments. 3. Redirections are performed as described above (see [Redirections](redirections)). 4. The text after the β€˜`=`’ in each variable assignment undergoes tilde expansion, parameter expansion, command substitution, arithmetic expansion, and quote removal before being assigned to the variable. If no command name results, the variable assignments affect the current shell environment. In the case of such a command (one that consists only of assignment statements and redirections), assignment statements are performed before redirections. Otherwise, the variables are added to the environment of the executed command and do not affect the current shell environment. If any of the assignments attempts to assign a value to a readonly variable, an error occurs, and the command exits with a non-zero status. If no command name results, redirections are performed, but do not affect the current shell environment. A redirection error causes the command to exit with a non-zero status. If there is a command name left after expansion, execution proceeds as described below. Otherwise, the command exits. If one of the expansions contained a command substitution, the exit status of the command is the exit status of the last command substitution performed. If there were no command substitutions, the command exits with a status of zero. bash Pipelines Pipelines ========= A `pipeline` is a sequence of one or more commands separated by one of the control operators β€˜`|`’ or β€˜`|&`’. The format for a pipeline is ``` [time [-p]] [!] command1 [ | or |& command2 ] … ``` The output of each command in the pipeline is connected via a pipe to the input of the next command. That is, each command reads the previous command’s output. This connection is performed before any redirections specified by command1. If β€˜`|&`’ is used, command1’s standard error, in addition to its standard output, is connected to command2’s standard input through the pipe; it is shorthand for `2>&1 |`. This implicit redirection of the standard error to the standard output is performed after any redirections specified by command1. The reserved word `time` causes timing statistics to be printed for the pipeline once it finishes. The statistics currently consist of elapsed (wall-clock) time and user and system time consumed by the command’s execution. The `-p` option changes the output format to that specified by POSIX. When the shell is in POSIX mode (see [Bash POSIX Mode](bash-posix-mode)), it does not recognize `time` as a reserved word if the next token begins with a β€˜`-`’. The `TIMEFORMAT` variable may be set to a format string that specifies how the timing information should be displayed. See [Bash Variables](bash-variables), for a description of the available formats. The use of `time` as a reserved word permits the timing of shell builtins, shell functions, and pipelines. An external `time` command cannot time these easily. When the shell is in POSIX mode (see [Bash POSIX Mode](bash-posix-mode)), `time` may be followed by a newline. In this case, the shell displays the total user and system time consumed by the shell and its children. The `TIMEFORMAT` variable may be used to specify the format of the time information. If the pipeline is not executed asynchronously (see [Lists of Commands](lists)), the shell waits for all commands in the pipeline to complete. Each command in a multi-command pipeline, where pipes are created, is executed in its own *subshell*, which is a separate process (see [Command Execution Environment](command-execution-environment)). If the `lastpipe` option is enabled using the `shopt` builtin (see [The Shopt Builtin](the-shopt-builtin)), the last element of a pipeline may be run by the shell process when job control is not active. The exit status of a pipeline is the exit status of the last command in the pipeline, unless the `pipefail` option is enabled (see [The Set Builtin](the-set-builtin)). If `pipefail` is enabled, the pipeline’s return status is the value of the last (rightmost) command to exit with a non-zero status, or zero if all commands exit successfully. If the reserved word β€˜`!`’ precedes the pipeline, the exit status is the logical negation of the exit status as described above. The shell waits for all commands in the pipeline to terminate before returning a value. bash Grouping Commands Grouping Commands ================= Bash provides two ways to group a list of commands to be executed as a unit. When commands are grouped, redirections may be applied to the entire command list. For example, the output of all the commands in the list may be redirected to a single stream. `()` ``` ( list ) ``` Placing a list of commands between parentheses forces the shell to create a subshell (see [Command Execution Environment](command-execution-environment)), and each of the commands in list is executed in that subshell environment. Since the list is executed in a subshell, variable assignments do not remain in effect after the subshell completes. `{}` ``` { list; } ``` Placing a list of commands between curly braces causes the list to be executed in the current shell context. No subshell is created. The semicolon (or newline) following list is required. In addition to the creation of a subshell, there is a subtle difference between these two constructs due to historical reasons. The braces are reserved words, so they must be separated from the list by `blank`s or other shell metacharacters. The parentheses are operators, and are recognized as separate tokens by the shell even if they are not separated from the list by whitespace. The exit status of both of these constructs is the exit status of list. bash Shell Syntax Shell Syntax ============ When the shell reads input, it proceeds through a sequence of operations. If the input indicates the beginning of a comment, the shell ignores the comment symbol (β€˜`#`’), and the rest of that line. Otherwise, roughly speaking, the shell reads its input and divides the input into words and operators, employing the quoting rules to select which meanings to assign various words and characters. The shell then parses these tokens into commands and other constructs, removes the special meaning of certain words or characters, expands others, redirects input and output as needed, executes the specified command, waits for the command’s exit status, and makes that exit status available for further inspection or processing. * [Shell Operation](shell-operation) * [Quoting](quoting) * [Comments](comments) bash Bash Startup Files Bash Startup Files ================== This section describes how Bash executes its startup files. If any of the files exist but cannot be read, Bash reports an error. Tildes are expanded in filenames as described above under Tilde Expansion (see [Tilde Expansion](tilde-expansion)). Interactive shells are described in [Interactive Shells](interactive-shells). #### Invoked as an interactive login shell, or with `--login` When Bash is invoked as an interactive login shell, or as a non-interactive shell with the `--login` option, it first reads and executes commands from the file `/etc/profile`, if that file exists. After reading that file, it looks for `~/.bash\_profile`, `~/.bash\_login`, and `~/.profile`, in that order, and reads and executes commands from the first one that exists and is readable. The `--noprofile` option may be used when the shell is started to inhibit this behavior. When an interactive login shell exits, or a non-interactive login shell executes the `exit` builtin command, Bash reads and executes commands from the file `~/.bash\_logout`, if it exists. #### Invoked as an interactive non-login shell When an interactive shell that is not a login shell is started, Bash reads and executes commands from `~/.bashrc`, if that file exists. This may be inhibited by using the `--norc` option. The `--rcfile file` option will force Bash to read and execute commands from file instead of `~/.bashrc`. So, typically, your `~/.bash\_profile` contains the line ``` if [ -f ~/.bashrc ]; then . ~/.bashrc; fi ``` after (or before) any login-specific initializations. #### Invoked non-interactively When Bash is started non-interactively, to run a shell script, for example, it looks for the variable `BASH_ENV` in the environment, expands its value if it appears there, and uses the expanded value as the name of a file to read and execute. Bash behaves as if the following command were executed: ``` if [ -n "$BASH_ENV" ]; then . "$BASH_ENV"; fi ``` but the value of the `PATH` variable is not used to search for the filename. As noted above, if a non-interactive shell is invoked with the `--login` option, Bash attempts to read and execute commands from the login shell startup files. #### Invoked with name `sh` If Bash is invoked with the name `sh`, it tries to mimic the startup behavior of historical versions of `sh` as closely as possible, while conforming to the POSIX standard as well. When invoked as an interactive login shell, or as a non-interactive shell with the `--login` option, it first attempts to read and execute commands from `/etc/profile` and `~/.profile`, in that order. The `--noprofile` option may be used to inhibit this behavior. When invoked as an interactive shell with the name `sh`, Bash looks for the variable `ENV`, expands its value if it is defined, and uses the expanded value as the name of a file to read and execute. Since a shell invoked as `sh` does not attempt to read and execute commands from any other startup files, the `--rcfile` option has no effect. A non-interactive shell invoked with the name `sh` does not attempt to read any other startup files. When invoked as `sh`, Bash enters POSIX mode after the startup files are read. #### Invoked in POSIX mode When Bash is started in POSIX mode, as with the `--posix` command line option, it follows the POSIX standard for startup files. In this mode, interactive shells expand the `ENV` variable and commands are read and executed from the file whose name is the expanded value. No other startup files are read. #### Invoked by remote shell daemon Bash attempts to determine when it is being run with its standard input connected to a network connection, as when executed by the historical remote shell daemon, usually `rshd`, or the secure shell daemon `sshd`. If Bash determines it is being run non-interactively in this fashion, it reads and executes commands from `~/.bashrc`, if that file exists and is readable. It will not do this if invoked as `sh`. The `--norc` option may be used to inhibit this behavior, and the `--rcfile` option may be used to force another file to be read, but neither `rshd` nor `sshd` generally invoke the shell with those options or allow them to be specified. #### Invoked with unequal effective and real UID/GIDs If Bash is started with the effective user (group) id not equal to the real user (group) id, and the `-p` option is not supplied, no startup files are read, shell functions are not inherited from the environment, the `SHELLOPTS`, `BASHOPTS`, `CDPATH`, and `GLOBIGNORE` variables, if they appear in the environment, are ignored, and the effective user id is set to the real user id. If the `-p` option is supplied at invocation, the startup behavior is the same, but the effective user id is not reset. bash The Directory Stack The Directory Stack =================== The directory stack is a list of recently-visited directories. The `pushd` builtin adds directories to the stack as it changes the current directory, and the `popd` builtin removes specified directories from the stack and changes the current directory to the directory removed. The `dirs` builtin displays the contents of the directory stack. The current directory is always the "top" of the directory stack. The contents of the directory stack are also visible as the value of the `DIRSTACK` shell variable. * [Directory Stack Builtins](directory-stack-builtins) bash Pattern Matching Pattern Matching ================ Any character that appears in a pattern, other than the special pattern characters described below, matches itself. The NUL character may not occur in a pattern. A backslash escapes the following character; the escaping backslash is discarded when matching. The special pattern characters must be quoted if they are to be matched literally. The special pattern characters have the following meanings: `*` Matches any string, including the null string. When the `globstar` shell option is enabled, and β€˜`\*`’ is used in a filename expansion context, two adjacent β€˜`\*`’s used as a single pattern will match all files and zero or more directories and subdirectories. If followed by a β€˜`/`’, two adjacent β€˜`\*`’s will match only directories and subdirectories. `?` Matches any single character. `[…]` Matches any one of the enclosed characters. A pair of characters separated by a hyphen denotes a range expression; any character that falls between those two characters, inclusive, using the current locale’s collating sequence and character set, is matched. If the first character following the β€˜`[`’ is a β€˜`!`’ or a β€˜`^`’ then any character not enclosed is matched. A β€˜`-`’ may be matched by including it as the first or last character in the set. A β€˜`]`’ may be matched by including it as the first character in the set. The sorting order of characters in range expressions, and the characters included in the range, are determined by the current locale and the values of the `LC_COLLATE` and `LC_ALL` shell variables, if set. For example, in the default C locale, β€˜`[a-dx-z]`’ is equivalent to β€˜`[abcdxyz]`’. Many locales sort characters in dictionary order, and in these locales β€˜`[a-dx-z]`’ is typically not equivalent to β€˜`[abcdxyz]`’; it might be equivalent to β€˜`[aBbCcDdxYyZz]`’, for example. To obtain the traditional interpretation of ranges in bracket expressions, you can force the use of the C locale by setting the `LC_COLLATE` or `LC_ALL` environment variable to the value β€˜`C`’, or enable the `globasciiranges` shell option. Within β€˜`[`’ and β€˜`]`’, *character classes* can be specified using the syntax `[:`class`:]`, where class is one of the following classes defined in the POSIX standard: ``` alnum alpha ascii blank cntrl digit graph lower print punct space upper word xdigit ``` A character class matches any character belonging to that class. The `word` character class matches letters, digits, and the character β€˜`\_`’. Within β€˜`[`’ and β€˜`]`’, an *equivalence class* can be specified using the syntax `[=`c`=]`, which matches all characters with the same collation weight (as defined by the current locale) as the character c. Within β€˜`[`’ and β€˜`]`’, the syntax `[.`symbol`.]` matches the collating symbol symbol. If the `extglob` shell option is enabled using the `shopt` builtin, the shell recognizes several extended pattern matching operators. In the following description, a pattern-list is a list of one or more patterns separated by a β€˜`|`’. When matching filenames, the `dotglob` shell option determines the set of filenames that are tested, as described above. Composite patterns may be formed using one or more of the following sub-patterns: `?(pattern-list)` Matches zero or one occurrence of the given patterns. `*(pattern-list)` Matches zero or more occurrences of the given patterns. `+(pattern-list)` Matches one or more occurrences of the given patterns. `@(pattern-list)` Matches one of the given patterns. `!(pattern-list)` Matches anything except one of the given patterns. The `extglob` option changes the behavior of the parser, since the parentheses are normally treated as operators with syntactic meaning. To ensure that extended matching patterns are parsed correctly, make sure that `extglob` is enabled before parsing constructs containing the patterns, including shell functions and command substitutions. When matching filenames, the `dotglob` shell option determines the set of filenames that are tested: when `dotglob` is enabled, the set of filenames includes all files beginning with β€˜`.`’, but the filenames β€˜`.`’ and β€˜`..`’ must be matched by a pattern or sub-pattern that begins with a dot; when it is disabled, the set does not include any filenames beginning with β€œ.” unless the pattern or sub-pattern begins with a β€˜`.`’. As above, β€˜`.`’ only has a special meaning when matching filenames. Complicated extended pattern matching against long strings is slow, especially when the patterns contain alternations and the strings contain multiple matches. Using separate matches against shorter strings, or using arrays of strings instead of a single long string, may be faster. bash Bash Builtin Commands Bash Builtin Commands ===================== This section describes builtin commands which are unique to or have been extended in Bash. Some of these commands are specified in the POSIX standard. `alias` ``` alias [-p] [name[=value] …] ``` Without arguments or with the `-p` option, `alias` prints the list of aliases on the standard output in a form that allows them to be reused as input. If arguments are supplied, an alias is defined for each name whose value is given. If no value is given, the name and value of the alias is printed. Aliases are described in [Aliases](aliases). `bind` ``` bind [-m keymap] [-lpsvPSVX] bind [-m keymap] [-q function] [-u function] [-r keyseq] bind [-m keymap] -f filename bind [-m keymap] -x keyseq:shell-command bind [-m keymap] keyseq:function-name bind [-m keymap] keyseq:readline-command bind readline-command-line ``` Display current Readline (see [Command Line Editing](command-line-editing)) key and function bindings, bind a key sequence to a Readline function or macro, or set a Readline variable. Each non-option argument is a command as it would appear in a Readline initialization file (see [Readline Init File](readline-init-file)), but each binding or command must be passed as a separate argument; e.g., β€˜`"\C-x\C-r":re-read-init-file`’. Options, if supplied, have the following meanings: `-m keymap` Use keymap as the keymap to be affected by the subsequent bindings. Acceptable keymap names are `emacs`, `emacs-standard`, `emacs-meta`, `emacs-ctlx`, `vi`, `vi-move`, `vi-command`, and `vi-insert`. `vi` is equivalent to `vi-command` (`vi-move` is also a synonym); `emacs` is equivalent to `emacs-standard`. `-l` List the names of all Readline functions. `-p` Display Readline function names and bindings in such a way that they can be used as input or in a Readline initialization file. `-P` List current Readline function names and bindings. `-v` Display Readline variable names and values in such a way that they can be used as input or in a Readline initialization file. `-V` List current Readline variable names and values. `-s` Display Readline key sequences bound to macros and the strings they output in such a way that they can be used as input or in a Readline initialization file. `-S` Display Readline key sequences bound to macros and the strings they output. `-f filename` Read key bindings from filename. `-q function` Query about which keys invoke the named function. `-u function` Unbind all keys bound to the named function. `-r keyseq` Remove any current binding for keyseq. `-x keyseq:shell-command` Cause shell-command to be executed whenever keyseq is entered. When shell-command is executed, the shell sets the `READLINE_LINE` variable to the contents of the Readline line buffer and the `READLINE_POINT` and `READLINE_MARK` variables to the current location of the insertion point and the saved insertion point (the mark), respectively. The shell assigns any numeric argument the user supplied to the `READLINE_ARGUMENT` variable. If there was no argument, that variable is not set. If the executed command changes the value of any of `READLINE_LINE`, `READLINE_POINT`, or `READLINE_MARK`, those new values will be reflected in the editing state. `-X` List all key sequences bound to shell commands and the associated commands in a format that can be reused as input. The return status is zero unless an invalid option is supplied or an error occurs. `builtin` ``` builtin [shell-builtin [args]] ``` Run a shell builtin, passing it args, and return its exit status. This is useful when defining a shell function with the same name as a shell builtin, retaining the functionality of the builtin within the function. The return status is non-zero if shell-builtin is not a shell builtin command. `caller` ``` caller [expr] ``` Returns the context of any active subroutine call (a shell function or a script executed with the `.` or `source` builtins). Without expr, `caller` displays the line number and source filename of the current subroutine call. If a non-negative integer is supplied as expr, `caller` displays the line number, subroutine name, and source file corresponding to that position in the current execution call stack. This extra information may be used, for example, to print a stack trace. The current frame is frame 0. The return value is 0 unless the shell is not executing a subroutine call or expr does not correspond to a valid position in the call stack. `command` ``` command [-pVv] command [arguments …] ``` Runs command with arguments ignoring any shell function named command. Only shell builtin commands or commands found by searching the `PATH` are executed. If there is a shell function named `ls`, running β€˜`command ls`’ within the function will execute the external command `ls` instead of calling the function recursively. The `-p` option means to use a default value for `PATH` that is guaranteed to find all of the standard utilities. The return status in this case is 127 if command cannot be found or an error occurred, and the exit status of command otherwise. If either the `-V` or `-v` option is supplied, a description of command is printed. The `-v` option causes a single word indicating the command or file name used to invoke command to be displayed; the `-V` option produces a more verbose description. In this case, the return status is zero if command is found, and non-zero if not. `declare` ``` declare [-aAfFgiIlnrtux] [-p] [name[=value] …] ``` Declare variables and give them attributes. If no names are given, then display the values of variables instead. The `-p` option will display the attributes and values of each name. When `-p` is used with name arguments, additional options, other than `-f` and `-F`, are ignored. When `-p` is supplied without name arguments, `declare` will display the attributes and values of all variables having the attributes specified by the additional options. If no other options are supplied with `-p`, `declare` will display the attributes and values of all shell variables. The `-f` option will restrict the display to shell functions. The `-F` option inhibits the display of function definitions; only the function name and attributes are printed. If the `extdebug` shell option is enabled using `shopt` (see [The Shopt Builtin](the-shopt-builtin)), the source file name and line number where each name is defined are displayed as well. `-F` implies `-f`. The `-g` option forces variables to be created or modified at the global scope, even when `declare` is executed in a shell function. It is ignored in all other cases. The `-I` option causes local variables to inherit the attributes (except the `nameref` attribute) and value of any existing variable with the same name at a surrounding scope. If there is no existing variable, the local variable is initially unset. The following options can be used to restrict output to variables with the specified attributes or to give variables attributes: `-a` Each name is an indexed array variable (see [Arrays](arrays)). `-A` Each name is an associative array variable (see [Arrays](arrays)). `-f` Use function names only. `-i` The variable is to be treated as an integer; arithmetic evaluation (see [Shell Arithmetic](shell-arithmetic)) is performed when the variable is assigned a value. `-l` When the variable is assigned a value, all upper-case characters are converted to lower-case. The upper-case attribute is disabled. `-n` Give each name the `nameref` attribute, making it a name reference to another variable. That other variable is defined by the value of name. All references, assignments, and attribute modifications to name, except for those using or changing the `-n` attribute itself, are performed on the variable referenced by name’s value. The nameref attribute cannot be applied to array variables. `-r` Make names readonly. These names cannot then be assigned values by subsequent assignment statements or unset. `-t` Give each name the `trace` attribute. Traced functions inherit the `DEBUG` and `RETURN` traps from the calling shell. The trace attribute has no special meaning for variables. `-u` When the variable is assigned a value, all lower-case characters are converted to upper-case. The lower-case attribute is disabled. `-x` Mark each name for export to subsequent commands via the environment. Using β€˜`+`’ instead of β€˜`-`’ turns off the attribute instead, with the exceptions that β€˜`+a`’ and β€˜`+A`’ may not be used to destroy array variables and β€˜`+r`’ will not remove the readonly attribute. When used in a function, `declare` makes each name local, as with the `local` command, unless the `-g` option is used. If a variable name is followed by =value, the value of the variable is set to value. When using `-a` or `-A` and the compound assignment syntax to create array variables, additional attributes do not take effect until subsequent assignments. The return status is zero unless an invalid option is encountered, an attempt is made to define a function using β€˜`-f foo=bar`’, an attempt is made to assign a value to a readonly variable, an attempt is made to assign a value to an array variable without using the compound assignment syntax (see [Arrays](arrays)), one of the names is not a valid shell variable name, an attempt is made to turn off readonly status for a readonly variable, an attempt is made to turn off array status for an array variable, or an attempt is made to display a non-existent function with `-f`. `echo` ``` echo [-neE] [arg …] ``` Output the args, separated by spaces, terminated with a newline. The return status is 0 unless a write error occurs. If `-n` is specified, the trailing newline is suppressed. If the `-e` option is given, interpretation of the following backslash-escaped characters is enabled. The `-E` option disables the interpretation of these escape characters, even on systems where they are interpreted by default. The `xpg_echo` shell option may be used to dynamically determine whether or not `echo` expands these escape characters by default. `echo` does not interpret `--` to mean the end of options. `echo` interprets the following escape sequences: `\a` alert (bell) `\b` backspace `\c` suppress further output `\e` `\E` escape `\f` form feed `\n` new line `\r` carriage return `\t` horizontal tab `\v` vertical tab `\\` backslash `\0nnn` the eight-bit character whose value is the octal value nnn (zero to three octal digits) `\xHH` the eight-bit character whose value is the hexadecimal value HH (one or two hex digits) `\uHHHH` the Unicode (ISO/IEC 10646) character whose value is the hexadecimal value HHHH (one to four hex digits) `\UHHHHHHHH` the Unicode (ISO/IEC 10646) character whose value is the hexadecimal value HHHHHHHH (one to eight hex digits) `enable` ``` enable [-a] [-dnps] [-f filename] [name …] ``` Enable and disable builtin shell commands. Disabling a builtin allows a disk command which has the same name as a shell builtin to be executed without specifying a full pathname, even though the shell normally searches for builtins before disk commands. If `-n` is used, the names become disabled. Otherwise names are enabled. For example, to use the `test` binary found via `$PATH` instead of the shell builtin version, type β€˜`enable -n test`’. If the `-p` option is supplied, or no name arguments appear, a list of shell builtins is printed. With no other arguments, the list consists of all enabled shell builtins. The `-a` option means to list each builtin with an indication of whether or not it is enabled. The `-f` option means to load the new builtin command name from shared object filename, on systems that support dynamic loading. Bash will use the value of the `BASH_LOADABLES_PATH` variable as a colon-separated list of directories in which to search for filename. The default is system-dependent. The `-d` option will delete a builtin loaded with `-f`. If there are no options, a list of the shell builtins is displayed. The `-s` option restricts `enable` to the POSIX special builtins. If `-s` is used with `-f`, the new builtin becomes a special builtin (see [Special Builtins](special-builtins)). If no options are supplied and a name is not a shell builtin, `enable` will attempt to load name from a shared object named name, as if the command were β€˜`enable -f name name`’. The return status is zero unless a name is not a shell builtin or there is an error loading a new builtin from a shared object. `help` ``` help [-dms] [pattern] ``` Display helpful information about builtin commands. If pattern is specified, `help` gives detailed help on all commands matching pattern, otherwise a list of the builtins is printed. Options, if supplied, have the following meanings: `-d` Display a short description of each pattern `-m` Display the description of each pattern in a manpage-like format `-s` Display only a short usage synopsis for each pattern The return status is zero unless no command matches pattern. `let` ``` let expression [expression …] ``` The `let` builtin allows arithmetic to be performed on shell variables. Each expression is evaluated according to the rules given below in [Shell Arithmetic](shell-arithmetic). If the last expression evaluates to 0, `let` returns 1; otherwise 0 is returned. `local` ``` local [option] name[=value] … ``` For each argument, a local variable named name is created, and assigned value. The option can be any of the options accepted by `declare`. `local` can only be used within a function; it makes the variable name have a visible scope restricted to that function and its children. If name is β€˜`-`’, the set of shell options is made local to the function in which `local` is invoked: shell options changed using the `set` builtin inside the function are restored to their original values when the function returns. The restore is effected as if a series of `set` commands were executed to restore the values that were in place before the function. The return status is zero unless `local` is used outside a function, an invalid name is supplied, or name is a readonly variable. `logout` ``` logout [n] ``` Exit a login shell, returning a status of n to the shell’s parent. `mapfile` ``` mapfile [-d delim] [-n count] [-O origin] [-s count] [-t] [-u fd] [-C callback] [-c quantum] [array] ``` Read lines from the standard input into the indexed array variable array, or from file descriptor fd if the `-u` option is supplied. The variable `MAPFILE` is the default array. Options, if supplied, have the following meanings: `-d` The first character of delim is used to terminate each input line, rather than newline. If delim is the empty string, `mapfile` will terminate a line when it reads a NUL character. `-n` Copy at most count lines. If count is 0, all lines are copied. `-O` Begin assigning to array at index origin. The default index is 0. `-s` Discard the first count lines read. `-t` Remove a trailing delim (default newline) from each line read. `-u` Read lines from file descriptor fd instead of the standard input. `-C` Evaluate callback each time quantum lines are read. The `-c` option specifies quantum. `-c` Specify the number of lines read between each call to callback. If `-C` is specified without `-c`, the default quantum is 5000. When callback is evaluated, it is supplied the index of the next array element to be assigned and the line to be assigned to that element as additional arguments. callback is evaluated after the line is read but before the array element is assigned. If not supplied with an explicit origin, `mapfile` will clear array before assigning to it. `mapfile` returns successfully unless an invalid option or option argument is supplied, array is invalid or unassignable, or array is not an indexed array. `printf` ``` printf [-v var] format [arguments] ``` Write the formatted arguments to the standard output under the control of the format. The `-v` option causes the output to be assigned to the variable var rather than being printed to the standard output. The format is a character string which contains three types of objects: plain characters, which are simply copied to standard output, character escape sequences, which are converted and copied to the standard output, and format specifications, each of which causes printing of the next successive argument. In addition to the standard `printf(1)` formats, `printf` interprets the following extensions: `%b` Causes `printf` to expand backslash escape sequences in the corresponding argument in the same way as `echo -e` (see [Bash Builtin Commands](#Bash-Builtins)). `%q` Causes `printf` to output the corresponding argument in a format that can be reused as shell input. `%Q` like `%q`, but applies any supplied precision to the argument before quoting it. `%(datefmt)T` Causes `printf` to output the date-time string resulting from using datefmt as a format string for `strftime`(3). The corresponding argument is an integer representing the number of seconds since the epoch. Two special argument values may be used: -1 represents the current time, and -2 represents the time the shell was invoked. If no argument is specified, conversion behaves as if -1 had been given. This is an exception to the usual `printf` behavior. The %b, %q, and %T directives all use the field width and precision arguments from the format specification and write that many bytes from (or use that wide a field for) the expanded argument, which usually contains more characters than the original. Arguments to non-string format specifiers are treated as C language constants, except that a leading plus or minus sign is allowed, and if the leading character is a single or double quote, the value is the ASCII value of the following character. The format is reused as necessary to consume all of the arguments. If the format requires more arguments than are supplied, the extra format specifications behave as if a zero value or null string, as appropriate, had been supplied. The return value is zero on success, non-zero on failure. `read` ``` read [-ers] [-a aname] [-d delim] [-i text] [-n nchars] [-N nchars] [-p prompt] [-t timeout] [-u fd] [name …] ``` One line is read from the standard input, or from the file descriptor fd supplied as an argument to the `-u` option, split into words as described above in [Word Splitting](word-splitting), and the first word is assigned to the first name, the second word to the second name, and so on. If there are more words than names, the remaining words and their intervening delimiters are assigned to the last name. If there are fewer words read from the input stream than names, the remaining names are assigned empty values. The characters in the value of the `IFS` variable are used to split the line into words using the same rules the shell uses for expansion (described above in [Word Splitting](word-splitting)). The backslash character β€˜`\`’ may be used to remove any special meaning for the next character read and for line continuation. Options, if supplied, have the following meanings: `-a aname` The words are assigned to sequential indices of the array variable aname, starting at 0. All elements are removed from aname before the assignment. Other name arguments are ignored. `-d delim` The first character of delim is used to terminate the input line, rather than newline. If delim is the empty string, `read` will terminate a line when it reads a NUL character. `-e` Readline (see [Command Line Editing](command-line-editing)) is used to obtain the line. Readline uses the current (or default, if line editing was not previously active) editing settings, but uses Readline’s default filename completion. `-i text` If Readline is being used to read the line, text is placed into the editing buffer before editing begins. `-n nchars` `read` returns after reading nchars characters rather than waiting for a complete line of input, but honors a delimiter if fewer than nchars characters are read before the delimiter. `-N nchars` `read` returns after reading exactly nchars characters rather than waiting for a complete line of input, unless EOF is encountered or `read` times out. Delimiter characters encountered in the input are not treated specially and do not cause `read` to return until nchars characters are read. The result is not split on the characters in `IFS`; the intent is that the variable is assigned exactly the characters read (with the exception of backslash; see the `-r` option below). `-p prompt` Display prompt, without a trailing newline, before attempting to read any input. The prompt is displayed only if input is coming from a terminal. `-r` If this option is given, backslash does not act as an escape character. The backslash is considered to be part of the line. In particular, a backslash-newline pair may not then be used as a line continuation. `-s` Silent mode. If input is coming from a terminal, characters are not echoed. `-t timeout` Cause `read` to time out and return failure if a complete line of input (or a specified number of characters) is not read within timeout seconds. timeout may be a decimal number with a fractional portion following the decimal point. This option is only effective if `read` is reading input from a terminal, pipe, or other special file; it has no effect when reading from regular files. If `read` times out, `read` saves any partial input read into the specified variable name. If timeout is 0, `read` returns immediately, without trying to read any data. The exit status is 0 if input is available on the specified file descriptor, or the read will return EOF, non-zero otherwise. The exit status is greater than 128 if the timeout is exceeded. `-u fd` Read input from file descriptor fd. If no names are supplied, the line read, without the ending delimiter but otherwise unmodified, is assigned to the variable `REPLY`. The exit status is zero, unless end-of-file is encountered, `read` times out (in which case the status is greater than 128), a variable assignment error (such as assigning to a readonly variable) occurs, or an invalid file descriptor is supplied as the argument to `-u`. `readarray` ``` readarray [-d delim] [-n count] [-O origin] [-s count] [-t] [-u fd] [-C callback] [-c quantum] [array] ``` Read lines from the standard input into the indexed array variable array, or from file descriptor fd if the `-u` option is supplied. A synonym for `mapfile`. `source` ``` source filename ``` A synonym for `.` (see [Bourne Shell Builtins](bourne-shell-builtins)). `type` ``` type [-afptP] [name …] ``` For each name, indicate how it would be interpreted if used as a command name. If the `-t` option is used, `type` prints a single word which is one of β€˜`alias`’, β€˜`function`’, β€˜`builtin`’, β€˜`file`’ or β€˜`keyword`’, if name is an alias, shell function, shell builtin, disk file, or shell reserved word, respectively. If the name is not found, then nothing is printed, and `type` returns a failure status. If the `-p` option is used, `type` either returns the name of the disk file that would be executed, or nothing if `-t` would not return β€˜`file`’. The `-P` option forces a path search for each name, even if `-t` would not return β€˜`file`’. If a command is hashed, `-p` and `-P` print the hashed value, which is not necessarily the file that appears first in `$PATH`. If the `-a` option is used, `type` returns all of the places that contain an executable named file. This includes aliases and functions, if and only if the `-p` option is not also used. If the `-f` option is used, `type` does not attempt to find shell functions, as with the `command` builtin. The return status is zero if all of the names are found, non-zero if any are not found. `typeset` ``` typeset [-afFgrxilnrtux] [-p] [name[=value] …] ``` The `typeset` command is supplied for compatibility with the Korn shell. It is a synonym for the `declare` builtin command. `ulimit` ``` ulimit [-HS] -a ulimit [-HS] [-bcdefiklmnpqrstuvxPRT] [limit] ``` `ulimit` provides control over the resources available to processes started by the shell, on systems that allow such control. If an option is given, it is interpreted as follows: `-S` Change and report the soft limit associated with a resource. `-H` Change and report the hard limit associated with a resource. `-a` All current limits are reported; no limits are set. `-b` The maximum socket buffer size. `-c` The maximum size of core files created. `-d` The maximum size of a process’s data segment. `-e` The maximum scheduling priority ("nice"). `-f` The maximum size of files written by the shell and its children. `-i` The maximum number of pending signals. `-k` The maximum number of kqueues that may be allocated. `-l` The maximum size that may be locked into memory. `-m` The maximum resident set size (many systems do not honor this limit). `-n` The maximum number of open file descriptors (most systems do not allow this value to be set). `-p` The pipe buffer size. `-q` The maximum number of bytes in POSIX message queues. `-r` The maximum real-time scheduling priority. `-s` The maximum stack size. `-t` The maximum amount of cpu time in seconds. `-u` The maximum number of processes available to a single user. `-v` The maximum amount of virtual memory available to the shell, and, on some systems, to its children. `-x` The maximum number of file locks. `-P` The maximum number of pseudoterminals. `-R` The maximum time a real-time process can run before blocking, in microseconds. `-T` The maximum number of threads. If limit is given, and the `-a` option is not used, limit is the new value of the specified resource. The special limit values `hard`, `soft`, and `unlimited` stand for the current hard limit, the current soft limit, and no limit, respectively. A hard limit cannot be increased by a non-root user once it is set; a soft limit may be increased up to the value of the hard limit. Otherwise, the current value of the soft limit for the specified resource is printed, unless the `-H` option is supplied. When more than one resource is specified, the limit name and unit, if appropriate, are printed before the value. When setting new limits, if neither `-H` nor `-S` is supplied, both the hard and soft limits are set. If no option is given, then `-f` is assumed. Values are in 1024-byte increments, except for `-t`, which is in seconds; `-R`, which is in microseconds; `-p`, which is in units of 512-byte blocks; `-P`, `-T`, `-b`, `-k`, `-n` and `-u`, which are unscaled values; and, when in POSIX Mode (see [Bash POSIX Mode](bash-posix-mode)), `-c` and `-f`, which are in 512-byte increments. The return status is zero unless an invalid option or argument is supplied, or an error occurs while setting a new limit. `unalias` ``` unalias [-a] [name … ] ``` Remove each name from the list of aliases. If `-a` is supplied, all aliases are removed. Aliases are described in [Aliases](aliases).
programming_docs
bash Function Index Function Index ============== | | | | --- | --- | | Jump to: | [**A**](#Function-Index_fn_letter-A) [**B**](#Function-Index_fn_letter-B) [**C**](#Function-Index_fn_letter-C) [**D**](#Function-Index_fn_letter-D) [**E**](#Function-Index_fn_letter-E) [**F**](#Function-Index_fn_letter-F) [**G**](#Function-Index_fn_letter-G) [**H**](#Function-Index_fn_letter-H) [**I**](#Function-Index_fn_letter-I) [**K**](#Function-Index_fn_letter-K) [**M**](#Function-Index_fn_letter-M) [**N**](#Function-Index_fn_letter-N) [**O**](#Function-Index_fn_letter-O) [**P**](#Function-Index_fn_letter-P) [**Q**](#Function-Index_fn_letter-Q) [**R**](#Function-Index_fn_letter-R) [**S**](#Function-Index_fn_letter-S) [**T**](#Function-Index_fn_letter-T) [**U**](#Function-Index_fn_letter-U) [**Y**](#Function-Index_fn_letter-Y) | | | | | | --- | --- | --- | | | Index Entry | Section | | A | | | | | [`abort (C-g)`](miscellaneous-commands#abort%20(C-g)) | [Miscellaneous Commands](miscellaneous-commands#Miscellaneous%20Commands) | | | [`accept-line (Newline or Return)`](commands-for-history#accept-line%20(Newline%20or%20Return)) | [Commands For History](commands-for-history#Commands%20For%20History) | | | [`alias-expand-line ()`](miscellaneous-commands#alias-expand-line%20()) | [Miscellaneous Commands](miscellaneous-commands#Miscellaneous%20Commands) | | B | | | | | [`backward-char (C-b)`](commands-for-moving#backward-char%20(C-b)) | [Commands For Moving](commands-for-moving#Commands%20For%20Moving) | | | [`backward-delete-char (Rubout)`](commands-for-text#backward-delete-char%20(Rubout)) | [Commands For Text](commands-for-text#Commands%20For%20Text) | | | [`backward-kill-line (C-x Rubout)`](commands-for-killing#backward-kill-line%20(C-x%20Rubout)) | [Commands For Killing](commands-for-killing#Commands%20For%20Killing) | | | [`backward-kill-word (M-DEL)`](commands-for-killing#backward-kill-word%20(M-DEL)) | [Commands For Killing](commands-for-killing#Commands%20For%20Killing) | | | [`backward-word (M-b)`](commands-for-moving#backward-word%20(M-b)) | [Commands For Moving](commands-for-moving#Commands%20For%20Moving) | | | [`beginning-of-history (M-<)`](commands-for-history#beginning-of-history%20(M-<)) | [Commands For History](commands-for-history#Commands%20For%20History) | | | [`beginning-of-line (C-a)`](commands-for-moving#beginning-of-line%20(C-a)) | [Commands For Moving](commands-for-moving#Commands%20For%20Moving) | | | [`bracketed-paste-begin ()`](commands-for-text#bracketed-paste-begin%20()) | [Commands For Text](commands-for-text#Commands%20For%20Text) | | C | | | | | [`call-last-kbd-macro (C-x e)`](keyboard-macros#call-last-kbd-macro%20(C-x%20e)) | [Keyboard Macros](keyboard-macros#Keyboard%20Macros) | | | [`capitalize-word (M-c)`](commands-for-text#capitalize-word%20(M-c)) | [Commands For Text](commands-for-text#Commands%20For%20Text) | | | [`character-search (C-])`](miscellaneous-commands#character-search%20(C-%5D)) | [Miscellaneous Commands](miscellaneous-commands#Miscellaneous%20Commands) | | | [`character-search-backward (M-C-])`](miscellaneous-commands#character-search-backward%20(M-C-%5D)) | [Miscellaneous Commands](miscellaneous-commands#Miscellaneous%20Commands) | | | [`clear-display (M-C-l)`](commands-for-moving#clear-display%20(M-C-l)) | [Commands For Moving](commands-for-moving#Commands%20For%20Moving) | | | [`clear-screen (C-l)`](commands-for-moving#clear-screen%20(C-l)) | [Commands For Moving](commands-for-moving#Commands%20For%20Moving) | | | [`complete (TAB)`](commands-for-completion#complete%20(TAB)) | [Commands For Completion](commands-for-completion#Commands%20For%20Completion) | | | [`complete-command (M-!)`](commands-for-completion#complete-command%20(M-!)) | [Commands For Completion](commands-for-completion#Commands%20For%20Completion) | | | [`complete-filename (M-/)`](commands-for-completion#complete-filename%20(M-/)) | [Commands For Completion](commands-for-completion#Commands%20For%20Completion) | | | [`complete-hostname (M-@)`](commands-for-completion#complete-hostname%20(M-@)) | [Commands For Completion](commands-for-completion#Commands%20For%20Completion) | | | [`complete-into-braces (M-{)`](commands-for-completion#complete-into-braces%20(M-%7B)) | [Commands For Completion](commands-for-completion#Commands%20For%20Completion) | | | [`complete-username (M-~)`](commands-for-completion#complete-username%20(M-~)) | [Commands For Completion](commands-for-completion#Commands%20For%20Completion) | | | [`complete-variable (M-$)`](commands-for-completion#complete-variable%20(M-%24)) | [Commands For Completion](commands-for-completion#Commands%20For%20Completion) | | | [`copy-backward-word ()`](commands-for-killing#copy-backward-word%20()) | [Commands For Killing](commands-for-killing#Commands%20For%20Killing) | | | [`copy-forward-word ()`](commands-for-killing#copy-forward-word%20()) | [Commands For Killing](commands-for-killing#Commands%20For%20Killing) | | | [`copy-region-as-kill ()`](commands-for-killing#copy-region-as-kill%20()) | [Commands For Killing](commands-for-killing#Commands%20For%20Killing) | | D | | | | | [`dabbrev-expand ()`](commands-for-completion#dabbrev-expand%20()) | [Commands For Completion](commands-for-completion#Commands%20For%20Completion) | | | [`delete-char (C-d)`](commands-for-text#delete-char%20(C-d)) | [Commands For Text](commands-for-text#Commands%20For%20Text) | | | [`delete-char-or-list ()`](commands-for-completion#delete-char-or-list%20()) | [Commands For Completion](commands-for-completion#Commands%20For%20Completion) | | | [`delete-horizontal-space ()`](commands-for-killing#delete-horizontal-space%20()) | [Commands For Killing](commands-for-killing#Commands%20For%20Killing) | | | [`digit-argument (`M-0`, `M-1`, … `M--`)`](numeric-arguments#digit-argument%20(M-0,%20M-1,%20%E2%80%A6%20M--)) | [Numeric Arguments](numeric-arguments#Numeric%20Arguments) | | | [`display-shell-version (C-x C-v)`](miscellaneous-commands#display-shell-version%20(C-x%20C-v)) | [Miscellaneous Commands](miscellaneous-commands#Miscellaneous%20Commands) | | | [`do-lowercase-version (M-A, M-B, M-x, …)`](miscellaneous-commands#do-lowercase-version%20(M-A,%20M-B,%20M-x,%20%E2%80%A6)) | [Miscellaneous Commands](miscellaneous-commands#Miscellaneous%20Commands) | | | [`downcase-word (M-l)`](commands-for-text#downcase-word%20(M-l)) | [Commands For Text](commands-for-text#Commands%20For%20Text) | | | [`dump-functions ()`](miscellaneous-commands#dump-functions%20()) | [Miscellaneous Commands](miscellaneous-commands#Miscellaneous%20Commands) | | | [`dump-macros ()`](miscellaneous-commands#dump-macros%20()) | [Miscellaneous Commands](miscellaneous-commands#Miscellaneous%20Commands) | | | [`dump-variables ()`](miscellaneous-commands#dump-variables%20()) | [Miscellaneous Commands](miscellaneous-commands#Miscellaneous%20Commands) | | | [`dynamic-complete-history (M-TAB)`](commands-for-completion#dynamic-complete-history%20(M-TAB)) | [Commands For Completion](commands-for-completion#Commands%20For%20Completion) | | E | | | | | [`edit-and-execute-command (C-x C-e)`](miscellaneous-commands#edit-and-execute-command%20(C-x%20C-e)) | [Miscellaneous Commands](miscellaneous-commands#Miscellaneous%20Commands) | | | [`end-kbd-macro (C-x ))`](keyboard-macros#end-kbd-macro%20(C-x%20))) | [Keyboard Macros](keyboard-macros#Keyboard%20Macros) | | | [`*end-of-file* (usually C-d)`](commands-for-text#end-of-file%20(usually%20C-d)) | [Commands For Text](commands-for-text#Commands%20For%20Text) | | | [`end-of-history (M->)`](commands-for-history#end-of-history%20(M->)) | [Commands For History](commands-for-history#Commands%20For%20History) | | | [`end-of-line (C-e)`](commands-for-moving#end-of-line%20(C-e)) | [Commands For Moving](commands-for-moving#Commands%20For%20Moving) | | | [`exchange-point-and-mark (C-x C-x)`](miscellaneous-commands#exchange-point-and-mark%20(C-x%20C-x)) | [Miscellaneous Commands](miscellaneous-commands#Miscellaneous%20Commands) | | F | | | | | [`fetch-history ()`](commands-for-history#fetch-history%20()) | [Commands For History](commands-for-history#Commands%20For%20History) | | | [`forward-backward-delete-char ()`](commands-for-text#forward-backward-delete-char%20()) | [Commands For Text](commands-for-text#Commands%20For%20Text) | | | [`forward-char (C-f)`](commands-for-moving#forward-char%20(C-f)) | [Commands For Moving](commands-for-moving#Commands%20For%20Moving) | | | [`forward-search-history (C-s)`](commands-for-history#forward-search-history%20(C-s)) | [Commands For History](commands-for-history#Commands%20For%20History) | | | [`forward-word (M-f)`](commands-for-moving#forward-word%20(M-f)) | [Commands For Moving](commands-for-moving#Commands%20For%20Moving) | | G | | | | | [`glob-complete-word (M-g)`](miscellaneous-commands#glob-complete-word%20(M-g)) | [Miscellaneous Commands](miscellaneous-commands#Miscellaneous%20Commands) | | | [`glob-expand-word (C-x *)`](miscellaneous-commands#glob-expand-word%20(C-x%20*)) | [Miscellaneous Commands](miscellaneous-commands#Miscellaneous%20Commands) | | | [`glob-list-expansions (C-x g)`](miscellaneous-commands#glob-list-expansions%20(C-x%20g)) | [Miscellaneous Commands](miscellaneous-commands#Miscellaneous%20Commands) | | H | | | | | [`history-and-alias-expand-line ()`](miscellaneous-commands#history-and-alias-expand-line%20()) | [Miscellaneous Commands](miscellaneous-commands#Miscellaneous%20Commands) | | | [`history-expand-line (M-^)`](miscellaneous-commands#history-expand-line%20(M-%5E)) | [Miscellaneous Commands](miscellaneous-commands#Miscellaneous%20Commands) | | | [`history-search-backward ()`](commands-for-history#history-search-backward%20()) | [Commands For History](commands-for-history#Commands%20For%20History) | | | [`history-search-forward ()`](commands-for-history#history-search-forward%20()) | [Commands For History](commands-for-history#Commands%20For%20History) | | | [`history-substring-search-backward ()`](commands-for-history#history-substring-search-backward%20()) | [Commands For History](commands-for-history#Commands%20For%20History) | | | [`history-substring-search-forward ()`](commands-for-history#history-substring-search-forward%20()) | [Commands For History](commands-for-history#Commands%20For%20History) | | I | | | | | [`insert-comment (M-#)`](miscellaneous-commands#insert-comment%20(M-#)) | [Miscellaneous Commands](miscellaneous-commands#Miscellaneous%20Commands) | | | [`insert-completions (M-*)`](commands-for-completion#insert-completions%20(M-*)) | [Commands For Completion](commands-for-completion#Commands%20For%20Completion) | | | [`insert-last-argument (M-. or M-_)`](miscellaneous-commands#insert-last-argument%20(M-.%20or%20M-_)) | [Miscellaneous Commands](miscellaneous-commands#Miscellaneous%20Commands) | | K | | | | | [`kill-line (C-k)`](commands-for-killing#kill-line%20(C-k)) | [Commands For Killing](commands-for-killing#Commands%20For%20Killing) | | | [`kill-region ()`](commands-for-killing#kill-region%20()) | [Commands For Killing](commands-for-killing#Commands%20For%20Killing) | | | [`kill-whole-line ()`](commands-for-killing#kill-whole-line%20()) | [Commands For Killing](commands-for-killing#Commands%20For%20Killing) | | | [`kill-word (M-d)`](commands-for-killing#kill-word%20(M-d)) | [Commands For Killing](commands-for-killing#Commands%20For%20Killing) | | M | | | | | [`magic-space ()`](miscellaneous-commands#magic-space%20()) | [Miscellaneous Commands](miscellaneous-commands#Miscellaneous%20Commands) | | | [`menu-complete ()`](commands-for-completion#menu-complete%20()) | [Commands For Completion](commands-for-completion#Commands%20For%20Completion) | | | [`menu-complete-backward ()`](commands-for-completion#menu-complete-backward%20()) | [Commands For Completion](commands-for-completion#Commands%20For%20Completion) | | N | | | | | [`next-history (C-n)`](commands-for-history#next-history%20(C-n)) | [Commands For History](commands-for-history#Commands%20For%20History) | | | [`next-screen-line ()`](commands-for-moving#next-screen-line%20()) | [Commands For Moving](commands-for-moving#Commands%20For%20Moving) | | | [`non-incremental-forward-search-history (M-n)`](commands-for-history#non-incremental-forward-search-history%20(M-n)) | [Commands For History](commands-for-history#Commands%20For%20History) | | | [`non-incremental-reverse-search-history (M-p)`](commands-for-history#non-incremental-reverse-search-history%20(M-p)) | [Commands For History](commands-for-history#Commands%20For%20History) | | O | | | | | [`operate-and-get-next (C-o)`](commands-for-history#operate-and-get-next%20(C-o)) | [Commands For History](commands-for-history#Commands%20For%20History) | | | [`overwrite-mode ()`](commands-for-text#overwrite-mode%20()) | [Commands For Text](commands-for-text#Commands%20For%20Text) | | P | | | | | [`possible-command-completions (C-x !)`](commands-for-completion#possible-command-completions%20(C-x%20!)) | [Commands For Completion](commands-for-completion#Commands%20For%20Completion) | | | [`possible-completions (M-?)`](commands-for-completion#possible-completions%20(M-?)) | [Commands For Completion](commands-for-completion#Commands%20For%20Completion) | | | [`possible-filename-completions (C-x /)`](commands-for-completion#possible-filename-completions%20(C-x%20/)) | [Commands For Completion](commands-for-completion#Commands%20For%20Completion) | | | [`possible-hostname-completions (C-x @)`](commands-for-completion#possible-hostname-completions%20(C-x%20@)) | [Commands For Completion](commands-for-completion#Commands%20For%20Completion) | | | [`possible-username-completions (C-x ~)`](commands-for-completion#possible-username-completions%20(C-x%20~)) | [Commands For Completion](commands-for-completion#Commands%20For%20Completion) | | | [`possible-variable-completions (C-x $)`](commands-for-completion#possible-variable-completions%20(C-x%20%24)) | [Commands For Completion](commands-for-completion#Commands%20For%20Completion) | | | [`prefix-meta (ESC)`](miscellaneous-commands#prefix-meta%20(ESC)) | [Miscellaneous Commands](miscellaneous-commands#Miscellaneous%20Commands) | | | [`previous-history (C-p)`](commands-for-history#previous-history%20(C-p)) | [Commands For History](commands-for-history#Commands%20For%20History) | | | [`previous-screen-line ()`](commands-for-moving#previous-screen-line%20()) | [Commands For Moving](commands-for-moving#Commands%20For%20Moving) | | | [`print-last-kbd-macro ()`](keyboard-macros#print-last-kbd-macro%20()) | [Keyboard Macros](keyboard-macros#Keyboard%20Macros) | | Q | | | | | [`quoted-insert (C-q or C-v)`](commands-for-text#quoted-insert%20(C-q%20or%20C-v)) | [Commands For Text](commands-for-text#Commands%20For%20Text) | | R | | | | | [`re-read-init-file (C-x C-r)`](miscellaneous-commands#re-read-init-file%20(C-x%20C-r)) | [Miscellaneous Commands](miscellaneous-commands#Miscellaneous%20Commands) | | | [`redraw-current-line ()`](commands-for-moving#redraw-current-line%20()) | [Commands For Moving](commands-for-moving#Commands%20For%20Moving) | | | [`reverse-search-history (C-r)`](commands-for-history#reverse-search-history%20(C-r)) | [Commands For History](commands-for-history#Commands%20For%20History) | | | [`revert-line (M-r)`](miscellaneous-commands#revert-line%20(M-r)) | [Miscellaneous Commands](miscellaneous-commands#Miscellaneous%20Commands) | | S | | | | | [`self-insert (a, b, A, 1, !, …)`](commands-for-text#self-insert%20(a,%20b,%20A,%201,%20!,%20%E2%80%A6)) | [Commands For Text](commands-for-text#Commands%20For%20Text) | | | [`set-mark (C-@)`](miscellaneous-commands#set-mark%20(C-@)) | [Miscellaneous Commands](miscellaneous-commands#Miscellaneous%20Commands) | | | [`shell-backward-kill-word ()`](commands-for-killing#shell-backward-kill-word%20()) | [Commands For Killing](commands-for-killing#Commands%20For%20Killing) | | | [`shell-backward-word (M-C-b)`](commands-for-moving#shell-backward-word%20(M-C-b)) | [Commands For Moving](commands-for-moving#Commands%20For%20Moving) | | | [`shell-expand-line (M-C-e)`](miscellaneous-commands#shell-expand-line%20(M-C-e)) | [Miscellaneous Commands](miscellaneous-commands#Miscellaneous%20Commands) | | | [`shell-forward-word (M-C-f)`](commands-for-moving#shell-forward-word%20(M-C-f)) | [Commands For Moving](commands-for-moving#Commands%20For%20Moving) | | | [`shell-kill-word (M-C-d)`](commands-for-killing#shell-kill-word%20(M-C-d)) | [Commands For Killing](commands-for-killing#Commands%20For%20Killing) | | | [`shell-transpose-words (M-C-t)`](commands-for-killing#shell-transpose-words%20(M-C-t)) | [Commands For Killing](commands-for-killing#Commands%20For%20Killing) | | | [`skip-csi-sequence ()`](miscellaneous-commands#skip-csi-sequence%20()) | [Miscellaneous Commands](miscellaneous-commands#Miscellaneous%20Commands) | | | [`spell-correct-word (C-x s)`](miscellaneous-commands#spell-correct-word%20(C-x%20s)) | [Miscellaneous Commands](miscellaneous-commands#Miscellaneous%20Commands) | | | [`start-kbd-macro (C-x ()`](keyboard-macros#start-kbd-macro%20(C-x%20()) | [Keyboard Macros](keyboard-macros#Keyboard%20Macros) | | T | | | | | [`tilde-expand (M-&)`](miscellaneous-commands#tilde-expand%20(M-&)) | [Miscellaneous Commands](miscellaneous-commands#Miscellaneous%20Commands) | | | [`transpose-chars (C-t)`](commands-for-text#transpose-chars%20(C-t)) | [Commands For Text](commands-for-text#Commands%20For%20Text) | | | [`transpose-words (M-t)`](commands-for-text#transpose-words%20(M-t)) | [Commands For Text](commands-for-text#Commands%20For%20Text) | | U | | | | | [`undo (C-_ or C-x C-u)`](miscellaneous-commands#undo%20(C-_%20or%20C-x%20C-u)) | [Miscellaneous Commands](miscellaneous-commands#Miscellaneous%20Commands) | | | [`universal-argument ()`](numeric-arguments#universal-argument%20()) | [Numeric Arguments](numeric-arguments#Numeric%20Arguments) | | | [`unix-filename-rubout ()`](commands-for-killing#unix-filename-rubout%20()) | [Commands For Killing](commands-for-killing#Commands%20For%20Killing) | | | [`unix-line-discard (C-u)`](commands-for-killing#unix-line-discard%20(C-u)) | [Commands For Killing](commands-for-killing#Commands%20For%20Killing) | | | [`unix-word-rubout (C-w)`](commands-for-killing#unix-word-rubout%20(C-w)) | [Commands For Killing](commands-for-killing#Commands%20For%20Killing) | | | [`upcase-word (M-u)`](commands-for-text#upcase-word%20(M-u)) | [Commands For Text](commands-for-text#Commands%20For%20Text) | | Y | | | | | [`yank (C-y)`](commands-for-killing#yank%20(C-y)) | [Commands For Killing](commands-for-killing#Commands%20For%20Killing) | | | [`yank-last-arg (M-. or M-_)`](commands-for-history#yank-last-arg%20(M-.%20or%20M-_)) | [Commands For History](commands-for-history#Commands%20For%20History) | | | [`yank-nth-arg (M-C-y)`](commands-for-history#yank-nth-arg%20(M-C-y)) | [Commands For History](commands-for-history#Commands%20For%20History) | | | [`yank-pop (M-y)`](commands-for-killing#yank-pop%20(M-y)) | [Commands For Killing](commands-for-killing#Commands%20For%20Killing) | | | | | --- | --- | | Jump to: | [**A**](#Function-Index_fn_letter-A) [**B**](#Function-Index_fn_letter-B) [**C**](#Function-Index_fn_letter-C) [**D**](#Function-Index_fn_letter-D) [**E**](#Function-Index_fn_letter-E) [**F**](#Function-Index_fn_letter-F) [**G**](#Function-Index_fn_letter-G) [**H**](#Function-Index_fn_letter-H) [**I**](#Function-Index_fn_letter-I) [**K**](#Function-Index_fn_letter-K) [**M**](#Function-Index_fn_letter-M) [**N**](#Function-Index_fn_letter-N) [**O**](#Function-Index_fn_letter-O) [**P**](#Function-Index_fn_letter-P) [**Q**](#Function-Index_fn_letter-Q) [**R**](#Function-Index_fn_letter-R) [**S**](#Function-Index_fn_letter-S) [**T**](#Function-Index_fn_letter-T) [**U**](#Function-Index_fn_letter-U) [**Y**](#Function-Index_fn_letter-Y) | bash Special Parameters Special Parameters ================== The shell treats several parameters specially. These parameters may only be referenced; assignment to them is not allowed. `*` ($\*) Expands to the positional parameters, starting from one. When the expansion is not within double quotes, each positional parameter expands to a separate word. In contexts where it is performed, those words are subject to further word splitting and filename expansion. When the expansion occurs within double quotes, it expands to a single word with the value of each parameter separated by the first character of the `IFS` special variable. That is, `"$*"` is equivalent to `"$1c$2c…"`, where c is the first character of the value of the `IFS` variable. If `IFS` is unset, the parameters are separated by spaces. If `IFS` is null, the parameters are joined without intervening separators. `@` ($@) Expands to the positional parameters, starting from one. In contexts where word splitting is performed, this expands each positional parameter to a separate word; if not within double quotes, these words are subject to word splitting. In contexts where word splitting is not performed, this expands to a single word with each positional parameter separated by a space. When the expansion occurs within double quotes, and word splitting is performed, each parameter expands to a separate word. That is, `"$@"` is equivalent to `"$1" "$2" …`. If the double-quoted expansion occurs within a word, the expansion of the first parameter is joined with the beginning part of the original word, and the expansion of the last parameter is joined with the last part of the original word. When there are no positional parameters, `"$@"` and `$@` expand to nothing (i.e., they are removed). `#` ($#) Expands to the number of positional parameters in decimal. `?` ($?) Expands to the exit status of the most recently executed foreground pipeline. `-` ($-, a hyphen.) Expands to the current option flags as specified upon invocation, by the `set` builtin command, or those set by the shell itself (such as the `-i` option). `$` ($$) Expands to the process ID of the shell. In a subshell, it expands to the process ID of the invoking shell, not the subshell. `!` ($!) Expands to the process ID of the job most recently placed into the background, whether executed as an asynchronous command or using the `bg` builtin (see [Job Control Builtins](job-control-builtins)). `0` ($0) Expands to the name of the shell or shell script. This is set at shell initialization. If Bash is invoked with a file of commands (see [Shell Scripts](shell-scripts)), `$0` is set to the name of that file. If Bash is started with the `-c` option (see [Invoking Bash](invoking-bash)), then `$0` is set to the first argument after the string to be executed, if one is present. Otherwise, it is set to the filename used to invoke Bash, as given by argument zero.
programming_docs
bash Bourne Shell Variables Bourne Shell Variables ====================== Bash uses certain shell variables in the same way as the Bourne shell. In some cases, Bash assigns a default value to the variable. `CDPATH` A colon-separated list of directories used as a search path for the `cd` builtin command. `HOME` The current user’s home directory; the default for the `cd` builtin command. The value of this variable is also used by tilde expansion (see [Tilde Expansion](tilde-expansion)). `IFS` A list of characters that separate fields; used when the shell splits words as part of expansion. `MAIL` If this parameter is set to a filename or directory name and the `MAILPATH` variable is not set, Bash informs the user of the arrival of mail in the specified file or Maildir-format directory. `MAILPATH` A colon-separated list of filenames which the shell periodically checks for new mail. Each list entry can specify the message that is printed when new mail arrives in the mail file by separating the filename from the message with a β€˜`?`’. When used in the text of the message, `$_` expands to the name of the current mail file. `OPTARG` The value of the last option argument processed by the `getopts` builtin. `OPTIND` The index of the last option argument processed by the `getopts` builtin. `PATH` A colon-separated list of directories in which the shell looks for commands. A zero-length (null) directory name in the value of `PATH` indicates the current directory. A null directory name may appear as two adjacent colons, or as an initial or trailing colon. `PS1` The primary prompt string. The default value is β€˜`\s-\v\$` ’. See [Controlling the Prompt](controlling-the-prompt), for the complete list of escape sequences that are expanded before `PS1` is displayed. `PS2` The secondary prompt string. The default value is β€˜`>` ’. `PS2` is expanded in the same way as `PS1` before being displayed. bash Job Control Variables Job Control Variables ===================== `auto_resume` This variable controls how the shell interacts with the user and job control. If this variable exists then single word simple commands without redirections are treated as candidates for resumption of an existing job. There is no ambiguity allowed; if there is more than one job beginning with the string typed, then the most recently accessed job will be selected. The name of a stopped job, in this context, is the command line used to start it. If this variable is set to the value β€˜`exact`’, the string supplied must match the name of a stopped job exactly; if set to β€˜`substring`’, the string supplied needs to match a substring of the name of a stopped job. The β€˜`substring`’ value provides functionality analogous to the β€˜`%?`’ job ID (see [Job Control Basics](job-control-basics)). If set to any other value, the supplied string must be a prefix of a stopped job’s name; this provides functionality analogous to the β€˜`%`’ job ID. bash Positional Parameters Positional Parameters ===================== A *positional parameter* is a parameter denoted by one or more digits, other than the single digit `0`. Positional parameters are assigned from the shell’s arguments when it is invoked, and may be reassigned using the `set` builtin command. Positional parameter `N` may be referenced as `${N}`, or as `$N` when `N` consists of a single digit. Positional parameters may not be assigned to with assignment statements. The `set` and `shift` builtins are used to set and unset them (see [Shell Builtin Commands](shell-builtin-commands)). The positional parameters are temporarily replaced when a shell function is executed (see [Shell Functions](shell-functions)). When a positional parameter consisting of more than a single digit is expanded, it must be enclosed in braces. bash Specifying Numeric Arguments Specifying Numeric Arguments ============================ `digit-argument (`M-0`, `M-1`, … `M--`)` Add this digit to the argument already accumulating, or start a new argument. `M--` starts a negative argument. `universal-argument ()` This is another way to specify an argument. If this command is followed by one or more digits, optionally with a leading minus sign, those digits define the argument. If the command is followed by digits, executing `universal-argument` again ends the numeric argument, but is otherwise ignored. As a special case, if this command is immediately followed by a character that is neither a digit nor minus sign, the argument count for the next command is multiplied by four. The argument count is initially one, so executing this function the first time makes the argument count four, a second time makes the argument count sixteen, and so on. By default, this is not bound to a key. bash Is this Shell Interactive? Is this Shell Interactive? ========================== To determine within a startup script whether or not Bash is running interactively, test the value of the β€˜`-`’ special parameter. It contains `i` when the shell is interactive. For example: ``` case "$-" in *i*) echo This shell is interactive ;; *) echo This shell is not interactive ;; esac ``` Alternatively, startup scripts may examine the variable `PS1`; it is unset in non-interactive shells, and set in interactive shells. Thus: ``` if [ -z "$PS1" ]; then echo This shell is not interactive else echo This shell is interactive fi ``` bash Introduction to Line Editing Introduction to Line Editing ============================ The following paragraphs describe the notation used to represent keystrokes. The text `C-k` is read as β€˜Control-K’ and describes the character produced when the `k` key is pressed while the Control key is depressed. The text `M-k` is read as β€˜Meta-K’ and describes the character produced when the Meta key (if you have one) is depressed, and the `k` key is pressed. The Meta key is labeled `ALT` on many keyboards. On keyboards with two keys labeled `ALT` (usually to either side of the space bar), the `ALT` on the left side is generally set to work as a Meta key. The `ALT` key on the right may also be configured to work as a Meta key or may be configured as some other modifier, such as a Compose key for typing accented characters. If you do not have a Meta or `ALT` key, or another key working as a Meta key, the identical keystroke can be generated by typing `ESC` *first*, and then typing `k`. Either process is known as *metafying* the `k` key. The text `M-C-k` is read as β€˜Meta-Control-k’ and describes the character produced by *metafying* `C-k`. In addition, several keys have their own names. Specifically, `DEL`, `ESC`, `LFD`, `SPC`, `RET`, and `TAB` all stand for themselves when seen in this text, or in an init file (see [Readline Init File](readline-init-file)). If your keyboard lacks a `LFD` key, typing `C-j` will produce the desired character. The `RET` key may be labeled `Return` or `Enter` on some keyboards. bash Shell Operation Shell Operation =============== The following is a brief description of the shell’s operation when it reads and executes a command. Basically, the shell does the following: 1. Reads its input from a file (see [Shell Scripts](shell-scripts)), from a string supplied as an argument to the `-c` invocation option (see [Invoking Bash](invoking-bash)), or from the user’s terminal. 2. Breaks the input into words and operators, obeying the quoting rules described in [Quoting](quoting). These tokens are separated by `metacharacters`. Alias expansion is performed by this step (see [Aliases](aliases)). 3. Parses the tokens into simple and compound commands (see [Shell Commands](shell-commands)). 4. Performs the various shell expansions (see [Shell Expansions](shell-expansions)), breaking the expanded tokens into lists of filenames (see [Filename Expansion](filename-expansion)) and commands and arguments. 5. Performs any necessary redirections (see [Redirections](redirections)) and removes the redirection operators and their operands from the argument list. 6. Executes the command (see [Executing Commands](executing-commands)). 7. Optionally waits for the command to complete and collects its exit status (see [Exit Status](exit-status)). bash Readline Bare Essentials Readline Bare Essentials ======================== In order to enter characters into the line, simply type them. The typed character appears where the cursor was, and then the cursor moves one space to the right. If you mistype a character, you can use your erase character to back up and delete the mistyped character. Sometimes you may mistype a character, and not notice the error until you have typed several other characters. In that case, you can type `C-b` to move the cursor to the left, and then correct your mistake. Afterwards, you can move the cursor to the right with `C-f`. When you add text in the middle of a line, you will notice that characters to the right of the cursor are β€˜pushed over’ to make room for the text that you have inserted. Likewise, when you delete text behind the cursor, characters to the right of the cursor are β€˜pulled back’ to fill in the blank space created by the removal of the text. A list of the bare essentials for editing the text of an input line follows. `C-b` Move back one character. `C-f` Move forward one character. `DEL` or `Backspace` Delete the character to the left of the cursor. `C-d` Delete the character underneath the cursor. Printing characters Insert the character into the line at the cursor. `C-\_` or `C-x C-u` Undo the last editing command. You can undo all the way back to an empty line. (Depending on your configuration, the `Backspace` key might be set to delete the character to the left of the cursor and the `DEL` key set to delete the character underneath the cursor, like `C-d`, rather than the character to the left of the cursor.) bash Letting Readline Type For You Letting Readline Type For You ============================= `complete (TAB)` Attempt to perform completion on the text before point. The actual completion performed is application-specific. Bash attempts completion treating the text as a variable (if the text begins with β€˜`$`’), username (if the text begins with β€˜`~`’), hostname (if the text begins with β€˜`@`’), or command (including aliases and functions) in turn. If none of these produces a match, filename completion is attempted. `possible-completions (M-?)` List the possible completions of the text before point. When displaying completions, Readline sets the number of columns used for display to the value of `completion-display-width`, the value of the environment variable `COLUMNS`, or the screen width, in that order. `insert-completions (M-*)` Insert all completions of the text before point that would have been generated by `possible-completions`. `menu-complete ()` Similar to `complete`, but replaces the word to be completed with a single match from the list of possible completions. Repeated execution of `menu-complete` steps through the list of possible completions, inserting each match in turn. At the end of the list of completions, the bell is rung (subject to the setting of `bell-style`) and the original text is restored. An argument of n moves n positions forward in the list of matches; a negative argument may be used to move backward through the list. This command is intended to be bound to `TAB`, but is unbound by default. `menu-complete-backward ()` Identical to `menu-complete`, but moves backward through the list of possible completions, as if `menu-complete` had been given a negative argument. `delete-char-or-list ()` Deletes the character under the cursor if not at the beginning or end of the line (like `delete-char`). If at the end of the line, behaves identically to `possible-completions`. This command is unbound by default. `complete-filename (M-/)` Attempt filename completion on the text before point. `possible-filename-completions (C-x /)` List the possible completions of the text before point, treating it as a filename. `complete-username (M-~)` Attempt completion on the text before point, treating it as a username. `possible-username-completions (C-x ~)` List the possible completions of the text before point, treating it as a username. `complete-variable (M-$)` Attempt completion on the text before point, treating it as a shell variable. `possible-variable-completions (C-x $)` List the possible completions of the text before point, treating it as a shell variable. `complete-hostname (M-@)` Attempt completion on the text before point, treating it as a hostname. `possible-hostname-completions (C-x @)` List the possible completions of the text before point, treating it as a hostname. `complete-command (M-!)` Attempt completion on the text before point, treating it as a command name. Command completion attempts to match the text against aliases, reserved words, shell functions, shell builtins, and finally executable filenames, in that order. `possible-command-completions (C-x !)` List the possible completions of the text before point, treating it as a command name. `dynamic-complete-history (M-TAB)` Attempt completion on the text before point, comparing the text against lines from the history list for possible completion matches. `dabbrev-expand ()` Attempt menu completion on the text before point, comparing the text against lines from the history list for possible completion matches. `complete-into-braces (M-{)` Perform filename completion and insert the list of possible completions enclosed within braces so the list is available to the shell (see [Brace Expansion](brace-expansion)). bash Programmable Completion Programmable Completion ======================= When word completion is attempted for an argument to a command for which a completion specification (a compspec) has been defined using the `complete` builtin (see [Programmable Completion Builtins](programmable-completion-builtins)), the programmable completion facilities are invoked. First, the command name is identified. If a compspec has been defined for that command, the compspec is used to generate the list of possible completions for the word. If the command word is the empty string (completion attempted at the beginning of an empty line), any compspec defined with the `-E` option to `complete` is used. If the command word is a full pathname, a compspec for the full pathname is searched for first. If no compspec is found for the full pathname, an attempt is made to find a compspec for the portion following the final slash. If those searches do not result in a compspec, any compspec defined with the `-D` option to `complete` is used as the default. If there is no default compspec, Bash attempts alias expansion on the command word as a final resort, and attempts to find a compspec for the command word from any successful expansion Once a compspec has been found, it is used to generate the list of matching words. If a compspec is not found, the default Bash completion described above (see [Letting Readline Type For You](commands-for-completion)) is performed. First, the actions specified by the compspec are used. Only matches which are prefixed by the word being completed are returned. When the `-f` or `-d` option is used for filename or directory name completion, the shell variable `FIGNORE` is used to filter the matches. See [Bash Variables](bash-variables), for a description of `FIGNORE`. Any completions specified by a filename expansion pattern to the `-G` option are generated next. The words generated by the pattern need not match the word being completed. The `GLOBIGNORE` shell variable is not used to filter the matches, but the `FIGNORE` shell variable is used. Next, the string specified as the argument to the `-W` option is considered. The string is first split using the characters in the `IFS` special variable as delimiters. Shell quoting is honored within the string, in order to provide a mechanism for the words to contain shell metacharacters or characters in the value of `IFS`. Each word is then expanded using brace expansion, tilde expansion, parameter and variable expansion, command substitution, and arithmetic expansion, as described above (see [Shell Expansions](shell-expansions)). The results are split using the rules described above (see [Word Splitting](word-splitting)). The results of the expansion are prefix-matched against the word being completed, and the matching words become the possible completions. After these matches have been generated, any shell function or command specified with the `-F` and `-C` options is invoked. When the command or function is invoked, the `COMP_LINE`, `COMP_POINT`, `COMP_KEY`, and `COMP_TYPE` variables are assigned values as described above (see [Bash Variables](bash-variables)). If a shell function is being invoked, the `COMP_WORDS` and `COMP_CWORD` variables are also set. When the function or command is invoked, the first argument ($1) is the name of the command whose arguments are being completed, the second argument ($2) is the word being completed, and the third argument ($3) is the word preceding the word being completed on the current command line. No filtering of the generated completions against the word being completed is performed; the function or command has complete freedom in generating the matches. Any function specified with `-F` is invoked first. The function may use any of the shell facilities, including the `compgen` and `compopt` builtins described below (see [Programmable Completion Builtins](programmable-completion-builtins)), to generate the matches. It must put the possible completions in the `COMPREPLY` array variable, one per array element. Next, any command specified with the `-C` option is invoked in an environment equivalent to command substitution. It should print a list of completions, one per line, to the standard output. Backslash may be used to escape a newline, if necessary. After all of the possible completions are generated, any filter specified with the `-X` option is applied to the list. The filter is a pattern as used for pathname expansion; a β€˜`&`’ in the pattern is replaced with the text of the word being completed. A literal β€˜`&`’ may be escaped with a backslash; the backslash is removed before attempting a match. Any completion that matches the pattern will be removed from the list. A leading β€˜`!`’ negates the pattern; in this case any completion not matching the pattern will be removed. If the `nocasematch` shell option (see the description of `shopt` in [The Shopt Builtin](the-shopt-builtin)) is enabled, the match is performed without regard to the case of alphabetic characters. Finally, any prefix and suffix specified with the `-P` and `-S` options are added to each member of the completion list, and the result is returned to the Readline completion code as the list of possible completions. If the previously-applied actions do not generate any matches, and the `-o dirnames` option was supplied to `complete` when the compspec was defined, directory name completion is attempted. If the `-o plusdirs` option was supplied to `complete` when the compspec was defined, directory name completion is attempted and any matches are added to the results of the other actions. By default, if a compspec is found, whatever it generates is returned to the completion code as the full set of possible completions. The default Bash completions are not attempted, and the Readline default of filename completion is disabled. If the `-o bashdefault` option was supplied to `complete` when the compspec was defined, the default Bash completions are attempted if the compspec generates no matches. If the `-o default` option was supplied to `complete` when the compspec was defined, Readline’s default completion will be performed if the compspec (and, if attempted, the default Bash completions) generate no matches. When a compspec indicates that directory name completion is desired, the programmable completion functions force Readline to append a slash to completed names which are symbolic links to directories, subject to the value of the mark-directories Readline variable, regardless of the setting of the mark-symlinked-directories Readline variable. There is some support for dynamically modifying completions. This is most useful when used in combination with a default completion specified with `-D`. It’s possible for shell functions executed as completion handlers to indicate that completion should be retried by returning an exit status of 124. If a shell function returns 124, and changes the compspec associated with the command on which completion is being attempted (supplied as the first argument when the function is executed), programmable completion restarts from the beginning, with an attempt to find a new compspec for that command. This allows a set of completions to be built dynamically as completion is attempted, rather than being loaded all at once. For instance, assuming that there is a library of compspecs, each kept in a file corresponding to the name of the command, the following default completion function would load completions dynamically: ``` _completion_loader() { . "/etc/bash_completion.d/$1.sh" >/dev/null 2>&1 && return 124 } complete -D -F _completion_loader -o bashdefault -o default ```
programming_docs
bash The Restricted Shell The Restricted Shell ==================== If Bash is started with the name `rbash`, or the `--restricted` or `-r` option is supplied at invocation, the shell becomes restricted. A restricted shell is used to set up an environment more controlled than the standard shell. A restricted shell behaves identically to `bash` with the exception that the following are disallowed or not performed: * Changing directories with the `cd` builtin. * Setting or unsetting the values of the `SHELL`, `PATH`, `HISTFILE`, `ENV`, or `BASH_ENV` variables. * Specifying command names containing slashes. * Specifying a filename containing a slash as an argument to the `.` builtin command. * Specifying a filename containing a slash as an argument to the `history` builtin command. * Specifying a filename containing a slash as an argument to the `-p` option to the `hash` builtin command. * Importing function definitions from the shell environment at startup. * Parsing the value of `SHELLOPTS` from the shell environment at startup. * Redirecting output using the β€˜`>`’, β€˜`>|`’, β€˜`<>`’, β€˜`>&`’, β€˜`&>`’, and β€˜`>>`’ redirection operators. * Using the `exec` builtin to replace the shell with another command. * Adding or deleting builtin commands with the `-f` and `-d` options to the `enable` builtin. * Using the `enable` builtin command to enable disabled shell builtins. * Specifying the `-p` option to the `command` builtin. * Turning off restricted mode with β€˜`set +r`’ or β€˜`shopt -u restricted\_shell`’. These restrictions are enforced after any startup files are read. When a command that is found to be a shell script is executed (see [Shell Scripts](shell-scripts)), `rbash` turns off any restrictions in the shell spawned to execute the script. The restricted shell mode is only one component of a useful restricted environment. It should be accompanied by setting `PATH` to a value that allows execution of only a few verified commands (commands that allow shell escapes are particularly vulnerable), changing the current directory to a non-writable directory other than `$HOME` after login, not allowing the restricted shell to execute shell scripts, and cleaning the environment of variables that cause some commands to modify their behavior (e.g., `VISUAL` or `PAGER`). Modern systems provide more secure ways to implement a restricted environment, such as `jails`, `zones`, or `containers`. bash Job Control Job Control =========== This chapter discusses what job control is, how it works, and how Bash allows you to access its facilities. * [Job Control Basics](job-control-basics) * [Job Control Builtins](job-control-builtins) * [Job Control Variables](job-control-variables) bash Aliases Aliases ======= *Aliases* allow a string to be substituted for a word when it is used as the first word of a simple command. The shell maintains a list of aliases that may be set and unset with the `alias` and `unalias` builtin commands. The first word of each simple command, if unquoted, is checked to see if it has an alias. If so, that word is replaced by the text of the alias. The characters β€˜`/`’, β€˜`$`’, β€˜```’, β€˜`=`’ and any of the shell metacharacters or quoting characters listed above may not appear in an alias name. The replacement text may contain any valid shell input, including shell metacharacters. The first word of the replacement text is tested for aliases, but a word that is identical to an alias being expanded is not expanded a second time. This means that one may alias `ls` to `"ls -F"`, for instance, and Bash does not try to recursively expand the replacement text. If the last character of the alias value is a `blank`, then the next command word following the alias is also checked for alias expansion. Aliases are created and listed with the `alias` command, and removed with the `unalias` command. There is no mechanism for using arguments in the replacement text, as in `csh`. If arguments are needed, use a shell function (see [Shell Functions](shell-functions)). Aliases are not expanded when the shell is not interactive, unless the `expand_aliases` shell option is set using `shopt` (see [The Shopt Builtin](the-shopt-builtin)). The rules concerning the definition and use of aliases are somewhat confusing. Bash always reads at least one complete line of input, and all lines that make up a compound command, before executing any of the commands on that line or the compound command. Aliases are expanded when a command is read, not when it is executed. Therefore, an alias definition appearing on the same line as another command does not take effect until the next line of input is read. The commands following the alias definition on that line are not affected by the new alias. This behavior is also an issue when functions are executed. Aliases are expanded when a function definition is read, not when the function is executed, because a function definition is itself a command. As a consequence, aliases defined in a function are not available until after that function is executed. To be safe, always put alias definitions on a separate line, and do not use `alias` in compound commands. For almost every purpose, shell functions are preferred over aliases. bash Shell Variables Shell Variables =============== This chapter describes the shell variables that Bash uses. Bash automatically assigns default values to a number of variables. * [Bourne Shell Variables](bourne-shell-variables) * [Bash Variables](bash-variables) bash Comments Comments ======== In a non-interactive shell, or an interactive shell in which the `interactive_comments` option to the `shopt` builtin is enabled (see [The Shopt Builtin](the-shopt-builtin)), a word beginning with β€˜`#`’ causes that word and all remaining characters on that line to be ignored. An interactive shell without the `interactive_comments` option enabled does not allow comments. The `interactive_comments` option is on by default in interactive shells. See [Interactive Shells](interactive-shells), for a description of what makes a shell interactive. bash What is Bash? What is Bash? ============= Bash is the shell, or command language interpreter, for the GNU operating system. The name is an acronym for the β€˜`Bourne-Again SHell`’, a pun on Stephen Bourne, the author of the direct ancestor of the current Unix shell `sh`, which appeared in the Seventh Edition Bell Labs Research version of Unix. Bash is largely compatible with `sh` and incorporates useful features from the Korn shell `ksh` and the C shell `csh`. It is intended to be a conformant implementation of the IEEE POSIX Shell and Tools portion of the IEEE POSIX specification (IEEE Standard 1003.1). It offers functional improvements over `sh` for both interactive and programming use. While the GNU operating system provides other shells, including a version of `csh`, Bash is the default shell. Like other GNU software, Bash is quite portable. It currently runs on nearly every version of Unix and a few other operating systems - independently-supported ports exist for MS-DOS, OS/2, and Windows platforms. bash Parameter and Variable Index Parameter and Variable Index ============================ | | | | --- | --- | | Jump to: | [**!**](#Variable-Index_vr_symbol-1) [**#**](#Variable-Index_vr_symbol-2) [**$**](#Variable-Index_vr_symbol-3) [**\***](#Variable-Index_vr_symbol-4) [**-**](#Variable-Index_vr_symbol-5) [**0**](#Variable-Index_vr_symbol-6) [**?**](#Variable-Index_vr_symbol-7) [**@**](#Variable-Index_vr_symbol-8) [**\_**](#Variable-Index_vr_symbol-9) [**A**](#Variable-Index_vr_letter-A) [**B**](#Variable-Index_vr_letter-B) [**C**](#Variable-Index_vr_letter-C) [**D**](#Variable-Index_vr_letter-D) [**E**](#Variable-Index_vr_letter-E) [**F**](#Variable-Index_vr_letter-F) [**G**](#Variable-Index_vr_letter-G) [**H**](#Variable-Index_vr_letter-H) [**I**](#Variable-Index_vr_letter-I) [**K**](#Variable-Index_vr_letter-K) [**L**](#Variable-Index_vr_letter-L) [**M**](#Variable-Index_vr_letter-M) [**O**](#Variable-Index_vr_letter-O) [**P**](#Variable-Index_vr_letter-P) [**R**](#Variable-Index_vr_letter-R) [**S**](#Variable-Index_vr_letter-S) [**T**](#Variable-Index_vr_letter-T) [**U**](#Variable-Index_vr_letter-U) [**V**](#Variable-Index_vr_letter-V) | | | | | | --- | --- | --- | | | Index Entry | Section | | ! | | | | | [`!`](special-parameters#!) | [Special Parameters](special-parameters#Special%20Parameters) | | # | | | | | [`#`](special-parameters##) | [Special Parameters](special-parameters#Special%20Parameters) | | $ | | | | | [`$`](special-parameters#%24) | [Special Parameters](special-parameters#Special%20Parameters) | | | [`$!`](special-parameters#!) | [Special Parameters](special-parameters#Special%20Parameters) | | | [`$#`](special-parameters##) | [Special Parameters](special-parameters#Special%20Parameters) | | | [`$$`](special-parameters#%24) | [Special Parameters](special-parameters#Special%20Parameters) | | | [`$*`](special-parameters#*) | [Special Parameters](special-parameters#Special%20Parameters) | | | [`$-`](special-parameters#-) | [Special Parameters](special-parameters#Special%20Parameters) | | | [`$0`](special-parameters#0) | [Special Parameters](special-parameters#Special%20Parameters) | | | [`$?`](special-parameters#?) | [Special Parameters](special-parameters#Special%20Parameters) | | | [`$@`](special-parameters#@) | [Special Parameters](special-parameters#Special%20Parameters) | | | [`$_`](bash-variables#%24_) | [Bash Variables](bash-variables#Bash%20Variables) | | \* | | | | | [`*`](special-parameters#*) | [Special Parameters](special-parameters#Special%20Parameters) | | - | | | | | [`-`](special-parameters#-) | [Special Parameters](special-parameters#Special%20Parameters) | | 0 | | | | | [`0`](special-parameters#0) | [Special Parameters](special-parameters#Special%20Parameters) | | ? | | | | | [`?`](special-parameters#?) | [Special Parameters](special-parameters#Special%20Parameters) | | @ | | | | | [`@`](special-parameters#@) | [Special Parameters](special-parameters#Special%20Parameters) | | \_ | | | | | [`_`](bash-variables#_) | [Bash Variables](bash-variables#Bash%20Variables) | | A | | | | | [`active-region-end-color`](readline-init-file-syntax#active-region-end-color) | [Readline Init File Syntax](readline-init-file-syntax#Readline%20Init%20File%20Syntax) | | | [`active-region-start-color`](readline-init-file-syntax#active-region-start-color) | [Readline Init File Syntax](readline-init-file-syntax#Readline%20Init%20File%20Syntax) | | | [`auto_resume`](job-control-variables#auto_resume) | [Job Control Variables](job-control-variables#Job%20Control%20Variables) | | B | | | | | [`BASH`](bash-variables#BASH) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`BASHOPTS`](bash-variables#BASHOPTS) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`BASHPID`](bash-variables#BASHPID) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`BASH_ALIASES`](bash-variables#BASH_ALIASES) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`BASH_ARGC`](bash-variables#BASH_ARGC) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`BASH_ARGV`](bash-variables#BASH_ARGV) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`BASH_ARGV0`](bash-variables#BASH_ARGV0) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`BASH_CMDS`](bash-variables#BASH_CMDS) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`BASH_COMMAND`](bash-variables#BASH_COMMAND) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`BASH_COMPAT`](bash-variables#BASH_COMPAT) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`BASH_ENV`](bash-variables#BASH_ENV) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`BASH_EXECUTION_STRING`](bash-variables#BASH_EXECUTION_STRING) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`BASH_LINENO`](bash-variables#BASH_LINENO) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`BASH_LOADABLES_PATH`](bash-variables#BASH_LOADABLES_PATH) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`BASH_REMATCH`](bash-variables#BASH_REMATCH) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`BASH_SOURCE`](bash-variables#BASH_SOURCE) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`BASH_SUBSHELL`](bash-variables#BASH_SUBSHELL) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`BASH_VERSINFO`](bash-variables#BASH_VERSINFO) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`BASH_VERSION`](bash-variables#BASH_VERSION) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`BASH_XTRACEFD`](bash-variables#BASH_XTRACEFD) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`bell-style`](readline-init-file-syntax#bell-style) | [Readline Init File Syntax](readline-init-file-syntax#Readline%20Init%20File%20Syntax) | | | [`bind-tty-special-chars`](readline-init-file-syntax#bind-tty-special-chars) | [Readline Init File Syntax](readline-init-file-syntax#Readline%20Init%20File%20Syntax) | | | [`blink-matching-paren`](readline-init-file-syntax#blink-matching-paren) | [Readline Init File Syntax](readline-init-file-syntax#Readline%20Init%20File%20Syntax) | | C | | | | | [`CDPATH`](bourne-shell-variables#CDPATH) | [Bourne Shell Variables](bourne-shell-variables#Bourne%20Shell%20Variables) | | | [`CHILD_MAX`](bash-variables#CHILD_MAX) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`colored-completion-prefix`](readline-init-file-syntax#colored-completion-prefix) | [Readline Init File Syntax](readline-init-file-syntax#Readline%20Init%20File%20Syntax) | | | [`colored-stats`](readline-init-file-syntax#colored-stats) | [Readline Init File Syntax](readline-init-file-syntax#Readline%20Init%20File%20Syntax) | | | [`COLUMNS`](bash-variables#COLUMNS) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`comment-begin`](readline-init-file-syntax#comment-begin) | [Readline Init File Syntax](readline-init-file-syntax#Readline%20Init%20File%20Syntax) | | | [`completion-display-width`](readline-init-file-syntax#completion-display-width) | [Readline Init File Syntax](readline-init-file-syntax#Readline%20Init%20File%20Syntax) | | | [`completion-ignore-case`](readline-init-file-syntax#completion-ignore-case) | [Readline Init File Syntax](readline-init-file-syntax#Readline%20Init%20File%20Syntax) | | | [`completion-map-case`](readline-init-file-syntax#completion-map-case) | [Readline Init File Syntax](readline-init-file-syntax#Readline%20Init%20File%20Syntax) | | | [`completion-prefix-display-length`](readline-init-file-syntax#completion-prefix-display-length) | [Readline Init File Syntax](readline-init-file-syntax#Readline%20Init%20File%20Syntax) | | | [`completion-query-items`](readline-init-file-syntax#completion-query-items) | [Readline Init File Syntax](readline-init-file-syntax#Readline%20Init%20File%20Syntax) | | | [`COMPREPLY`](bash-variables#COMPREPLY) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`COMP_CWORD`](bash-variables#COMP_CWORD) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`COMP_KEY`](bash-variables#COMP_KEY) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`COMP_LINE`](bash-variables#COMP_LINE) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`COMP_POINT`](bash-variables#COMP_POINT) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`COMP_TYPE`](bash-variables#COMP_TYPE) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`COMP_WORDBREAKS`](bash-variables#COMP_WORDBREAKS) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`COMP_WORDS`](bash-variables#COMP_WORDS) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`convert-meta`](readline-init-file-syntax#convert-meta) | [Readline Init File Syntax](readline-init-file-syntax#Readline%20Init%20File%20Syntax) | | | [`COPROC`](bash-variables#COPROC) | [Bash Variables](bash-variables#Bash%20Variables) | | D | | | | | [`DIRSTACK`](bash-variables#DIRSTACK) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`disable-completion`](readline-init-file-syntax#disable-completion) | [Readline Init File Syntax](readline-init-file-syntax#Readline%20Init%20File%20Syntax) | | E | | | | | [`echo-control-characters`](readline-init-file-syntax#echo-control-characters) | [Readline Init File Syntax](readline-init-file-syntax#Readline%20Init%20File%20Syntax) | | | [`editing-mode`](readline-init-file-syntax#editing-mode) | [Readline Init File Syntax](readline-init-file-syntax#Readline%20Init%20File%20Syntax) | | | [`EMACS`](bash-variables#EMACS) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`emacs-mode-string`](readline-init-file-syntax#emacs-mode-string) | [Readline Init File Syntax](readline-init-file-syntax#Readline%20Init%20File%20Syntax) | | | [`enable-active-region`](readline-init-file-syntax#enable-active-region) | [Readline Init File Syntax](readline-init-file-syntax#Readline%20Init%20File%20Syntax) | | | [`enable-bracketed-paste`](readline-init-file-syntax#enable-bracketed-paste) | [Readline Init File Syntax](readline-init-file-syntax#Readline%20Init%20File%20Syntax) | | | [`enable-keypad`](readline-init-file-syntax#enable-keypad) | [Readline Init File Syntax](readline-init-file-syntax#Readline%20Init%20File%20Syntax) | | | [`ENV`](bash-variables#ENV) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`EPOCHREALTIME`](bash-variables#EPOCHREALTIME) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`EPOCHSECONDS`](bash-variables#EPOCHSECONDS) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`EUID`](bash-variables#EUID) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`EXECIGNORE`](bash-variables#EXECIGNORE) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`expand-tilde`](readline-init-file-syntax#expand-tilde) | [Readline Init File Syntax](readline-init-file-syntax#Readline%20Init%20File%20Syntax) | | F | | | | | [`FCEDIT`](bash-variables#FCEDIT) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`FIGNORE`](bash-variables#FIGNORE) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`FUNCNAME`](bash-variables#FUNCNAME) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`FUNCNEST`](bash-variables#FUNCNEST) | [Bash Variables](bash-variables#Bash%20Variables) | | G | | | | | [`GLOBIGNORE`](bash-variables#GLOBIGNORE) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`GROUPS`](bash-variables#GROUPS) | [Bash Variables](bash-variables#Bash%20Variables) | | H | | | | | [`histchars`](bash-variables#histchars) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`HISTCMD`](bash-variables#HISTCMD) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`HISTCONTROL`](bash-variables#HISTCONTROL) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`HISTFILE`](bash-variables#HISTFILE) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`HISTFILESIZE`](bash-variables#HISTFILESIZE) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`HISTIGNORE`](bash-variables#HISTIGNORE) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`history-preserve-point`](readline-init-file-syntax#history-preserve-point) | [Readline Init File Syntax](readline-init-file-syntax#Readline%20Init%20File%20Syntax) | | | [`history-size`](readline-init-file-syntax#history-size) | [Readline Init File Syntax](readline-init-file-syntax#Readline%20Init%20File%20Syntax) | | | [`HISTSIZE`](bash-variables#HISTSIZE) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`HISTTIMEFORMAT`](bash-variables#HISTTIMEFORMAT) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`HOME`](bourne-shell-variables#HOME) | [Bourne Shell Variables](bourne-shell-variables#Bourne%20Shell%20Variables) | | | [`horizontal-scroll-mode`](readline-init-file-syntax#horizontal-scroll-mode) | [Readline Init File Syntax](readline-init-file-syntax#Readline%20Init%20File%20Syntax) | | | [`HOSTFILE`](bash-variables#HOSTFILE) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`HOSTNAME`](bash-variables#HOSTNAME) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`HOSTTYPE`](bash-variables#HOSTTYPE) | [Bash Variables](bash-variables#Bash%20Variables) | | I | | | | | [`IFS`](bourne-shell-variables#IFS) | [Bourne Shell Variables](bourne-shell-variables#Bourne%20Shell%20Variables) | | | [`IGNOREEOF`](bash-variables#IGNOREEOF) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`input-meta`](readline-init-file-syntax#input-meta) | [Readline Init File Syntax](readline-init-file-syntax#Readline%20Init%20File%20Syntax) | | | [`INPUTRC`](bash-variables#INPUTRC) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`INSIDE_EMACS`](bash-variables#INSIDE_EMACS) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`isearch-terminators`](readline-init-file-syntax#isearch-terminators) | [Readline Init File Syntax](readline-init-file-syntax#Readline%20Init%20File%20Syntax) | | K | | | | | [`keymap`](readline-init-file-syntax#keymap) | [Readline Init File Syntax](readline-init-file-syntax#Readline%20Init%20File%20Syntax) | | L | | | | | [`LANG`](creating-internationalized-scripts#LANG) | [Creating Internationalized Scripts](creating-internationalized-scripts#Creating%20Internationalized%20Scripts) | | | [`LANG`](bash-variables#LANG) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`LC_ALL`](bash-variables#LC_ALL) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`LC_COLLATE`](bash-variables#LC_COLLATE) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`LC_CTYPE`](bash-variables#LC_CTYPE) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`LC_MESSAGES`](creating-internationalized-scripts#LC_MESSAGES) | [Creating Internationalized Scripts](creating-internationalized-scripts#Creating%20Internationalized%20Scripts) | | | [`LC_MESSAGES`](bash-variables#LC_MESSAGES) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`LC_NUMERIC`](bash-variables#LC_NUMERIC) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`LC_TIME`](bash-variables#LC_TIME) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`LINENO`](bash-variables#LINENO) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`LINES`](bash-variables#LINES) | [Bash Variables](bash-variables#Bash%20Variables) | | M | | | | | [`MACHTYPE`](bash-variables#MACHTYPE) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`MAIL`](bourne-shell-variables#MAIL) | [Bourne Shell Variables](bourne-shell-variables#Bourne%20Shell%20Variables) | | | [`MAILCHECK`](bash-variables#MAILCHECK) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`MAILPATH`](bourne-shell-variables#MAILPATH) | [Bourne Shell Variables](bourne-shell-variables#Bourne%20Shell%20Variables) | | | [`MAPFILE`](bash-variables#MAPFILE) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`mark-modified-lines`](readline-init-file-syntax#mark-modified-lines) | [Readline Init File Syntax](readline-init-file-syntax#Readline%20Init%20File%20Syntax) | | | [`mark-symlinked-directories`](readline-init-file-syntax#mark-symlinked-directories) | [Readline Init File Syntax](readline-init-file-syntax#Readline%20Init%20File%20Syntax) | | | [`match-hidden-files`](readline-init-file-syntax#match-hidden-files) | [Readline Init File Syntax](readline-init-file-syntax#Readline%20Init%20File%20Syntax) | | | [`menu-complete-display-prefix`](readline-init-file-syntax#menu-complete-display-prefix) | [Readline Init File Syntax](readline-init-file-syntax#Readline%20Init%20File%20Syntax) | | | [`meta-flag`](readline-init-file-syntax#meta-flag) | [Readline Init File Syntax](readline-init-file-syntax#Readline%20Init%20File%20Syntax) | | O | | | | | [`OLDPWD`](bash-variables#OLDPWD) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`OPTARG`](bourne-shell-variables#OPTARG) | [Bourne Shell Variables](bourne-shell-variables#Bourne%20Shell%20Variables) | | | [`OPTERR`](bash-variables#OPTERR) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`OPTIND`](bourne-shell-variables#OPTIND) | [Bourne Shell Variables](bourne-shell-variables#Bourne%20Shell%20Variables) | | | [`OSTYPE`](bash-variables#OSTYPE) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`output-meta`](readline-init-file-syntax#output-meta) | [Readline Init File Syntax](readline-init-file-syntax#Readline%20Init%20File%20Syntax) | | P | | | | | [`page-completions`](readline-init-file-syntax#page-completions) | [Readline Init File Syntax](readline-init-file-syntax#Readline%20Init%20File%20Syntax) | | | [`PATH`](bourne-shell-variables#PATH) | [Bourne Shell Variables](bourne-shell-variables#Bourne%20Shell%20Variables) | | | [`PIPESTATUS`](bash-variables#PIPESTATUS) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`POSIXLY_CORRECT`](bash-variables#POSIXLY_CORRECT) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`PPID`](bash-variables#PPID) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`PROMPT_COMMAND`](bash-variables#PROMPT_COMMAND) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`PROMPT_DIRTRIM`](bash-variables#PROMPT_DIRTRIM) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`PS0`](bash-variables#PS0) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`PS1`](bourne-shell-variables#PS1) | [Bourne Shell Variables](bourne-shell-variables#Bourne%20Shell%20Variables) | | | [`PS2`](bourne-shell-variables#PS2) | [Bourne Shell Variables](bourne-shell-variables#Bourne%20Shell%20Variables) | | | [`PS3`](bash-variables#PS3) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`PS4`](bash-variables#PS4) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`PWD`](bash-variables#PWD) | [Bash Variables](bash-variables#Bash%20Variables) | | R | | | | | [`RANDOM`](bash-variables#RANDOM) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`READLINE_ARGUMENT`](bash-variables#READLINE_ARGUMENT) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`READLINE_LINE`](bash-variables#READLINE_LINE) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`READLINE_MARK`](bash-variables#READLINE_MARK) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`READLINE_POINT`](bash-variables#READLINE_POINT) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`REPLY`](bash-variables#REPLY) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`revert-all-at-newline`](readline-init-file-syntax#revert-all-at-newline) | [Readline Init File Syntax](readline-init-file-syntax#Readline%20Init%20File%20Syntax) | | S | | | | | [`SECONDS`](bash-variables#SECONDS) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`SHELL`](bash-variables#SHELL) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`SHELLOPTS`](bash-variables#SHELLOPTS) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`SHLVL`](bash-variables#SHLVL) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`show-all-if-ambiguous`](readline-init-file-syntax#show-all-if-ambiguous) | [Readline Init File Syntax](readline-init-file-syntax#Readline%20Init%20File%20Syntax) | | | [`show-all-if-unmodified`](readline-init-file-syntax#show-all-if-unmodified) | [Readline Init File Syntax](readline-init-file-syntax#Readline%20Init%20File%20Syntax) | | | [`show-mode-in-prompt`](readline-init-file-syntax#show-mode-in-prompt) | [Readline Init File Syntax](readline-init-file-syntax#Readline%20Init%20File%20Syntax) | | | [`skip-completed-text`](readline-init-file-syntax#skip-completed-text) | [Readline Init File Syntax](readline-init-file-syntax#Readline%20Init%20File%20Syntax) | | | [`SRANDOM`](bash-variables#SRANDOM) | [Bash Variables](bash-variables#Bash%20Variables) | | T | | | | | [`TEXTDOMAIN`](creating-internationalized-scripts#TEXTDOMAIN) | [Creating Internationalized Scripts](creating-internationalized-scripts#Creating%20Internationalized%20Scripts) | | | [`TEXTDOMAINDIR`](creating-internationalized-scripts#TEXTDOMAINDIR) | [Creating Internationalized Scripts](creating-internationalized-scripts#Creating%20Internationalized%20Scripts) | | | [`TIMEFORMAT`](bash-variables#TIMEFORMAT) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`TMOUT`](bash-variables#TMOUT) | [Bash Variables](bash-variables#Bash%20Variables) | | | [`TMPDIR`](bash-variables#TMPDIR) | [Bash Variables](bash-variables#Bash%20Variables) | | U | | | | | [`UID`](bash-variables#UID) | [Bash Variables](bash-variables#Bash%20Variables) | | V | | | | | [`vi-cmd-mode-string`](readline-init-file-syntax#vi-cmd-mode-string) | [Readline Init File Syntax](readline-init-file-syntax#Readline%20Init%20File%20Syntax) | | | [`vi-ins-mode-string`](readline-init-file-syntax#vi-ins-mode-string) | [Readline Init File Syntax](readline-init-file-syntax#Readline%20Init%20File%20Syntax) | | | [`visible-stats`](readline-init-file-syntax#visible-stats) | [Readline Init File Syntax](readline-init-file-syntax#Readline%20Init%20File%20Syntax) | | | | | --- | --- | | Jump to: | [**!**](#Variable-Index_vr_symbol-1) [**#**](#Variable-Index_vr_symbol-2) [**$**](#Variable-Index_vr_symbol-3) [**\***](#Variable-Index_vr_symbol-4) [**-**](#Variable-Index_vr_symbol-5) [**0**](#Variable-Index_vr_symbol-6) [**?**](#Variable-Index_vr_symbol-7) [**@**](#Variable-Index_vr_symbol-8) [**\_**](#Variable-Index_vr_symbol-9) [**A**](#Variable-Index_vr_letter-A) [**B**](#Variable-Index_vr_letter-B) [**C**](#Variable-Index_vr_letter-C) [**D**](#Variable-Index_vr_letter-D) [**E**](#Variable-Index_vr_letter-E) [**F**](#Variable-Index_vr_letter-F) [**G**](#Variable-Index_vr_letter-G) [**H**](#Variable-Index_vr_letter-H) [**I**](#Variable-Index_vr_letter-I) [**K**](#Variable-Index_vr_letter-K) [**L**](#Variable-Index_vr_letter-L) [**M**](#Variable-Index_vr_letter-M) [**O**](#Variable-Index_vr_letter-O) [**P**](#Variable-Index_vr_letter-P) [**R**](#Variable-Index_vr_letter-R) [**S**](#Variable-Index_vr_letter-S) [**T**](#Variable-Index_vr_letter-T) [**U**](#Variable-Index_vr_letter-U) [**V**](#Variable-Index_vr_letter-V) |
programming_docs
bash ANSI-C Quoting ANSI-C Quoting ============== Character sequences of the form $’string’ are treated as a special kind of single quotes. The sequence expands to string, with backslash-escaped characters in string replaced as specified by the ANSI C standard. Backslash escape sequences, if present, are decoded as follows: `\a` alert (bell) `\b` backspace `\e` `\E` an escape character (not ANSI C) `\f` form feed `\n` newline `\r` carriage return `\t` horizontal tab `\v` vertical tab `\\` backslash `\'` single quote `\"` double quote `\?` question mark `\nnn` the eight-bit character whose value is the octal value nnn (one to three octal digits) `\xHH` the eight-bit character whose value is the hexadecimal value HH (one or two hex digits) `\uHHHH` the Unicode (ISO/IEC 10646) character whose value is the hexadecimal value HHHH (one to four hex digits) `\UHHHHHHHH` the Unicode (ISO/IEC 10646) character whose value is the hexadecimal value HHHHHHHH (one to eight hex digits) `\cx` a control-x character The expanded result is single-quoted, as if the dollar sign had not been present. bash Compiling For Multiple Architectures Compiling For Multiple Architectures ==================================== You can compile Bash for more than one kind of computer at the same time, by placing the object files for each architecture in their own directory. To do this, you must use a version of `make` that supports the `VPATH` variable, such as GNU `make`. `cd` to the directory where you want the object files and executables to go and run the `configure` script from the source directory (see [Basic Installation](basic-installation)). You may need to supply the `--srcdir=PATH` argument to tell `configure` where the source files are. `configure` automatically checks for the source code in the directory that `configure` is in and in β€˜..’. If you have to use a `make` that does not support the `VPATH` variable, you can compile Bash for one architecture at a time in the source code directory. After you have installed Bash for one architecture, use β€˜`make distclean`’ before reconfiguring for another architecture. Alternatively, if your system supports symbolic links, you can use the `support/mkclone` script to create a build tree which has symbolic links back to each file in the source directory. Here’s an example that creates a build directory in the current directory from a source directory `/usr/gnu/src/bash-2.0`: ``` bash /usr/gnu/src/bash-2.0/support/mkclone -s /usr/gnu/src/bash-2.0 . ``` The `mkclone` script requires Bash, so you must have already built Bash for at least one architecture before you can create build directories for other architectures. bash Shell Functions Shell Functions =============== Shell functions are a way to group commands for later execution using a single name for the group. They are executed just like a "regular" command. When the name of a shell function is used as a simple command name, the list of commands associated with that function name is executed. Shell functions are executed in the current shell context; no new process is created to interpret them. Functions are declared using this syntax: ``` fname () compound-command [ redirections ] ``` or ``` function fname [()] compound-command [ redirections ] ``` This defines a shell function named fname. The reserved word `function` is optional. If the `function` reserved word is supplied, the parentheses are optional. The *body* of the function is the compound command compound-command (see [Compound Commands](compound-commands)). That command is usually a list enclosed between { and }, but may be any compound command listed above. If the `function` reserved word is used, but the parentheses are not supplied, the braces are recommended. compound-command is executed whenever fname is specified as the name of a simple command. When the shell is in POSIX mode (see [Bash POSIX Mode](bash-posix-mode)), fname must be a valid shell name and may not be the same as one of the special builtins (see [Special Builtins](special-builtins)). In default mode, a function name can be any unquoted shell word that does not contain β€˜`$`’. Any redirections (see [Redirections](redirections)) associated with the shell function are performed when the function is executed. A function definition may be deleted using the `-f` option to the `unset` builtin (see [Bourne Shell Builtins](bourne-shell-builtins)). The exit status of a function definition is zero unless a syntax error occurs or a readonly function with the same name already exists. When executed, the exit status of a function is the exit status of the last command executed in the body. Note that for historical reasons, in the most common usage the curly braces that surround the body of the function must be separated from the body by `blank`s or newlines. This is because the braces are reserved words and are only recognized as such when they are separated from the command list by whitespace or another shell metacharacter. Also, when using the braces, the list must be terminated by a semicolon, a β€˜`&`’, or a newline. When a function is executed, the arguments to the function become the positional parameters during its execution (see [Positional Parameters](positional-parameters)). The special parameter β€˜`#`’ that expands to the number of positional parameters is updated to reflect the change. Special parameter `0` is unchanged. The first element of the `FUNCNAME` variable is set to the name of the function while the function is executing. All other aspects of the shell execution environment are identical between a function and its caller with these exceptions: the `DEBUG` and `RETURN` traps are not inherited unless the function has been given the `trace` attribute using the `declare` builtin or the `-o functrace` option has been enabled with the `set` builtin, (in which case all functions inherit the `DEBUG` and `RETURN` traps), and the `ERR` trap is not inherited unless the `-o errtrace` shell option has been enabled. See [Bourne Shell Builtins](bourne-shell-builtins), for the description of the `trap` builtin. The `FUNCNEST` variable, if set to a numeric value greater than 0, defines a maximum function nesting level. Function invocations that exceed the limit cause the entire command to abort. If the builtin command `return` is executed in a function, the function completes and execution resumes with the next command after the function call. Any command associated with the `RETURN` trap is executed before execution resumes. When a function completes, the values of the positional parameters and the special parameter β€˜`#`’ are restored to the values they had prior to the function’s execution. If a numeric argument is given to `return`, that is the function’s return status; otherwise the function’s return status is the exit status of the last command executed before the `return`. Variables local to the function may be declared with the `local` builtin (*local variables*). Ordinarily, variables and their values are shared between a function and its caller. These variables are visible only to the function and the commands it invokes. This is particularly important when a shell function calls other functions. In the following description, the *current scope* is a currently- executing function. Previous scopes consist of that function’s caller and so on, back to the "global" scope, where the shell is not executing any shell function. Consequently, a local variable at the current local scope is a variable declared using the `local` or `declare` builtins in the function that is currently executing. Local variables "shadow" variables with the same name declared at previous scopes. For instance, a local variable declared in a function hides a global variable of the same name: references and assignments refer to the local variable, leaving the global variable unmodified. When the function returns, the global variable is once again visible. The shell uses *dynamic scoping* to control a variable’s visibility within functions. With dynamic scoping, visible variables and their values are a result of the sequence of function calls that caused execution to reach the current function. The value of a variable that a function sees depends on its value within its caller, if any, whether that caller is the "global" scope or another shell function. This is also the value that a local variable declaration "shadows", and the value that is restored when the function returns. For example, if a variable `var` is declared as local in function `func1`, and `func1` calls another function `func2`, references to `var` made from within `func2` will resolve to the local variable `var` from `func1`, shadowing any global variable named `var`. The following script demonstrates this behavior. When executed, the script displays ``` In func2, var = func1 local ``` ``` func1() { local var='func1 local' func2 } func2() { echo "In func2, var = $var" } var=global func1 ``` The `unset` builtin also acts using the same dynamic scope: if a variable is local to the current scope, `unset` will unset it; otherwise the unset will refer to the variable found in any calling scope as described above. If a variable at the current local scope is unset, it will remain so (appearing as unset) until it is reset in that scope or until the function returns. Once the function returns, any instance of the variable at a previous scope will become visible. If the unset acts on a variable at a previous scope, any instance of a variable with that name that had been shadowed will become visible (see below how `localvar_unset`shell option changes this behavior). Function names and definitions may be listed with the `-f` option to the `declare` (`typeset`) builtin command (see [Bash Builtin Commands](bash-builtins)). The `-F` option to `declare` or `typeset` will list the function names only (and optionally the source file and line number, if the `extdebug` shell option is enabled). Functions may be exported so that child shell processes (those created when executing a separate shell invocation) automatically have them defined with the `-f` option to the `export` builtin (see [Bourne Shell Builtins](bourne-shell-builtins)). Functions may be recursive. The `FUNCNEST` variable may be used to limit the depth of the function call stack and restrict the number of function invocations. By default, no limit is placed on the number of recursive calls. bash What is an Interactive Shell? What is an Interactive Shell? ============================= An interactive shell is one started without non-option arguments (unless `-s` is specified) and without specifying the `-c` option, whose input and error output are both connected to terminals (as determined by `isatty(3)`), or one started with the `-i` option. An interactive shell generally reads from and writes to a user’s terminal. The `-s` invocation option may be used to set the positional parameters when an interactive shell is started. bash Commands For Manipulating The History Commands For Manipulating The History ===================================== `accept-line (Newline or Return)` Accept the line regardless of where the cursor is. If this line is non-empty, add it to the history list according to the setting of the `HISTCONTROL` and `HISTIGNORE` variables. If this line is a modified history line, then restore the history line to its original state. `previous-history (C-p)` Move β€˜back’ through the history list, fetching the previous command. `next-history (C-n)` Move β€˜forward’ through the history list, fetching the next command. `beginning-of-history (M-<)` Move to the first line in the history. `end-of-history (M->)` Move to the end of the input history, i.e., the line currently being entered. `reverse-search-history (C-r)` Search backward starting at the current line and moving β€˜up’ through the history as necessary. This is an incremental search. This command sets the region to the matched text and activates the mark. `forward-search-history (C-s)` Search forward starting at the current line and moving β€˜down’ through the history as necessary. This is an incremental search. This command sets the region to the matched text and activates the mark. `non-incremental-reverse-search-history (M-p)` Search backward starting at the current line and moving β€˜up’ through the history as necessary using a non-incremental search for a string supplied by the user. The search string may match anywhere in a history line. `non-incremental-forward-search-history (M-n)` Search forward starting at the current line and moving β€˜down’ through the history as necessary using a non-incremental search for a string supplied by the user. The search string may match anywhere in a history line. `history-search-forward ()` Search forward through the history for the string of characters between the start of the current line and the point. The search string must match at the beginning of a history line. This is a non-incremental search. By default, this command is unbound. `history-search-backward ()` Search backward through the history for the string of characters between the start of the current line and the point. The search string must match at the beginning of a history line. This is a non-incremental search. By default, this command is unbound. `history-substring-search-forward ()` Search forward through the history for the string of characters between the start of the current line and the point. The search string may match anywhere in a history line. This is a non-incremental search. By default, this command is unbound. `history-substring-search-backward ()` Search backward through the history for the string of characters between the start of the current line and the point. The search string may match anywhere in a history line. This is a non-incremental search. By default, this command is unbound. `yank-nth-arg (M-C-y)` Insert the first argument to the previous command (usually the second word on the previous line) at point. With an argument n, insert the nth word from the previous command (the words in the previous command begin with word 0). A negative argument inserts the nth word from the end of the previous command. Once the argument n is computed, the argument is extracted as if the β€˜`!n`’ history expansion had been specified. `yank-last-arg (M-. or M-_)` Insert last argument to the previous command (the last word of the previous history entry). With a numeric argument, behave exactly like `yank-nth-arg`. Successive calls to `yank-last-arg` move back through the history list, inserting the last word (or the word specified by the argument to the first call) of each line in turn. Any numeric argument supplied to these successive calls determines the direction to move through the history. A negative argument switches the direction through the history (back or forward). The history expansion facilities are used to extract the last argument, as if the β€˜`!$`’ history expansion had been specified. `operate-and-get-next (C-o)` Accept the current line for return to the calling application as if a newline had been entered, and fetch the next line relative to the current line from the history for editing. A numeric argument, if supplied, specifies the history entry to use instead of the current line. `fetch-history ()` With a numeric argument, fetch that entry from the history list and make it the current line. Without an argument, move back to the first entry in the history list. bash Looping Constructs Looping Constructs ================== Bash supports the following looping constructs. Note that wherever a β€˜`;`’ appears in the description of a command’s syntax, it may be replaced with one or more newlines. `until` The syntax of the `until` command is: ``` until test-commands; do consequent-commands; done ``` Execute consequent-commands as long as test-commands has an exit status which is not zero. The return status is the exit status of the last command executed in consequent-commands, or zero if none was executed. `while` The syntax of the `while` command is: ``` while test-commands; do consequent-commands; done ``` Execute consequent-commands as long as test-commands has an exit status of zero. The return status is the exit status of the last command executed in consequent-commands, or zero if none was executed. `for` The syntax of the `for` command is: ``` for name [ [in [words …] ] ; ] do commands; done ``` Expand words (see [Shell Expansions](shell-expansions)), and execute commands once for each member in the resultant list, with name bound to the current member. If β€˜`in words`’ is not present, the `for` command executes the commands once for each positional parameter that is set, as if β€˜`in "$@"`’ had been specified (see [Special Parameters](special-parameters)). The return status is the exit status of the last command that executes. If there are no items in the expansion of words, no commands are executed, and the return status is zero. An alternate form of the `for` command is also supported: ``` for (( expr1 ; expr2 ; expr3 )) ; do commands ; done ``` First, the arithmetic expression expr1 is evaluated according to the rules described below (see [Shell Arithmetic](shell-arithmetic)). The arithmetic expression expr2 is then evaluated repeatedly until it evaluates to zero. Each time expr2 evaluates to a non-zero value, commands are executed and the arithmetic expression expr3 is evaluated. If any expression is omitted, it behaves as if it evaluates to 1. The return value is the exit status of the last command in commands that is executed, or false if any of the expressions is invalid. The `break` and `continue` builtins (see [Bourne Shell Builtins](bourne-shell-builtins)) may be used to control loop execution. bash Reserved Words Reserved Words ============== Reserved words are words that have special meaning to the shell. They are used to begin and end the shell’s compound commands. The following words are recognized as reserved when unquoted and the first word of a command (see below for exceptions): | | | | | | | | --- | --- | --- | --- | --- | --- | | `if` | `then` | `elif` | `else` | `fi` | `time` | | `for` | `in` | `until` | `while` | `do` | `done` | | `case` | `esac` | `coproc` | `select` | `function` | | `{` | `}` | `[[` | `]]` | `!` | `in` is recognized as a reserved word if it is the third word of a `case` or `select` command. `in` and `do` are recognized as reserved words if they are the third word in a `for` command. bash Quote Removal Quote Removal ============= After the preceding expansions, all unquoted occurrences of the characters β€˜`\`’, β€˜`'`’, and β€˜`"`’ that did not result from one of the above expansions are removed. bash Shell Parameters Shell Parameters ================ A *parameter* is an entity that stores values. It can be a `name`, a number, or one of the special characters listed below. A *variable* is a parameter denoted by a `name`. A variable has a `value` and zero or more `attributes`. Attributes are assigned using the `declare` builtin command (see the description of the `declare` builtin in [Bash Builtin Commands](bash-builtins)). A parameter is set if it has been assigned a value. The null string is a valid value. Once a variable is set, it may be unset only by using the `unset` builtin command. A variable may be assigned to by a statement of the form ``` name=[value] ``` If value is not given, the variable is assigned the null string. All values undergo tilde expansion, parameter and variable expansion, command substitution, arithmetic expansion, and quote removal (see [Shell Parameter Expansion](shell-parameter-expansion)). If the variable has its `integer` attribute set, then value is evaluated as an arithmetic expression even if the `$((…))` expansion is not used (see [Arithmetic Expansion](arithmetic-expansion)). Word splitting and filename expansion are not performed. Assignment statements may also appear as arguments to the `alias`, `declare`, `typeset`, `export`, `readonly`, and `local` builtin commands (*declaration* commands). When in POSIX mode (see [Bash POSIX Mode](bash-posix-mode)), these builtins may appear in a command after one or more instances of the `command` builtin and retain these assignment statement properties. In the context where an assignment statement is assigning a value to a shell variable or array index (see [Arrays](arrays)), the β€˜`+=`’ operator can be used to append to or add to the variable’s previous value. This includes arguments to builtin commands such as `declare` that accept assignment statements (declaration commands). When β€˜`+=`’ is applied to a variable for which the `integer` attribute has been set, value is evaluated as an arithmetic expression and added to the variable’s current value, which is also evaluated. When β€˜`+=`’ is applied to an array variable using compound assignment (see [Arrays](arrays)), the variable’s value is not unset (as it is when using β€˜`=`’), and new values are appended to the array beginning at one greater than the array’s maximum index (for indexed arrays), or added as additional key-value pairs in an associative array. When applied to a string-valued variable, value is expanded and appended to the variable’s value. A variable can be assigned the `nameref` attribute using the `-n` option to the `declare` or `local` builtin commands (see [Bash Builtin Commands](bash-builtins)) to create a *nameref*, or a reference to another variable. This allows variables to be manipulated indirectly. Whenever the nameref variable is referenced, assigned to, unset, or has its attributes modified (other than using or changing the nameref attribute itself), the operation is actually performed on the variable specified by the nameref variable’s value. A nameref is commonly used within shell functions to refer to a variable whose name is passed as an argument to the function. For instance, if a variable name is passed to a shell function as its first argument, running ``` declare -n ref=$1 ``` inside the function creates a nameref variable `ref` whose value is the variable name passed as the first argument. References and assignments to `ref`, and changes to its attributes, are treated as references, assignments, and attribute modifications to the variable whose name was passed as `$1`. If the control variable in a `for` loop has the nameref attribute, the list of words can be a list of shell variables, and a name reference will be established for each word in the list, in turn, when the loop is executed. Array variables cannot be given the nameref attribute. However, nameref variables can reference array variables and subscripted array variables. Namerefs can be unset using the `-n` option to the `unset` builtin (see [Bourne Shell Builtins](bourne-shell-builtins)). Otherwise, if `unset` is executed with the name of a nameref variable as an argument, the variable referenced by the nameref variable will be unset. * [Positional Parameters](positional-parameters) * [Special Parameters](special-parameters)
programming_docs
bash Arrays Arrays ====== Bash provides one-dimensional indexed and associative array variables. Any variable may be used as an indexed array; the `declare` builtin will explicitly declare an array. There is no maximum limit on the size of an array, nor any requirement that members be indexed or assigned contiguously. Indexed arrays are referenced using integers (including arithmetic expressions (see [Shell Arithmetic](shell-arithmetic))) and are zero-based; associative arrays use arbitrary strings. Unless otherwise noted, indexed array indices must be non-negative integers. An indexed array is created automatically if any variable is assigned to using the syntax ``` name[subscript]=value ``` The subscript is treated as an arithmetic expression that must evaluate to a number. To explicitly declare an array, use ``` declare -a name ``` The syntax ``` declare -a name[subscript] ``` is also accepted; the subscript is ignored. Associative arrays are created using ``` declare -A name ``` Attributes may be specified for an array variable using the `declare` and `readonly` builtins. Each attribute applies to all members of an array. Arrays are assigned to using compound assignments of the form ``` name=(value1 value2 … ) ``` where each value may be of the form `[subscript]=`string. Indexed array assignments do not require anything but string. When assigning to indexed arrays, if the optional subscript is supplied, that index is assigned to; otherwise the index of the element assigned is the last index assigned to by the statement plus one. Indexing starts at zero. Each value in the list undergoes all the shell expansions described above (see [Shell Expansions](shell-expansions)). When assigning to an associative array, the words in a compound assignment may be either assignment statements, for which the subscript is required, or a list of words that is interpreted as a sequence of alternating keys and values: name=(key1 value1 key2 value2 … ). These are treated identically to name=( [key1]=value1 [key2]=value2 … ). The first word in the list determines how the remaining words are interpreted; all assignments in a list must be of the same type. When using key/value pairs, the keys may not be missing or empty; a final missing value is treated like the empty string. This syntax is also accepted by the `declare` builtin. Individual array elements may be assigned to using the `name[subscript]=value` syntax introduced above. When assigning to an indexed array, if name is subscripted by a negative number, that number is interpreted as relative to one greater than the maximum index of name, so negative indices count back from the end of the array, and an index of -1 references the last element. The β€˜`+=`’ operator will append to an array variable when assigning using the compound assignment syntax; see [Shell Parameters](shell-parameters) above. Any element of an array may be referenced using `${name[subscript]}`. The braces are required to avoid conflicts with the shell’s filename expansion operators. If the subscript is β€˜`@`’ or β€˜`\*`’, the word expands to all members of the array name. These subscripts differ only when the word appears within double quotes. If the word is double-quoted, `${name[*]}` expands to a single word with the value of each array member separated by the first character of the `IFS` variable, and `${name[@]}` expands each element of name to a separate word. When there are no array members, `${name[@]}` expands to nothing. If the double-quoted expansion occurs within a word, the expansion of the first parameter is joined with the beginning part of the original word, and the expansion of the last parameter is joined with the last part of the original word. This is analogous to the expansion of the special parameters β€˜`@`’ and β€˜`\*`’. `${#name[subscript]}` expands to the length of `${name[subscript]}`. If subscript is β€˜`@`’ or β€˜`\*`’, the expansion is the number of elements in the array. If the subscript used to reference an element of an indexed array evaluates to a number less than zero, it is interpreted as relative to one greater than the maximum index of the array, so negative indices count back from the end of the array, and an index of -1 refers to the last element. Referencing an array variable without a subscript is equivalent to referencing with a subscript of 0. Any reference to a variable using a valid subscript is legal, and `bash` will create an array if necessary. An array variable is considered set if a subscript has been assigned a value. The null string is a valid value. It is possible to obtain the keys (indices) of an array as well as the values. ${!name[@]} and ${!name[\*]} expand to the indices assigned in array variable name. The treatment when in double quotes is similar to the expansion of the special parameters β€˜`@`’ and β€˜`\*`’ within double quotes. The `unset` builtin is used to destroy arrays. `unset name[subscript]` destroys the array element at index subscript. Negative subscripts to indexed arrays are interpreted as described above. Unsetting the last element of an array variable does not unset the variable. `unset name`, where name is an array, removes the entire array. `unset name[subscript]` behaves differently depending on the array type when given a subscript of β€˜`\*`’ or β€˜`@`’. When name is an associative array, it removes the element with key β€˜`\*`’ or β€˜`@`’. If name is an indexed array, `unset` removes all of the elements, but does not remove the array itself. When using a variable name with a subscript as an argument to a command, such as with `unset`, without using the word expansion syntax described above, the argument is subject to the shell’s filename expansion. If filename expansion is not desired, the argument should be quoted. The `declare`, `local`, and `readonly` builtins each accept a `-a` option to specify an indexed array and a `-A` option to specify an associative array. If both options are supplied, `-A` takes precedence. The `read` builtin accepts a `-a` option to assign a list of words read from the standard input to an array, and can read values from the standard input into individual array elements. The `set` and `declare` builtins display array values in a way that allows them to be reused as input. bash Event Designators Event Designators ================= An event designator is a reference to a command line entry in the history list. Unless the reference is absolute, events are relative to the current position in the history list. `!` Start a history substitution, except when followed by a space, tab, the end of the line, β€˜`=`’ or β€˜`(`’ (when the `extglob` shell option is enabled using the `shopt` builtin). `!n` Refer to command line n. `!-n` Refer to the command n lines back. `!!` Refer to the previous command. This is a synonym for β€˜`!-1`’. `!string` Refer to the most recent command preceding the current position in the history list starting with string. `!?string[?]` Refer to the most recent command preceding the current position in the history list containing string. The trailing β€˜`?`’ may be omitted if the string is followed immediately by a newline. If string is missing, the string from the most recent search is used; it is an error if there is no previous search string. `^string1^string2^` Quick Substitution. Repeat the last command, replacing string1 with string2. Equivalent to `!!:s^string1^string2^`. `!#` The entire command line typed so far. bash Single Quotes Single Quotes ============= Enclosing characters in single quotes (β€˜`'`’) preserves the literal value of each character within the quotes. A single quote may not occur between single quotes, even when preceded by a backslash. bash Sharing Defaults Sharing Defaults ================ If you want to set default values for `configure` scripts to share, you can create a site shell script called `config.site` that gives default values for variables like `CC`, `cache_file`, and `prefix`. `configure` looks for `PREFIX/share/config.site` if it exists, then `PREFIX/etc/config.site` if it exists. Or, you can set the `CONFIG_SITE` environment variable to the location of the site script. A warning: the Bash `configure` looks for a site script, but not all `configure` scripts do. bash Bourne Shell Builtins Bourne Shell Builtins ===================== The following shell builtin commands are inherited from the Bourne Shell. These commands are implemented as specified by the POSIX standard. `: (a colon)` ``` : [arguments] ``` Do nothing beyond expanding arguments and performing redirections. The return status is zero. `. (a period)` ``` . filename [arguments] ``` Read and execute commands from the filename argument in the current shell context. If filename does not contain a slash, the `PATH` variable is used to find filename, but filename does not need to be executable. When Bash is not in POSIX mode, it searches the current directory if filename is not found in `$PATH`. If any arguments are supplied, they become the positional parameters when filename is executed. Otherwise the positional parameters are unchanged. If the `-T` option is enabled, `.` inherits any trap on `DEBUG`; if it is not, any `DEBUG` trap string is saved and restored around the call to `.`, and `.` unsets the `DEBUG` trap while it executes. If `-T` is not set, and the sourced file changes the `DEBUG` trap, the new value is retained when `.` completes. The return status is the exit status of the last command executed, or zero if no commands are executed. If filename is not found, or cannot be read, the return status is non-zero. This builtin is equivalent to `source`. `break` ``` break [n] ``` Exit from a `for`, `while`, `until`, or `select` loop. If n is supplied, the nth enclosing loop is exited. n must be greater than or equal to 1. The return status is zero unless n is not greater than or equal to 1. `cd` ``` cd [-L|[-P [-e]] [-@] [directory] ``` Change the current working directory to directory. If directory is not supplied, the value of the `HOME` shell variable is used. If the shell variable `CDPATH` exists, it is used as a search path: each directory name in `CDPATH` is searched for directory, with alternative directory names in `CDPATH` separated by a colon (β€˜`:`’). If directory begins with a slash, `CDPATH` is not used. The `-P` option means to not follow symbolic links: symbolic links are resolved while `cd` is traversing directory and before processing an instance of β€˜`..`’ in directory. By default, or when the `-L` option is supplied, symbolic links in directory are resolved after `cd` processes an instance of β€˜`..`’ in directory. If β€˜`..`’ appears in directory, it is processed by removing the immediately preceding pathname component, back to a slash or the beginning of directory. If the `-e` option is supplied with `-P` and the current working directory cannot be successfully determined after a successful directory change, `cd` will return an unsuccessful status. On systems that support it, the `-@` option presents the extended attributes associated with a file as a directory. If directory is β€˜`-`’, it is converted to `$OLDPWD` before the directory change is attempted. If a non-empty directory name from `CDPATH` is used, or if β€˜`-`’ is the first argument, and the directory change is successful, the absolute pathname of the new working directory is written to the standard output. If the directory change is successful, `cd` sets the value of the `PWD` environment variable to the new directory name, and sets the `OLDPWD` environment variable to the value of the current working directory before the change. The return status is zero if the directory is successfully changed, non-zero otherwise. `continue` ``` continue [n] ``` Resume the next iteration of an enclosing `for`, `while`, `until`, or `select` loop. If n is supplied, the execution of the nth enclosing loop is resumed. n must be greater than or equal to 1. The return status is zero unless n is not greater than or equal to 1. `eval` ``` eval [arguments] ``` The arguments are concatenated together into a single command, which is then read and executed, and its exit status returned as the exit status of `eval`. If there are no arguments or only empty arguments, the return status is zero. `exec` ``` exec [-cl] [-a name] [command [arguments]] ``` If command is supplied, it replaces the shell without creating a new process. If the `-l` option is supplied, the shell places a dash at the beginning of the zeroth argument passed to command. This is what the `login` program does. The `-c` option causes command to be executed with an empty environment. If `-a` is supplied, the shell passes name as the zeroth argument to command. If command cannot be executed for some reason, a non-interactive shell exits, unless the `execfail` shell option is enabled. In that case, it returns failure. An interactive shell returns failure if the file cannot be executed. A subshell exits unconditionally if `exec` fails. If no command is specified, redirections may be used to affect the current shell environment. If there are no redirection errors, the return status is zero; otherwise the return status is non-zero. `exit` ``` exit [n] ``` Exit the shell, returning a status of n to the shell’s parent. If n is omitted, the exit status is that of the last command executed. Any trap on `EXIT` is executed before the shell terminates. `export` ``` export [-fn] [-p] [name[=value]] ``` Mark each name to be passed to child processes in the environment. If the `-f` option is supplied, the names refer to shell functions; otherwise the names refer to shell variables. The `-n` option means to no longer mark each name for export. If no names are supplied, or if the `-p` option is given, a list of names of all exported variables is displayed. The `-p` option displays output in a form that may be reused as input. If a variable name is followed by =value, the value of the variable is set to value. The return status is zero unless an invalid option is supplied, one of the names is not a valid shell variable name, or `-f` is supplied with a name that is not a shell function. `getopts` ``` getopts optstring name [arg …] ``` `getopts` is used by shell scripts to parse positional parameters. optstring contains the option characters to be recognized; if a character is followed by a colon, the option is expected to have an argument, which should be separated from it by whitespace. The colon (β€˜`:`’) and question mark (β€˜`?`’) may not be used as option characters. Each time it is invoked, `getopts` places the next option in the shell variable name, initializing name if it does not exist, and the index of the next argument to be processed into the variable `OPTIND`. `OPTIND` is initialized to 1 each time the shell or a shell script is invoked. When an option requires an argument, `getopts` places that argument into the variable `OPTARG`. The shell does not reset `OPTIND` automatically; it must be manually reset between multiple calls to `getopts` within the same shell invocation if a new set of parameters is to be used. When the end of options is encountered, `getopts` exits with a return value greater than zero. `OPTIND` is set to the index of the first non-option argument, and name is set to β€˜`?`’. `getopts` normally parses the positional parameters, but if more arguments are supplied as arg values, `getopts` parses those instead. `getopts` can report errors in two ways. If the first character of optstring is a colon, silent error reporting is used. In normal operation, diagnostic messages are printed when invalid options or missing option arguments are encountered. If the variable `OPTERR` is set to 0, no error messages will be displayed, even if the first character of `optstring` is not a colon. If an invalid option is seen, `getopts` places β€˜`?`’ into name and, if not silent, prints an error message and unsets `OPTARG`. If `getopts` is silent, the option character found is placed in `OPTARG` and no diagnostic message is printed. If a required argument is not found, and `getopts` is not silent, a question mark (β€˜`?`’) is placed in name, `OPTARG` is unset, and a diagnostic message is printed. If `getopts` is silent, then a colon (β€˜`:`’) is placed in name and `OPTARG` is set to the option character found. `hash` ``` hash [-r] [-p filename] [-dt] [name] ``` Each time `hash` is invoked, it remembers the full pathnames of the commands specified as name arguments, so they need not be searched for on subsequent invocations. The commands are found by searching through the directories listed in `$PATH`. Any previously-remembered pathname is discarded. The `-p` option inhibits the path search, and filename is used as the location of name. The `-r` option causes the shell to forget all remembered locations. The `-d` option causes the shell to forget the remembered location of each name. If the `-t` option is supplied, the full pathname to which each name corresponds is printed. If multiple name arguments are supplied with `-t`, the name is printed before the hashed full pathname. The `-l` option causes output to be displayed in a format that may be reused as input. If no arguments are given, or if only `-l` is supplied, information about remembered commands is printed. The return status is zero unless a name is not found or an invalid option is supplied. `pwd` ``` pwd [-LP] ``` Print the absolute pathname of the current working directory. If the `-P` option is supplied, the pathname printed will not contain symbolic links. If the `-L` option is supplied, the pathname printed may contain symbolic links. The return status is zero unless an error is encountered while determining the name of the current directory or an invalid option is supplied. `readonly` ``` readonly [-aAf] [-p] [name[=value]] … ``` Mark each name as readonly. The values of these names may not be changed by subsequent assignment. If the `-f` option is supplied, each name refers to a shell function. The `-a` option means each name refers to an indexed array variable; the `-A` option means each name refers to an associative array variable. If both options are supplied, `-A` takes precedence. If no name arguments are given, or if the `-p` option is supplied, a list of all readonly names is printed. The other options may be used to restrict the output to a subset of the set of readonly names. The `-p` option causes output to be displayed in a format that may be reused as input. If a variable name is followed by =value, the value of the variable is set to value. The return status is zero unless an invalid option is supplied, one of the name arguments is not a valid shell variable or function name, or the `-f` option is supplied with a name that is not a shell function. `return` ``` return [n] ``` Cause a shell function to stop executing and return the value n to its caller. If n is not supplied, the return value is the exit status of the last command executed in the function. If `return` is executed by a trap handler, the last command used to determine the status is the last command executed before the trap handler. If `return` is executed during a `DEBUG` trap, the last command used to determine the status is the last command executed by the trap handler before `return` was invoked. `return` may also be used to terminate execution of a script being executed with the `.` (`source`) builtin, returning either n or the exit status of the last command executed within the script as the exit status of the script. If n is supplied, the return value is its least significant 8 bits. Any command associated with the `RETURN` trap is executed before execution resumes after the function or script. The return status is non-zero if `return` is supplied a non-numeric argument or is used outside a function and not during the execution of a script by `.` or `source`. `shift` ``` shift [n] ``` Shift the positional parameters to the left by n. The positional parameters from n+1 … `$#` are renamed to `$1` … `$#`-n. Parameters represented by the numbers `$#` down to `$#`-n+1 are unset. n must be a non-negative number less than or equal to `$#`. If n is zero or greater than `$#`, the positional parameters are not changed. If n is not supplied, it is assumed to be 1. The return status is zero unless n is greater than `$#` or less than zero, non-zero otherwise. `test` `[` ``` test expr ``` Evaluate a conditional expression expr and return a status of 0 (true) or 1 (false). Each operator and operand must be a separate argument. Expressions are composed of the primaries described below in [Bash Conditional Expressions](bash-conditional-expressions). `test` does not accept any options, nor does it accept and ignore an argument of `--` as signifying the end of options. When the `[` form is used, the last argument to the command must be a `]`. Expressions may be combined using the following operators, listed in decreasing order of precedence. The evaluation depends on the number of arguments; see below. Operator precedence is used when there are five or more arguments. `! expr` True if expr is false. `( expr )` Returns the value of expr. This may be used to override the normal precedence of operators. `expr1 -a expr2` True if both expr1 and expr2 are true. `expr1 -o expr2` True if either expr1 or expr2 is true. The `test` and `[` builtins evaluate conditional expressions using a set of rules based on the number of arguments. 0 arguments The expression is false. 1 argument The expression is true if, and only if, the argument is not null. 2 arguments If the first argument is β€˜`!`’, the expression is true if and only if the second argument is null. If the first argument is one of the unary conditional operators (see [Bash Conditional Expressions](bash-conditional-expressions)), the expression is true if the unary test is true. If the first argument is not a valid unary operator, the expression is false. 3 arguments The following conditions are applied in the order listed. 1. If the second argument is one of the binary conditional operators (see [Bash Conditional Expressions](bash-conditional-expressions)), the result of the expression is the result of the binary test using the first and third arguments as operands. The β€˜`-a`’ and β€˜`-o`’ operators are considered binary operators when there are three arguments. 2. If the first argument is β€˜`!`’, the value is the negation of the two-argument test using the second and third arguments. 3. If the first argument is exactly β€˜`(`’ and the third argument is exactly β€˜`)`’, the result is the one-argument test of the second argument. 4. Otherwise, the expression is false. 4 arguments The following conditions are applied in the order listed. 1. If the first argument is β€˜`!`’, the result is the negation of the three-argument expression composed of the remaining arguments. 2. If the first argument is exactly β€˜`(`’ and the fourth argument is exactly β€˜`)`’, the result is the two-argument test of the second and third arguments. 3. Otherwise, the expression is parsed and evaluated according to precedence using the rules listed above. 5 or more arguments The expression is parsed and evaluated according to precedence using the rules listed above. When used with `test` or β€˜`[`’, the β€˜`<`’ and β€˜`>`’ operators sort lexicographically using ASCII ordering. `times` ``` times ``` Print out the user and system times used by the shell and its children. The return status is zero. `trap` ``` trap [-lp] [arg] [sigspec …] ``` The commands in arg are to be read and executed when the shell receives signal sigspec. If arg is absent (and there is a single sigspec) or equal to β€˜`-`’, each specified signal’s disposition is reset to the value it had when the shell was started. If arg is the null string, then the signal specified by each sigspec is ignored by the shell and commands it invokes. If arg is not present and `-p` has been supplied, the shell displays the trap commands associated with each sigspec. If no arguments are supplied, or only `-p` is given, `trap` prints the list of commands associated with each signal number in a form that may be reused as shell input. The `-l` option causes the shell to print a list of signal names and their corresponding numbers. Each sigspec is either a signal name or a signal number. Signal names are case insensitive and the `SIG` prefix is optional. If a sigspec is `0` or `EXIT`, arg is executed when the shell exits. If a sigspec is `DEBUG`, the command arg is executed before every simple command, `for` command, `case` command, `select` command, every arithmetic `for` command, and before the first command executes in a shell function. Refer to the description of the `extdebug` option to the `shopt` builtin (see [The Shopt Builtin](the-shopt-builtin)) for details of its effect on the `DEBUG` trap. If a sigspec is `RETURN`, the command arg is executed each time a shell function or a script executed with the `.` or `source` builtins finishes executing. If a sigspec is `ERR`, the command arg is executed whenever a pipeline (which may consist of a single simple command), a list, or a compound command returns a non-zero exit status, subject to the following conditions. The `ERR` trap is not executed if the failed command is part of the command list immediately following an `until` or `while` keyword, part of the test following the `if` or `elif` reserved words, part of a command executed in a `&&` or `||` list except the command following the final `&&` or `||`, any command in a pipeline but the last, or if the command’s return status is being inverted using `!`. These are the same conditions obeyed by the `errexit` (`-e`) option. Signals ignored upon entry to the shell cannot be trapped or reset. Trapped signals that are not being ignored are reset to their original values in a subshell or subshell environment when one is created. The return status is zero unless a sigspec does not specify a valid signal. `umask` ``` umask [-p] [-S] [mode] ``` Set the shell process’s file creation mask to mode. If mode begins with a digit, it is interpreted as an octal number; if not, it is interpreted as a symbolic mode mask similar to that accepted by the `chmod` command. If mode is omitted, the current value of the mask is printed. If the `-S` option is supplied without a mode argument, the mask is printed in a symbolic format. If the `-p` option is supplied, and mode is omitted, the output is in a form that may be reused as input. The return status is zero if the mode is successfully changed or if no mode argument is supplied, and non-zero otherwise. Note that when the mode is interpreted as an octal number, each number of the umask is subtracted from `7`. Thus, a umask of `022` results in permissions of `755`. `unset` ``` unset [-fnv] [name] ``` Remove each variable or function name. If the `-v` option is given, each name refers to a shell variable and that variable is removed. If the `-f` option is given, the names refer to shell functions, and the function definition is removed. If the `-n` option is supplied, and name is a variable with the `nameref` attribute, name will be unset rather than the variable it references. `-n` has no effect if the `-f` option is supplied. If no options are supplied, each name refers to a variable; if there is no variable by that name, a function with that name, if any, is unset. Readonly variables and functions may not be unset. Some shell variables lose their special behavior if they are unset; such behavior is noted in the description of the individual variables. The return status is zero unless a name is readonly or may not be unset.
programming_docs
bash Introduction Introduction ============ * [What is Bash?](what-is-bash_003f) * [What is a shell?](what-is-a-shell_003f) bash Some Miscellaneous Commands Some Miscellaneous Commands =========================== `re-read-init-file (C-x C-r)` Read in the contents of the inputrc file, and incorporate any bindings or variable assignments found there. `abort (C-g)` Abort the current editing command and ring the terminal’s bell (subject to the setting of `bell-style`). `do-lowercase-version (M-A, M-B, M-x, …)` If the metafied character x is upper case, run the command that is bound to the corresponding metafied lower case character. The behavior is undefined if x is already lower case. `prefix-meta (ESC)` Metafy the next character typed. This is for keyboards without a meta key. Typing β€˜`ESC f`’ is equivalent to typing `M-f`. `undo (C-_ or C-x C-u)` Incremental undo, separately remembered for each line. `revert-line (M-r)` Undo all changes made to this line. This is like executing the `undo` command enough times to get back to the beginning. `tilde-expand (M-&)` Perform tilde expansion on the current word. `set-mark (C-@)` Set the mark to the point. If a numeric argument is supplied, the mark is set to that position. `exchange-point-and-mark (C-x C-x)` Swap the point with the mark. The current cursor position is set to the saved position, and the old cursor position is saved as the mark. `character-search (C-])` A character is read and point is moved to the next occurrence of that character. A negative argument searches for previous occurrences. `character-search-backward (M-C-])` A character is read and point is moved to the previous occurrence of that character. A negative argument searches for subsequent occurrences. `skip-csi-sequence ()` Read enough characters to consume a multi-key sequence such as those defined for keys like Home and End. Such sequences begin with a Control Sequence Indicator (CSI), usually ESC-[. If this sequence is bound to "\e[", keys producing such sequences will have no effect unless explicitly bound to a Readline command, instead of inserting stray characters into the editing buffer. This is unbound by default, but usually bound to ESC-[. `insert-comment (M-#)` Without a numeric argument, the value of the `comment-begin` variable is inserted at the beginning of the current line. If a numeric argument is supplied, this command acts as a toggle: if the characters at the beginning of the line do not match the value of `comment-begin`, the value is inserted, otherwise the characters in `comment-begin` are deleted from the beginning of the line. In either case, the line is accepted as if a newline had been typed. The default value of `comment-begin` causes this command to make the current line a shell comment. If a numeric argument causes the comment character to be removed, the line will be executed by the shell. `dump-functions ()` Print all of the functions and their key bindings to the Readline output stream. If a numeric argument is supplied, the output is formatted in such a way that it can be made part of an inputrc file. This command is unbound by default. `dump-variables ()` Print all of the settable variables and their values to the Readline output stream. If a numeric argument is supplied, the output is formatted in such a way that it can be made part of an inputrc file. This command is unbound by default. `dump-macros ()` Print all of the Readline key sequences bound to macros and the strings they output. If a numeric argument is supplied, the output is formatted in such a way that it can be made part of an inputrc file. This command is unbound by default. `spell-correct-word (C-x s)` Perform spelling correction on the current word, treating it as a directory or filename, in the same way as the `cdspell` shell option. Word boundaries are the same as those used by `shell-forward-word`. `glob-complete-word (M-g)` The word before point is treated as a pattern for pathname expansion, with an asterisk implicitly appended. This pattern is used to generate a list of matching file names for possible completions. `glob-expand-word (C-x *)` The word before point is treated as a pattern for pathname expansion, and the list of matching file names is inserted, replacing the word. If a numeric argument is supplied, a β€˜`\*`’ is appended before pathname expansion. `glob-list-expansions (C-x g)` The list of expansions that would have been generated by `glob-expand-word` is displayed, and the line is redrawn. If a numeric argument is supplied, a β€˜`\*`’ is appended before pathname expansion. `display-shell-version (C-x C-v)` Display version information about the current instance of Bash. `shell-expand-line (M-C-e)` Expand the line as the shell does. This performs alias and history expansion as well as all of the shell word expansions (see [Shell Expansions](shell-expansions)). `history-expand-line (M-^)` Perform history expansion on the current line. `magic-space ()` Perform history expansion on the current line and insert a space (see [History Expansion](history-interaction)). `alias-expand-line ()` Perform alias expansion on the current line (see [Aliases](aliases)). `history-and-alias-expand-line ()` Perform history and alias expansion on the current line. `insert-last-argument (M-. or M-_)` A synonym for `yank-last-arg`. `edit-and-execute-command (C-x C-e)` Invoke an editor on the current command line, and execute the result as shell commands. Bash attempts to invoke `$VISUAL`, `$EDITOR`, and `emacs` as the editor, in that order. bash Shell Builtin Commands Shell Builtin Commands ====================== Builtin commands are contained within the shell itself. When the name of a builtin command is used as the first word of a simple command (see [Simple Commands](simple-commands)), the shell executes the command directly, without invoking another program. Builtin commands are necessary to implement functionality impossible or inconvenient to obtain with separate utilities. This section briefly describes the builtins which Bash inherits from the Bourne Shell, as well as the builtin commands which are unique to or have been extended in Bash. Several builtin commands are described in other chapters: builtin commands which provide the Bash interface to the job control facilities (see [Job Control Builtins](job-control-builtins)), the directory stack (see [Directory Stack Builtins](directory-stack-builtins)), the command history (see [Bash History Builtins](bash-history-builtins)), and the programmable completion facilities (see [Programmable Completion Builtins](programmable-completion-builtins)). Many of the builtins have been extended by POSIX or Bash. Unless otherwise noted, each builtin command documented as accepting options preceded by β€˜`-`’ accepts β€˜`--`’ to signify the end of the options. The `:`, `true`, `false`, and `test`/`[` builtins do not accept options and do not treat β€˜`--`’ specially. The `exit`, `logout`, `return`, `break`, `continue`, `let`, and `shift` builtins accept and process arguments beginning with β€˜`-`’ without requiring β€˜`--`’. Other builtins that accept arguments but are not specified as accepting options interpret arguments beginning with β€˜`-`’ as invalid options and require β€˜`--`’ to prevent this interpretation. * [Bourne Shell Builtins](bourne-shell-builtins) * [Bash Builtin Commands](bash-builtins) * [Modifying Shell Behavior](modifying-shell-behavior) * [Special Builtins](special-builtins) bash History Expansion History Expansion ================= The History library provides a history expansion feature that is similar to the history expansion provided by `csh`. This section describes the syntax used to manipulate the history information. History expansions introduce words from the history list into the input stream, making it easy to repeat commands, insert the arguments to a previous command into the current input line, or fix errors in previous commands quickly. History expansion is performed immediately after a complete line is read, before the shell breaks it into words, and is performed on each line individually. Bash attempts to inform the history expansion functions about quoting still in effect from previous lines. History expansion takes place in two parts. The first is to determine which line from the history list should be used during substitution. The second is to select portions of that line for inclusion into the current one. The line selected from the history is called the *event*, and the portions of that line that are acted upon are called *words*. Various *modifiers* are available to manipulate the selected words. The line is broken into words in the same fashion that Bash does, so that several words surrounded by quotes are considered one word. History expansions are introduced by the appearance of the history expansion character, which is β€˜`!`’ by default. History expansion implements shell-like quoting conventions: a backslash can be used to remove the special handling for the next character; single quotes enclose verbatim sequences of characters, and can be used to inhibit history expansion; and characters enclosed within double quotes may be subject to history expansion, since backslash can escape the history expansion character, but single quotes may not, since they are not treated specially within double quotes. When using the shell, only β€˜`\`’ and β€˜`'`’ may be used to escape the history expansion character, but the history expansion character is also treated as quoted if it immediately precedes the closing double quote in a double-quoted string. Several shell options settable with the `shopt` builtin (see [The Shopt Builtin](the-shopt-builtin)) may be used to tailor the behavior of history expansion. If the `histverify` shell option is enabled, and Readline is being used, history substitutions are not immediately passed to the shell parser. Instead, the expanded line is reloaded into the Readline editing buffer for further modification. If Readline is being used, and the `histreedit` shell option is enabled, a failed history expansion will be reloaded into the Readline editing buffer for correction. The `-p` option to the `history` builtin command may be used to see what a history expansion will do before using it. The `-s` option to the `history` builtin may be used to add commands to the end of the history list without actually executing them, so that they are available for subsequent recall. This is most useful in conjunction with Readline. The shell allows control of the various characters used by the history expansion mechanism with the `histchars` variable, as explained above (see [Bash Variables](bash-variables)). The shell uses the history comment character to mark history timestamps when writing the history file. * [Event Designators](event-designators) * [Word Designators](word-designators) * [Modifiers](modifiers) bash Shell Parameter Expansion Shell Parameter Expansion ========================= The β€˜`$`’ character introduces parameter expansion, command substitution, or arithmetic expansion. The parameter name or symbol to be expanded may be enclosed in braces, which are optional but serve to protect the variable to be expanded from characters immediately following it which could be interpreted as part of the name. When braces are used, the matching ending brace is the first β€˜`}`’ not escaped by a backslash or within a quoted string, and not within an embedded arithmetic expansion, command substitution, or parameter expansion. The basic form of parameter expansion is ${parameter}. The value of parameter is substituted. The parameter is a shell parameter as described above (see [Shell Parameters](shell-parameters)) or an array reference (see [Arrays](arrays)). The braces are required when parameter is a positional parameter with more than one digit, or when parameter is followed by a character that is not to be interpreted as part of its name. If the first character of parameter is an exclamation point (!), and parameter is not a nameref, it introduces a level of indirection. Bash uses the value formed by expanding the rest of parameter as the new parameter; this is then expanded and that value is used in the rest of the expansion, rather than the expansion of the original parameter. This is known as `indirect expansion`. The value is subject to tilde expansion, parameter expansion, command substitution, and arithmetic expansion. If parameter is a nameref, this expands to the name of the variable referenced by parameter instead of performing the complete indirect expansion. The exceptions to this are the expansions of ${!prefix\*} and ${!name[@]} described below. The exclamation point must immediately follow the left brace in order to introduce indirection. In each of the cases below, word is subject to tilde expansion, parameter expansion, command substitution, and arithmetic expansion. When not performing substring expansion, using the form described below (e.g., β€˜`:-`’), Bash tests for a parameter that is unset or null. Omitting the colon results in a test only for a parameter that is unset. Put another way, if the colon is included, the operator tests for both parameter’s existence and that its value is not null; if the colon is omitted, the operator tests only for existence. `${parameter:-word}` If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted. ``` $ v=123 $ echo ${v-unset} 123 ``` `${parameter:=word}` If parameter is unset or null, the expansion of word is assigned to parameter. The value of parameter is then substituted. Positional parameters and special parameters may not be assigned to in this way. ``` $ var= $ : ${var:=DEFAULT} $ echo $var DEFAULT ``` `${parameter:?word}` If parameter is null or unset, the expansion of word (or a message to that effect if word is not present) is written to the standard error and the shell, if it is not interactive, exits. Otherwise, the value of parameter is substituted. ``` $ var= $ : ${var:?var is unset or null} bash: var: var is unset or null ``` `${parameter:+word}` If parameter is null or unset, nothing is substituted, otherwise the expansion of word is substituted. ``` $ var=123 $ echo ${var:+var is set and not null} var is set and not null ``` `${parameter:offset}` `${parameter:offset:length}` This is referred to as Substring Expansion. It expands to up to length characters of the value of parameter starting at the character specified by offset. If parameter is β€˜`@`’ or β€˜`\*`’, an indexed array subscripted by β€˜`@`’ or β€˜`\*`’, or an associative array name, the results differ as described below. If length is omitted, it expands to the substring of the value of parameter starting at the character specified by offset and extending to the end of the value. length and offset are arithmetic expressions (see [Shell Arithmetic](shell-arithmetic)). If offset evaluates to a number less than zero, the value is used as an offset in characters from the end of the value of parameter. If length evaluates to a number less than zero, it is interpreted as an offset in characters from the end of the value of parameter rather than a number of characters, and the expansion is the characters between offset and that result. Note that a negative offset must be separated from the colon by at least one space to avoid being confused with the β€˜`:-`’ expansion. Here are some examples illustrating substring expansion on parameters and subscripted arrays: ``` $ string=01234567890abcdefgh $ echo ${string:7} 7890abcdefgh $ echo ${string:7:0} $ echo ${string:7:2} 78 $ echo ${string:7:-2} 7890abcdef $ echo ${string: -7} bcdefgh $ echo ${string: -7:0} $ echo ${string: -7:2} bc $ echo ${string: -7:-2} bcdef $ set -- 01234567890abcdefgh $ echo ${1:7} 7890abcdefgh $ echo ${1:7:0} $ echo ${1:7:2} 78 $ echo ${1:7:-2} 7890abcdef $ echo ${1: -7} bcdefgh $ echo ${1: -7:0} $ echo ${1: -7:2} bc $ echo ${1: -7:-2} bcdef $ array[0]=01234567890abcdefgh $ echo ${array[0]:7} 7890abcdefgh $ echo ${array[0]:7:0} $ echo ${array[0]:7:2} 78 $ echo ${array[0]:7:-2} 7890abcdef $ echo ${array[0]: -7} bcdefgh $ echo ${array[0]: -7:0} $ echo ${array[0]: -7:2} bc $ echo ${array[0]: -7:-2} bcdef ``` If parameter is β€˜`@`’ or β€˜`\*`’, the result is length positional parameters beginning at offset. A negative offset is taken relative to one greater than the greatest positional parameter, so an offset of -1 evaluates to the last positional parameter. It is an expansion error if length evaluates to a number less than zero. The following examples illustrate substring expansion using positional parameters: ``` $ set -- 1 2 3 4 5 6 7 8 9 0 a b c d e f g h $ echo ${@:7} 7 8 9 0 a b c d e f g h $ echo ${@:7:0} $ echo ${@:7:2} 7 8 $ echo ${@:7:-2} bash: -2: substring expression < 0 $ echo ${@: -7:2} b c $ echo ${@:0} ./bash 1 2 3 4 5 6 7 8 9 0 a b c d e f g h $ echo ${@:0:2} ./bash 1 $ echo ${@: -7:0} ``` If parameter is an indexed array name subscripted by β€˜`@`’ or β€˜`\*`’, the result is the length members of the array beginning with `${parameter[offset]}`. A negative offset is taken relative to one greater than the maximum index of the specified array. It is an expansion error if length evaluates to a number less than zero. These examples show how you can use substring expansion with indexed arrays: ``` $ array=(0 1 2 3 4 5 6 7 8 9 0 a b c d e f g h) $ echo ${array[@]:7} 7 8 9 0 a b c d e f g h $ echo ${array[@]:7:2} 7 8 $ echo ${array[@]: -7:2} b c $ echo ${array[@]: -7:-2} bash: -2: substring expression < 0 $ echo ${array[@]:0} 0 1 2 3 4 5 6 7 8 9 0 a b c d e f g h $ echo ${array[@]:0:2} 0 1 $ echo ${array[@]: -7:0} ``` Substring expansion applied to an associative array produces undefined results. Substring indexing is zero-based unless the positional parameters are used, in which case the indexing starts at 1 by default. If offset is 0, and the positional parameters are used, `$0` is prefixed to the list. `${!prefix*}` `${!prefix@}` Expands to the names of variables whose names begin with prefix, separated by the first character of the `IFS` special variable. When β€˜`@`’ is used and the expansion appears within double quotes, each variable name expands to a separate word. `${!name[@]}` `${!name[*]}` If name is an array variable, expands to the list of array indices (keys) assigned in name. If name is not an array, expands to 0 if name is set and null otherwise. When β€˜`@`’ is used and the expansion appears within double quotes, each key expands to a separate word. `${#parameter}` The length in characters of the expanded value of parameter is substituted. If parameter is β€˜`\*`’ or β€˜`@`’, the value substituted is the number of positional parameters. If parameter is an array name subscripted by β€˜`\*`’ or β€˜`@`’, the value substituted is the number of elements in the array. If parameter is an indexed array name subscripted by a negative number, that number is interpreted as relative to one greater than the maximum index of parameter, so negative indices count back from the end of the array, and an index of -1 references the last element. `${parameter#word}` `${parameter##word}` The word is expanded to produce a pattern and matched according to the rules described below (see [Pattern Matching](pattern-matching)). If the pattern matches the beginning of the expanded value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the β€˜`#`’ case) or the longest matching pattern (the β€˜`##`’ case) deleted. If parameter is β€˜`@`’ or β€˜`\*`’, the pattern removal operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with β€˜`@`’ or β€˜`\*`’, the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list. `${parameter%word}` `${parameter%%word}` The word is expanded to produce a pattern and matched according to the rules described below (see [Pattern Matching](pattern-matching)). If the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is the value of parameter with the shortest matching pattern (the β€˜`%`’ case) or the longest matching pattern (the β€˜`%%`’ case) deleted. If parameter is β€˜`@`’ or β€˜`\*`’, the pattern removal operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with β€˜`@`’ or β€˜`\*`’, the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list. `${parameter/pattern/string}` `${parameter//pattern/string}` `${parameter/#pattern/string}` `${parameter/%pattern/string}` The pattern is expanded to produce a pattern just as in filename expansion. Parameter is expanded and the longest match of pattern against its value is replaced with string. string undergoes tilde expansion, parameter and variable expansion, arithmetic expansion, command and process substitution, and quote removal. The match is performed according to the rules described below (see [Pattern Matching](pattern-matching)). In the first form above, only the first match is replaced. If there are two slashes separating parameter and pattern (the second form above), all matches of pattern are replaced with string. If pattern is preceded by β€˜`#`’ (the third form above), it must match at the beginning of the expanded value of parameter. If pattern is preceded by β€˜`%`’ (the fourth form above), it must match at the end of the expanded value of parameter. If the expansion of string is null, matches of pattern are deleted. If string is null, matches of pattern are deleted and the β€˜`/`’ following pattern may be omitted. If the `patsub_replacement` shell option is enabled using `shopt`, any unquoted instances of β€˜`&`’ in string are replaced with the matching portion of pattern. This is intended to duplicate a common `sed` idiom. Quoting any part of string inhibits replacement in the expansion of the quoted portion, including replacement strings stored in shell variables. Backslash will escape β€˜`&`’ in string; the backslash is removed in order to permit a literal β€˜`&`’ in the replacement string. Users should take care if string is double-quoted to avoid unwanted interactions between the backslash and double-quoting, since backslash has special meaning within double quotes. Pattern substitution performs the check for unquoted β€˜`&`’ after expanding string, so users should ensure to properly quote any occurrences of β€˜`&`’ they want to be taken literally in the replacement and ensure any instances of β€˜`&`’ they want to be replaced are unquoted. For instance, ``` var=abcdef rep='& ' echo ${var/abc/& } echo "${var/abc/& }" echo ${var/abc/$rep} echo "${var/abc/$rep}" ``` will display four lines of "abc def", while ``` var=abcdef rep='& ' echo ${var/abc/\& } echo "${var/abc/\& }" echo ${var/abc/"& "} echo ${var/abc/"$rep"} ``` will display four lines of "& def". Like the pattern removal operators, double quotes surrounding the replacement string quote the expanded characters, while double quotes enclosing the entire parameter substitution do not, since the expansion is performed in a context that doesn’t take any enclosing double quotes into account. Since backslash can escape β€˜`&`’, it can also escape a backslash in the replacement string. This means that β€˜`\\`’ will insert a literal backslash into the replacement, so these two `echo` commands ``` var=abcdef rep='\\&xyz' echo ${var/abc/\\&xyz} echo ${var/abc/$rep} ``` will both output β€˜`\abcxyzdef`’. It should rarely be necessary to enclose only string in double quotes. If the `nocasematch` shell option (see the description of `shopt` in [The Shopt Builtin](the-shopt-builtin)) is enabled, the match is performed without regard to the case of alphabetic characters. If parameter is β€˜`@`’ or β€˜`\*`’, the substitution operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with β€˜`@`’ or β€˜`\*`’, the substitution operation is applied to each member of the array in turn, and the expansion is the resultant list. `${parameter^pattern}` `${parameter^^pattern}` `${parameter,pattern}` `${parameter,,pattern}` This expansion modifies the case of alphabetic characters in parameter. The pattern is expanded to produce a pattern just as in filename expansion. Each character in the expanded value of parameter is tested against pattern, and, if it matches the pattern, its case is converted. The pattern should not attempt to match more than one character. The β€˜`^`’ operator converts lowercase letters matching pattern to uppercase; the β€˜`,`’ operator converts matching uppercase letters to lowercase. The β€˜`^^`’ and β€˜`,,`’ expansions convert each matched character in the expanded value; the β€˜`^`’ and β€˜`,`’ expansions match and convert only the first character in the expanded value. If pattern is omitted, it is treated like a β€˜`?`’, which matches every character. If parameter is β€˜`@`’ or β€˜`\*`’, the case modification operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with β€˜`@`’ or β€˜`\*`’, the case modification operation is applied to each member of the array in turn, and the expansion is the resultant list. `${parameter@operator}` The expansion is either a transformation of the value of parameter or information about parameter itself, depending on the value of operator. Each operator is a single letter: `U` The expansion is a string that is the value of parameter with lowercase alphabetic characters converted to uppercase. `u` The expansion is a string that is the value of parameter with the first character converted to uppercase, if it is alphabetic. `L` The expansion is a string that is the value of parameter with uppercase alphabetic characters converted to lowercase. `Q` The expansion is a string that is the value of parameter quoted in a format that can be reused as input. `E` The expansion is a string that is the value of parameter with backslash escape sequences expanded as with the `$'…'` quoting mechanism. `P` The expansion is a string that is the result of expanding the value of parameter as if it were a prompt string (see [Controlling the Prompt](controlling-the-prompt)). `A` The expansion is a string in the form of an assignment statement or `declare` command that, if evaluated, will recreate parameter with its attributes and value. `K` Produces a possibly-quoted version of the value of parameter, except that it prints the values of indexed and associative arrays as a sequence of quoted key-value pairs (see [Arrays](arrays)). `a` The expansion is a string consisting of flag values representing parameter’s attributes. `k` Like the β€˜`K`’ transformation, but expands the keys and values of indexed and associative arrays to separate words after word splitting. If parameter is β€˜`@`’ or β€˜`\*`’, the operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with β€˜`@`’ or β€˜`\*`’, the operation is applied to each member of the array in turn, and the expansion is the resultant list. The result of the expansion is subject to word splitting and filename expansion as described below.
programming_docs
bash Interactive Shells Interactive Shells ================== * [What is an Interactive Shell?](what-is-an-interactive-shell_003f) * [Is this Shell Interactive?](is-this-shell-interactive_003f) * [Interactive Shell Behavior](interactive-shell-behavior) bash Invoking Bash Invoking Bash ============= ``` bash [long-opt] [-ir] [-abefhkmnptuvxdBCDHP] [-o option] [-O shopt_option] [argument …] bash [long-opt] [-abefhkmnptuvxdBCDHP] [-o option] [-O shopt_option] -c string [argument …] bash [long-opt] -s [-abefhkmnptuvxdBCDHP] [-o option] [-O shopt_option] [argument …] ``` All of the single-character options used with the `set` builtin (see [The Set Builtin](the-set-builtin)) can be used as options when the shell is invoked. In addition, there are several multi-character options that you can use. These options must appear on the command line before the single-character options to be recognized. `--debugger` Arrange for the debugger profile to be executed before the shell starts. Turns on extended debugging mode (see [The Shopt Builtin](the-shopt-builtin) for a description of the `extdebug` option to the `shopt` builtin). `--dump-po-strings` A list of all double-quoted strings preceded by β€˜`$`’ is printed on the standard output in the GNU `gettext` PO (portable object) file format. Equivalent to `-D` except for the output format. `--dump-strings` Equivalent to `-D`. `--help` Display a usage message on standard output and exit successfully. `--init-file filename` `--rcfile filename` Execute commands from filename (instead of `~/.bashrc`) in an interactive shell. `--login` Equivalent to `-l`. `--noediting` Do not use the GNU Readline library (see [Command Line Editing](command-line-editing)) to read command lines when the shell is interactive. `--noprofile` Don’t load the system-wide startup file `/etc/profile` or any of the personal initialization files `~/.bash\_profile`, `~/.bash\_login`, or `~/.profile` when Bash is invoked as a login shell. `--norc` Don’t read the `~/.bashrc` initialization file in an interactive shell. This is on by default if the shell is invoked as `sh`. `--posix` Change the behavior of Bash where the default operation differs from the POSIX standard to match the standard. This is intended to make Bash behave as a strict superset of that standard. See [Bash POSIX Mode](bash-posix-mode), for a description of the Bash POSIX mode. `--restricted` Make the shell a restricted shell (see [The Restricted Shell](the-restricted-shell)). `--verbose` Equivalent to `-v`. Print shell input lines as they’re read. `--version` Show version information for this instance of Bash on the standard output and exit successfully. There are several single-character options that may be supplied at invocation which are not available with the `set` builtin. `-c` Read and execute commands from the first non-option argument command\_string, then exit. If there are arguments after the command\_string, the first argument is assigned to `$0` and any remaining arguments are assigned to the positional parameters. The assignment to `$0` sets the name of the shell, which is used in warning and error messages. `-i` Force the shell to run interactively. Interactive shells are described in [Interactive Shells](interactive-shells). `-l` Make this shell act as if it had been directly invoked by login. When the shell is interactive, this is equivalent to starting a login shell with β€˜`exec -l bash`’. When the shell is not interactive, the login shell startup files will be executed. β€˜`exec bash -l`’ or β€˜`exec bash --login`’ will replace the current shell with a Bash login shell. See [Bash Startup Files](bash-startup-files), for a description of the special behavior of a login shell. `-r` Make the shell a restricted shell (see [The Restricted Shell](the-restricted-shell)). `-s` If this option is present, or if no arguments remain after option processing, then commands are read from the standard input. This option allows the positional parameters to be set when invoking an interactive shell or when reading input through a pipe. `-D` A list of all double-quoted strings preceded by β€˜`$`’ is printed on the standard output. These are the strings that are subject to language translation when the current locale is not `C` or `POSIX` (see [Locale-Specific Translation](locale-translation)). This implies the `-n` option; no commands will be executed. `[-+]O [shopt\_option]` shopt\_option is one of the shell options accepted by the `shopt` builtin (see [The Shopt Builtin](the-shopt-builtin)). If shopt\_option is present, `-O` sets the value of that option; `+O` unsets it. If shopt\_option is not supplied, the names and values of the shell options accepted by `shopt` are printed on the standard output. If the invocation option is `+O`, the output is displayed in a format that may be reused as input. `--` A `--` signals the end of options and disables further option processing. Any arguments after the `--` are treated as filenames and arguments. A *login* shell is one whose first character of argument zero is β€˜`-`’, or one invoked with the `--login` option. An *interactive* shell is one started without non-option arguments, unless `-s` is specified, without specifying the `-c` option, and whose input and output are both connected to terminals (as determined by `isatty(3)`), or one started with the `-i` option. See [Interactive Shells](interactive-shells), for more information. If arguments remain after option processing, and neither the `-c` nor the `-s` option has been supplied, the first argument is assumed to be the name of a file containing shell commands (see [Shell Scripts](shell-scripts)). When Bash is invoked in this fashion, `$0` is set to the name of the file, and the positional parameters are set to the remaining arguments. Bash reads and executes commands from this file, then exits. Bash’s exit status is the exit status of the last command executed in the script. If no commands are executed, the exit status is 0. bash Appendix A Reporting Bugs Appendix A Reporting Bugs ========================= Please report all bugs you find in Bash. But first, you should make sure that it really is a bug, and that it appears in the latest version of Bash. The latest version of Bash is always available for FTP from <ftp://ftp.gnu.org/pub/gnu/bash/> and from <http://git.savannah.gnu.org/cgit/bash.git/snapshot/bash-master.tar.gz>. Once you have determined that a bug actually exists, use the `bashbug` command to submit a bug report. If you have a fix, you are encouraged to mail that as well! Suggestions and β€˜philosophical’ bug reports may be mailed to [[email protected]](mailto:[email protected]) or posted to the Usenet newsgroup `gnu.bash.bug`. All bug reports should include: * The version number of Bash. * The hardware and operating system. * The compiler used to compile Bash. * A description of the bug behaviour. * A short script or β€˜recipe’ which exercises the bug and may be used to reproduce it. `bashbug` inserts the first three items automatically into the template it provides for filing a bug report. Please send all reports concerning this manual to [[email protected]](mailto:[email protected]). bash Bash Variables Bash Variables ============== These variables are set or used by Bash, but other shells do not normally treat them specially. A few variables used by Bash are described in different chapters: variables for controlling the job control facilities (see [Job Control Variables](job-control-variables)). `_` ($\_, an underscore.) At shell startup, set to the pathname used to invoke the shell or shell script being executed as passed in the environment or argument list. Subsequently, expands to the last argument to the previous simple command executed in the foreground, after expansion. Also set to the full pathname used to invoke each command executed and placed in the environment exported to that command. When checking mail, this parameter holds the name of the mail file. `BASH` The full pathname used to execute the current instance of Bash. `BASHOPTS` A colon-separated list of enabled shell options. Each word in the list is a valid argument for the `-s` option to the `shopt` builtin command (see [The Shopt Builtin](the-shopt-builtin)). The options appearing in `BASHOPTS` are those reported as β€˜`on`’ by β€˜`shopt`’. If this variable is in the environment when Bash starts up, each shell option in the list will be enabled before reading any startup files. This variable is readonly. `BASHPID` Expands to the process ID of the current Bash process. This differs from `$$` under certain circumstances, such as subshells that do not require Bash to be re-initialized. Assignments to `BASHPID` have no effect. If `BASHPID` is unset, it loses its special properties, even if it is subsequently reset. `BASH_ALIASES` An associative array variable whose members correspond to the internal list of aliases as maintained by the `alias` builtin. (see [Bourne Shell Builtins](bourne-shell-builtins)). Elements added to this array appear in the alias list; however, unsetting array elements currently does not cause aliases to be removed from the alias list. If `BASH_ALIASES` is unset, it loses its special properties, even if it is subsequently reset. `BASH_ARGC` An array variable whose values are the number of parameters in each frame of the current bash execution call stack. The number of parameters to the current subroutine (shell function or script executed with `.` or `source`) is at the top of the stack. When a subroutine is executed, the number of parameters passed is pushed onto `BASH_ARGC`. The shell sets `BASH_ARGC` only when in extended debugging mode (see [The Shopt Builtin](the-shopt-builtin) for a description of the `extdebug` option to the `shopt` builtin). Setting `extdebug` after the shell has started to execute a script, or referencing this variable when `extdebug` is not set, may result in inconsistent values. `BASH_ARGV` An array variable containing all of the parameters in the current bash execution call stack. The final parameter of the last subroutine call is at the top of the stack; the first parameter of the initial call is at the bottom. When a subroutine is executed, the parameters supplied are pushed onto `BASH_ARGV`. The shell sets `BASH_ARGV` only when in extended debugging mode (see [The Shopt Builtin](the-shopt-builtin) for a description of the `extdebug` option to the `shopt` builtin). Setting `extdebug` after the shell has started to execute a script, or referencing this variable when `extdebug` is not set, may result in inconsistent values. `BASH_ARGV0` When referenced, this variable expands to the name of the shell or shell script (identical to `$0`; See [Special Parameters](special-parameters), for the description of special parameter 0). Assignment to `BASH_ARGV0` causes the value assigned to also be assigned to `$0`. If `BASH_ARGV0` is unset, it loses its special properties, even if it is subsequently reset. `BASH_CMDS` An associative array variable whose members correspond to the internal hash table of commands as maintained by the `hash` builtin (see [Bourne Shell Builtins](bourne-shell-builtins)). Elements added to this array appear in the hash table; however, unsetting array elements currently does not cause command names to be removed from the hash table. If `BASH_CMDS` is unset, it loses its special properties, even if it is subsequently reset. `BASH_COMMAND` The command currently being executed or about to be executed, unless the shell is executing a command as the result of a trap, in which case it is the command executing at the time of the trap. If `BASH_COMMAND` is unset, it loses its special properties, even if it is subsequently reset. `BASH_COMPAT` The value is used to set the shell’s compatibility level. See [Shell Compatibility Mode](shell-compatibility-mode), for a description of the various compatibility levels and their effects. The value may be a decimal number (e.g., 4.2) or an integer (e.g., 42) corresponding to the desired compatibility level. If `BASH_COMPAT` is unset or set to the empty string, the compatibility level is set to the default for the current version. If `BASH_COMPAT` is set to a value that is not one of the valid compatibility levels, the shell prints an error message and sets the compatibility level to the default for the current version. The valid values correspond to the compatibility levels described below (see [Shell Compatibility Mode](shell-compatibility-mode)). For example, 4.2 and 42 are valid values that correspond to the `compat42` `shopt` option and set the compatibility level to 42. The current version is also a valid value. `BASH_ENV` If this variable is set when Bash is invoked to execute a shell script, its value is expanded and used as the name of a startup file to read before executing the script. See [Bash Startup Files](bash-startup-files). `BASH_EXECUTION_STRING` The command argument to the `-c` invocation option. `BASH_LINENO` An array variable whose members are the line numbers in source files where each corresponding member of `FUNCNAME` was invoked. `${BASH_LINENO[$i]}` is the line number in the source file (`${BASH_SOURCE[$i+1]}`) where `${FUNCNAME[$i]}` was called (or `${BASH_LINENO[$i-1]}` if referenced within another shell function). Use `LINENO` to obtain the current line number. `BASH_LOADABLES_PATH` A colon-separated list of directories in which the shell looks for dynamically loadable builtins specified by the `enable` command. `BASH_REMATCH` An array variable whose members are assigned by the β€˜`=~`’ binary operator to the `[[` conditional command (see [Conditional Constructs](conditional-constructs)). The element with index 0 is the portion of the string matching the entire regular expression. The element with index n is the portion of the string matching the nth parenthesized subexpression. `BASH_SOURCE` An array variable whose members are the source filenames where the corresponding shell function names in the `FUNCNAME` array variable are defined. The shell function `${FUNCNAME[$i]}` is defined in the file `${BASH_SOURCE[$i]}` and called from `${BASH_SOURCE[$i+1]}` `BASH_SUBSHELL` Incremented by one within each subshell or subshell environment when the shell begins executing in that environment. The initial value is 0. If `BASH_SUBSHELL` is unset, it loses its special properties, even if it is subsequently reset. `BASH_VERSINFO` A readonly array variable (see [Arrays](arrays)) whose members hold version information for this instance of Bash. The values assigned to the array members are as follows: `BASH_VERSINFO[0]` The major version number (the *release*). `BASH_VERSINFO[1]` The minor version number (the *version*). `BASH_VERSINFO[2]` The patch level. `BASH_VERSINFO[3]` The build version. `BASH_VERSINFO[4]` The release status (e.g., `beta1`). `BASH_VERSINFO[5]` The value of `MACHTYPE`. `BASH_VERSION` The version number of the current instance of Bash. `BASH_XTRACEFD` If set to an integer corresponding to a valid file descriptor, Bash will write the trace output generated when β€˜`set -x`’ is enabled to that file descriptor. This allows tracing output to be separated from diagnostic and error messages. The file descriptor is closed when `BASH_XTRACEFD` is unset or assigned a new value. Unsetting `BASH_XTRACEFD` or assigning it the empty string causes the trace output to be sent to the standard error. Note that setting `BASH_XTRACEFD` to 2 (the standard error file descriptor) and then unsetting it will result in the standard error being closed. `CHILD_MAX` Set the number of exited child status values for the shell to remember. Bash will not allow this value to be decreased below a POSIX-mandated minimum, and there is a maximum value (currently 8192) that this may not exceed. The minimum value is system-dependent. `COLUMNS` Used by the `select` command to determine the terminal width when printing selection lists. Automatically set if the `checkwinsize` option is enabled (see [The Shopt Builtin](the-shopt-builtin)), or in an interactive shell upon receipt of a `SIGWINCH`. `COMP_CWORD` An index into `${COMP_WORDS}` of the word containing the current cursor position. This variable is available only in shell functions invoked by the programmable completion facilities (see [Programmable Completion](programmable-completion)). `COMP_LINE` The current command line. This variable is available only in shell functions and external commands invoked by the programmable completion facilities (see [Programmable Completion](programmable-completion)). `COMP_POINT` The index of the current cursor position relative to the beginning of the current command. If the current cursor position is at the end of the current command, the value of this variable is equal to `${#COMP_LINE}`. This variable is available only in shell functions and external commands invoked by the programmable completion facilities (see [Programmable Completion](programmable-completion)). `COMP_TYPE` Set to an integer value corresponding to the type of completion attempted that caused a completion function to be called: `TAB`, for normal completion, β€˜`?`’, for listing completions after successive tabs, β€˜`!`’, for listing alternatives on partial word completion, β€˜`@`’, to list completions if the word is not unmodified, or β€˜`%`’, for menu completion. This variable is available only in shell functions and external commands invoked by the programmable completion facilities (see [Programmable Completion](programmable-completion)). `COMP_KEY` The key (or final key of a key sequence) used to invoke the current completion function. `COMP_WORDBREAKS` The set of characters that the Readline library treats as word separators when performing word completion. If `COMP_WORDBREAKS` is unset, it loses its special properties, even if it is subsequently reset. `COMP_WORDS` An array variable consisting of the individual words in the current command line. The line is split into words as Readline would split it, using `COMP_WORDBREAKS` as described above. This variable is available only in shell functions invoked by the programmable completion facilities (see [Programmable Completion](programmable-completion)). `COMPREPLY` An array variable from which Bash reads the possible completions generated by a shell function invoked by the programmable completion facility (see [Programmable Completion](programmable-completion)). Each array element contains one possible completion. `COPROC` An array variable created to hold the file descriptors for output from and input to an unnamed coprocess (see [Coprocesses](coprocesses)). `DIRSTACK` An array variable containing the current contents of the directory stack. Directories appear in the stack in the order they are displayed by the `dirs` builtin. Assigning to members of this array variable may be used to modify directories already in the stack, but the `pushd` and `popd` builtins must be used to add and remove directories. Assignment to this variable will not change the current directory. If `DIRSTACK` is unset, it loses its special properties, even if it is subsequently reset. `EMACS` If Bash finds this variable in the environment when the shell starts with value β€˜`t`’, it assumes that the shell is running in an Emacs shell buffer and disables line editing. `ENV` Expanded and executed similarly to `BASH_ENV` (see [Bash Startup Files](bash-startup-files)) when an interactive shell is invoked in POSIX Mode (see [Bash POSIX Mode](bash-posix-mode)). `EPOCHREALTIME` Each time this parameter is referenced, it expands to the number of seconds since the Unix Epoch as a floating point value with micro-second granularity (see the documentation for the C library function `time` for the definition of Epoch). Assignments to `EPOCHREALTIME` are ignored. If `EPOCHREALTIME` is unset, it loses its special properties, even if it is subsequently reset. `EPOCHSECONDS` Each time this parameter is referenced, it expands to the number of seconds since the Unix Epoch (see the documentation for the C library function `time` for the definition of Epoch). Assignments to `EPOCHSECONDS` are ignored. If `EPOCHSECONDS` is unset, it loses its special properties, even if it is subsequently reset. `EUID` The numeric effective user id of the current user. This variable is readonly. `EXECIGNORE` A colon-separated list of shell patterns (see [Pattern Matching](pattern-matching)) defining the list of filenames to be ignored by command search using `PATH`. Files whose full pathnames match one of these patterns are not considered executable files for the purposes of completion and command execution via `PATH` lookup. This does not affect the behavior of the `[`, `test`, and `[[` commands. Full pathnames in the command hash table are not subject to `EXECIGNORE`. Use this variable to ignore shared library files that have the executable bit set, but are not executable files. The pattern matching honors the setting of the `extglob` shell option. `FCEDIT` The editor used as a default by the `-e` option to the `fc` builtin command. `FIGNORE` A colon-separated list of suffixes to ignore when performing filename completion. A filename whose suffix matches one of the entries in `FIGNORE` is excluded from the list of matched filenames. A sample value is β€˜`.o:~`’ `FUNCNAME` An array variable containing the names of all shell functions currently in the execution call stack. The element with index 0 is the name of any currently-executing shell function. The bottom-most element (the one with the highest index) is `"main"`. This variable exists only when a shell function is executing. Assignments to `FUNCNAME` have no effect. If `FUNCNAME` is unset, it loses its special properties, even if it is subsequently reset. This variable can be used with `BASH_LINENO` and `BASH_SOURCE`. Each element of `FUNCNAME` has corresponding elements in `BASH_LINENO` and `BASH_SOURCE` to describe the call stack. For instance, `${FUNCNAME[$i]}` was called from the file `${BASH_SOURCE[$i+1]}` at line number `${BASH_LINENO[$i]}`. The `caller` builtin displays the current call stack using this information. `FUNCNEST` If set to a numeric value greater than 0, defines a maximum function nesting level. Function invocations that exceed this nesting level will cause the current command to abort. `GLOBIGNORE` A colon-separated list of patterns defining the set of file names to be ignored by filename expansion. If a file name matched by a filename expansion pattern also matches one of the patterns in `GLOBIGNORE`, it is removed from the list of matches. The pattern matching honors the setting of the `extglob` shell option. `GROUPS` An array variable containing the list of groups of which the current user is a member. Assignments to `GROUPS` have no effect. If `GROUPS` is unset, it loses its special properties, even if it is subsequently reset. `histchars` Up to three characters which control history expansion, quick substitution, and tokenization (see [History Expansion](history-interaction)). The first character is the *history expansion* character, that is, the character which signifies the start of a history expansion, normally β€˜`!`’. The second character is the character which signifies β€˜quick substitution’ when seen as the first character on a line, normally β€˜`^`’. The optional third character is the character which indicates that the remainder of the line is a comment when found as the first character of a word, usually β€˜`#`’. The history comment character causes history substitution to be skipped for the remaining words on the line. It does not necessarily cause the shell parser to treat the rest of the line as a comment. `HISTCMD` The history number, or index in the history list, of the current command. Assignments to `HISTCMD` are ignored. If `HISTCMD` is unset, it loses its special properties, even if it is subsequently reset. `HISTCONTROL` A colon-separated list of values controlling how commands are saved on the history list. If the list of values includes β€˜`ignorespace`’, lines which begin with a space character are not saved in the history list. A value of β€˜`ignoredups`’ causes lines which match the previous history entry to not be saved. A value of β€˜`ignoreboth`’ is shorthand for β€˜`ignorespace`’ and β€˜`ignoredups`’. A value of β€˜`erasedups`’ causes all previous lines matching the current line to be removed from the history list before that line is saved. Any value not in the above list is ignored. If `HISTCONTROL` is unset, or does not include a valid value, all lines read by the shell parser are saved on the history list, subject to the value of `HISTIGNORE`. The second and subsequent lines of a multi-line compound command are not tested, and are added to the history regardless of the value of `HISTCONTROL`. `HISTFILE` The name of the file to which the command history is saved. The default value is `~/.bash\_history`. `HISTFILESIZE` The maximum number of lines contained in the history file. When this variable is assigned a value, the history file is truncated, if necessary, to contain no more than that number of lines by removing the oldest entries. The history file is also truncated to this size after writing it when a shell exits. If the value is 0, the history file is truncated to zero size. Non-numeric values and numeric values less than zero inhibit truncation. The shell sets the default value to the value of `HISTSIZE` after reading any startup files. `HISTIGNORE` A colon-separated list of patterns used to decide which command lines should be saved on the history list. Each pattern is anchored at the beginning of the line and must match the complete line (no implicit β€˜`\*`’ is appended). Each pattern is tested against the line after the checks specified by `HISTCONTROL` are applied. In addition to the normal shell pattern matching characters, β€˜`&`’ matches the previous history line. β€˜`&`’ may be escaped using a backslash; the backslash is removed before attempting a match. The second and subsequent lines of a multi-line compound command are not tested, and are added to the history regardless of the value of `HISTIGNORE`. The pattern matching honors the setting of the `extglob` shell option. `HISTIGNORE` subsumes the function of `HISTCONTROL`. A pattern of β€˜`&`’ is identical to `ignoredups`, and a pattern of β€˜`[ ]\*`’ is identical to `ignorespace`. Combining these two patterns, separating them with a colon, provides the functionality of `ignoreboth`. `HISTSIZE` The maximum number of commands to remember on the history list. If the value is 0, commands are not saved in the history list. Numeric values less than zero result in every command being saved on the history list (there is no limit). The shell sets the default value to 500 after reading any startup files. `HISTTIMEFORMAT` If this variable is set and not null, its value is used as a format string for `strftime` to print the time stamp associated with each history entry displayed by the `history` builtin. If this variable is set, time stamps are written to the history file so they may be preserved across shell sessions. This uses the history comment character to distinguish timestamps from other history lines. `HOSTFILE` Contains the name of a file in the same format as `/etc/hosts` that should be read when the shell needs to complete a hostname. The list of possible hostname completions may be changed while the shell is running; the next time hostname completion is attempted after the value is changed, Bash adds the contents of the new file to the existing list. If `HOSTFILE` is set, but has no value, or does not name a readable file, Bash attempts to read `/etc/hosts` to obtain the list of possible hostname completions. When `HOSTFILE` is unset, the hostname list is cleared. `HOSTNAME` The name of the current host. `HOSTTYPE` A string describing the machine Bash is running on. `IGNOREEOF` Controls the action of the shell on receipt of an `EOF` character as the sole input. If set, the value denotes the number of consecutive `EOF` characters that can be read as the first character on an input line before the shell will exit. If the variable exists but does not have a numeric value, or has no value, then the default is 10. If the variable does not exist, then `EOF` signifies the end of input to the shell. This is only in effect for interactive shells. `INPUTRC` The name of the Readline initialization file, overriding the default of `~/.inputrc`. `INSIDE_EMACS` If Bash finds this variable in the environment when the shell starts, it assumes that the shell is running in an Emacs shell buffer and may disable line editing depending on the value of `TERM`. `LANG` Used to determine the locale category for any category not specifically selected with a variable starting with `LC_`. `LC_ALL` This variable overrides the value of `LANG` and any other `LC_` variable specifying a locale category. `LC_COLLATE` This variable determines the collation order used when sorting the results of filename expansion, and determines the behavior of range expressions, equivalence classes, and collating sequences within filename expansion and pattern matching (see [Filename Expansion](filename-expansion)). `LC_CTYPE` This variable determines the interpretation of characters and the behavior of character classes within filename expansion and pattern matching (see [Filename Expansion](filename-expansion)). `LC_MESSAGES` This variable determines the locale used to translate double-quoted strings preceded by a β€˜`$`’ (see [Locale-Specific Translation](locale-translation)). `LC_NUMERIC` This variable determines the locale category used for number formatting. `LC_TIME` This variable determines the locale category used for data and time formatting. `LINENO` The line number in the script or shell function currently executing. If `LINENO` is unset, it loses its special properties, even if it is subsequently reset. `LINES` Used by the `select` command to determine the column length for printing selection lists. Automatically set if the `checkwinsize` option is enabled (see [The Shopt Builtin](the-shopt-builtin)), or in an interactive shell upon receipt of a `SIGWINCH`. `MACHTYPE` A string that fully describes the system type on which Bash is executing, in the standard GNU cpu-company-system format. `MAILCHECK` How often (in seconds) that the shell should check for mail in the files specified in the `MAILPATH` or `MAIL` variables. The default is 60 seconds. When it is time to check for mail, the shell does so before displaying the primary prompt. If this variable is unset, or set to a value that is not a number greater than or equal to zero, the shell disables mail checking. `MAPFILE` An array variable created to hold the text read by the `mapfile` builtin when no variable name is supplied. `OLDPWD` The previous working directory as set by the `cd` builtin. `OPTERR` If set to the value 1, Bash displays error messages generated by the `getopts` builtin command. `OSTYPE` A string describing the operating system Bash is running on. `PIPESTATUS` An array variable (see [Arrays](arrays)) containing a list of exit status values from the processes in the most-recently-executed foreground pipeline (which may contain only a single command). `POSIXLY_CORRECT` If this variable is in the environment when Bash starts, the shell enters POSIX mode (see [Bash POSIX Mode](bash-posix-mode)) before reading the startup files, as if the `--posix` invocation option had been supplied. If it is set while the shell is running, Bash enables POSIX mode, as if the command ``` set -o posix ``` had been executed. When the shell enters POSIX mode, it sets this variable if it was not already set. `PPID` The process ID of the shell’s parent process. This variable is readonly. `PROMPT_COMMAND` If this variable is set, and is an array, the value of each set element is interpreted as a command to execute before printing the primary prompt (`$PS1`). If this is set but not an array variable, its value is used as a command to execute instead. `PROMPT_DIRTRIM` If set to a number greater than zero, the value is used as the number of trailing directory components to retain when expanding the `\w` and `\W` prompt string escapes (see [Controlling the Prompt](controlling-the-prompt)). Characters removed are replaced with an ellipsis. `PS0` The value of this parameter is expanded like `PS1` and displayed by interactive shells after reading a command and before the command is executed. `PS3` The value of this variable is used as the prompt for the `select` command. If this variable is not set, the `select` command prompts with β€˜`#?` ’ `PS4` The value of this parameter is expanded like `PS1` and the expanded value is the prompt printed before the command line is echoed when the `-x` option is set (see [The Set Builtin](the-set-builtin)). The first character of the expanded value is replicated multiple times, as necessary, to indicate multiple levels of indirection. The default is β€˜`+` ’. `PWD` The current working directory as set by the `cd` builtin. `RANDOM` Each time this parameter is referenced, it expands to a random integer between 0 and 32767. Assigning a value to this variable seeds the random number generator. If `RANDOM` is unset, it loses its special properties, even if it is subsequently reset. `READLINE_ARGUMENT` Any numeric argument given to a Readline command that was defined using β€˜`bind -x`’ (see [Bash Builtin Commands](bash-builtins) when it was invoked. `READLINE_LINE` The contents of the Readline line buffer, for use with β€˜`bind -x`’ (see [Bash Builtin Commands](bash-builtins)). `READLINE_MARK` The position of the *mark* (saved insertion point) in the Readline line buffer, for use with β€˜`bind -x`’ (see [Bash Builtin Commands](bash-builtins)). The characters between the insertion point and the mark are often called the *region*. `READLINE_POINT` The position of the insertion point in the Readline line buffer, for use with β€˜`bind -x`’ (see [Bash Builtin Commands](bash-builtins)). `REPLY` The default variable for the `read` builtin. `SECONDS` This variable expands to the number of seconds since the shell was started. Assignment to this variable resets the count to the value assigned, and the expanded value becomes the value assigned plus the number of seconds since the assignment. The number of seconds at shell invocation and the current time are always determined by querying the system clock. If `SECONDS` is unset, it loses its special properties, even if it is subsequently reset. `SHELL` This environment variable expands to the full pathname to the shell. If it is not set when the shell starts, Bash assigns to it the full pathname of the current user’s login shell. `SHELLOPTS` A colon-separated list of enabled shell options. Each word in the list is a valid argument for the `-o` option to the `set` builtin command (see [The Set Builtin](the-set-builtin)). The options appearing in `SHELLOPTS` are those reported as β€˜`on`’ by β€˜`set -o`’. If this variable is in the environment when Bash starts up, each shell option in the list will be enabled before reading any startup files. This variable is readonly. `SHLVL` Incremented by one each time a new instance of Bash is started. This is intended to be a count of how deeply your Bash shells are nested. `SRANDOM` This variable expands to a 32-bit pseudo-random number each time it is referenced. The random number generator is not linear on systems that support `/dev/urandom` or `arc4random`, so each returned number has no relationship to the numbers preceding it. The random number generator cannot be seeded, so assignments to this variable have no effect. If `SRANDOM` is unset, it loses its special properties, even if it is subsequently reset. `TIMEFORMAT` The value of this parameter is used as a format string specifying how the timing information for pipelines prefixed with the `time` reserved word should be displayed. The β€˜`%`’ character introduces an escape sequence that is expanded to a time value or other information. The escape sequences and their meanings are as follows; the braces denote optional portions. `%%` A literal β€˜`%`’. `%[p][l]R` The elapsed time in seconds. `%[p][l]U` The number of CPU seconds spent in user mode. `%[p][l]S` The number of CPU seconds spent in system mode. `%P` The CPU percentage, computed as (%U + %S) / %R. The optional p is a digit specifying the precision, the number of fractional digits after a decimal point. A value of 0 causes no decimal point or fraction to be output. At most three places after the decimal point may be specified; values of p greater than 3 are changed to 3. If p is not specified, the value 3 is used. The optional `l` specifies a longer format, including minutes, of the form MMmSS.FFs. The value of p determines whether or not the fraction is included. If this variable is not set, Bash acts as if it had the value ``` $'\nreal\t%3lR\nuser\t%3lU\nsys\t%3lS' ``` If the value is null, no timing information is displayed. A trailing newline is added when the format string is displayed. `TMOUT` If set to a value greater than zero, `TMOUT` is treated as the default timeout for the `read` builtin (see [Bash Builtin Commands](bash-builtins)). The `select` command (see [Conditional Constructs](conditional-constructs)) terminates if input does not arrive after `TMOUT` seconds when input is coming from a terminal. In an interactive shell, the value is interpreted as the number of seconds to wait for a line of input after issuing the primary prompt. Bash terminates after waiting for that number of seconds if a complete line of input does not arrive. `TMPDIR` If set, Bash uses its value as the name of a directory in which Bash creates temporary files for the shell’s use. `UID` The numeric real user id of the current user. This variable is readonly.
programming_docs
bash Executing Commands Executing Commands ================== * [Simple Command Expansion](simple-command-expansion) * [Command Search and Execution](command-search-and-execution) * [Command Execution Environment](command-execution-environment) * [Environment](environment) * [Exit Status](exit-status) * [Signals](signals) bash Interactive Shell Behavior Interactive Shell Behavior ========================== When the shell is running interactively, it changes its behavior in several ways. 1. Startup files are read and executed as described in [Bash Startup Files](bash-startup-files). 2. Job Control (see [Job Control](job-control)) is enabled by default. When job control is in effect, Bash ignores the keyboard-generated job control signals `SIGTTIN`, `SIGTTOU`, and `SIGTSTP`. 3. Bash expands and displays `PS1` before reading the first line of a command, and expands and displays `PS2` before reading the second and subsequent lines of a multi-line command. Bash expands and displays `PS0` after it reads a command but before executing it. See [Controlling the Prompt](controlling-the-prompt), for a complete list of prompt string escape sequences. 4. Bash executes the values of the set elements of the `PROMPT_COMMAND` array variable as commands before printing the primary prompt, `$PS1` (see [Bash Variables](bash-variables)). 5. Readline (see [Command Line Editing](command-line-editing)) is used to read commands from the user’s terminal. 6. Bash inspects the value of the `ignoreeof` option to `set -o` instead of exiting immediately when it receives an `EOF` on its standard input when reading a command (see [The Set Builtin](the-set-builtin)). 7. Command history (see [Bash History Facilities](bash-history-facilities)) and history expansion (see [History Expansion](history-interaction)) are enabled by default. Bash will save the command history to the file named by `$HISTFILE` when a shell with history enabled exits. 8. Alias expansion (see [Aliases](aliases)) is performed by default. 9. In the absence of any traps, Bash ignores `SIGTERM` (see [Signals](signals)). 10. In the absence of any traps, `SIGINT` is caught and handled (see [Signals](signals)). `SIGINT` will interrupt some shell builtins. 11. An interactive login shell sends a `SIGHUP` to all jobs on exit if the `huponexit` shell option has been enabled (see [Signals](signals)). 12. The `-n` invocation option is ignored, and β€˜`set -n`’ has no effect (see [The Set Builtin](the-set-builtin)). 13. Bash will check for mail periodically, depending on the values of the `MAIL`, `MAILPATH`, and `MAILCHECK` shell variables (see [Bash Variables](bash-variables)). 14. Expansion errors due to references to unbound shell variables after β€˜`set -u`’ has been enabled will not cause the shell to exit (see [The Set Builtin](the-set-builtin)). 15. The shell will not exit on expansion errors caused by var being unset or null in `${var:?word}` expansions (see [Shell Parameter Expansion](shell-parameter-expansion)). 16. Redirection errors encountered by shell builtins will not cause the shell to exit. 17. When running in POSIX mode, a special builtin returning an error status will not cause the shell to exit (see [Bash POSIX Mode](bash-posix-mode)). 18. A failed `exec` will not cause the shell to exit (see [Bourne Shell Builtins](bourne-shell-builtins)). 19. Parser syntax errors will not cause the shell to exit. 20. If the `cdspell` shell option is enabled, the shell will attempt simple spelling correction for directory arguments to the `cd` builtin (see the description of the `cdspell` option to the `shopt` builtin in [The Shopt Builtin](the-shopt-builtin)). The `cdspell` option is only effective in interactive shells. 21. The shell will check the value of the `TMOUT` variable and exit if a command is not read within the specified number of seconds after printing `$PS1` (see [Bash Variables](bash-variables)). bash Tilde Expansion Tilde Expansion =============== If a word begins with an unquoted tilde character (β€˜`~`’), all of the characters up to the first unquoted slash (or all characters, if there is no unquoted slash) are considered a *tilde-prefix*. If none of the characters in the tilde-prefix are quoted, the characters in the tilde-prefix following the tilde are treated as a possible *login name*. If this login name is the null string, the tilde is replaced with the value of the `HOME` shell variable. If `HOME` is unset, the home directory of the user executing the shell is substituted instead. Otherwise, the tilde-prefix is replaced with the home directory associated with the specified login name. If the tilde-prefix is β€˜`~+`’, the value of the shell variable `PWD` replaces the tilde-prefix. If the tilde-prefix is β€˜`~-`’, the value of the shell variable `OLDPWD`, if it is set, is substituted. If the characters following the tilde in the tilde-prefix consist of a number N, optionally prefixed by a β€˜`+`’ or a β€˜`-`’, the tilde-prefix is replaced with the corresponding element from the directory stack, as it would be displayed by the `dirs` builtin invoked with the characters following tilde in the tilde-prefix as an argument (see [The Directory Stack](the-directory-stack)). If the tilde-prefix, sans the tilde, consists of a number without a leading β€˜`+`’ or β€˜`-`’, β€˜`+`’ is assumed. If the login name is invalid, or the tilde expansion fails, the word is left unchanged. Each variable assignment is checked for unquoted tilde-prefixes immediately following a β€˜`:`’ or the first β€˜`=`’. In these cases, tilde expansion is also performed. Consequently, one may use filenames with tildes in assignments to `PATH`, `MAILPATH`, and `CDPATH`, and the shell assigns the expanded value. The following table shows how Bash treats unquoted tilde-prefixes: `~` The value of `$HOME` `~/foo` `$HOME/foo` `~fred/foo` The subdirectory `foo` of the home directory of the user `fred` `~+/foo` `$PWD/foo` `~-/foo` `${OLDPWD-'~-'}/foo` `~N` The string that would be displayed by β€˜`dirs +N`’ `~+N` The string that would be displayed by β€˜`dirs +N`’ `~-N` The string that would be displayed by β€˜`dirs -N`’ Bash also performs tilde expansion on words satisfying the conditions of variable assignments (see [Shell Parameters](shell-parameters)) when they appear as arguments to simple commands. Bash does not do this, except for the declaration commands listed above, when in POSIX mode. scikit_image scikit-image 0.18.0 docs scikit-image 0.18.0 docs ======================== scikit-image is an image processing toolbox for [SciPy](https://www.scipy.org). View the latest [release notes here](https://scikit-image.org/docs/0.18.x/release_notes.html). Sections -------- | | | | --- | --- | | [Overview](https://scikit-image.org/docs/0.18.x/overview.html) Introduction to scikit-image. | [API Reference](api/api) ([changes](https://scikit-image.org/docs/0.18.x/api_changes.html)) Documentation for the functions included in scikit-image. | | [Mission Statement](https://scikit-image.org/docs/0.18.x/values.html) Our mission, vision, and values. | [Governance](https://scikit-image.org/docs/0.18.x/skips/1-governance.html) How decisions are made in scikit-image. | | [Installation](https://scikit-image.org/docs/0.18.x/install.html) How to install scikit-image. | [User Guide](user_guide) Usage guidelines. | | [Glossary](https://scikit-image.org/docs/0.18.x/glossary.html) Definitions of common terms. | [Contribute](https://scikit-image.org/docs/0.18.x/contribute.html) Take part in development. Core developers, please [read your guide](https://scikit-image.org/docs/0.18.x/core_developer.html). | | [Gallery](https://scikit-image.org/docs/0.18.x/auto_examples/index.html) Introductory generic and domain-specific examples. | [License Info](https://scikit-image.org/docs/0.18.x/license.html) Conditions on the use and redistribution of this package. | | [SKIPs](https://scikit-image.org/docs/0.18.x/skips/index.html) **s**ci**k**it-**i**mage **p**roposals, documents describing major changes to the library. | [Code of Conduct](https://scikit-image.org/docs/0.18.x/conduct/code_of_conduct.html) Community interaction guidelines. | Indices ------- | | | | --- | --- | | [Search Page](https://scikit-image.org/docs/0.18.x/search.html) Search this documentation. | [Index](https://scikit-image.org/docs/0.18.x/genindex.html) All functions, classes, terms. | scikit_image User Guide User Guide ========== * [Getting started](user_guide/getting_started) * [A crash course on NumPy for images](user_guide/numpy_images) + [NumPy indexing](user_guide/numpy_images#numpy-indexing) + [Color images](user_guide/numpy_images#color-images) + [Coordinate conventions](user_guide/numpy_images#coordinate-conventions) + [Notes on the order of array dimensions](user_guide/numpy_images#notes-on-the-order-of-array-dimensions) + [A note on the time dimension](user_guide/numpy_images#a-note-on-the-time-dimension) * [Image data types and what they mean](user_guide/data_types) + [Input types](user_guide/data_types#input-types) + [Output types](user_guide/data_types#output-types) + [Working with OpenCV](user_guide/data_types#working-with-opencv) + [Image processing pipeline](user_guide/data_types#image-processing-pipeline) + [Rescaling intensity values](user_guide/data_types#rescaling-intensity-values) + [Note about negative values](user_guide/data_types#note-about-negative-values) + [References](user_guide/data_types#references) * [I/O Plugin Infrastructure](user_guide/plugins) * [Handling Video Files](user_guide/video) + [A Workaround: Convert the Video to an Image Sequence](user_guide/video#a-workaround-convert-the-video-to-an-image-sequence) + [PyAV](user_guide/video#pyav) + [Adding Random Access to PyAV](user_guide/video#adding-random-access-to-pyav) + [MoviePy](user_guide/video#moviepy) + [Imageio](user_guide/video#imageio) + [OpenCV](user_guide/video#opencv) * [Data visualization](user_guide/visualization) + [Matplotlib](user_guide/visualization#matplotlib) + [Plotly](user_guide/visualization#plotly) + [Mayavi](user_guide/visualization#mayavi) + [Napari](user_guide/visualization#napari) * [Image adjustment: transforming image content](user_guide/transforming_image_data) + [Color manipulation](user_guide/transforming_image_data#color-manipulation) + [Contrast and exposure](user_guide/transforming_image_data#contrast-and-exposure) * [Geometrical transformations of images](user_guide/geometrical_transform) + [Cropping, resizing and rescaling images](user_guide/geometrical_transform#cropping-resizing-and-rescaling-images) + [Projective transforms (homographies)](user_guide/geometrical_transform#projective-transforms-homographies) * [Tutorials](user_guide/tutorials) + [Image Segmentation](user_guide/tutorial_segmentation) + [How to parallelize loops](user_guide/tutorial_parallelization) * [Getting help on using `skimage`](user_guide/getting_help) + [Examples gallery](user_guide/getting_help#examples-gallery) + [Search field](user_guide/getting_help#search-field) + [API Discovery](user_guide/getting_help#api-discovery) + [Docstrings](user_guide/getting_help#docstrings) + [Mailing-list](user_guide/getting_help#mailing-list) * [Image Viewer](user_guide/viewer) + [Quick Start](user_guide/viewer#quick-start) scikit_image I/O Plugin Infrastructure I/O Plugin Infrastructure ========================= A plugin consists of two files, the source and the descriptor `.ini`. Let’s say we’d like to provide a plugin for `imshow` using `matplotlib`. We’ll call our plugin `mpl`: ``` skimage/io/_plugins/mpl.py skimage/io/_plugins/mpl.ini ``` The name of the `.py` and `.ini` files must correspond. Inside the `.ini` file, we give the plugin meta-data: ``` [mpl] <-- name of the plugin, may be anything description = Matplotlib image I/O plugin provides = imshow <-- a comma-separated list, one or more of imshow, imsave, imread, _app_show ``` The β€œprovides”-line lists all the functions provided by the plugin. Since our plugin provides `imshow`, we have to define it inside `mpl.py`: ``` # This is mpl.py import matplotlib.pyplot as plt def imshow(img): plt.imshow(img) ``` Note that, by default, `imshow` is non-blocking, so a special function `_app_show` must be provided to block the GUI. We can modify our plugin to provide it as follows: ``` [mpl] provides = imshow, _app_show ``` ``` # This is mpl.py import matplotlib.pyplot as plt def imshow(img): plt.imshow(img) def _app_show(): plt.show() ``` Any plugin in the `_plugins` directory is automatically examined by `skimage.io` upon import. You may list all the plugins on your system: ``` >>> import skimage.io as io >>> io.find_available_plugins() {'gtk': ['imshow'], 'matplotlib': ['imshow', 'imread', 'imread_collection'], 'pil': ['imread', 'imsave', 'imread_collection'], 'qt': ['imshow', 'imsave', 'imread', 'imread_collection'], 'test': ['imsave', 'imshow', 'imread', 'imread_collection'],} ``` or only those already loaded: ``` >>> io.find_available_plugins(loaded=True) {'matplotlib': ['imshow', 'imread', 'imread_collection'], 'pil': ['imread', 'imsave', 'imread_collection']} ``` A plugin is loaded using the `use_plugin` command: ``` >>> import skimage.io as io >>> io.use_plugin('pil') # Use all capabilities provided by PIL ``` or ``` >>> io.use_plugin('pil', 'imread') # Use only the imread capability of PIL ``` Note that, if more than one plugin provides certain functionality, the last plugin loaded is used. To query a plugin’s capabilities, use `plugin_info`: ``` >>> io.plugin_info('pil') >>> {'description': 'Image reading via the Python Imaging Library', 'provides': 'imread, imsave'} ``` scikit_image A crash course on NumPy for images A crash course on NumPy for images ================================== Images in `scikit-image` are represented by NumPy ndarrays. Hence, many common operations can be achieved using standard NumPy methods for manipulating arrays: ``` >>> from skimage import data >>> camera = data.camera() >>> type(camera) <type 'numpy.ndarray'> ``` Retrieving the geometry of the image and the number of pixels: ``` >>> camera.shape (512, 512) >>> camera.size 262144 ``` Retrieving statistical information about image intensity values: ``` >>> camera.min(), camera.max() (0, 255) >>> camera.mean() 118.31400299072266 ``` NumPy arrays representing images can be of different integer or float numerical types. See [Image data types and what they mean](data_types#data-types) for more information about these types and how `scikit-image` treats them. NumPy indexing -------------- NumPy indexing can be used both for looking at the pixel values and to modify them: ``` >>> # Get the value of the pixel at the 10th row and 20th column >>> camera[10, 20] 153 >>> # Set to black the pixel at the 3rd row and 10th column >>> camera[3, 10] = 0 ``` Be careful! In NumPy indexing, the first dimension (`camera.shape[0]`) corresponds to rows, while the second (`camera.shape[1]`) corresponds to columns, with the origin (`camera[0, 0]`) at the top-left corner. This matches matrix/linear algebra notation, but is in contrast to Cartesian (x, y) coordinates. See [Coordinate conventions](#coordinate-conventions) below for more details. Beyond individual pixels, it is possible to access/modify values of whole sets of pixels using the different indexing capabilities of NumPy. Slicing: ``` >>> # Set the first ten lines to "black" (0) >>> camera[:10] = 0 ``` Masking (indexing with masks of booleans): ``` >>> mask = camera < 87 >>> # Set to "white" (255) the pixels where mask is True >>> camera[mask] = 255 ``` Fancy indexing (indexing with sets of indices): ``` >>> inds_r = np.arange(len(camera)) >>> inds_c = 4 * inds_r % len(camera) >>> camera[inds_r, inds_c] = 0 ``` Masks are very useful when you need to select a set of pixels on which to perform the manipulations. The mask can be any boolean array of the same shape as the image (or a shape broadcastable to the image shape). This can be used to define a region of interest, for example, a disk: ``` >>> nrows, ncols = camera.shape >>> row, col = np.ogrid[:nrows, :ncols] >>> cnt_row, cnt_col = nrows / 2, ncols / 2 >>> outer_disk_mask = ((row - cnt_row)**2 + (col - cnt_col)**2 > ... (nrows / 2)**2) >>> camera[outer_disk_mask] = 0 ``` Boolean operations from NumPy can be used to define even more complex masks: ``` >>> lower_half = row > cnt_row >>> lower_half_disk = np.logical_and(lower_half, outer_disk_mask) >>> camera = data.camera() >>> camera[lower_half_disk] = 0 ``` Color images ------------ All of the above remains true for color images. A color image is a NumPy array with an additional trailing dimension for the channels: ``` >>> cat = data.chelsea() >>> type(cat) <type 'numpy.ndarray'> >>> cat.shape (300, 451, 3) ``` This shows that `cat` is a 300-by-451 pixel image with three channels (red, green, and blue). As before, we can get and set the pixel values: ``` >>> cat[10, 20] array([151, 129, 115], dtype=uint8) >>> # Set the pixel at (50th row, 60th column) to "black" >>> cat[50, 60] = 0 >>> # set the pixel at (50th row, 61st column) to "green" >>> cat[50, 61] = [0, 255, 0] # [red, green, blue] ``` We can also use 2D boolean masks for 2D multichannel images, as we did with the grayscale image above: Using a 2D mask on a 2D color image ``` >>> from skimage import data >>> cat = data.chelsea() >>> reddish = cat[:, :, 0] > 160 >>> cat[reddish] = [0, 255, 0] >>> plt.imshow(cat) ``` ([Source code](numpy_images-1.py), [png](numpy_images-1.png), [pdf](numpy_images-1.pdf)) Coordinate conventions ---------------------- Because `scikit-image` represents images using NumPy arrays, the coordinate conventions must match. Two-dimensional (2D) grayscale images (such as `camera` above) are indexed by rows and columns (abbreviated to either `(row, col)` or `(r, c)`), with the lowest element `(0, 0)` at the top-left corner. In various parts of the library, you will also see `rr` and `cc` refer to lists of row and column coordinates. We distinguish this convention from `(x, y)`, which commonly denote standard Cartesian coordinates, where `x` is the horizontal coordinate, `y` - the vertical one, and the origin is at the bottom left (Matplotlib axes, for example, use this convention). In the case of multichannel images, the last dimension is used for color channels and is denoted by `channel` or `ch`. Finally, for volumetric (3D) images, such as videos, magnetic resonance imaging (MRI) scans, confocal microscopy, etc. we refer to the leading dimension as `plane`, abbreviated as `pln` or `p`. These conventions are summarized below: Dimension name and order conventions in scikit-image| Image type | Coordinates | | --- | --- | | 2D grayscale | (row, col) | | 2D multichannel (eg. RGB) | (row, col, ch) | | 3D grayscale | (pln, row, col) | | 3D multichannel | (pln, row, col, ch) | Many functions in `scikit-image` can operate on 3D images directly: ``` >>> im3d = np.random.rand(100, 1000, 1000) >>> from skimage import morphology >>> from scipy import ndimage as ndi >>> seeds = ndi.label(im3d < 0.1)[0] >>> ws = morphology.watershed(im3d, seeds) ``` In many cases, however, the third spatial dimension has lower resolution than the other two. Some `scikit-image` functions provide a `spacing` keyword argument to help handle this kind of data: ``` >>> from skimage import segmentation >>> slics = segmentation.slic(im3d, spacing=[5, 1, 1], multichannel=False) ``` Other times, the processing must be done plane-wise. When planes are stacked along the leading dimension (in agreement with our convention), the following syntax can be used: ``` >>> from skimage import filters >>> edges = np.empty_like(im3d) >>> for pln, image in enumerate(im3d): ... # Iterate over the leading dimension ... edges[pln] = filters.sobel(image) ``` Notes on the order of array dimensions -------------------------------------- Although the labeling of the axes might seem arbitrary, it can have a significant effect on the speed of operations. This is because modern processors never retrieve just one item from memory, but rather a whole chunk of adjacent items (an operation called prefetching). Therefore, processing of elements that are next to each other in memory is faster than processing them when they are scattered, even if the number of operations is the same: ``` >>> def in_order_multiply(arr, scalar): ... for plane in list(range(arr.shape[0])): ... arr[plane, :, :] *= scalar ... >>> def out_of_order_multiply(arr, scalar): ... for plane in list(range(arr.shape[2])): ... arr[:, :, plane] *= scalar ... >>> import time >>> im3d = np.random.rand(100, 1024, 1024) >>> t0 = time.time(); x = in_order_multiply(im3d, 5); t1 = time.time() >>> print("%.2f seconds" % (t1 - t0)) 0.14 seconds >>> s0 = time.time(); x = out_of_order_multiply(im3d, 5); s1 = time.time() >>> print("%.2f seconds" % (s1 - s0)) 1.18 seconds >>> print("Speedup: %.1fx" % ((s1 - s0) / (t1 - t0))) Speedup: 8.6x ``` When the last/rightmost dimension becomes even larger the speedup is even more dramatic. It is worth thinking about *data locality* when developing algorithms. In particular, `scikit-image` uses C-contiguous arrays by default. When using nested loops, the last/rightmost dimension of the array should be in the innermost loop of the computation. In the example above, the `*=` numpy operator iterates over all remaining dimensions. A note on the time dimension ---------------------------- Although `scikit-image` does not currently provide functions to work specifically with time-varying 3D data, its compatibility with NumPy arrays allows us to work quite naturally with a 5D array of the shape (t, pln, row, col, ch): ``` >>> for timepoint in image5d: ... # Each timepoint is a 3D multichannel image ... do_something_with(timepoint) ``` We can then supplement the above table as follows: Addendum to dimension names and orders in scikit-image| Image type | coordinates | | --- | --- | | 2D color video | (t, row, col, ch) | | 3D multichannel video | (t, pln, row, col, ch) |
programming_docs
scikit_image Geometrical transformations of images Geometrical transformations of images ===================================== Cropping, resizing and rescaling images --------------------------------------- Images being NumPy arrays (as described in the [A crash course on NumPy for images](numpy_images#numpy) section), cropping an image can be done with simple slicing operations. Below we crop a 100x100 square corresponding to the top-left corner of the astronaut image. Note that this operation is done for all color channels (the color dimension is the last, third dimension): ``` >>> from skimage import data >>> img = data.astronaut() >>> top_left = img[:100, :100] ``` In order to change the shape of the image, [`skimage.color`](../api/skimage.color#module-skimage.color "skimage.color") provides several functions described in [Rescale, resize, and downscale](https://scikit-image.org/docs/0.18.x/auto_examples/transform/plot_rescale.html#sphx-glr-auto-examples-transform-plot-rescale-py) . ``` from skimage import data, color from skimage.transform import rescale, resize, downscale_local_mean image = color.rgb2gray(data.astronaut()) image_rescaled = rescale(image, 0.25, anti_aliasing=False) image_resized = resize(image, (image.shape[0] // 4, image.shape[1] // 4), anti_aliasing=True) image_downscaled = downscale_local_mean(image, (4, 3)) ``` Projective transforms (homographies) ------------------------------------ [Homographies](https://en.wikipedia.org/wiki/Homography) are transformations of a Euclidean space that preserve the alignment of points. Specific cases of homographies correspond to the conservation of more properties, such as parallelism (affine transformation), shape (similar transformation) or distances (Euclidean transformation). The different types of homographies available in scikit-image are presented in [Types of homographies](https://scikit-image.org/docs/0.18.x/auto_examples/transform/plot_transform_types.html#sphx-glr-auto-examples-transform-plot-transform-types-py). Projective transformations can either be created using the explicit parameters (e.g. scale, shear, rotation and translation): ``` from skimage import data from skimage import transform from skimage import img_as_float tform = transform.EuclideanTransform( rotation=np.pi / 12., translation = (100, -20) ) ``` or the full transformation matrix: ``` from skimage import data from skimage import transform from skimage import img_as_float matrix = np.array([[np.cos(np.pi/12), -np.sin(np.pi/12), 100], [np.sin(np.pi/12), np.cos(np.pi/12), -20], [0, 0, 1]]) tform = transform.EuclideanTransform(matrix) ``` The transformation matrix of a transform is available as its `tform.params` attribute. Transformations can be composed by multiplying matrices with the `@` matrix multiplication operator. Transformation matrices use [Homogeneous coordinates](https://en.wikipedia.org/wiki/Homogeneous_coordinates), which are the extension of Cartesian coordinates used in Euclidean geometry to the more general projective geometry. In particular, points at infinity can be represented with finite coordinates. Transformations can be applied to images using [`skimage.transform.warp()`](../api/skimage.transform#skimage.transform.warp "skimage.transform.warp"): ``` img = img_as_float(data.chelsea()) tf_img = transform.warp(img, tform.inverse) ``` The different transformations in [`skimage.transform`](../api/skimage.transform#module-skimage.transform "skimage.transform") have a `estimate` method in order to estimate the parameters of the transformation from two sets of points (the source and the destination), as explained in the [Using geometric transformations](https://scikit-image.org/docs/0.18.x/auto_examples/transform/plot_geometric.html#sphx-glr-auto-examples-transform-plot-geometric-py) tutorial: ``` text = data.text() src = np.array([[0, 0], [0, 50], [300, 50], [300, 0]]) dst = np.array([[155, 15], [65, 40], [260, 130], [360, 95]]) tform3 = transform.ProjectiveTransform() tform3.estimate(src, dst) warped = transform.warp(text, tform3, output_shape=(50, 300)) ``` The `estimate` method uses least-squares optimization to minimize the distance between source and optimization. Source and destination points can be determined manually, or using the different methods for feature detection available in [`skimage.feature`](../api/skimage.feature#module-skimage.feature "skimage.feature"), such as * [Corner detection](https://scikit-image.org/docs/0.18.x/auto_examples/features_detection/plot_corner.html#sphx-glr-auto-examples-features-detection-plot-corner-py), * [ORB feature detector and binary descriptor](https://scikit-image.org/docs/0.18.x/auto_examples/features_detection/plot_orb.html#sphx-glr-auto-examples-features-detection-plot-orb-py), * [BRIEF binary descriptor](https://scikit-image.org/docs/0.18.x/auto_examples/features_detection/plot_brief.html#sphx-glr-auto-examples-features-detection-plot-brief-py), * etc. and matching points using [`skimage.feature.match_descriptors()`](../api/skimage.feature#skimage.feature.match_descriptors "skimage.feature.match_descriptors") before estimating transformation parameters. However, spurious matches are often made, and it is advisable to use the RANSAC algorithm (instead of simple least-squares optimization) to improve the robustness to outliers, as explained in [Robust matching using RANSAC](https://scikit-image.org/docs/0.18.x/auto_examples/transform/plot_matching.html#sphx-glr-auto-examples-transform-plot-matching-py). Examples showing applications of transformation estimation are * stereo matching [Fundamental matrix estimation](https://scikit-image.org/docs/0.18.x/auto_examples/transform/plot_fundamental_matrix.html#sphx-glr-auto-examples-transform-plot-fundamental-matrix-py) and * image rectification [Using geometric transformations](https://scikit-image.org/docs/0.18.x/auto_examples/transform/plot_geometric.html#sphx-glr-auto-examples-transform-plot-geometric-py) The `estimate` method is point-based, that is, it uses only a set of points from the source and destination images. For estimating translations (shifts), it is also possible to use a *full-field* method using all pixels, based on Fourier-space cross-correlation. This method is implemented by `skimage.registration.register_translation()` and explained in the [Image Registration](https://scikit-image.org/docs/0.18.x/auto_examples/registration/plot_register_translation.html#sphx-glr-auto-examples-registration-plot-register-translation-py) tutorial. The [Using Polar and Log-Polar Transformations for Registration](https://scikit-image.org/docs/0.18.x/auto_examples/registration/plot_register_rotation.html#sphx-glr-auto-examples-registration-plot-register-rotation-py) tutorial explains a variant of this full-field method for estimating a rotation, by using first a log-polar transformation. scikit_image How to parallelize loops How to parallelize loops ======================== In image processing, we frequently apply the same algorithm on a large batch of images. In this paragraph, we propose to use [joblib](https://joblib.readthedocs.io) to parallelize loops. Here is an example of such repetitive tasks: ``` from skimage import data, color, util from skimage.restoration import denoise_tv_chambolle from skimage.feature import hog def task(image): """ Apply some functions and return an image. """ image = denoise_tv_chambolle(image[0][0], weight=0.1, multichannel=True) fd, hog_image = hog(color.rgb2gray(image), orientations=8, pixels_per_cell=(16, 16), cells_per_block=(1, 1), visualize=True) return hog_image # Prepare images hubble = data.hubble_deep_field() width = 10 pics = util.view_as_windows(hubble, (width, hubble.shape[1], hubble.shape[2]), step=width) ``` To call the function `task` on each element of the list `pics`, it is usual to write a for loop. To measure the execution time of this loop, you can use ipython and measure the execution time with `%timeit`. ``` def classic_loop(): for image in pics: task(image) %timeit classic_loop() ``` Another equivalent way to code this loop is to use a comprehension list which has the same efficiency. ``` def comprehension_loop(): [task(image) for image in pics] %timeit comprehension_loop() ``` `joblib` is a library providing an easy way to parallelize for loops once we have a comprehension list. The number of jobs can be specified. ``` from joblib import Parallel, delayed def joblib_loop(): Parallel(n_jobs=4)(delayed(task)(i) for i in pics) %timeit joblib_loop() ``` scikit_image Image Segmentation Image Segmentation ================== Image segmentation is the task of labeling the pixels of objects of interest in an image. In this tutorial, we will see how to segment objects from a background. We use the `coins` image from `skimage.data`. This image shows several coins outlined against a darker background. The segmentation of the coins cannot be done directly from the histogram of grey values, because the background shares enough grey levels with the coins that a thresholding segmentation is not sufficient. ``` >>> from skimage import data >>> from skimage.exposure import histogram >>> coins = data.coins() >>> hist, hist_centers = histogram(coins) ``` Simply thresholding the image leads either to missing significant parts of the coins, or to merging parts of the background with the coins. This is due to the inhomogeneous lighting of the image. A first idea is to take advantage of the local contrast, that is, to use the gradients rather than the grey values. Edge-based segmentation ----------------------- Let us first try to detect edges that enclose the coins. For edge detection, we use the [Canny detector](https://en.wikipedia.org/wiki/Canny_edge_detector) of `skimage.feature.canny` ``` >>> from skimage.feature import canny >>> edges = canny(coins/255.) ``` As the background is very smooth, almost all edges are found at the boundary of the coins, or inside the coins. ``` >>> from scipy import ndimage as ndi >>> fill_coins = ndi.binary_fill_holes(edges) ``` Now that we have contours that delineate the outer boundary of the coins, we fill the inner part of the coins using the `ndi.binary_fill_holes` function, which uses mathematical morphology to fill the holes. Most coins are well segmented out of the background. Small objects from the background can be easily removed using the `ndi.label` function to remove objects smaller than a small threshold. ``` >>> label_objects, nb_labels = ndi.label(fill_coins) >>> sizes = np.bincount(label_objects.ravel()) >>> mask_sizes = sizes > 20 >>> mask_sizes[0] = 0 >>> coins_cleaned = mask_sizes[label_objects] ``` However, the segmentation is not very satisfying, since one of the coins has not been segmented correctly at all. The reason is that the contour that we got from the Canny detector was not completely closed, therefore the filling function did not fill the inner part of the coin. Therefore, this segmentation method is not very robust: if we miss a single pixel of the contour of the object, we will not be able to fill it. Of course, we could try to dilate the contours in order to close them. However, it is preferable to try a more robust method. Region-based segmentation ------------------------- Let us first determine markers of the coins and the background. These markers are pixels that we can label unambiguously as either object or background. Here, the markers are found at the two extreme parts of the histogram of grey values: ``` >>> markers = np.zeros_like(coins) >>> markers[coins < 30] = 1 >>> markers[coins > 150] = 2 ``` We will use these markers in a watershed segmentation. The name watershed comes from an analogy with hydrology. The [watershed transform](https://en.wikipedia.org/wiki/Watershed_%28image_processing%29) floods an image of elevation starting from markers, in order to determine the catchment basins of these markers. Watershed lines separate these catchment basins, and correspond to the desired segmentation. The choice of the elevation map is critical for good segmentation. Here, the amplitude of the gradient provides a good elevation map. We use the Sobel operator for computing the amplitude of the gradient: ``` >>> from skimage.filters import sobel >>> elevation_map = sobel(coins) ``` From the 3-D surface plot shown below, we see that high barriers effectively separate the coins from the background. and here is the corresponding 2-D plot: The next step is to find markers of the background and the coins based on the extreme parts of the histogram of grey values: ``` >>> markers = np.zeros_like(coins) >>> markers[coins < 30] = 1 >>> markers[coins > 150] = 2 ``` Let us now compute the watershed transform: ``` >>> from skimage.segmentation import watershed >>> segmentation = watershed(elevation_map, markers) ``` With this method, the result is satisfying for all coins. Even if the markers for the background were not well distributed, the barriers in the elevation map were high enough for these markers to flood the entire background. We remove a few small holes with mathematical morphology: ``` >>> segmentation = ndi.binary_fill_holes(segmentation - 1) ``` We can now label all the coins one by one using `ndi.label`: ``` >>> labeled_coins, _ = ndi.label(segmentation) ``` scikit_image Handling Video Files Handling Video Files ==================== Sometimes it is necessary to read a sequence of images from a standard video file, such as .avi and .mov files. In a scientific context, it is usually better to avoid these formats in favor of a simple directory of images or a multi-dimensional TIF. Video formats are more difficult to read piecemeal, typically do not support random frame access or research-minded meta data, and use lossy compression if not carefully configured. But video files are in widespread use, and they are easy to share, so it is convenient to be equipped to read and write them when necessary. Tools for reading video files vary in their ease of installation and use, their disk and memory usage, and their cross-platform compatibility. This is a practical guide. A Workaround: Convert the Video to an Image Sequence ---------------------------------------------------- For a one-off solution, the simplest, surest route is to convert the video to a collection of sequentially-numbered image files, often called an image sequence. Then the images files can be read into an `ImageCollection` by [`skimage.io.imread_collection`](../api/skimage.io#skimage.io.imread_collection "skimage.io.imread_collection"). Converting the video to frames can be done easily in [ImageJ](https://imagej.nih.gov/ij/), a cross-platform, GUI-based program from the bio-imaging community, or [FFmpeg](https://www.ffmpeg.org/), a powerful command-line utility for manipulating video files. In FFmpeg, the following command generates an image file from each frame in a video. The files are numbered with five digits, padded on the left with zeros. ``` ffmpeg -i "video.mov" -f image2 "video-frame%05d.png" ``` More information is available in an [FFmpeg tutorial on image sequences](https://en.wikibooks.org/wiki/FFMPEG_An_Intermediate_Guide/image_sequence#Making_an_Image_Sequence_from_a_video). Generating an image sequence has disadvantages: they can be large and unwieldy, and generating them can take some time. It is generally preferable to work directly with the original video file. For a more direct solution, we need to execute FFmpeg or LibAV from Python to read frames from the video. FFmpeg and LibAV are two large open-source projects that decode video from the sprawling variety of formats used in the wild. There are several ways to use them from Python. Each, unfortunately, has some disadvantages. PyAV ---- [PyAV](http://docs.mikeboers.com/pyav/develop/) uses FFmpeg’s (or LibAV’s) libraries to read image data directly from the video file. It invokes them using Cython bindings, so it is very fast. ``` import av v = av.open('path/to/video.mov') ``` PyAV’s API reflects the way frames are stored in a video file. ``` for packet in container.demux(): for frame in packet.decode(): if frame.type == 'video': img = frame.to_image() # PIL/Pillow image arr = np.asarray(img) # numpy array # Do something! ``` Adding Random Access to PyAV ---------------------------- The `Video` class in [PIMS](https://github.com/soft-matter/pims) invokes PyAV and adds additional functionality to solve a common problem in scientific applications, accessing a video by frame number. Video file formats are designed to be searched in an approximate way, by time, and they do not support an efficient means of seeking a specific frame number. PIMS adds this missing functionality by decoding (but not reading) the entire video at and producing an internal table of contents that supports indexing by frame. ``` import pims v = pims.Video('path/to/video.mov') v[-1] # a 2D numpy array representing the last frame ``` MoviePy ------- [Moviepy](https://zulko.github.io/moviepy) invokes FFmpeg through a subprocess, pipes the decoded video from FFmpeg into RAM, and reads it out. This approach is straightforward, but it can be brittle, and it’s not workable for large videos that exceed available RAM. It works on all platforms if FFmpeg is installed. Since it does not link to FFmpeg’s underlying libraries, it is easier to install but about [half as fast](https://gist.github.com/mikeboers/6843684). ``` from moviepy.editor import VideoFileClip myclip = VideoFileClip("some_video.avi") ``` Imageio ------- [Imageio](http://imageio.github.io/) takes the same approach as MoviePy. It supports a wide range of other image file formats as well. ``` import imageio filename = '/tmp/file.mp4' vid = imageio.get_reader(filename, 'ffmpeg') for num, image in vid.iter_data(): print(image.mean()) metadata = vid.get_meta_data() ``` OpenCV ------ Finally, another solution is the [VideoReader](https://docs.opencv.org/2.4/modules/highgui/doc/reading_and_writing_images_and_video.html#videocapture-open) class in OpenCV, which has bindings to FFmpeg. If you need OpenCV for other reasons, then this may be the best approach. scikit_image Getting started Getting started =============== `scikit-image` is an image processing Python package that works with [`numpy`](https://numpy.org/doc/stable/reference/index.html#module-numpy "(in NumPy v1.19)") arrays. The package is imported as `skimage`: ``` >>> import skimage ``` Most functions of `skimage` are found within submodules: ``` >>> from skimage import data >>> camera = data.camera() ``` A list of submodules and functions is found on the [API reference](https://scikit-image.org/docs/stable/api/api.html) webpage. Within scikit-image, images are represented as NumPy arrays, for example 2-D arrays for grayscale 2-D images ``` >>> type(camera) <type 'numpy.ndarray'> >>> # An image with 512 rows and 512 columns >>> camera.shape (512, 512) ``` The [`skimage.data`](../api/skimage.data#module-skimage.data "skimage.data") submodule provides a set of functions returning example images, that can be used to get started quickly on using scikit-image’s functions: ``` >>> coins = data.coins() >>> from skimage import filters >>> threshold_value = filters.threshold_otsu(coins) >>> threshold_value 107 ``` Of course, it is also possible to load your own images as NumPy arrays from image files, using [`skimage.io.imread()`](../api/skimage.io#skimage.io.imread "skimage.io.imread"): ``` >>> import os >>> filename = os.path.join(skimage.data_dir, 'moon.png') >>> from skimage import io >>> moon = io.imread(filename) ``` Use [natsort](https://pypi.org/project/natsort/) to load multiple images ``` >>> import os >>> from natsort import natsorted, ns >>> from skimage import io >>> list_files = os.listdir('.') >>> list_files ['01.png', '010.png', '0101.png', '0190.png', '02.png'] >>> list_files = natsorted(list_files) >>> list_files ['01.png', '02.png', '010.png', '0101.png', '0190.png'] >>> image_list = [] >>> for filename in list_files: ... image_list.append(io.imread(filename)) ```
programming_docs
scikit_image Getting help on using skimage Getting help on using skimage ============================= Besides the user guide, there exist other opportunities to get help on using `skimage`. Examples gallery ---------------- The [General examples](https://scikit-image.org/docs/0.18.x/auto_examples/index.html#examples-gallery) gallery provides graphical examples of typical image processing tasks. By a quick glance at the different thumbnails, the user may find an example close to a typical use case of interest. Each graphical example page displays an introductory paragraph, a figure, and the source code that generated the figure. Downloading the Python source code enables one to modify quickly the example into a case closer to one’s image processing applications. Users are warmly encouraged to report on their use of `skimage` on the [Mailing-list](#mailing-list), in order to propose more examples in the future. Contributing examples to the gallery can be done on github (see [How to contribute to scikit-image](https://scikit-image.org/docs/0.18.x/contribute.html)). Search field ------------ The `quick search` field located in the navigation bar of the html documentation can be used to search for specific keywords (segmentation, rescaling, denoising, etc.). API Discovery ------------- NumPy provides a `lookfor` function to search API functions. By default `lookfor` will search the NumPy API. NumPy lookfor example: ``np.lookfor('eigenvector') `` But it can be used to search in modules, by passing in the module name as a string: `` np.lookfor('boundaries', 'skimage') `` or the module itself. `` > import skimage > np.lookfor('boundaries', skimage) `` Docstrings ---------- Docstrings of `skimage` functions are formatted using [Numpy’s documentation standard](https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt), starting with a `Parameters` section for the arguments and a `Returns` section for the objects returned by the function. Also, most functions include one or more examples. Mailing-list ------------ The scikit-image mailing-list is [[email protected]](mailto:scikit-image%40python.org) (users should [join](https://mail.python.org/mailman3/lists/scikit-image.python.org/) before posting). This mailing-list is shared by users and developers, and it is the right place to ask any question about `skimage`, or in general, image processing using Python. Posting snippets of code with minimal examples ensures to get more relevant and focused answers. We would love to hear from how you use `skimage` for your work on the mailing-list! scikit_image Image adjustment: transforming image content Image adjustment: transforming image content ============================================ Color manipulation ------------------ Most functions for manipulating color channels are found in the submodule [`skimage.color`](../api/skimage.color#module-skimage.color "skimage.color"). ### Conversion between color models Color images can be represented using different [color spaces](https://en.wikipedia.org/wiki/Color_space). One of the most common color spaces is the [RGB space](https://en.wikipedia.org/wiki/RGB_color_model), where an image has red, green and blue channels. However, other color models are widely used, such as the [HSV color model](https://en.wikipedia.org/wiki/HSL_and_HSV), where hue, saturation and value are independent channels, or the [CMYK model](https://en.wikipedia.org/wiki/CMYK_color_model) used for printing. [`skimage.color`](../api/skimage.color#module-skimage.color "skimage.color") provides utility functions to convert images to and from different color spaces. Integer-type arrays can be transformed to floating-point type by the conversion operation: ``` >>> # bright saturated red >>> red_pixel_rgb = np.array([[[255, 0, 0]]], dtype=np.uint8) >>> color.rgb2hsv(red_pixel_rgb) array([[[ 0., 1., 1.]]]) >>> #Β darker saturated blue >>> dark_blue_pixel_rgb = np.array([[[0, 0, 100]]], dtype=np.uint8) >>> color.rgb2hsv(dark_blue_pixel_rgb) array([[[ 0.66666667, 1. , 0.39215686]]]) >>> # less saturated pink >>> pink_pixel_rgb = np.array([[[255, 100, 255]]], dtype=np.uint8) >>> color.rgb2hsv(pink_pixel_rgb) array([[[ 0.83333333, 0.60784314, 1. ]]]) ``` ### Conversion from RGBA to RGB - Removing alpha channel through alpha blending Converting an RGBA image to an RGB image by alpha blending it with a background is realized with [`rgba2rgb()`](../api/skimage.color#skimage.color.rgba2rgb "skimage.color.rgba2rgb") ``` >>> from skimage.color import rgba2rgb >>> from skimage import data >>> img_rgba = data.logo() >>> img_rgb = rgba2rgb(img_rgba) ``` ### Conversion between color and gray values Converting an RGB image to a grayscale image is realized with [`rgb2gray()`](../api/skimage.color#skimage.color.rgb2gray "skimage.color.rgb2gray") ``` >>> from skimage.color import rgb2gray >>> from skimage import data >>> img = data.astronaut() >>> img_gray = rgb2gray(img) ``` [`rgb2gray()`](../api/skimage.color#skimage.color.rgb2gray "skimage.color.rgb2gray") uses a non-uniform weighting of color channels, because of the different sensitivity of the human eye to different colors. Therefore, such a weighting ensures [luminance preservation](https://en.wikipedia.org/wiki/Grayscale#Converting_color_to_grayscale) from RGB to grayscale: ``` >>> red_pixel = np.array([[[255, 0, 0]]], dtype=np.uint8) >>> color.rgb2gray(red_pixel) array([[ 0.2125]]) >>> green_pixel = np.array([[[0, 255, 0]]], dtype=np.uint8) >>> color.rgb2gray(green_pixel) array([[ 0.7154]]) ``` Converting a grayscale image to RGB with [`gray2rgb()`](../api/skimage.color#skimage.color.gray2rgb "skimage.color.gray2rgb") simply duplicates the gray values over the three color channels. ### Image inversion An inverted image is also called complementary image. For binary images, True values become False and conversely. For grayscale images, pixel values are replaced by the difference of the maximum value of the data type and the actual value. For RGB images, the same operation is done for each channel. This operation can be achieved with [`skimage.util.invert()`](../api/skimage.util#skimage.util.invert "skimage.util.invert"): ``` >>> from skimage import util >>> img = data.camera() >>> inverted_img = util.invert(img) ``` ### Painting images with labels [`label2rgb()`](../api/skimage.color#skimage.color.label2rgb "skimage.color.label2rgb") can be used to superimpose colors on a grayscale image using an array of labels to encode the regions to be represented with the same color. Examples: * [Tinting gray-scale images](https://scikit-image.org/docs/0.18.x/auto_examples/color_exposure/plot_tinting_grayscale_images.html#sphx-glr-auto-examples-color-exposure-plot-tinting-grayscale-images-py) * [Find the intersection of two segmentations](https://scikit-image.org/docs/0.18.x/auto_examples/segmentation/plot_join_segmentations.html#sphx-glr-auto-examples-segmentation-plot-join-segmentations-py) * [RAG Thresholding](https://scikit-image.org/docs/0.18.x/auto_examples/segmentation/plot_rag_mean_color.html#sphx-glr-auto-examples-segmentation-plot-rag-mean-color-py) Contrast and exposure --------------------- Image pixels can take values determined by the `dtype` of the image (see [Image data types and what they mean](data_types#data-types)), such as 0 to 255 for `uint8` images or `[0, 1]` for floating-point images. However, most images either have a narrower range of values (because of poor contrast), or have most pixel values concentrated in a subrange of the accessible values. [`skimage.exposure`](../api/skimage.exposure#module-skimage.exposure "skimage.exposure") provides functions that spread the intensity values over a larger range. A first class of methods compute a nonlinear function of the intensity, that is independent of the pixel values of a specific image. Such methods are often used for correcting a known non-linearity of sensors, or receptors such as the human eye. A well-known example is [Gamma correction](https://en.wikipedia.org/wiki/Gamma_correction), implemented in [`adjust_gamma()`](../api/skimage.exposure#skimage.exposure.adjust_gamma "skimage.exposure.adjust_gamma"). Other methods re-distribute pixel values according to the *histogram* of the image. The histogram of pixel values is computed with [`skimage.exposure.histogram()`](../api/skimage.exposure#skimage.exposure.histogram "skimage.exposure.histogram"): ``` >>> image = np.array([[1, 3], [1, 1]]) >>> exposure.histogram(image) (array([3, 0, 1]), array([1, 2, 3])) ``` [`histogram()`](../api/skimage.exposure#skimage.exposure.histogram "skimage.exposure.histogram") returns the number of pixels for each value bin, and the centers of the bins. The behavior of [`histogram()`](../api/skimage.exposure#skimage.exposure.histogram "skimage.exposure.histogram") is therefore slightly different from the one of [`numpy.histogram()`](https://numpy.org/doc/stable/reference/generated/numpy.histogram.html#numpy.histogram "(in NumPy v1.19)"), which returns the boundaries of the bins. The simplest contrast enhancement [`rescale_intensity()`](../api/skimage.exposure#skimage.exposure.rescale_intensity "skimage.exposure.rescale_intensity") consists in stretching pixel values to the whole allowed range, using a linear transformation: ``` >>> from skimage import exposure >>> text = data.text() >>> text.min(), text.max() (10, 197) >>> better_contrast = exposure.rescale_intensity(text) >>> better_contrast.min(), better_contrast.max() (0, 255) ``` Even if an image uses the whole value range, sometimes there is very little weight at the ends of the value range. In such a case, clipping pixel values using percentiles of the image improves the contrast (at the expense of some loss of information, because some pixels are saturated by this operation): ``` >>> moon = data.moon() >>> v_min, v_max = np.percentile(moon, (0.2, 99.8)) >>> v_min, v_max (10.0, 186.0) >>> better_contrast = exposure.rescale_intensity( ... moon, in_range=(v_min, v_max)) ``` The function [`equalize_hist()`](../api/skimage.exposure#skimage.exposure.equalize_hist "skimage.exposure.equalize_hist") maps the cumulative distribution function (cdf) of pixel values onto a linear cdf, ensuring that all parts of the value range are equally represented in the image. As a result, details are enhanced in large regions with poor contrast. As a further refinement, histogram equalization can be performed in subregions of the image with [`equalize_adapthist()`](../api/skimage.exposure#skimage.exposure.equalize_adapthist "skimage.exposure.equalize_adapthist"), in order to correct for exposure gradients across the image. See the example [Histogram Equalization](https://scikit-image.org/docs/0.18.x/auto_examples/color_exposure/plot_equalize.html#sphx-glr-auto-examples-color-exposure-plot-equalize-py). Examples: * [Histogram Equalization](https://scikit-image.org/docs/0.18.x/auto_examples/color_exposure/plot_equalize.html#sphx-glr-auto-examples-color-exposure-plot-equalize-py) scikit_image Image data types and what they mean Image data types and what they mean =================================== In `skimage`, images are simply [numpy](https://docs.scipy.org/doc/numpy/user/) arrays, which support a variety of data types [1](#id2), *i.e.* β€œdtypes”. To avoid distorting image intensities (see [Rescaling intensity values](#rescaling-intensity-values)), we assume that images use the following dtype ranges: | Data type | Range | | --- | --- | | uint8 | 0 to 255 | | uint16 | 0 to 65535 | | uint32 | 0 to 232 - 1 | | float | -1 to 1 or 0 to 1 | | int8 | -128 to 127 | | int16 | -32768 to 32767 | | int32 | -231 to 231 - 1 | Note that float images should be restricted to the range -1 to 1 even though the data type itself can exceed this range; all integer dtypes, on the other hand, have pixel intensities that can span the entire data type range. With a few exceptions, *64-bit (u)int images are not supported*. Functions in `skimage` are designed so that they accept any of these dtypes, but, for efficiency, *may return an image of a different dtype* (see [Output types](#output-types)). If you need a particular dtype, `skimage` provides utility functions that convert dtypes and properly rescale image intensities (see [Input types](#input-types)). You should **never use** `astype` on an image, because it violates these assumptions about the dtype range: ``` >>> from skimage.util import img_as_float >>> image = np.arange(0, 50, 10, dtype=np.uint8) >>> print(image.astype(float)) # These float values are out of range. [ 0. 10. 20. 30. 40.] >>> print(img_as_float(image)) [ 0. 0.03921569 0.07843137 0.11764706 0.15686275] ``` Input types ----------- Although we aim to preserve the data range and type of input images, functions may support only a subset of these data-types. In such a case, the input will be converted to the required type (if possible), and a warning message printed to the log if a memory copy is needed. Type requirements should be noted in the docstrings. The following utility functions in the main package are available to developers and users: | Function name | Description | | --- | --- | | img\_as\_float | Convert to 64-bit floating point. | | img\_as\_ubyte | Convert to 8-bit uint. | | img\_as\_uint | Convert to 16-bit uint. | | img\_as\_int | Convert to 16-bit int. | These functions convert images to the desired dtype and *properly rescale their values*: ``` >>> from skimage.util import img_as_ubyte >>> image = np.array([0, 0.5, 1], dtype=float) >>> img_as_ubyte(image) array([ 0, 128, 255], dtype=uint8) ``` Be careful! These conversions can result in a loss of precision, since 8 bits cannot hold the same amount of information as 64 bits: ``` >>> image = np.array([0, 0.5, 0.503, 1], dtype=float) >>> image_as_ubyte(image) array([ 0, 128, 128, 255], dtype=uint8) ``` Additionally, some functions take a `preserve_range` argument where a range conversion is convenient but not necessary. For example, interpolation in `transform.warp` requires an image of type float, which should have a range in [0, 1]. So, by default, input images will be rescaled to this range. However, in some cases, the image values represent physical measurements, such as temperature or rainfall values, that the user does not want rescaled. With `preserve_range=True`, the original range of the data will be preserved, even though the output is a float image. Users must then ensure this non-standard image is properly processed by downstream functions, which may expect an image in [0, 1]. ``` >>> from skimage import data >>> from skimage.transform import rescale >>> image = data.coins() >>> image.dtype, image.min(), image.max(), image.shape (dtype('uint8'), 1, 252, (303, 384)) >>> rescaled = rescale(image, 0.5) >>> (rescaled.dtype, np.round(rescaled.min(), 4), ... np.round(rescaled.max(), 4), rescaled.shape) (dtype('float64'), 0.0147, 0.9456, (152, 192)) >>> rescaled = rescale(image, 0.5, preserve_range=True) >>> (rescaled.dtype, np.round(rescaled.min()), ... np.round(rescaled.max()), rescaled.shape (dtype('float64'), 4.0, 241.0, (152, 192)) ``` Output types ------------ The output type of a function is determined by the function author and is documented for the benefit of the user. While this requires the user to explicitly convert the output to whichever format is needed, it ensures that no unnecessary data copies take place. A user that requires a specific type of output (e.g., for display purposes), may write: ``` >>> from skimage.util import img_as_uint >>> out = img_as_uint(sobel(image)) >>> plt.imshow(out) ``` Working with OpenCV ------------------- It is possible that you may need to use an image created using `skimage` with [OpenCV](https://opencv.org/) or vice versa. OpenCV image data can be accessed (without copying) in NumPy (and, thus, in scikit-image). OpenCV uses BGR (instead of scikit-image’s RGB) for color images, and its dtype is uint8 by default (See [Image data types and what they mean](#image-data-types-and-what-they-mean)). BGR stands for Blue Green Red. ### Converting BGR to RGB or vice versa The color images in `skimage` and OpenCV have 3 dimensions: width, height and color. RGB and BGR use the same color space, except the order of colors is reversed. Note that in `scikit-image` we usually refer to `rows` and `columns` instead of width and height (see [Coordinate conventions](numpy_images#numpy-images-coordinate-conventions)). The following instruction effectively reverses the order of the colors, leaving the rows and columns unaffected. ``` >>> image = image[:, :, ::-1] ``` ### Using an image from OpenCV with `skimage` If cv\_image is an array of unsigned bytes, `skimage` will understand it by default. If you prefer working with floating point images, `img_as_float()` can be used to convert the image: ``` >>> from skimage.util import img_as_float >>> image = img_as_float(any_opencv_image) ``` ### Using an image from `skimage` with OpenCV The reverse can be achieved with `img_as_ubyte()`: ``` >>> from skimage.util import img_as_ubyte >>> cv_image = img_as_ubyte(any_skimage_image) ``` Image processing pipeline ------------------------- This dtype behavior allows you to string together any `skimage` function without worrying about the image dtype. On the other hand, if you want to use a custom function that requires a particular dtype, you should call one of the dtype conversion functions (here, `func1` and `func2` are `skimage` functions): ``` >>> from skimage.util import img_as_float >>> image = img_as_float(func1(func2(image))) >>> processed_image = custom_func(image) ``` Better yet, you can convert the image internally and use a simplified processing pipeline: ``` >>> def custom_func(image): ... image = img_as_float(image) ... # do something ... >>> processed_image = custom_func(func1(func2(image))) ``` Rescaling intensity values -------------------------- When possible, functions should avoid blindly stretching image intensities (e.g. rescaling a float image so that the min and max intensities are 0 and 1), since this can heavily distort an image. For example, if you’re looking for bright markers in dark images, there may be an image where no markers are present; stretching its input intensity to span the full range would make background noise look like markers. Sometimes, however, you have images that should span the entire intensity range but do not. For example, some cameras store images with 10-, 12-, or 14-bit depth per pixel. If these images are stored in an array with dtype uint16, then the image won’t extend over the full intensity range, and thus, would appear dimmer than it should. To correct for this, you can use the `rescale_intensity` function to rescale the image so that it uses the full dtype range: ``` >>> from skimage import exposure >>> image = exposure.rescale_intensity(img10bit, in_range=(0, 2**10 - 1)) ``` Here, the `in_range` argument is set to the maximum range for a 10-bit image. By default, `rescale_intensity` stretches the values of `in_range` to match the range of the dtype. `rescale_intensity` also accepts strings as inputs to `in_range` and `out_range`, so the example above could also be written as: ``` >>> image = exposure.rescale_intensity(img10bit, in_range='uint10') ``` Note about negative values -------------------------- People very often represent images in signed dtypes, even though they only manipulate the positive values of the image (e.g., using only 0-127 in an int8 image). For this reason, conversion functions *only spread the positive values* of a signed dtype over the entire range of an unsigned dtype. In other words, negative values are clipped to 0 when converting from signed to unsigned dtypes. (Negative values are preserved when converting between signed dtypes.) To prevent this clipping behavior, you should rescale your image beforehand: ``` >>> image = exposure.rescale_intensity(img_int32, out_range=(0, 2**31 - 1)) >>> img_uint8 = img_as_ubyte(image) ``` This behavior is symmetric: The values in an unsigned dtype are spread over just the positive range of a signed dtype. References ---------- `1` <https://docs.scipy.org/doc/numpy/user/basics.types.html>
programming_docs
scikit_image Image Viewer Image Viewer ============ Warning The scikit-image viewer is deprecated since 0.18 and will be removed in 0.20. Please, refer to the [visualization](https://scikit-image.org/docs/stable/user_guide/visualization.html) software page for alternatives. Quick Start ----------- `skimage.viewer` provides a [matplotlib](https://matplotlib.org/)-based canvas for displaying images and a Qt-based GUI-toolkit, with the goal of making it easy to create interactive image editors. You can simply use it to display an image: ``` from skimage import data from skimage.viewer import ImageViewer image = data.coins() viewer = ImageViewer(image) viewer.show() ``` Of course, you could just as easily use `imshow` from [matplotlib](https://matplotlib.org/) (or alternatively, `skimage.io.imshow` which adds support for multiple io-plugins) to display images. The advantage of `ImageViewer` is that you can easily add plugins for manipulating images. Currently, only a few plugins are implemented, but it is easy to write your own. Before going into the details, let’s see an example of how a pre-defined plugin is added to the viewer: ``` from skimage.viewer.plugins.lineprofile import LineProfile viewer = ImageViewer(image) viewer += LineProfile(viewer) overlay, data = viewer.show()[0] ``` The viewer’s `show()` method returns a list of tuples, one for each attached plugin. Each tuple contains two elements: an overlay of the same shape as the input image, and a data field (which may be `None`). A plugin class documents its return value in its `output` method. In this example, only one plugin is attached, so the list returned by `show` will have length 1. We extract the single tuple and bind its `overlay` and `data` elements to individual variables. Here, `overlay` contains an image of the line drawn on the viewer, and `data` contains the 1-dimensional intensity profile along that line. At the moment, there are not many plugins pre-defined, but there is a really simple interface for creating your own plugin. First, let us create a plugin to call the total-variation denoising function, `denoise_tv_bregman`: ``` from skimage.filters import denoise_tv_bregman from skimage.viewer.plugins.base import Plugin denoise_plugin = Plugin(image_filter=denoise_tv_bregman) ``` Note The `Plugin` assumes the first argument given to the image filter is the image from the image viewer. In the future, this should be changed so you can pass the image to a different argument of the filter function. To actually interact with the filter, you have to add widgets that adjust the parameters of the function. Typically, that means adding a slider widget and connecting it to the filter parameter and the minimum and maximum values of the slider: ``` from skimage.viewer.widgets import Slider from skimage.viewer.widgets.history import SaveButtons denoise_plugin += Slider('weight', 0.01, 0.5, update_on='release') denoise_plugin += SaveButtons() ``` Here, we connect a slider widget to the filter’s β€˜weight’ argument. We also added some buttons for saving the image to file or to the `scikit-image` image stack (see `skimage.io.push` and `skimage.io.pop`). All that’s left is to create an image viewer and add the plugin to that viewer. ``` viewer = ImageViewer(image) viewer += denoise_plugin denoised = viewer.show()[0][0] ``` Here, we access only the overlay returned by the plugin, which contains the filtered image for the last used setting of `weight`. scikit_image Data visualization Data visualization ================== Data visualization takes an important place in image processing. Data can be a simple unique 2D image or a more complex with multidimensional aspects: 3D in space, timeslapse, multiple channels. Therefore, the visualization strategy will depend on the data complexity and a range of tools external to scikit-image can be used for this purpose. Historically, scikit-image provided viewer tools but powerful packages are now available and must be preferred. Matplotlib ---------- [Matplotlib](https://matplotlib.org/) is a library able to generate static plots, which includes image visualization. Plotly ------ [Plotly](https://dash.plotly.com/) is a plotting library relying on web technologies with interaction capabilities. Mayavi ------ [Mayavi](https://docs.enthought.com/mayavi/mayavi/) can be used to visualize 3D images. Napari ------ [Napari](https://napari.org/) is a multi-dimensional image viewer. It’s designed for browsing, annotating, and analyzing large multi-dimensional images. scikit_image Tutorials Tutorials ========= * [Image Segmentation](tutorial_segmentation) * [How to parallelize loops](tutorial_parallelization) scikit_image Module: viewer Module: viewer ============== | | | | --- | --- | | [`skimage.viewer.CollectionViewer`](#skimage.viewer.CollectionViewer "skimage.viewer.CollectionViewer")(image\_collection) | Viewer for displaying image collections. | | [`skimage.viewer.ImageViewer`](#skimage.viewer.ImageViewer "skimage.viewer.ImageViewer")(image[, useblit]) | Viewer for displaying images. | | [`skimage.viewer.canvastools`](skimage.viewer.canvastools#module-skimage.viewer.canvastools "skimage.viewer.canvastools") | | | [`skimage.viewer.plugins`](skimage.viewer.plugins#module-skimage.viewer.plugins "skimage.viewer.plugins") | | | `skimage.viewer.qt` | | | [`skimage.viewer.utils`](skimage.viewer.utils#module-skimage.viewer.utils "skimage.viewer.utils") | | | [`skimage.viewer.viewers`](skimage.viewer.viewers#module-skimage.viewer.viewers "skimage.viewer.viewers") | | | [`skimage.viewer.widgets`](skimage.viewer.widgets#module-skimage.viewer.widgets "skimage.viewer.widgets") | Widgets for interacting with ImageViewer. | CollectionViewer ---------------- `class skimage.viewer.CollectionViewer(image_collection, update_on='move', **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L331-L407) Bases: `skimage.viewer.viewers.core.ImageViewer` Viewer for displaying image collections. Select the displayed frame of the image collection using the slider or with the following keyboard shortcuts: left/right arrows Previous/next image in collection. number keys, 0–9 0% to 90% of collection. For example, β€œ5” goes to the image in the middle (i.e. 50%) of the collection. home/end keys First/last image in collection. Parameters `image_collectionlist of images` List of images to be displayed. `update_on{β€˜move’ | β€˜release’}` Control whether image is updated on slide or release of the image slider. Using β€˜on\_release’ will give smoother behavior when displaying large images or when writing a plugin/subclass that requires heavy computation. `__init__(image_collection, update_on='move', **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L356-L379) Initialize self. See help(type(self)) for accurate signature. `keyPressEvent(event)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L396-L407) `update_index(name, index)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L381-L394) Select image on display using index into image collection. ImageViewer ----------- `class skimage.viewer.ImageViewer(image, useblit=True)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L49-L328) Bases: [`object`](https://docs.python.org/3.9/library/functions.html#object "(in Python v3.9)") Viewer for displaying images. This viewer is a simple container object that holds a Matplotlib axes for showing images. [`ImageViewer`](#skimage.viewer.ImageViewer "skimage.viewer.ImageViewer") doesn’t subclass the Matplotlib axes (or figure) because of the high probability of name collisions. Subclasses and plugins will likely extend the [`update_image`](#skimage.viewer.ImageViewer.update_image "skimage.viewer.ImageViewer.update_image") method to add custom overlays or filter the displayed image. Parameters `imagearray` Image being viewed. #### Examples ``` >>> from skimage import data >>> image = data.coins() >>> viewer = ImageViewer(image) >>> viewer.show() ``` Attributes `canvas, fig, axMatplotlib canvas, figure, and axes` Matplotlib canvas, figure, and axes used to display image. `imagearray` Image being viewed. Setting this value will update the displayed frame. `original_imagearray` Plugins typically operate on (but don’t change) the *original* image. `pluginslist` List of attached plugins. `__init__(image, useblit=True)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L92-L151) Initialize self. See help(type(self)) for accurate signature. `add_tool(tool)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L307-L311) `closeEvent(event)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L237-L238) `connect_event(event, callback)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L292-L295) Connect callback function to matplotlib event and return id. `disconnect_event(callback_id)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L297-L299) Disconnect callback by its id (returned by [`connect_event`](#skimage.viewer.ImageViewer.connect_event "skimage.viewer.ImageViewer.connect_event")). `dock_areas = {'bottom': None, 'left': None, 'right': None, 'top': None}` `property image` `open_file(filename=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L186-L193) Open image file and display in viewer. `original_image_changed = None` `redraw()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L258-L262) `remove_tool(tool)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L313-L319) `reset_image()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L289-L290) `save_to_file(filename=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L208-L235) Save current image to file. The current behavior is not ideal: It saves the image displayed on screen, so all images will be converted to RGB, and the image size is not preserved (resizing the viewer window will alter the size of the saved image). `show(main_window=True)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L248-L256) Show ImageViewer and attached plugins. This behaves much like [`matplotlib.pyplot.show`](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.show.html#matplotlib.pyplot.show "(in Matplotlib v3.3.3)") and `QWidget.show`. `update_image(image)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L195-L201) Update displayed image. This method can be overridden or extended in subclasses and plugins to react to image changes. scikit_image Module: restoration Module: restoration =================== Image restoration module. | | | | --- | --- | | [`skimage.restoration.ball_kernel`](#skimage.restoration.ball_kernel "skimage.restoration.ball_kernel")(radius, ndim) | Create a ball kernel for restoration.rolling\_ball. | | [`skimage.restoration.calibrate_denoiser`](#skimage.restoration.calibrate_denoiser "skimage.restoration.calibrate_denoiser")(…) | Calibrate a denoising function and return optimal J-invariant version. | | [`skimage.restoration.cycle_spin`](#skimage.restoration.cycle_spin "skimage.restoration.cycle_spin")(x, func, …) | Cycle spinning (repeatedly apply func to shifted versions of x). | | [`skimage.restoration.denoise_bilateral`](#skimage.restoration.denoise_bilateral "skimage.restoration.denoise_bilateral")(image) | Denoise image using bilateral filter. | | [`skimage.restoration.denoise_nl_means`](#skimage.restoration.denoise_nl_means "skimage.restoration.denoise_nl_means")(image) | Perform non-local means denoising on 2-D or 3-D grayscale images, and 2-D RGB images. | | [`skimage.restoration.denoise_tv_bregman`](#skimage.restoration.denoise_tv_bregman "skimage.restoration.denoise_tv_bregman")(…) | Perform total-variation denoising using split-Bregman optimization. | | [`skimage.restoration.denoise_tv_chambolle`](#skimage.restoration.denoise_tv_chambolle "skimage.restoration.denoise_tv_chambolle")(image) | Perform total-variation denoising on n-dimensional images. | | [`skimage.restoration.denoise_wavelet`](#skimage.restoration.denoise_wavelet "skimage.restoration.denoise_wavelet")(image[, …]) | Perform wavelet denoising on an image. | | [`skimage.restoration.ellipsoid_kernel`](#skimage.restoration.ellipsoid_kernel "skimage.restoration.ellipsoid_kernel")(shape, …) | Create an ellipoid kernel for restoration.rolling\_ball. | | [`skimage.restoration.estimate_sigma`](#skimage.restoration.estimate_sigma "skimage.restoration.estimate_sigma")(image[, …]) | Robust wavelet-based estimator of the (Gaussian) noise standard deviation. | | [`skimage.restoration.inpaint_biharmonic`](#skimage.restoration.inpaint_biharmonic "skimage.restoration.inpaint_biharmonic")(…) | Inpaint masked points in image with biharmonic equations. | | [`skimage.restoration.richardson_lucy`](#skimage.restoration.richardson_lucy "skimage.restoration.richardson_lucy")(image, psf) | Richardson-Lucy deconvolution. | | [`skimage.restoration.rolling_ball`](#skimage.restoration.rolling_ball "skimage.restoration.rolling_ball")(image, \*[, …]) | Estimate background intensity by rolling/translating a kernel. | | [`skimage.restoration.unsupervised_wiener`](#skimage.restoration.unsupervised_wiener "skimage.restoration.unsupervised_wiener")(…) | Unsupervised Wiener-Hunt deconvolution. | | [`skimage.restoration.unwrap_phase`](#skimage.restoration.unwrap_phase "skimage.restoration.unwrap_phase")(image[, …]) | Recover the original from a wrapped phase image. | | [`skimage.restoration.wiener`](#skimage.restoration.wiener "skimage.restoration.wiener")(image, psf, balance) | Wiener-Hunt deconvolution | ball\_kernel ------------ `skimage.restoration.ball_kernel(radius, ndim)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/restoration/rolling_ball.py#L117-L152) Create a ball kernel for restoration.rolling\_ball. Parameters `radiusint` Radius of the ball. `ndimint` Number of dimensions of the ball. `ndim` should match the dimensionality of the image the kernel will be applied to. Returns `kernelndarray` The kernel containing the surface intensity of the top half of the ellipsoid. See also [`rolling_ball`](#skimage.restoration.rolling_ball "skimage.restoration.rolling_ball") calibrate\_denoiser ------------------- `skimage.restoration.calibrate_denoiser(image, denoise_function, denoise_parameters, *, stride=4, approximate_loss=True, extra_output=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/restoration/j_invariant.py#L161-L254) Calibrate a denoising function and return optimal J-invariant version. The returned function is partially evaluated with optimal parameter values set for denoising the input image. Parameters `imagendarray` Input data to be denoised (converted using `img_as_float`). `denoise_functionfunction` Denoising function to be calibrated. `denoise_parametersdict of list` Ranges of parameters for `denoise_function` to be calibrated over. `strideint, optional` Stride used in masking procedure that converts `denoise_function` to J-invariance. `approximate_lossbool, optional` Whether to approximate the self-supervised loss used to evaluate the denoiser by only computing it on one masked version of the image. If False, the runtime will be a factor of `stride**image.ndim` longer. `extra_outputbool, optional` If True, return parameters and losses in addition to the calibrated denoising function Returns `best_denoise_functionfunction` The optimal J-invariant version of `denoise_function`. `If extra_output is True, the following tuple is also returned:` `(parameters_tested, losses)tuple (list of dict, list of int)` List of parameters tested for `denoise_function`, as a dictionary of kwargs Self-supervised loss for each set of parameters in `parameters_tested`. #### Notes The calibration procedure uses a self-supervised mean-square-error loss to evaluate the performance of J-invariant versions of `denoise_function`. The minimizer of the self-supervised loss is also the minimizer of the ground-truth loss (i.e., the true MSE error) [1]. The returned function can be used on the original noisy image, or other images with similar characteristics. `Increasing the stride increases the performance of best_denoise_function` at the expense of increasing its runtime. It has no effect on the runtime of the calibration. #### References `1` J. Batson & L. Royer. Noise2Self: Blind Denoising by Self-Supervision, International Conference on Machine Learning, p. 524-533 (2019). #### Examples ``` >>> from skimage import color, data >>> from skimage.restoration import denoise_wavelet >>> import numpy as np >>> img = color.rgb2gray(data.astronaut()[:50, :50]) >>> noisy = img + 0.5 * img.std() * np.random.randn(*img.shape) >>> parameters = {'sigma': np.arange(0.1, 0.4, 0.02)} >>> denoising_function = calibrate_denoiser(noisy, denoise_wavelet, ... denoise_parameters=parameters) >>> denoised_img = denoising_function(img) ``` cycle\_spin ----------- `skimage.restoration.cycle_spin(x, func, max_shifts, shift_steps=1, num_workers=None, multichannel=False, func_kw={})` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/restoration/_cycle_spin.py#L49-L145) Cycle spinning (repeatedly apply func to shifted versions of x). Parameters `xarray-like` Data for input to `func`. `funcfunction` A function to apply to circularly shifted versions of `x`. Should take `x` as its first argument. Any additional arguments can be supplied via `func_kw`. `max_shiftsint or tuple` If an integer, shifts in `range(0, max_shifts+1)` will be used along each axis of `x`. If a tuple, `range(0, max_shifts[i]+1)` will be along axis i. `shift_stepsint or tuple, optional` The step size for the shifts applied along axis, i, are:: `range((0, max_shifts[i]+1, shift_steps[i]))`. If an integer is provided, the same step size is used for all axes. `num_workersint or None, optional` The number of parallel threads to use during cycle spinning. If set to `None`, the full set of available cores are used. `multichannelbool, optional` Whether to treat the final axis as channels (no cycle shifts are performed over the channels axis). `func_kwdict, optional` Additional keyword arguments to supply to `func`. Returns `avg_ynp.ndarray` The output of `func(x, **func_kw)` averaged over all combinations of the specified axis shifts. #### Notes Cycle spinning was proposed as a way to approach shift-invariance via performing several circular shifts of a shift-variant transform [[1]](#r67eed921dbd3-1). For a n-level discrete wavelet transforms, one may wish to perform all shifts up to `max_shifts = 2**n - 1`. In practice, much of the benefit can often be realized with only a small number of shifts per axis. For transforms such as the blockwise discrete cosine transform, one may wish to evaluate shifts up to the block size used by the transform. #### References `1` R.R. Coifman and D.L. Donoho. β€œTranslation-Invariant De-Noising”. Wavelets and Statistics, Lecture Notes in Statistics, vol.103. Springer, New York, 1995, pp.125-150. [DOI:10.1007/978-1-4612-2544-7\_9](https://doi.org/10.1007/978-1-4612-2544-7_9) #### Examples ``` >>> import skimage.data >>> from skimage import img_as_float >>> from skimage.restoration import denoise_wavelet, cycle_spin >>> img = img_as_float(skimage.data.camera()) >>> sigma = 0.1 >>> img = img + sigma * np.random.standard_normal(img.shape) >>> denoised = cycle_spin(img, func=denoise_wavelet, ... max_shifts=3) ``` denoise\_bilateral ------------------ `skimage.restoration.denoise_bilateral(image, win_size=None, sigma_color=None, sigma_spatial=1, bins=10000, mode='constant', cval=0, multichannel=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/restoration/_denoise.py#L91-L232) Denoise image using bilateral filter. Parameters `imagendarray, shape (M, N[, 3])` Input image, 2D grayscale or RGB. `win_sizeint` Window size for filtering. If win\_size is not specified, it is calculated as `max(5, 2 * ceil(3 * sigma_spatial) + 1)`. `sigma_colorfloat` Standard deviation for grayvalue/color distance (radiometric similarity). A larger value results in averaging of pixels with larger radiometric differences. Note, that the image will be converted using the `img_as_float` function and thus the standard deviation is in respect to the range `[0, 1]`. If the value is `None` the standard deviation of the `image` will be used. `sigma_spatialfloat` Standard deviation for range distance. A larger value results in averaging of pixels with larger spatial differences. `binsint` Number of discrete values for Gaussian weights of color filtering. A larger value results in improved accuracy. `mode{β€˜constant’, β€˜edge’, β€˜symmetric’, β€˜reflect’, β€˜wrap’}` How to handle values outside the image borders. See [`numpy.pad`](https://numpy.org/doc/stable/reference/generated/numpy.pad.html#numpy.pad "(in NumPy v1.19)") for detail. `cvalstring` Used in conjunction with mode β€˜constant’, the value outside the image boundaries. `multichannelbool` Whether the last axis of the image is to be interpreted as multiple channels or another spatial dimension. Returns `denoisedndarray` Denoised image. #### Notes This is an edge-preserving, denoising filter. It averages pixels based on their spatial closeness and radiometric similarity [[1]](#rb832e60bc162-1). Spatial closeness is measured by the Gaussian function of the Euclidean distance between two pixels and a certain standard deviation (`sigma_spatial`). Radiometric similarity is measured by the Gaussian function of the Euclidean distance between two color values and a certain standard deviation (`sigma_color`). #### References `1` C. Tomasi and R. Manduchi. β€œBilateral Filtering for Gray and Color Images.” IEEE International Conference on Computer Vision (1998) 839-846. [DOI:10.1109/ICCV.1998.710815](https://doi.org/10.1109/ICCV.1998.710815) #### Examples ``` >>> from skimage import data, img_as_float >>> astro = img_as_float(data.astronaut()) >>> astro = astro[220:300, 220:320] >>> noisy = astro + 0.6 * astro.std() * np.random.random(astro.shape) >>> noisy = np.clip(noisy, 0, 1) >>> denoised = denoise_bilateral(noisy, sigma_color=0.05, sigma_spatial=15, ... multichannel=True) ``` ### Examples using `skimage.restoration.denoise_bilateral` [Rank filters](https://scikit-image.org/docs/0.18.x/auto_examples/applications/plot_rank_filters.html#sphx-glr-auto-examples-applications-plot-rank-filters-py) denoise\_nl\_means ------------------ `skimage.restoration.denoise_nl_means(image, patch_size=7, patch_distance=11, h=0.1, multichannel=False, fast_mode=True, sigma=0.0, *, preserve_range=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/restoration/non_local_means.py#L11-L164) Perform non-local means denoising on 2-D or 3-D grayscale images, and 2-D RGB images. Parameters `image2D or 3D ndarray` Input image to be denoised, which can be 2D or 3D, and grayscale or RGB (for 2D images only, see `multichannel` parameter). `patch_sizeint, optional` Size of patches used for denoising. `patch_distanceint, optional` Maximal distance in pixels where to search patches used for denoising. `hfloat, optional` Cut-off distance (in gray levels). The higher h, the more permissive one is in accepting patches. A higher h results in a smoother image, at the expense of blurring features. For a Gaussian noise of standard deviation sigma, a rule of thumb is to choose the value of h to be sigma of slightly less. `multichannelbool, optional` Whether the last axis of the image is to be interpreted as multiple channels or another spatial dimension. `fast_modebool, optional` If True (default value), a fast version of the non-local means algorithm is used. If False, the original version of non-local means is used. See the Notes section for more details about the algorithms. `sigmafloat, optional` The standard deviation of the (Gaussian) noise. If provided, a more robust computation of patch weights is computed that takes the expected noise variance into account (see Notes below). `preserve_rangebool, optional` Whether to keep the original range of values. Otherwise, the input image is converted according to the conventions of `img_as_float`. Also see <https://scikit-image.org/docs/dev/user_guide/data_types.html> Returns `resultndarray` Denoised image, of same shape as `image`. #### Notes The non-local means algorithm is well suited for denoising images with specific textures. The principle of the algorithm is to average the value of a given pixel with values of other pixels in a limited neighbourhood, provided that the *patches* centered on the other pixels are similar enough to the patch centered on the pixel of interest. In the original version of the algorithm [[1]](#rc9b3919da938-1), corresponding to `fast=False`, the computational complexity is: ``` image.size * patch_size ** image.ndim * patch_distance ** image.ndim ``` Hence, changing the size of patches or their maximal distance has a strong effect on computing times, especially for 3-D images. However, the default behavior corresponds to `fast_mode=True`, for which another version of non-local means [[2]](#rc9b3919da938-2) is used, corresponding to a complexity of: ``` image.size * patch_distance ** image.ndim ``` The computing time depends only weakly on the patch size, thanks to the computation of the integral of patches distances for a given shift, that reduces the number of operations [[1]](#rc9b3919da938-1). Therefore, this algorithm executes faster than the classic algorithm (`fast_mode=False`), at the expense of using twice as much memory. This implementation has been proven to be more efficient compared to other alternatives, see e.g. [[3]](#rc9b3919da938-3). Compared to the classic algorithm, all pixels of a patch contribute to the distance to another patch with the same weight, no matter their distance to the center of the patch. This coarser computation of the distance can result in a slightly poorer denoising performance. Moreover, for small images (images with a linear size that is only a few times the patch size), the classic algorithm can be faster due to boundary effects. The image is padded using the `reflect` mode of [`skimage.util.pad`](skimage.util#skimage.util.pad "skimage.util.pad") before denoising. If the noise standard deviation, `sigma`, is provided a more robust computation of patch weights is used. Subtracting the known noise variance from the computed patch distances improves the estimates of patch similarity, giving a moderate improvement to denoising performance [[4]](#rc9b3919da938-4). It was also mentioned as an option for the fast variant of the algorithm in [[3]](#rc9b3919da938-3). When `sigma` is provided, a smaller `h` should typically be used to avoid oversmoothing. The optimal value for `h` depends on the image content and noise level, but a reasonable starting point is `h = 0.8 * sigma` when `fast_mode` is `True`, or `h = 0.6 * sigma` when `fast_mode` is `False`. #### References `1(1,2)` A. Buades, B. Coll, & J-M. Morel. A non-local algorithm for image denoising. In CVPR 2005, Vol. 2, pp. 60-65, IEEE. [DOI:10.1109/CVPR.2005.38](https://doi.org/10.1109/CVPR.2005.38) `2` J. Darbon, A. Cunha, T.F. Chan, S. Osher, and G.J. Jensen, Fast nonlocal filtering applied to electron cryomicroscopy, in 5th IEEE International Symposium on Biomedical Imaging: From Nano to Macro, 2008, pp. 1331-1334. [DOI:10.1109/ISBI.2008.4541250](https://doi.org/10.1109/ISBI.2008.4541250) `3(1,2)` Jacques Froment. Parameter-Free Fast Pixelwise Non-Local Means Denoising. Image Processing On Line, 2014, vol. 4, pp. 300-326. [DOI:10.5201/ipol.2014.120](https://doi.org/10.5201/ipol.2014.120) `4` A. Buades, B. Coll, & J-M. Morel. Non-Local Means Denoising. Image Processing On Line, 2011, vol. 1, pp. 208-212. [DOI:10.5201/ipol.2011.bcm\_nlm](https://doi.org/10.5201/ipol.2011.bcm_nlm) #### Examples ``` >>> a = np.zeros((40, 40)) >>> a[10:-10, 10:-10] = 1. >>> a += 0.3 * np.random.randn(*a.shape) >>> denoised_a = denoise_nl_means(a, 7, 5, 0.1) ``` denoise\_tv\_bregman -------------------- `skimage.restoration.denoise_tv_bregman(image, weight, max_iter=100, eps=0.001, isotropic=True, *, multichannel=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/restoration/_denoise.py#L235-L312) Perform total-variation denoising using split-Bregman optimization. Total-variation denoising (also know as total-variation regularization) tries to find an image with less total-variation under the constraint of being similar to the input image, which is controlled by the regularization parameter ([[1]](#rc0e3588f2bc3-1), [[2]](#rc0e3588f2bc3-2), [[3]](#rc0e3588f2bc3-3), [[4]](#rc0e3588f2bc3-4)). Parameters `imagendarray` Input data to be denoised (converted using img\_as\_float`). `weightfloat` Denoising weight. The smaller the `weight`, the more denoising (at the expense of less similarity to the `input`). The regularization parameter `lambda` is chosen as `2 * weight`. `epsfloat, optional` Relative difference of the value of the cost function that determines the stop criterion. The algorithm stops when: ``` SUM((u(n) - u(n-1))**2) < eps ``` `max_iterint, optional` Maximal number of iterations used for the optimization. `isotropicboolean, optional` Switch between isotropic and anisotropic TV denoising. `multichannelbool, optional` Apply total-variation denoising separately for each channel. This option should be true for color images, otherwise the denoising is also applied in the channels dimension. Returns `undarray` Denoised image. #### References `1` <https://en.wikipedia.org/wiki/Total_variation_denoising> `2` Tom Goldstein and Stanley Osher, β€œThe Split Bregman Method For L1 Regularized Problems”, <ftp://ftp.math.ucla.edu/pub/camreport/cam08-29.pdf> `3` Pascal Getreuer, β€œRudin–Osher–Fatemi Total Variation Denoising using Split Bregman” in Image Processing On Line on 2012–05–19, <https://www.ipol.im/pub/art/2012/g-tvd/article_lr.pdf> `4` <https://web.math.ucsb.edu/~cgarcia/UGProjects/BregmanAlgorithms_JacquelineBush.pdf> denoise\_tv\_chambolle ---------------------- `skimage.restoration.denoise_tv_chambolle(image, weight=0.1, eps=0.0002, n_iter_max=200, multichannel=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/restoration/_denoise.py#L396-L479) Perform total-variation denoising on n-dimensional images. Parameters `imagendarray of ints, uints or floats` Input data to be denoised. `image` can be of any numeric type, but it is cast into an ndarray of floats for the computation of the denoised image. `weightfloat, optional` Denoising weight. The greater `weight`, the more denoising (at the expense of fidelity to `input`). `epsfloat, optional` Relative difference of the value of the cost function that determines the stop criterion. The algorithm stops when: (E\_(n-1) - E\_n) < eps \* E\_0 `n_iter_maxint, optional` Maximal number of iterations used for the optimization. `multichannelbool, optional` Apply total-variation denoising separately for each channel. This option should be true for color images, otherwise the denoising is also applied in the channels dimension. Returns `outndarray` Denoised image. #### Notes Make sure to set the multichannel parameter appropriately for color images. The principle of total variation denoising is explained in <https://en.wikipedia.org/wiki/Total_variation_denoising> The principle of total variation denoising is to minimize the total variation of the image, which can be roughly described as the integral of the norm of the image gradient. Total variation denoising tends to produce β€œcartoon-like” images, that is, piecewise-constant images. This code is an implementation of the algorithm of Rudin, Fatemi and Osher that was proposed by Chambolle in [[1]](#r3f46bb237e10-1). #### References `1` A. Chambolle, An algorithm for total variation minimization and applications, Journal of Mathematical Imaging and Vision, Springer, 2004, 20, 89-97. #### Examples 2D example on astronaut image: ``` >>> from skimage import color, data >>> img = color.rgb2gray(data.astronaut())[:50, :50] >>> img += 0.5 * img.std() * np.random.randn(*img.shape) >>> denoised_img = denoise_tv_chambolle(img, weight=60) ``` 3D example on synthetic data: ``` >>> x, y, z = np.ogrid[0:20, 0:20, 0:20] >>> mask = (x - 22)**2 + (y - 20)**2 + (z - 17)**2 < 8**2 >>> mask = mask.astype(float) >>> mask += 0.2*np.random.randn(*mask.shape) >>> res = denoise_tv_chambolle(mask, weight=100) ``` denoise\_wavelet ---------------- `skimage.restoration.denoise_wavelet(image, sigma=None, wavelet='db1', mode='soft', wavelet_levels=None, multichannel=False, convert2ycbcr=False, method='BayesShrink', rescale_sigma=True)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/restoration/_denoise.py#L694-L863) Perform wavelet denoising on an image. Parameters `imagendarray ([M[, N[, …P]][, C]) of ints, uints or floats` Input data to be denoised. `image` can be of any numeric type, but it is cast into an ndarray of floats for the computation of the denoised image. `sigmafloat or list, optional` The noise standard deviation used when computing the wavelet detail coefficient threshold(s). When None (default), the noise standard deviation is estimated via the method in [[2]](#r3b8ec6d23a4e-2). `waveletstring, optional` The type of wavelet to perform and can be any of the options `pywt.wavelist` outputs. The default is `β€˜db1’`. For example, `wavelet` can be any of `{'db2', 'haar', 'sym9'}` and many more. `mode{β€˜soft’, β€˜hard’}, optional` An optional argument to choose the type of denoising performed. It noted that choosing soft thresholding given additive noise finds the best approximation of the original image. `wavelet_levelsint or None, optional` The number of wavelet decomposition levels to use. The default is three less than the maximum number of possible decomposition levels. `multichannelbool, optional` Apply wavelet denoising separately for each channel (where channels correspond to the final axis of the array). `convert2ycbcrbool, optional` If True and multichannel True, do the wavelet denoising in the YCbCr colorspace instead of the RGB color space. This typically results in better performance for RGB images. `method{β€˜BayesShrink’, β€˜VisuShrink’}, optional` Thresholding method to be used. The currently supported methods are β€œBayesShrink” [[1]](#r3b8ec6d23a4e-1) and β€œVisuShrink” [[2]](#r3b8ec6d23a4e-2). Defaults to β€œBayesShrink”. `rescale_sigmabool, optional` If False, no rescaling of the user-provided `sigma` will be performed. The default of `True` rescales sigma appropriately if the image is rescaled internally. New in version 0.16: `rescale_sigma` was introduced in 0.16 Returns `outndarray` Denoised image. #### Notes The wavelet domain is a sparse representation of the image, and can be thought of similarly to the frequency domain of the Fourier transform. Sparse representations have most values zero or near-zero and truly random noise is (usually) represented by many small values in the wavelet domain. Setting all values below some threshold to 0 reduces the noise in the image, but larger thresholds also decrease the detail present in the image. If the input is 3D, this function performs wavelet denoising on each color plane separately. Changed in version 0.16: For floating point inputs, the original input range is maintained and there is no clipping applied to the output. Other input types will be converted to a floating point value in the range [-1, 1] or [0, 1] depending on the input image range. Unless `rescale_sigma = False`, any internal rescaling applied to the `image` will also be applied to `sigma` to maintain the same relative amplitude. Many wavelet coefficient thresholding approaches have been proposed. By default, `denoise_wavelet` applies BayesShrink, which is an adaptive thresholding method that computes separate thresholds for each wavelet sub-band as described in [[1]](#r3b8ec6d23a4e-1). If `method == "VisuShrink"`, a single β€œuniversal threshold” is applied to all wavelet detail coefficients as described in [[2]](#r3b8ec6d23a4e-2). This threshold is designed to remove all Gaussian noise at a given `sigma` with high probability, but tends to produce images that appear overly smooth. Although any of the wavelets from `PyWavelets` can be selected, the thresholding methods assume an orthogonal wavelet transform and may not choose the threshold appropriately for biorthogonal wavelets. Orthogonal wavelets are desirable because white noise in the input remains white noise in the subbands. Biorthogonal wavelets lead to colored noise in the subbands. Additionally, the orthogonal wavelets in PyWavelets are orthonormal so that noise variance in the subbands remains identical to the noise variance of the input. Example orthogonal wavelets are the Daubechies (e.g. β€˜db2’) or symmlet (e.g. β€˜sym2’) families. #### References `1(1,2)` Chang, S. Grace, Bin Yu, and Martin Vetterli. β€œAdaptive wavelet thresholding for image denoising and compression.” Image Processing, IEEE Transactions on 9.9 (2000): 1532-1546. [DOI:10.1109/83.862633](https://doi.org/10.1109/83.862633) `2(1,2,3)` D. L. Donoho and I. M. Johnstone. β€œIdeal spatial adaptation by wavelet shrinkage.” Biometrika 81.3 (1994): 425-455. [DOI:10.1093/biomet/81.3.425](https://doi.org/10.1093/biomet/81.3.425) #### Examples ``` >>> from skimage import color, data >>> img = img_as_float(data.astronaut()) >>> img = color.rgb2gray(img) >>> img += 0.1 * np.random.randn(*img.shape) >>> img = np.clip(img, 0, 1) >>> denoised_img = denoise_wavelet(img, sigma=0.1, rescale_sigma=True) ``` ellipsoid\_kernel ----------------- `skimage.restoration.ellipsoid_kernel(shape, intensity)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/restoration/rolling_ball.py#L155-L192) Create an ellipoid kernel for restoration.rolling\_ball. Parameters `shapearraylike` Length of the principal axis of the ellipsoid (excluding the intensity axis). The kernel needs to have the same dimensionality as the image it will be applied to. `intensityint` Length of the intensity axis of the ellipsoid. Returns `kernelndarray` The kernel containing the surface intensity of the top half of the ellipsoid. See also [`rolling_ball`](#skimage.restoration.rolling_ball "skimage.restoration.rolling_ball") ### Examples using `skimage.restoration.ellipsoid_kernel` [Use rolling-ball algorithm for estimating background intensity](https://scikit-image.org/docs/0.18.x/auto_examples/segmentation/plot_rolling_ball.html#sphx-glr-auto-examples-segmentation-plot-rolling-ball-py) estimate\_sigma --------------- `skimage.restoration.estimate_sigma(image, average_sigmas=False, multichannel=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/restoration/_denoise.py#L866-L923) Robust wavelet-based estimator of the (Gaussian) noise standard deviation. Parameters `imagendarray` Image for which to estimate the noise standard deviation. `average_sigmasbool, optional` If true, average the channel estimates of `sigma`. Otherwise return a list of sigmas corresponding to each channel. `multichannelbool` Estimate sigma separately for each channel. Returns `sigmafloat or list` Estimated noise standard deviation(s). If `multichannel` is True and `average_sigmas` is False, a separate noise estimate for each channel is returned. Otherwise, the average of the individual channel estimates is returned. #### Notes This function assumes the noise follows a Gaussian distribution. The estimation algorithm is based on the median absolute deviation of the wavelet detail coefficients as described in section 4.2 of [[1]](#rbc448ac95825-1). #### References `1` D. L. Donoho and I. M. Johnstone. β€œIdeal spatial adaptation by wavelet shrinkage.” Biometrika 81.3 (1994): 425-455. [DOI:10.1093/biomet/81.3.425](https://doi.org/10.1093/biomet/81.3.425) #### Examples ``` >>> import skimage.data >>> from skimage import img_as_float >>> img = img_as_float(skimage.data.camera()) >>> sigma = 0.1 >>> img = img + sigma * np.random.standard_normal(img.shape) >>> sigma_hat = estimate_sigma(img, multichannel=False) ``` inpaint\_biharmonic ------------------- `skimage.restoration.inpaint_biharmonic(image, mask, multichannel=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/restoration/inpaint.py#L76-L152) Inpaint masked points in image with biharmonic equations. Parameters `image(M[, N[, …, P]][, C]) ndarray` Input image. `mask(M[, N[, …, P]]) ndarray` Array of pixels to be inpainted. Have to be the same shape as one of the β€˜image’ channels. Unknown pixels have to be represented with 1, known pixels - with 0. `multichannelboolean, optional` If True, the last `image` dimension is considered as a color channel, otherwise as spatial. Returns `out(M[, N[, …, P]][, C]) ndarray` Input image with masked pixels inpainted. #### References `1` N.S.Hoang, S.B.Damelin, β€œOn surface completion and image inpainting by biharmonic functions: numerical aspects”, [arXiv:1707.06567](https://arxiv.org/abs/1707.06567) `2` C. K. Chui and H. N. Mhaskar, MRA Contextual-Recovery Extension of Smooth Functions on Manifolds, Appl. and Comp. Harmonic Anal., 28 (2010), 104-113, [DOI:10.1016/j.acha.2009.04.004](https://doi.org/10.1016/j.acha.2009.04.004) #### Examples ``` >>> img = np.tile(np.square(np.linspace(0, 1, 5)), (5, 1)) >>> mask = np.zeros_like(img) >>> mask[2, 2:] = 1 >>> mask[1, 3:] = 1 >>> mask[0, 4:] = 1 >>> out = inpaint_biharmonic(img, mask) ``` richardson\_lucy ---------------- `skimage.restoration.richardson_lucy(image, psf, iterations=50, clip=True, filter_epsilon=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/restoration/deconvolution.py#L329-L385) Richardson-Lucy deconvolution. Parameters `imagendarray` Input degraded image (can be N dimensional). `psfndarray` The point spread function. `iterationsint, optional` Number of iterations. This parameter plays the role of regularisation. `clipboolean, optional` True by default. If true, pixel value of the result above 1 or under -1 are thresholded for skimage pipeline compatibility. **filter\_epsilon: float, optional** Value below which intermediate results become 0 to avoid division by small numbers. Returns `im_deconvndarray` The deconvolved image. #### References `1` <https://en.wikipedia.org/wiki/Richardson%E2%80%93Lucy_deconvolution> #### Examples ``` >>> from skimage import img_as_float, data, restoration >>> camera = img_as_float(data.camera()) >>> from scipy.signal import convolve2d >>> psf = np.ones((5, 5)) / 25 >>> camera = convolve2d(camera, psf, 'same') >>> camera += 0.1 * camera.std() * np.random.standard_normal(camera.shape) >>> deconvolved = restoration.richardson_lucy(camera, psf, 5) ``` rolling\_ball ------------- `skimage.restoration.rolling_ball(image, *, radius=100, kernel=None, nansafe=False, num_threads=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/restoration/rolling_ball.py#L6-L114) Estimate background intensity by rolling/translating a kernel. This rolling ball algorithm estimates background intensity for a ndimage in case of uneven exposure. It is a generalization of the frequently used rolling ball algorithm [[1]](#r62497d9283b1-1). Parameters `imagendarray` The image to be filtered. `radiusint, optional` Radius of a ball shaped kernel to be rolled/translated in the image. Used if `kernel = None`. `kernelndarray, optional` The kernel to be rolled/translated in the image. It must have the same number of dimensions as `image`. Kernel is filled with the intensity of the kernel at that position. **nansafe: bool, optional** If `False` (default) assumes that none of the values in `image` are `np.nan`, and uses a faster implementation. **num\_threads: int, optional** The maximum number of threads to use. If `None` use the OpenMP default value; typically equal to the maximum number of virtual cores. Note: This is an upper limit to the number of threads. The exact number is determined by the system’s OpenMP library. Returns `backgroundndarray` The estimated background of the image. #### Notes For the pixel that has its background intensity estimated (without loss of generality at `center`) the rolling ball method centers `kernel` under it and raises the kernel until the surface touches the image umbra at some `pos=(y,x)`. The background intensity is then estimated using the image intensity at that position (`image[pos]`) plus the difference of `kernel[center] - kernel[pos]`. This algorithm assumes that dark pixels correspond to the background. If you have a bright background, invert the image before passing it to the function, e.g., using `utils.invert`. See the gallery example for details. This algorithm is sensitive to noise (in particular salt-and-pepper noise). If this is a problem in your image, you can apply mild gaussian smoothing before passing the image to this function. #### References `1` Sternberg, Stanley R. β€œBiomedical image processing.” Computer 1 (1983): 22-34. [DOI:10.1109/MC.1983.1654163](https://doi.org/10.1109/MC.1983.1654163) #### Examples ``` >>> import numpy as np >>> from skimage import data >>> from skimage.restoration import rolling_ball >>> image = data.coins() >>> background = rolling_ball(data.coins()) >>> filtered_image = image - background ``` ``` >>> import numpy as np >>> from skimage import data >>> from skimage.restoration import rolling_ball, ellipsoid_kernel >>> image = data.coins() >>> kernel = ellipsoid_kernel((101, 101), 75) >>> background = rolling_ball(data.coins(), kernel=kernel) >>> filtered_image = image - background ``` ### Examples using `skimage.restoration.rolling_ball` [Use rolling-ball algorithm for estimating background intensity](https://scikit-image.org/docs/0.18.x/auto_examples/segmentation/plot_rolling_ball.html#sphx-glr-auto-examples-segmentation-plot-rolling-ball-py) unsupervised\_wiener -------------------- `skimage.restoration.unsupervised_wiener(image, psf, reg=None, user_params=None, is_real=True, clip=True)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/restoration/deconvolution.py#L140-L326) Unsupervised Wiener-Hunt deconvolution. Return the deconvolution with a Wiener-Hunt approach, where the hyperparameters are automatically estimated. The algorithm is a stochastic iterative process (Gibbs sampler) described in the reference below. See also `wiener` function. Parameters `image(M, N) ndarray` The input degraded image. `psfndarray` The impulse response (input image’s space) or the transfer function (Fourier space). Both are accepted. The transfer function is automatically recognized as being complex (`np.iscomplexobj(psf)`). `regndarray, optional` The regularisation operator. The Laplacian by default. It can be an impulse response or a transfer function, as for the psf. `user_paramsdict, optional` Dictionary of parameters for the Gibbs sampler. See below. `clipboolean, optional` True by default. If true, pixel values of the result above 1 or under -1 are thresholded for skimage pipeline compatibility. Returns `x_postmean(M, N) ndarray` The deconvolved image (the posterior mean). `chainsdict` The keys `noise` and `prior` contain the chain list of noise and prior precision respectively. Other Parameters **The keys of ``user\_params`` are:** `thresholdfloat` The stopping criterion: the norm of the difference between to successive approximated solution (empirical mean of object samples, see Notes section). 1e-4 by default. `burninint` The number of sample to ignore to start computation of the mean. 15 by default. `min_iterint` The minimum number of iterations. 30 by default. `max_iterint` The maximum number of iterations if `threshold` is not satisfied. 200 by default. `callbackcallable (None by default)` A user provided callable to which is passed, if the function exists, the current image sample for whatever purpose. The user can store the sample, or compute other moments than the mean. It has no influence on the algorithm execution and is only for inspection. #### Notes The estimated image is design as the posterior mean of a probability law (from a Bayesian analysis). The mean is defined as a sum over all the possible images weighted by their respective probability. Given the size of the problem, the exact sum is not tractable. This algorithm use of MCMC to draw image under the posterior law. The practical idea is to only draw highly probable images since they have the biggest contribution to the mean. At the opposite, the less probable images are drawn less often since their contribution is low. Finally the empirical mean of these samples give us an estimation of the mean, and an exact computation with an infinite sample set. #### References `1` FranΓ§ois Orieux, Jean-FranΓ§ois Giovannelli, and Thomas Rodet, β€œBayesian estimation of regularization and point spread function parameters for Wiener-Hunt deconvolution”, J. Opt. Soc. Am. A 27, 1593-1607 (2010) <https://www.osapublishing.org/josaa/abstract.cfm?URI=josaa-27-7-1593> <http://research.orieux.fr/files/papers/OGR-JOSA10.pdf> #### Examples ``` >>> from skimage import color, data, restoration >>> img = color.rgb2gray(data.astronaut()) >>> from scipy.signal import convolve2d >>> psf = np.ones((5, 5)) / 25 >>> img = convolve2d(img, psf, 'same') >>> img += 0.1 * img.std() * np.random.standard_normal(img.shape) >>> deconvolved_img = restoration.unsupervised_wiener(img, psf) ``` unwrap\_phase ------------- `skimage.restoration.unwrap_phase(image, wrap_around=False, seed=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/restoration/unwrap.py#L10-L113) Recover the original from a wrapped phase image. From an image wrapped to lie in the interval [-pi, pi), recover the original, unwrapped image. Parameters `image1D, 2D or 3D ndarray of floats, optionally a masked array` The values should be in the range [-pi, pi). If a masked array is provided, the masked entries will not be changed, and their values will not be used to guide the unwrapping of neighboring, unmasked values. Masked 1D arrays are not allowed, and will raise a `ValueError`. `wrap_aroundbool or sequence of bool, optional` When an element of the sequence is `True`, the unwrapping process will regard the edges along the corresponding axis of the image to be connected and use this connectivity to guide the phase unwrapping process. If only a single boolean is given, it will apply to all axes. Wrap around is not supported for 1D arrays. `seedint, optional` Unwrapping 2D or 3D images uses random initialization. This sets the seed of the PRNG to achieve deterministic behavior. Returns `image_unwrappedarray_like, double` Unwrapped image of the same shape as the input. If the input `image` was a masked array, the mask will be preserved. Raises ValueError If called with a masked 1D array or called with a 1D array and `wrap_around=True`. #### References `1` Miguel Arevallilo Herraez, David R. Burton, Michael J. Lalor, and Munther A. Gdeisat, β€œFast two-dimensional phase-unwrapping algorithm based on sorting by reliability following a noncontinuous path”, Journal Applied Optics, Vol. 41, No. 35 (2002) 7437, `2` Abdul-Rahman, H., Gdeisat, M., Burton, D., & Lalor, M., β€œFast three-dimensional phase-unwrapping algorithm based on sorting by reliability following a non-continuous path. In W. Osten, C. Gorecki, & E. L. Novak (Eds.), Optical Metrology (2005) 32–40, International Society for Optics and Photonics. #### Examples ``` >>> c0, c1 = np.ogrid[-1:1:128j, -1:1:128j] >>> image = 12 * np.pi * np.exp(-(c0**2 + c1**2)) >>> image_wrapped = np.angle(np.exp(1j * image)) >>> image_unwrapped = unwrap_phase(image_wrapped) >>> np.std(image_unwrapped - image) < 1e-6 # A constant offset is normal True ``` ### Examples using `skimage.restoration.unwrap_phase` [Phase Unwrapping](https://scikit-image.org/docs/0.18.x/auto_examples/filters/plot_phase_unwrap.html#sphx-glr-auto-examples-filters-plot-phase-unwrap-py) wiener ------ `skimage.restoration.wiener(image, psf, balance, reg=None, is_real=True, clip=True)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/restoration/deconvolution.py#L13-L137) Wiener-Hunt deconvolution Return the deconvolution with a Wiener-Hunt approach (i.e. with Fourier diagonalisation). Parameters `image(M, N) ndarray` Input degraded image `psfndarray` Point Spread Function. This is assumed to be the impulse response (input image space) if the data-type is real, or the transfer function (Fourier space) if the data-type is complex. There is no constraints on the shape of the impulse response. The transfer function must be of shape `(M, N)` if `is_real is True`, `(M, N // 2 + 1)` otherwise (see `np.fft.rfftn`). `balancefloat` The regularisation parameter value that tunes the balance between the data adequacy that improve frequency restoration and the prior adequacy that reduce frequency restoration (to avoid noise artifacts). `regndarray, optional` The regularisation operator. The Laplacian by default. It can be an impulse response or a transfer function, as for the psf. Shape constraint is the same as for the `psf` parameter. `is_realboolean, optional` True by default. Specify if `psf` and `reg` are provided with hermitian hypothesis, that is only half of the frequency plane is provided (due to the redundancy of Fourier transform of real signal). It’s apply only if `psf` and/or `reg` are provided as transfer function. For the hermitian property see `uft` module or `np.fft.rfftn`. `clipboolean, optional` True by default. If True, pixel values of the result above 1 or under -1 are thresholded for skimage pipeline compatibility. Returns `im_deconv(M, N) ndarray` The deconvolved image. #### Notes This function applies the Wiener filter to a noisy and degraded image by an impulse response (or PSF). If the data model is \[y = Hx + n\] where \(n\) is noise, \(H\) the PSF and \(x\) the unknown original image, the Wiener filter is \[\hat x = F^\dagger (|\Lambda\_H|^2 + \lambda |\Lambda\_D|^2) \Lambda\_H^\dagger F y\] where \(F\) and \(F^\dagger\) are the Fourier and inverse Fourier transforms respectively, \(\Lambda\_H\) the transfer function (or the Fourier transform of the PSF, see [Hunt] below) and \(\Lambda\_D\) the filter to penalize the restored image frequencies (Laplacian by default, that is penalization of high frequency). The parameter \(\lambda\) tunes the balance between the data (that tends to increase high frequency, even those coming from noise), and the regularization. These methods are then specific to a prior model. Consequently, the application or the true image nature must corresponds to the prior model. By default, the prior model (Laplacian) introduce image smoothness or pixel correlation. It can also be interpreted as high-frequency penalization to compensate the instability of the solution with respect to the data (sometimes called noise amplification or β€œexplosive” solution). Finally, the use of Fourier space implies a circulant property of \(H\), see [Hunt]. #### References `1` FranΓ§ois Orieux, Jean-FranΓ§ois Giovannelli, and Thomas Rodet, β€œBayesian estimation of regularization and point spread function parameters for Wiener-Hunt deconvolution”, J. Opt. Soc. Am. A 27, 1593-1607 (2010) <https://www.osapublishing.org/josaa/abstract.cfm?URI=josaa-27-7-1593> <http://research.orieux.fr/files/papers/OGR-JOSA10.pdf> `2` B. R. Hunt β€œA matrix theory proof of the discrete convolution theorem”, IEEE Trans. on Audio and Electroacoustics, vol. au-19, no. 4, pp. 285-288, dec. 1971 #### Examples ``` >>> from skimage import color, data, restoration >>> img = color.rgb2gray(data.astronaut()) >>> from scipy.signal import convolve2d >>> psf = np.ones((5, 5)) / 25 >>> img = convolve2d(img, psf, 'same') >>> img += 0.1 * img.std() * np.random.standard_normal(img.shape) >>> deconvolved_img = restoration.wiener(img, psf, 1100) ```
programming_docs
scikit_image Module: measure Module: measure =============== | | | | --- | --- | | [`skimage.measure.approximate_polygon`](#skimage.measure.approximate_polygon "skimage.measure.approximate_polygon")(coords, …) | Approximate a polygonal chain with the specified tolerance. | | [`skimage.measure.block_reduce`](#skimage.measure.block_reduce "skimage.measure.block_reduce")(image, block\_size) | Downsample image by applying function `func` to local blocks. | | [`skimage.measure.euler_number`](#skimage.measure.euler_number "skimage.measure.euler_number")(image[, …]) | Calculate the Euler characteristic in binary image. | | [`skimage.measure.find_contours`](#skimage.measure.find_contours "skimage.measure.find_contours")(image[, …]) | Find iso-valued contours in a 2D array for a given level value. | | [`skimage.measure.grid_points_in_poly`](#skimage.measure.grid_points_in_poly "skimage.measure.grid_points_in_poly")(shape, verts) | Test whether points on a specified grid are inside a polygon. | | [`skimage.measure.inertia_tensor`](#skimage.measure.inertia_tensor "skimage.measure.inertia_tensor")(image[, mu]) | Compute the inertia tensor of the input image. | | [`skimage.measure.inertia_tensor_eigvals`](#skimage.measure.inertia_tensor_eigvals "skimage.measure.inertia_tensor_eigvals")(image) | Compute the eigenvalues of the inertia tensor of the image. | | [`skimage.measure.label`](#skimage.measure.label "skimage.measure.label")(input[, background, …]) | Label connected regions of an integer array. | | [`skimage.measure.marching_cubes`](#skimage.measure.marching_cubes "skimage.measure.marching_cubes")(volume[, …]) | Marching cubes algorithm to find surfaces in 3d volumetric data. | | [`skimage.measure.marching_cubes_classic`](#skimage.measure.marching_cubes_classic "skimage.measure.marching_cubes_classic")(volume) | Classic marching cubes algorithm to find surfaces in 3d volumetric data. | | [`skimage.measure.marching_cubes_lewiner`](#skimage.measure.marching_cubes_lewiner "skimage.measure.marching_cubes_lewiner")(volume) | Lewiner marching cubes algorithm to find surfaces in 3d volumetric data. | | [`skimage.measure.mesh_surface_area`](#skimage.measure.mesh_surface_area "skimage.measure.mesh_surface_area")(verts, faces) | Compute surface area, given vertices & triangular faces | | [`skimage.measure.moments`](#skimage.measure.moments "skimage.measure.moments")(image[, order]) | Calculate all raw image moments up to a certain order. | | [`skimage.measure.moments_central`](#skimage.measure.moments_central "skimage.measure.moments_central")(image[, …]) | Calculate all central image moments up to a certain order. | | [`skimage.measure.moments_coords`](#skimage.measure.moments_coords "skimage.measure.moments_coords")(coords[, order]) | Calculate all raw image moments up to a certain order. | | [`skimage.measure.moments_coords_central`](#skimage.measure.moments_coords_central "skimage.measure.moments_coords_central")(coords) | Calculate all central image moments up to a certain order. | | [`skimage.measure.moments_hu`](#skimage.measure.moments_hu "skimage.measure.moments_hu")(nu) | Calculate Hu’s set of image moments (2D-only). | | [`skimage.measure.moments_normalized`](#skimage.measure.moments_normalized "skimage.measure.moments_normalized")(mu[, order]) | Calculate all normalized central image moments up to a certain order. | | [`skimage.measure.perimeter`](#skimage.measure.perimeter "skimage.measure.perimeter")(image[, neighbourhood]) | Calculate total perimeter of all objects in binary image. | | [`skimage.measure.perimeter_crofton`](#skimage.measure.perimeter_crofton "skimage.measure.perimeter_crofton")(image[, …]) | Calculate total Crofton perimeter of all objects in binary image. | | [`skimage.measure.points_in_poly`](#skimage.measure.points_in_poly "skimage.measure.points_in_poly")(points, verts) | Test whether points lie inside a polygon. | | [`skimage.measure.profile_line`](#skimage.measure.profile_line "skimage.measure.profile_line")(image, src, dst) | Return the intensity profile of an image measured along a scan line. | | [`skimage.measure.ransac`](#skimage.measure.ransac "skimage.measure.ransac")(data, model\_class, …) | Fit a model to data with the RANSAC (random sample consensus) algorithm. | | [`skimage.measure.regionprops`](#skimage.measure.regionprops "skimage.measure.regionprops")(label\_image[, …]) | Measure properties of labeled image regions. | | [`skimage.measure.regionprops_table`](#skimage.measure.regionprops_table "skimage.measure.regionprops_table")(label\_image) | Compute image properties and return them as a pandas-compatible table. | | [`skimage.measure.shannon_entropy`](#skimage.measure.shannon_entropy "skimage.measure.shannon_entropy")(image[, base]) | Calculate the Shannon entropy of an image. | | [`skimage.measure.subdivide_polygon`](#skimage.measure.subdivide_polygon "skimage.measure.subdivide_polygon")(coords[, …]) | Subdivision of polygonal curves using B-Splines. | | [`skimage.measure.CircleModel`](#skimage.measure.CircleModel "skimage.measure.CircleModel")() | Total least squares estimator for 2D circles. | | [`skimage.measure.EllipseModel`](#skimage.measure.EllipseModel "skimage.measure.EllipseModel")() | Total least squares estimator for 2D ellipses. | | [`skimage.measure.LineModelND`](#skimage.measure.LineModelND "skimage.measure.LineModelND")() | Total least squares estimator for N-dimensional lines. | approximate\_polygon -------------------- `skimage.measure.approximate_polygon(coords, tolerance)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/_polygon.py#L5-L92) Approximate a polygonal chain with the specified tolerance. It is based on the Douglas-Peucker algorithm. Note that the approximated polygon is always within the convex hull of the original polygon. Parameters `coords(N, 2) array` Coordinate array. `tolerancefloat` Maximum distance from original points of polygon to approximated polygonal chain. If tolerance is 0, the original coordinate array is returned. Returns `coords(M, 2) array` Approximated polygonal chain where M <= N. #### References `1` <https://en.wikipedia.org/wiki/Ramer-Douglas-Peucker_algorithm> block\_reduce ------------- `skimage.measure.block_reduce(image, block_size, func=<function sum>, cval=0, func_kwargs=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/block.py#L5-L87) Downsample image by applying function `func` to local blocks. This function is useful for max and mean pooling, for example. Parameters `imagendarray` N-dimensional input image. `block_sizearray_like` Array containing down-sampling integer factor along each axis. `funccallable` Function object which is used to calculate the return value for each local block. This function must implement an `axis` parameter. Primary functions are `numpy.sum`, `numpy.min`, `numpy.max`, `numpy.mean` and `numpy.median`. See also `func_kwargs`. `cvalfloat` Constant padding value if image is not perfectly divisible by the block size. `func_kwargsdict` Keyword arguments passed to `func`. Notably useful for passing dtype argument to `np.mean`. Takes dictionary of inputs, e.g.: `func_kwargs={'dtype': np.float16})`. Returns `imagendarray` Down-sampled image with same number of dimensions as input image. #### Examples ``` >>> from skimage.measure import block_reduce >>> image = np.arange(3*3*4).reshape(3, 3, 4) >>> image array([[[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]], [[12, 13, 14, 15], [16, 17, 18, 19], [20, 21, 22, 23]], [[24, 25, 26, 27], [28, 29, 30, 31], [32, 33, 34, 35]]]) >>> block_reduce(image, block_size=(3, 3, 1), func=np.mean) array([[[16., 17., 18., 19.]]]) >>> image_max1 = block_reduce(image, block_size=(1, 3, 4), func=np.max) >>> image_max1 array([[[11]], [[23]], [[35]]]) >>> image_max2 = block_reduce(image, block_size=(3, 1, 4), func=np.max) >>> image_max2 array([[[27], [31], [35]]]) ``` euler\_number ------------- `skimage.measure.euler_number(image, connectivity=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/_regionprops_utils.py#L58-L183) Calculate the Euler characteristic in binary image. For 2D objects, the Euler number is the number of objects minus the number of holes. For 3D objects, the Euler number is obtained as the number of objects plus the number of holes, minus the number of tunnels, or loops. Parameters **image: (N, M) ndarray or (N, M, D) ndarray.** 2D or 3D images. If image is not binary, all values strictly greater than zero are considered as the object. `connectivityint, optional` Maximum number of orthogonal hops to consider a pixel/voxel as a neighbor. Accepted values are ranging from 1 to input.ndim. If `None`, a full connectivity of `input.ndim` is used. 4 or 8 neighborhoods are defined for 2D images (connectivity 1 and 2, respectively). 6 or 26 neighborhoods are defined for 3D images, (connectivity 1 and 3, respectively). Connectivity 2 is not defined. Returns `euler_numberint` Euler characteristic of the set of all objects in the image. #### Notes The Euler characteristic is an integer number that describes the topology of the set of all objects in the input image. If object is 4-connected, then background is 8-connected, and conversely. The computation of the Euler characteristic is based on an integral geometry formula in discretized space. In practice, a neighbourhood configuration is constructed, and a LUT is applied for each configuration. The coefficients used are the ones of Ohser et al. It can be useful to compute the Euler characteristic for several connectivities. A large relative difference between results for different connectivities suggests that the image resolution (with respect to the size of objects and holes) is too low. #### References `1` S. Rivollier. Analyse d’image geometrique et morphometrique par diagrammes de forme et voisinages adaptatifs generaux. PhD thesis, 2010. Ecole Nationale Superieure des Mines de Saint-Etienne. <https://tel.archives-ouvertes.fr/tel-00560838> `2` Ohser J., Nagel W., Schladitz K. (2002) The Euler Number of Discretized Sets - On the Choice of Adjacency in Homogeneous Lattices. In: Mecke K., Stoyan D. (eds) Morphology of Condensed Matter. Lecture Notes in Physics, vol 600. Springer, Berlin, Heidelberg. #### Examples ``` >>> import numpy as np >>> SAMPLE = np.zeros((100,100,100)); >>> SAMPLE[40:60, 40:60, 40:60]=1 >>> euler_number(SAMPLE) 1... >>> SAMPLE[45:55,45:55,45:55] = 0; >>> euler_number(SAMPLE) 2... >>> SAMPLE = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0], ... [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0], ... [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0], ... [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0], ... [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0], ... [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], ... [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], ... [1, 0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 1, 1, 0], ... [0, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 1, 1, 1, 1], ... [0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1]]) >>> euler_number(SAMPLE) # doctest: 0 >>> euler_number(SAMPLE, connectivity=1) # doctest: 2 ``` ### Examples using `skimage.measure.euler_number` [Euler number](https://scikit-image.org/docs/0.18.x/auto_examples/segmentation/plot_euler_number.html#sphx-glr-auto-examples-segmentation-plot-euler-number-py) find\_contours -------------- `skimage.measure.find_contours(image, level=None, fully_connected='low', positive_orientation='low', *, mask=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/_find_contours.py#L11-L154) Find iso-valued contours in a 2D array for a given level value. Uses the β€œmarching squares” method to compute a the iso-valued contours of the input 2D array for a particular level value. Array values are linearly interpolated to provide better precision for the output contours. Parameters `image2D ndarray of double` Input image in which to find contours. `levelfloat, optional` Value along which to find contours in the array. By default, the level is set to (max(image) + min(image)) / 2 Changed in version 0.18: This parameter is now optional. `fully_connectedstr, {β€˜low’, β€˜high’}` Indicates whether array elements below the given level value are to be considered fully-connected (and hence elements above the value will only be face connected), or vice-versa. (See notes below for details.) `positive_orientationstr, {β€˜low’, β€˜high’}` Indicates whether the output contours will produce positively-oriented polygons around islands of low- or high-valued elements. If β€˜low’ then contours will wind counter- clockwise around elements below the iso-value. Alternately, this means that low-valued elements are always on the left of the contour. (See below for details.) `mask2D ndarray of bool, or None` A boolean mask, True where we want to draw contours. Note that NaN values are always excluded from the considered region (`mask` is set to `False` wherever `array` is `NaN`). Returns `contourslist of (n,2)-ndarrays` Each contour is an ndarray of shape `(n, 2)`, consisting of n `(row, column)` coordinates along the contour. See also [`skimage.measure.marching_cubes`](#skimage.measure.marching_cubes "skimage.measure.marching_cubes") #### Notes The marching squares algorithm is a special case of the marching cubes algorithm [[1]](#r8ed60f468bf9-1). A simple explanation is available here: <http://users.polytech.unice.fr/~lingrand/MarchingCubes/algo.html> There is a single ambiguous case in the marching squares algorithm: when a given `2 x 2`-element square has two high-valued and two low-valued elements, each pair diagonally adjacent. (Where high- and low-valued is with respect to the contour value sought.) In this case, either the high-valued elements can be β€˜connected together’ via a thin isthmus that separates the low-valued elements, or vice-versa. When elements are connected together across a diagonal, they are considered β€˜fully connected’ (also known as β€˜face+vertex-connected’ or β€˜8-connected’). Only high-valued or low-valued elements can be fully-connected, the other set will be considered as β€˜face-connected’ or β€˜4-connected’. By default, low-valued elements are considered fully-connected; this can be altered with the β€˜fully\_connected’ parameter. Output contours are not guaranteed to be closed: contours which intersect the array edge or a masked-off region (either where mask is False or where array is NaN) will be left open. All other contours will be closed. (The closed-ness of a contours can be tested by checking whether the beginning point is the same as the end point.) Contours are oriented. By default, array values lower than the contour value are to the left of the contour and values greater than the contour value are to the right. This means that contours will wind counter-clockwise (i.e. in β€˜positive orientation’) around islands of low-valued pixels. This behavior can be altered with the β€˜positive\_orientation’ parameter. The order of the contours in the output list is determined by the position of the smallest `x,y` (in lexicographical order) coordinate in the contour. This is a side-effect of how the input array is traversed, but can be relied upon. Warning Array coordinates/values are assumed to refer to the *center* of the array element. Take a simple example input: `[0, 1]`. The interpolated position of 0.5 in this array is midway between the 0-element (at `x=0`) and the 1-element (at `x=1`), and thus would fall at `x=0.5`. This means that to find reasonable contours, it is best to find contours midway between the expected β€œlight” and β€œdark” values. In particular, given a binarized array, *do not* choose to find contours at the low or high value of the array. This will often yield degenerate contours, especially around structures that are a single array element wide. Instead choose a middle value, as above. #### References `1` Lorensen, William and Harvey E. Cline. Marching Cubes: A High Resolution 3D Surface Construction Algorithm. Computer Graphics (SIGGRAPH 87 Proceedings) 21(4) July 1987, p. 163-170). [DOI:10.1145/37401.37422](https://doi.org/10.1145/37401.37422) #### Examples ``` >>> a = np.zeros((3, 3)) >>> a[0, 0] = 1 >>> a array([[1., 0., 0.], [0., 0., 0.], [0., 0., 0.]]) >>> find_contours(a, 0.5) [array([[0. , 0.5], [0.5, 0. ]])] ``` ### Examples using `skimage.measure.find_contours` [Contour finding](https://scikit-image.org/docs/0.18.x/auto_examples/edges/plot_contours.html#sphx-glr-auto-examples-edges-plot-contours-py) [Measure region properties](https://scikit-image.org/docs/0.18.x/auto_examples/segmentation/plot_regionprops.html#sphx-glr-auto-examples-segmentation-plot-regionprops-py) grid\_points\_in\_poly ---------------------- `skimage.measure.grid_points_in_poly(shape, verts)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/pnpoly.py#L4-L29) Test whether points on a specified grid are inside a polygon. For each `(r, c)` coordinate on a grid, i.e. `(0, 0)`, `(0, 1)` etc., test whether that point lies inside a polygon. Parameters `shapetuple (M, N)` Shape of the grid. `verts(V, 2) array` Specify the V vertices of the polygon, sorted either clockwise or anti-clockwise. The first point may (but does not need to be) duplicated. Returns `mask(M, N) ndarray of bool` True where the grid falls inside the polygon. See also [`points_in_poly`](#skimage.measure.points_in_poly "skimage.measure.points_in_poly") inertia\_tensor --------------- `skimage.measure.inertia_tensor(image, mu=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/_moments.py#L379-L428) Compute the inertia tensor of the input image. Parameters `imagearray` The input image. `muarray, optional` The pre-computed central moments of `image`. The inertia tensor computation requires the central moments of the image. If an application requires both the central moments and the inertia tensor (for example, [`skimage.measure.regionprops`](#skimage.measure.regionprops "skimage.measure.regionprops")), then it is more efficient to pre-compute them and pass them to the inertia tensor call. Returns `Tarray, shape (image.ndim, image.ndim)` The inertia tensor of the input image. \(T\_{i, j}\) contains the covariance of image intensity along axes \(i\) and \(j\). #### References `1` <https://en.wikipedia.org/wiki/Moment_of_inertia#Inertia_tensor> `2` Bernd JΓ€hne. Spatio-Temporal Image Processing: Theory and Scientific Applications. (Chapter 8: Tensor Methods) Springer, 1993. inertia\_tensor\_eigvals ------------------------ `skimage.measure.inertia_tensor_eigvals(image, mu=None, T=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/_moments.py#L431-L469) Compute the eigenvalues of the inertia tensor of the image. The inertia tensor measures covariance of the image intensity along the image axes. (See [`inertia_tensor`](#skimage.measure.inertia_tensor "skimage.measure.inertia_tensor").) The relative magnitude of the eigenvalues of the tensor is thus a measure of the elongation of a (bright) object in the image. Parameters `imagearray` The input image. `muarray, optional` The pre-computed central moments of `image`. `Tarray, shape (image.ndim, image.ndim)` The pre-computed inertia tensor. If `T` is given, `mu` and `image` are ignored. Returns `eigvalslist of float, length image.ndim` The eigenvalues of the inertia tensor of `image`, in descending order. #### Notes Computing the eigenvalues requires the inertia tensor of the input image. This is much faster if the central moments (`mu`) are provided, or, alternatively, one can provide the inertia tensor (`T`) directly. label ----- `skimage.measure.label(input, background=None, return_num=False, connectivity=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/_label.py#L32-L120) Label connected regions of an integer array. Two pixels are connected when they are neighbors and have the same value. In 2D, they can be neighbors either in a 1- or 2-connected sense. The value refers to the maximum number of orthogonal hops to consider a pixel/voxel a neighbor: ``` 1-connectivity 2-connectivity diagonal connection close-up [ ] [ ] [ ] [ ] [ ] | \ | / | <- hop 2 [ ]--[x]--[ ] [ ]--[x]--[ ] [x]--[ ] | / | \ hop 1 [ ] [ ] [ ] [ ] ``` Parameters `inputndarray of dtype int` Image to label. `backgroundint, optional` Consider all pixels with this value as background pixels, and label them as 0. By default, 0-valued pixels are considered as background pixels. `return_numbool, optional` Whether to return the number of assigned labels. `connectivityint, optional` Maximum number of orthogonal hops to consider a pixel/voxel as a neighbor. Accepted values are ranging from 1 to input.ndim. If `None`, a full connectivity of `input.ndim` is used. Returns `labelsndarray of dtype int` Labeled array, where all connected regions are assigned the same integer value. `numint, optional` Number of labels, which equals the maximum label index and is only returned if return\_num is `True`. See also [`regionprops`](#skimage.measure.regionprops "skimage.measure.regionprops") [`regionprops_table`](#skimage.measure.regionprops_table "skimage.measure.regionprops_table") #### References `1` Christophe Fiorio and Jens Gustedt, β€œTwo linear time Union-Find strategies for image processing”, Theoretical Computer Science 154 (1996), pp. 165-181. `2` Kensheng Wu, Ekow Otoo and Arie Shoshani, β€œOptimizing connected component labeling algorithms”, Paper LBNL-56864, 2005, Lawrence Berkeley National Laboratory (University of California), <http://repositories.cdlib.org/lbnl/LBNL-56864> #### Examples ``` >>> import numpy as np >>> x = np.eye(3).astype(int) >>> print(x) [[1 0 0] [0 1 0] [0 0 1]] >>> print(label(x, connectivity=1)) [[1 0 0] [0 2 0] [0 0 3]] >>> print(label(x, connectivity=2)) [[1 0 0] [0 1 0] [0 0 1]] >>> print(label(x, background=-1)) [[1 2 2] [2 1 2] [2 2 1]] >>> x = np.array([[1, 0, 0], ... [1, 1, 5], ... [0, 0, 0]]) >>> print(label(x)) [[1 0 0] [1 1 2] [0 0 0]] ``` ### Examples using `skimage.measure.label` [Measure region properties](https://scikit-image.org/docs/0.18.x/auto_examples/segmentation/plot_regionprops.html#sphx-glr-auto-examples-segmentation-plot-regionprops-py) [Euler number](https://scikit-image.org/docs/0.18.x/auto_examples/segmentation/plot_euler_number.html#sphx-glr-auto-examples-segmentation-plot-euler-number-py) [Segment human cells (in mitosis)](https://scikit-image.org/docs/0.18.x/auto_examples/applications/plot_human_mitosis.html#sphx-glr-auto-examples-applications-plot-human-mitosis-py) marching\_cubes --------------- `skimage.measure.marching_cubes(volume, level=None, *, spacing=(1.0, 1.0, 1.0), gradient_direction='descent', step_size=1, allow_degenerate=True, method='lewiner', mask=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/_marching_cubes_lewiner.py#L11-L153) Marching cubes algorithm to find surfaces in 3d volumetric data. In contrast with Lorensen et al. approach [[2]](#rcddcc8f5d58b-2), Lewiner et al. algorithm is faster, resolves ambiguities, and guarantees topologically correct results. Therefore, this algorithm generally a better choice. Parameters `volume(M, N, P) array` Input data volume to find isosurfaces. Will internally be converted to float32 if necessary. `levelfloat, optional` Contour value to search for isosurfaces in `volume`. If not given or None, the average of the min and max of vol is used. `spacinglength-3 tuple of floats, optional` Voxel spacing in spatial dimensions corresponding to numpy array indexing dimensions (M, N, P) as in `volume`. `gradient_directionstring, optional` Controls if the mesh was generated from an isosurface with gradient descent toward objects of interest (the default), or the opposite, considering the *left-hand* rule. The two options are: \* descent : Object was greater than exterior \* ascent : Exterior was greater than object `step_sizeint, optional` Step size in voxels. Default 1. Larger steps yield faster but coarser results. The result will always be topologically correct though. `allow_degeneratebool, optional` Whether to allow degenerate (i.e. zero-area) triangles in the end-result. Default True. If False, degenerate triangles are removed, at the cost of making the algorithm slower. **method: str, optional** One of β€˜lewiner’, β€˜lorensen’ or β€˜\_lorensen’. Specify witch of Lewiner et al. or Lorensen et al. method will be used. The β€˜\_lorensen’ flag correspond to an old implementation that will be deprecated in version 0.19. `mask(M, N, P) array, optional` Boolean array. The marching cube algorithm will be computed only on True elements. This will save computational time when interfaces are located within certain region of the volume M, N, P-e.g. the top half of the cube-and also allow to compute finite surfaces-i.e. open surfaces that do not end at the border of the cube. Returns `verts(V, 3) array` Spatial coordinates for V unique mesh vertices. Coordinate order matches input `volume` (M, N, P). If `allow_degenerate` is set to True, then the presence of degenerate triangles in the mesh can make this array have duplicate vertices. `faces(F, 3) array` Define triangular faces via referencing vertex indices from `verts`. This algorithm specifically outputs triangles, so each face has exactly three indices. `normals(V, 3) array` The normal direction at each vertex, as calculated from the data. `values(V, ) array` Gives a measure for the maximum value of the data in the local region near each vertex. This can be used by visualization tools to apply a colormap to the mesh. See also [`skimage.measure.mesh_surface_area`](#skimage.measure.mesh_surface_area "skimage.measure.mesh_surface_area") [`skimage.measure.find_contours`](#skimage.measure.find_contours "skimage.measure.find_contours") #### Notes The algorithm [[1]](#rcddcc8f5d58b-1) is an improved version of Chernyaev’s Marching Cubes 33 algorithm. It is an efficient algorithm that relies on heavy use of lookup tables to handle the many different cases, keeping the algorithm relatively easy. This implementation is written in Cython, ported from Lewiner’s C++ implementation. To quantify the area of an isosurface generated by this algorithm, pass verts and faces to [`skimage.measure.mesh_surface_area`](#skimage.measure.mesh_surface_area "skimage.measure.mesh_surface_area"). Regarding visualization of algorithm output, to contour a volume named `myvolume` about the level 0.0, using the `mayavi` package: ``` >>> >> from mayavi import mlab >> verts, faces, _, _ = marching_cubes(myvolume, 0.0) >> mlab.triangular_mesh([vert[0] for vert in verts], [vert[1] for vert in verts], [vert[2] for vert in verts], faces) >> mlab.show() ``` Similarly using the `visvis` package: ``` >>> >> import visvis as vv >> verts, faces, normals, values = marching_cubes(myvolume, 0.0) >> vv.mesh(np.fliplr(verts), faces, normals, values) >> vv.use().Run() ``` To reduce the number of triangles in the mesh for better performance, see this [example](https://docs.enthought.com/mayavi/mayavi/auto/example_julia_set_decimation.html#example-julia-set-decimation) using the `mayavi` package. #### References `1` Thomas Lewiner, Helio Lopes, Antonio Wilson Vieira and Geovan Tavares. Efficient implementation of Marching Cubes’ cases with topological guarantees. Journal of Graphics Tools 8(2) pp. 1-15 (december 2003). [DOI:10.1080/10867651.2003.10487582](https://doi.org/10.1080/10867651.2003.10487582) `2` Lorensen, William and Harvey E. Cline. Marching Cubes: A High Resolution 3D Surface Construction Algorithm. Computer Graphics (SIGGRAPH 87 Proceedings) 21(4) July 1987, p. 163-170). [DOI:10.1145/37401.37422](https://doi.org/10.1145/37401.37422) marching\_cubes\_classic ------------------------ `skimage.measure.marching_cubes_classic(volume, level=None, spacing=(1.0, 1.0, 1.0), gradient_direction='descent')` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/_marching_cubes_classic.py#L7-L111) Classic marching cubes algorithm to find surfaces in 3d volumetric data. Note that the `marching_cubes()` algorithm is recommended over this algorithm, because it’s faster and produces better results. Parameters `volume(M, N, P) array of doubles` Input data volume to find isosurfaces. Will be cast to `np.float64`. `levelfloat` Contour value to search for isosurfaces in `volume`. If not given or None, the average of the min and max of vol is used. `spacinglength-3 tuple of floats` Voxel spacing in spatial dimensions corresponding to numpy array indexing dimensions (M, N, P) as in `volume`. `gradient_directionstring` Controls if the mesh was generated from an isosurface with gradient descent toward objects of interest (the default), or the opposite. The two options are: \* descent : Object was greater than exterior \* ascent : Exterior was greater than object Returns `verts(V, 3) array` Spatial coordinates for V unique mesh vertices. Coordinate order matches input `volume` (M, N, P). If `allow_degenerate` is set to True, then the presence of degenerate triangles in the mesh can make this array have duplicate vertices. `faces(F, 3) array` Define triangular faces via referencing vertex indices from `verts`. This algorithm specifically outputs triangles, so each face has exactly three indices. See also [`skimage.measure.marching_cubes`](#skimage.measure.marching_cubes "skimage.measure.marching_cubes") [`skimage.measure.mesh_surface_area`](#skimage.measure.mesh_surface_area "skimage.measure.mesh_surface_area") #### Notes The marching cubes algorithm is implemented as described in [[1]](#r1e43a330a523-1). A simple explanation is available here: ``` http://users.polytech.unice.fr/~lingrand/MarchingCubes/algo.html ``` There are several known ambiguous cases in the marching cubes algorithm. Using point labeling as in [[1]](#r1e43a330a523-1), Figure 4, as shown: ``` v8 ------ v7 / | / | y / | / | ^ z v4 ------ v3 | | / | v5 ----|- v6 |/ (note: NOT right handed!) | / | / ----> x | / | / v1 ------ v2 ``` Most notably, if v4, v8, v2, and v6 are all >= `level` (or any generalization of this case) two parallel planes are generated by this algorithm, separating v4 and v8 from v2 and v6. An equally valid interpretation would be a single connected thin surface enclosing all four points. This is the best known ambiguity, though there are others. This algorithm does not attempt to resolve such ambiguities; it is a naive implementation of marching cubes as in [[1]](#r1e43a330a523-1), but may be a good beginning for work with more recent techniques (Dual Marching Cubes, Extended Marching Cubes, Cubic Marching Squares, etc.). Because of interactions between neighboring cubes, the isosurface(s) generated by this algorithm are NOT guaranteed to be closed, particularly for complicated contours. Furthermore, this algorithm does not guarantee a single contour will be returned. Indeed, ALL isosurfaces which cross `level` will be found, regardless of connectivity. The output is a triangular mesh consisting of a set of unique vertices and connecting triangles. The order of these vertices and triangles in the output list is determined by the position of the smallest `x,y,z` (in lexicographical order) coordinate in the contour. This is a side-effect of how the input array is traversed, but can be relied upon. The generated mesh guarantees coherent orientation as of version 0.12. To quantify the area of an isosurface generated by this algorithm, pass outputs directly into [`skimage.measure.mesh_surface_area`](#skimage.measure.mesh_surface_area "skimage.measure.mesh_surface_area"). #### References `1(1,2,3)` Lorensen, William and Harvey E. Cline. Marching Cubes: A High Resolution 3D Surface Construction Algorithm. Computer Graphics (SIGGRAPH 87 Proceedings) 21(4) July 1987, p. 163-170). [DOI:10.1145/37401.37422](https://doi.org/10.1145/37401.37422) marching\_cubes\_lewiner ------------------------ `skimage.measure.marching_cubes_lewiner(volume, level=None, spacing=(1.0, 1.0, 1.0), gradient_direction='descent', step_size=1, allow_degenerate=True, use_classic=False, mask=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/_marching_cubes_lewiner.py#L156-L277) Lewiner marching cubes algorithm to find surfaces in 3d volumetric data. In contrast to `marching_cubes_classic()`, this algorithm is faster, resolves ambiguities, and guarantees topologically correct results. Therefore, this algorithm generally a better choice, unless there is a specific need for the classic algorithm. Parameters `volume(M, N, P) array` Input data volume to find isosurfaces. Will internally be converted to float32 if necessary. `levelfloat` Contour value to search for isosurfaces in `volume`. If not given or None, the average of the min and max of vol is used. `spacinglength-3 tuple of floats` Voxel spacing in spatial dimensions corresponding to numpy array indexing dimensions (M, N, P) as in `volume`. `gradient_directionstring` Controls if the mesh was generated from an isosurface with gradient descent toward objects of interest (the default), or the opposite, considering the *left-hand* rule. The two options are: \* descent : Object was greater than exterior \* ascent : Exterior was greater than object `step_sizeint` Step size in voxels. Default 1. Larger steps yield faster but coarser results. The result will always be topologically correct though. `allow_degeneratebool` Whether to allow degenerate (i.e. zero-area) triangles in the end-result. Default True. If False, degenerate triangles are removed, at the cost of making the algorithm slower. `use_classicbool` If given and True, the classic marching cubes by Lorensen (1987) is used. This option is included for reference purposes. Note that this algorithm has ambiguities and is not guaranteed to produce a topologically correct result. The results with using this option are *not* generally the same as the `marching_cubes_classic()` function. `mask(M, N, P) array` Boolean array. The marching cube algorithm will be computed only on True elements. This will save computational time when interfaces are located within certain region of the volume M, N, P-e.g. the top half of the cube-and also allow to compute finite surfaces-i.e. open surfaces that do not end at the border of the cube. Returns `verts(V, 3) array` Spatial coordinates for V unique mesh vertices. Coordinate order matches input `volume` (M, N, P). If `allow_degenerate` is set to True, then the presence of degenerate triangles in the mesh can make this array have duplicate vertices. `faces(F, 3) array` Define triangular faces via referencing vertex indices from `verts`. This algorithm specifically outputs triangles, so each face has exactly three indices. `normals(V, 3) array` The normal direction at each vertex, as calculated from the data. `values(V, ) array` Gives a measure for the maximum value of the data in the local region near each vertex. This can be used by visualization tools to apply a colormap to the mesh. See also [`skimage.measure.marching_cubes`](#skimage.measure.marching_cubes "skimage.measure.marching_cubes") [`skimage.measure.mesh_surface_area`](#skimage.measure.mesh_surface_area "skimage.measure.mesh_surface_area") #### Notes The algorithm [1] is an improved version of Chernyaev’s Marching Cubes 33 algorithm. It is an efficient algorithm that relies on heavy use of lookup tables to handle the many different cases, keeping the algorithm relatively easy. This implementation is written in Cython, ported from Lewiner’s C++ implementation. To quantify the area of an isosurface generated by this algorithm, pass verts and faces to [`skimage.measure.mesh_surface_area`](#skimage.measure.mesh_surface_area "skimage.measure.mesh_surface_area"). Regarding visualization of algorithm output, to contour a volume named `myvolume` about the level 0.0, using the `mayavi` package: ``` >>> from mayavi import mlab >>> verts, faces, normals, values = marching_cubes_lewiner(myvolume, 0.0) >>> mlab.triangular_mesh([vert[0] for vert in verts], ... [vert[1] for vert in verts], ... [vert[2] for vert in verts], ... faces) >>> mlab.show() ``` Similarly using the `visvis` package: ``` >>> import visvis as vv >>> verts, faces, normals, values = marching_cubes_lewiner(myvolume, 0.0) >>> vv.mesh(np.fliplr(verts), faces, normals, values) >>> vv.use().Run() ``` #### References `1` Thomas Lewiner, Helio Lopes, Antonio Wilson Vieira and Geovan Tavares. Efficient implementation of Marching Cubes’ cases with topological guarantees. Journal of Graphics Tools 8(2) pp. 1-15 (december 2003). [DOI:10.1080/10867651.2003.10487582](https://doi.org/10.1080/10867651.2003.10487582) mesh\_surface\_area ------------------- `skimage.measure.mesh_surface_area(verts, faces)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/_marching_cubes_classic.py#L157-L196) Compute surface area, given vertices & triangular faces Parameters `verts(V, 3) array of floats` Array containing (x, y, z) coordinates for V unique mesh vertices. `faces(F, 3) array of ints` List of length-3 lists of integers, referencing vertex coordinates as provided in `verts` Returns `areafloat` Surface area of mesh. Units now [coordinate units] \*\* 2. See also [`skimage.measure.marching_cubes`](#skimage.measure.marching_cubes "skimage.measure.marching_cubes") [`skimage.measure.marching_cubes_classic`](#skimage.measure.marching_cubes_classic "skimage.measure.marching_cubes_classic") #### Notes The arguments expected by this function are the first two outputs from [`skimage.measure.marching_cubes`](#skimage.measure.marching_cubes "skimage.measure.marching_cubes"). For unit correct output, ensure correct `spacing` was passed to [`skimage.measure.marching_cubes`](#skimage.measure.marching_cubes "skimage.measure.marching_cubes"). This algorithm works properly only if the `faces` provided are all triangles. moments ------- `skimage.measure.moments(image, order=3)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/_moments.py#L149-L191) Calculate all raw image moments up to a certain order. The following properties can be calculated from raw image moments: * Area as: `M[0, 0]`. * Centroid as: {`M[1, 0] / M[0, 0]`, `M[0, 1] / M[0, 0]`}. Note that raw moments are neither translation, scale nor rotation invariant. Parameters `imagenD double or uint8 array` Rasterized shape as image. `orderint, optional` Maximum order of moments. Default is 3. Returns `m(order + 1, order + 1) array` Raw image moments. #### References `1` Wilhelm Burger, Mark Burge. Principles of Digital Image Processing: Core Algorithms. Springer-Verlag, London, 2009. `2` B. JΓ€hne. Digital Image Processing. Springer-Verlag, Berlin-Heidelberg, 6. edition, 2005. `3` T. H. Reiss. Recognizing Planar Objects Using Invariant Image Features, from Lecture notes in computer science, p. 676. Springer, Berlin, 1993. `4` <https://en.wikipedia.org/wiki/Image_moment> #### Examples ``` >>> image = np.zeros((20, 20), dtype=np.double) >>> image[13:17, 13:17] = 1 >>> M = moments(image) >>> centroid = (M[1, 0] / M[0, 0], M[0, 1] / M[0, 0]) >>> centroid (14.5, 14.5) ``` moments\_central ---------------- `skimage.measure.moments_central(image, center=None, order=3, **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/_moments.py#L194-L250) Calculate all central image moments up to a certain order. The center coordinates (cr, cc) can be calculated from the raw moments as: {`M[1, 0] / M[0, 0]`, `M[0, 1] / M[0, 0]`}. Note that central moments are translation invariant but not scale and rotation invariant. Parameters `imagenD double or uint8 array` Rasterized shape as image. `centertuple of float, optional` Coordinates of the image centroid. This will be computed if it is not provided. `orderint, optional` The maximum order of moments computed. Returns `mu(order + 1, order + 1) array` Central image moments. #### References `1` Wilhelm Burger, Mark Burge. Principles of Digital Image Processing: Core Algorithms. Springer-Verlag, London, 2009. `2` B. JΓ€hne. Digital Image Processing. Springer-Verlag, Berlin-Heidelberg, 6. edition, 2005. `3` T. H. Reiss. Recognizing Planar Objects Using Invariant Image Features, from Lecture notes in computer science, p. 676. Springer, Berlin, 1993. `4` <https://en.wikipedia.org/wiki/Image_moment> #### Examples ``` >>> image = np.zeros((20, 20), dtype=np.double) >>> image[13:17, 13:17] = 1 >>> M = moments(image) >>> centroid = (M[1, 0] / M[0, 0], M[0, 1] / M[0, 0]) >>> moments_central(image, centroid) array([[16., 0., 20., 0.], [ 0., 0., 0., 0.], [20., 0., 25., 0.], [ 0., 0., 0., 0.]]) ``` moments\_coords --------------- `skimage.measure.moments_coords(coords, order=3)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/_moments.py#L7-L45) Calculate all raw image moments up to a certain order. The following properties can be calculated from raw image moments: * Area as: `M[0, 0]`. * Centroid as: {`M[1, 0] / M[0, 0]`, `M[0, 1] / M[0, 0]`}. Note that raw moments are neither translation, scale nor rotation invariant. Parameters `coords(N, D) double or uint8 array` Array of N points that describe an image of D dimensionality in Cartesian space. `orderint, optional` Maximum order of moments. Default is 3. Returns `M(order + 1, order + 1, …) array` Raw image moments. (D dimensions) #### References `1` Johannes Kilian. Simple Image Analysis By Moments. Durham University, version 0.2, Durham, 2001. #### Examples ``` >>> coords = np.array([[row, col] ... for row in range(13, 17) ... for col in range(14, 18)], dtype=np.double) >>> M = moments_coords(coords) >>> centroid = (M[1, 0] / M[0, 0], M[0, 1] / M[0, 0]) >>> centroid (14.5, 15.5) ``` moments\_coords\_central ------------------------ `skimage.measure.moments_coords_central(coords, center=None, order=3)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/_moments.py#L48-L146) Calculate all central image moments up to a certain order. The following properties can be calculated from raw image moments: * Area as: `M[0, 0]`. * Centroid as: {`M[1, 0] / M[0, 0]`, `M[0, 1] / M[0, 0]`}. Note that raw moments are neither translation, scale nor rotation invariant. Parameters `coords(N, D) double or uint8 array` Array of N points that describe an image of D dimensionality in Cartesian space. A tuple of coordinates as returned by `np.nonzero` is also accepted as input. `centertuple of float, optional` Coordinates of the image centroid. This will be computed if it is not provided. `orderint, optional` Maximum order of moments. Default is 3. Returns `Mc(order + 1, order + 1, …) array` Central image moments. (D dimensions) #### References `1` Johannes Kilian. Simple Image Analysis By Moments. Durham University, version 0.2, Durham, 2001. #### Examples ``` >>> coords = np.array([[row, col] ... for row in range(13, 17) ... for col in range(14, 18)]) >>> moments_coords_central(coords) array([[16., 0., 20., 0.], [ 0., 0., 0., 0.], [20., 0., 25., 0.], [ 0., 0., 0., 0.]]) ``` As seen above, for symmetric objects, odd-order moments (columns 1 and 3, rows 1 and 3) are zero when centered on the centroid, or center of mass, of the object (the default). If we break the symmetry by adding a new point, this no longer holds: ``` >>> coords2 = np.concatenate((coords, [[17, 17]]), axis=0) >>> np.round(moments_coords_central(coords2), ... decimals=2) array([[17. , 0. , 22.12, -2.49], [ 0. , 3.53, 1.73, 7.4 ], [25.88, 6.02, 36.63, 8.83], [ 4.15, 19.17, 14.8 , 39.6 ]]) ``` Image moments and central image moments are equivalent (by definition) when the center is (0, 0): ``` >>> np.allclose(moments_coords(coords), ... moments_coords_central(coords, (0, 0))) True ``` moments\_hu ----------- `skimage.measure.moments_hu(nu)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/_moments.py#L308-L348) Calculate Hu’s set of image moments (2D-only). Note that this set of moments is proofed to be translation, scale and rotation invariant. Parameters `nu(M, M) array` Normalized central image moments, where M must be >= 4. Returns `nu(7,) array` Hu’s set of image moments. #### References `1` M. K. Hu, β€œVisual Pattern Recognition by Moment Invariants”, IRE Trans. Info. Theory, vol. IT-8, pp. 179-187, 1962 `2` Wilhelm Burger, Mark Burge. Principles of Digital Image Processing: Core Algorithms. Springer-Verlag, London, 2009. `3` B. JΓ€hne. Digital Image Processing. Springer-Verlag, Berlin-Heidelberg, 6. edition, 2005. `4` T. H. Reiss. Recognizing Planar Objects Using Invariant Image Features, from Lecture notes in computer science, p. 676. Springer, Berlin, 1993. `5` <https://en.wikipedia.org/wiki/Image_moment> #### Examples ``` >>> image = np.zeros((20, 20), dtype=np.double) >>> image[13:17, 13:17] = 0.5 >>> image[10:12, 10:12] = 1 >>> mu = moments_central(image) >>> nu = moments_normalized(mu) >>> moments_hu(nu) array([7.45370370e-01, 3.51165981e-01, 1.04049179e-01, 4.06442107e-02, 2.64312299e-03, 2.40854582e-02, 4.33680869e-19]) ``` moments\_normalized ------------------- `skimage.measure.moments_normalized(mu, order=3)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/_moments.py#L253-L305) Calculate all normalized central image moments up to a certain order. Note that normalized central moments are translation and scale invariant but not rotation invariant. Parameters `mu(M,[ …,] M) array` Central image moments, where M must be greater than or equal to `order`. `orderint, optional` Maximum order of moments. Default is 3. Returns `nu(order + 1,[ …,] order + 1) array` Normalized central image moments. #### References `1` Wilhelm Burger, Mark Burge. Principles of Digital Image Processing: Core Algorithms. Springer-Verlag, London, 2009. `2` B. JΓ€hne. Digital Image Processing. Springer-Verlag, Berlin-Heidelberg, 6. edition, 2005. `3` T. H. Reiss. Recognizing Planar Objects Using Invariant Image Features, from Lecture notes in computer science, p. 676. Springer, Berlin, 1993. `4` <https://en.wikipedia.org/wiki/Image_moment> #### Examples ``` >>> image = np.zeros((20, 20), dtype=np.double) >>> image[13:17, 13:17] = 1 >>> m = moments(image) >>> centroid = (m[0, 1] / m[0, 0], m[1, 0] / m[0, 0]) >>> mu = moments_central(image, centroid) >>> moments_normalized(mu) array([[ nan, nan, 0.078125 , 0. ], [ nan, 0. , 0. , 0. ], [0.078125 , 0. , 0.00610352, 0. ], [0. , 0. , 0. , 0. ]]) ``` perimeter --------- `skimage.measure.perimeter(image, neighbourhood=4)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/_regionprops_utils.py#L186-L249) Calculate total perimeter of all objects in binary image. Parameters `image(N, M) ndarray` 2D binary image. `neighbourhood4 or 8, optional` Neighborhood connectivity for border pixel determination. It is used to compute the contour. A higher neighbourhood widens the border on which the perimeter is computed. Returns `perimeterfloat` Total perimeter of all objects in binary image. #### References `1` K. Benkrid, D. Crookes. Design and FPGA Implementation of a Perimeter Estimator. The Queen’s University of Belfast. <http://www.cs.qub.ac.uk/~d.crookes/webpubs/papers/perimeter.doc> #### Examples ``` >>> from skimage import data, util >>> from skimage.measure import label >>> # coins image (binary) >>> img_coins = data.coins() > 110 >>> # total perimeter of all objects in the image >>> perimeter(img_coins, neighbourhood=4) 7796.867... >>> perimeter(img_coins, neighbourhood=8) 8806.268... ``` ### Examples using `skimage.measure.perimeter` [Different perimeters](https://scikit-image.org/docs/0.18.x/auto_examples/segmentation/plot_perimeters.html#sphx-glr-auto-examples-segmentation-plot-perimeters-py) perimeter\_crofton ------------------ `skimage.measure.perimeter_crofton(image, directions=4)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/_regionprops_utils.py#L252-L328) Calculate total Crofton perimeter of all objects in binary image. Parameters `image(N, M) ndarray` 2D image. If image is not binary, all values strictly greater than zero are considered as the object. `directions2 or 4, optional` Number of directions used to approximate the Crofton perimeter. By default, 4 is used: it should be more accurate than 2. Computation time is the same in both cases. Returns `perimeterfloat` Total perimeter of all objects in binary image. #### Notes This measure is based on Crofton formula [1], which is a measure from integral geometry. It is defined for general curve length evaluation via a double integral along all directions. In a discrete space, 2 or 4 directions give a quite good approximation, 4 being more accurate than 2 for more complex shapes. Similar to [`perimeter()`](#skimage.measure.perimeter "skimage.measure.perimeter"), this function returns an approximation of the perimeter in continuous space. #### References `1` <https://en.wikipedia.org/wiki/Crofton_formula> `2` S. Rivollier. Analyse d’image geometrique et morphometrique par diagrammes de forme et voisinages adaptatifs generaux. PhD thesis, 2010. Ecole Nationale Superieure des Mines de Saint-Etienne. <https://tel.archives-ouvertes.fr/tel-00560838> #### Examples ``` >>> from skimage import data, util >>> from skimage.measure import label >>> # coins image (binary) >>> img_coins = data.coins() > 110 >>> # total perimeter of all objects in the image >>> perimeter_crofton(img_coins, directions=2) 8144.578... >>> perimeter_crofton(img_coins, directions=4) 7837.077... ``` ### Examples using `skimage.measure.perimeter_crofton` [Different perimeters](https://scikit-image.org/docs/0.18.x/auto_examples/segmentation/plot_perimeters.html#sphx-glr-auto-examples-segmentation-plot-perimeters-py) points\_in\_poly ---------------- `skimage.measure.points_in_poly(points, verts)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/pnpoly.py#L32-L53) Test whether points lie inside a polygon. Parameters `points(N, 2) array` Input points, `(x, y)`. `verts(M, 2) array` Vertices of the polygon, sorted either clockwise or anti-clockwise. The first point may (but does not need to be) duplicated. Returns `mask(N,) array of bool` True if corresponding point is inside the polygon. See also [`grid_points_in_poly`](#skimage.measure.grid_points_in_poly "skimage.measure.grid_points_in_poly") profile\_line ------------- `skimage.measure.profile_line(image, src, dst, linewidth=1, order=None, mode=None, cval=0.0, *, reduce_func=<function mean>)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/profile.py#L8-L127) Return the intensity profile of an image measured along a scan line. Parameters `imagendarray, shape (M, N[, C])` The image, either grayscale (2D array) or multichannel (3D array, where the final axis contains the channel information). `srcarray_like, shape (2, )` The coordinates of the start point of the scan line. `dstarray_like, shape (2, )` The coordinates of the end point of the scan line. The destination point is *included* in the profile, in contrast to standard numpy indexing. `linewidthint, optional` Width of the scan, perpendicular to the line `orderint in {0, 1, 2, 3, 4, 5}, optional` The order of the spline interpolation, default is 0 if image.dtype is bool and 1 otherwise. The order has to be in the range 0-5. See [`skimage.transform.warp`](skimage.transform#skimage.transform.warp "skimage.transform.warp") for detail. `mode{β€˜constant’, β€˜nearest’, β€˜reflect’, β€˜mirror’, β€˜wrap’}, optional` How to compute any values falling outside of the image. `cvalfloat, optional` If `mode` is β€˜constant’, what constant value to use outside the image. `reduce_funccallable, optional` Function used to calculate the aggregation of pixel values perpendicular to the profile\_line direction when `linewidth` > 1. If set to None the unreduced array will be returned. Returns `return_valuearray` The intensity profile along the scan line. The length of the profile is the ceil of the computed length of the scan line. #### Examples ``` >>> x = np.array([[1, 1, 1, 2, 2, 2]]) >>> img = np.vstack([np.zeros_like(x), x, x, x, np.zeros_like(x)]) >>> img array([[0, 0, 0, 0, 0, 0], [1, 1, 1, 2, 2, 2], [1, 1, 1, 2, 2, 2], [1, 1, 1, 2, 2, 2], [0, 0, 0, 0, 0, 0]]) >>> profile_line(img, (2, 1), (2, 4)) array([1., 1., 2., 2.]) >>> profile_line(img, (1, 0), (1, 6), cval=4) array([1., 1., 1., 2., 2., 2., 4.]) ``` The destination point is included in the profile, in contrast to standard numpy indexing. For example: ``` >>> profile_line(img, (1, 0), (1, 6)) # The final point is out of bounds array([1., 1., 1., 2., 2., 2., 0.]) >>> profile_line(img, (1, 0), (1, 5)) # This accesses the full first row array([1., 1., 1., 2., 2., 2.]) ``` For different reduce\_func inputs: ``` >>> profile_line(img, (1, 0), (1, 3), linewidth=3, reduce_func=np.mean) array([0.66666667, 0.66666667, 0.66666667, 1.33333333]) >>> profile_line(img, (1, 0), (1, 3), linewidth=3, reduce_func=np.max) array([1, 1, 1, 2]) >>> profile_line(img, (1, 0), (1, 3), linewidth=3, reduce_func=np.sum) array([2, 2, 2, 4]) ``` The unreduced array will be returned when `reduce_func` is None or when `reduce_func` acts on each pixel value individually. ``` >>> profile_line(img, (1, 2), (4, 2), linewidth=3, order=0, ... reduce_func=None) array([[1, 1, 2], [1, 1, 2], [1, 1, 2], [0, 0, 0]]) >>> profile_line(img, (1, 0), (1, 3), linewidth=3, reduce_func=np.sqrt) array([[1. , 1. , 0. ], [1. , 1. , 0. ], [1. , 1. , 0. ], [1.41421356, 1.41421356, 0. ]]) ``` ransac ------ `skimage.measure.ransac(data, model_class, min_samples, residual_threshold, is_data_valid=None, is_model_valid=None, max_trials=100, stop_sample_num=inf, stop_residuals_sum=0, stop_probability=1, random_state=None, initial_inliers=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/fit.py#L621-L881) Fit a model to data with the RANSAC (random sample consensus) algorithm. RANSAC is an iterative algorithm for the robust estimation of parameters from a subset of inliers from the complete data set. Each iteration performs the following tasks: 1. Select `min_samples` random samples from the original data and check whether the set of data is valid (see `is_data_valid`). 2. Estimate a model to the random subset (`model_cls.estimate(*data[random_subset]`) and check whether the estimated model is valid (see `is_model_valid`). 3. Classify all data as inliers or outliers by calculating the residuals to the estimated model (`model_cls.residuals(*data)`) - all data samples with residuals smaller than the `residual_threshold` are considered as inliers. 4. Save estimated model as best model if number of inlier samples is maximal. In case the current estimated model has the same number of inliers, it is only considered as the best model if it has less sum of residuals. These steps are performed either a maximum number of times or until one of the special stop criteria are met. The final model is estimated using all inlier samples of the previously determined best model. Parameters `data[list, tuple of] (N, …) array` Data set to which the model is fitted, where N is the number of data points and the remaining dimension are depending on model requirements. If the model class requires multiple input data arrays (e.g. source and destination coordinates of `skimage.transform.AffineTransform`), they can be optionally passed as tuple or list. Note, that in this case the functions `estimate(*data)`, `residuals(*data)`, `is_model_valid(model, *random_data)` and `is_data_valid(*random_data)` must all take each data array as separate arguments. `model_classobject` Object with the following object methods: * `success = estimate(*data)` * `residuals(*data)` where `success` indicates whether the model estimation succeeded (`True` or `None` for success, `False` for failure). `min_samplesint in range (0, N)` The minimum number of data points to fit a model to. `residual_thresholdfloat larger than 0` Maximum distance for a data point to be classified as an inlier. `is_data_validfunction, optional` This function is called with the randomly selected data before the model is fitted to it: `is_data_valid(*random_data)`. `is_model_validfunction, optional` This function is called with the estimated model and the randomly selected data: `is_model_valid(model, *random_data)`, . `max_trialsint, optional` Maximum number of iterations for random sample selection. `stop_sample_numint, optional` Stop iteration if at least this number of inliers are found. `stop_residuals_sumfloat, optional` Stop iteration if sum of residuals is less than or equal to this threshold. `stop_probabilityfloat in range [0, 1], optional` RANSAC iteration stops if at least one outlier-free set of the training data is sampled with `probability >= stop_probability`, depending on the current best model’s inlier ratio and the number of trials. This requires to generate at least N samples (trials): N >= log(1 - probability) / log(1 - e\*\*m) where the probability (confidence) is typically set to a high value such as 0.99, e is the current fraction of inliers w.r.t. the total number of samples, and m is the min\_samples value. `random_stateint, RandomState instance or None, optional` If int, random\_state is the seed used by the random number generator; If RandomState instance, random\_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. `initial_inliersarray-like of bool, shape (N,), optional` Initial samples selection for model estimation Returns `modelobject` Best model with largest consensus set. `inliers(N, ) array` Boolean mask of inliers classified as `True`. #### References `1` β€œRANSAC”, Wikipedia, <https://en.wikipedia.org/wiki/RANSAC> #### Examples Generate ellipse data without tilt and add noise: ``` >>> t = np.linspace(0, 2 * np.pi, 50) >>> xc, yc = 20, 30 >>> a, b = 5, 10 >>> x = xc + a * np.cos(t) >>> y = yc + b * np.sin(t) >>> data = np.column_stack([x, y]) >>> np.random.seed(seed=1234) >>> data += np.random.normal(size=data.shape) ``` Add some faulty data: ``` >>> data[0] = (100, 100) >>> data[1] = (110, 120) >>> data[2] = (120, 130) >>> data[3] = (140, 130) ``` Estimate ellipse model using all available data: ``` >>> model = EllipseModel() >>> model.estimate(data) True >>> np.round(model.params) array([ 72., 75., 77., 14., 1.]) ``` Estimate ellipse model using RANSAC: ``` >>> ransac_model, inliers = ransac(data, EllipseModel, 20, 3, max_trials=50) >>> abs(np.round(ransac_model.params)) array([20., 30., 5., 10., 0.]) >>> inliers array([False, False, False, False, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True], dtype=bool) >>> sum(inliers) > 40 True ``` RANSAC can be used to robustly estimate a geometric transformation. In this section, we also show how to use a proportion of the total samples, rather than an absolute number. ``` >>> from skimage.transform import SimilarityTransform >>> np.random.seed(0) >>> src = 100 * np.random.rand(50, 2) >>> model0 = SimilarityTransform(scale=0.5, rotation=1, translation=(10, 20)) >>> dst = model0(src) >>> dst[0] = (10000, 10000) >>> dst[1] = (-100, 100) >>> dst[2] = (50, 50) >>> ratio = 0.5 # use half of the samples >>> min_samples = int(ratio * len(src)) >>> model, inliers = ransac((src, dst), SimilarityTransform, min_samples, 10, ... initial_inliers=np.ones(len(src), dtype=bool)) >>> inliers array([False, False, False, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True, True]) ``` regionprops ----------- `skimage.measure.regionprops(label_image, intensity_image=None, cache=True, coordinates=None, *, extra_properties=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/_regionprops.py#L867-L1159) Measure properties of labeled image regions. Parameters `label_image(M, N[, P]) ndarray` Labeled input image. Labels with value 0 are ignored. Changed in version 0.14.1: Previously, `label_image` was processed by `numpy.squeeze` and so any number of singleton dimensions was allowed. This resulted in inconsistent handling of images with singleton dimensions. To recover the old behaviour, use `regionprops(np.squeeze(label_image), ...)`. `intensity_image(M, N[, P][, C]) ndarray, optional` Intensity (i.e., input) image with same size as labeled image, plus optionally an extra dimension for multichannel data. Default is None. Changed in version 0.18.0: The ability to provide an extra dimension for channels was added. `cachebool, optional` Determine whether to cache calculated properties. The computation is much faster for cached properties, whereas the memory consumption increases. `coordinatesDEPRECATED` This argument is deprecated and will be removed in a future version of scikit-image. See [Coordinate conventions](../user_guide/numpy_images#numpy-images-coordinate-conventions) for more details. Deprecated since version 0.16.0: Use β€œrc” coordinates everywhere. It may be sufficient to call `numpy.transpose` on your label image to get the same values as 0.15 and earlier. However, for some properties, the transformation will be less trivial. For example, the new orientation is \(\frac{\pi}{2}\) plus the old orientation. `extra_propertiesIterable of callables` Add extra property computation functions that are not included with skimage. The name of the property is derived from the function name, the dtype is inferred by calling the function on a small sample. If the name of an extra property clashes with the name of an existing property the extra property wil not be visible and a UserWarning is issued. A property computation function must take a region mask as its first argument. If the property requires an intensity image, it must accept the intensity image as the second argument. Returns `propertieslist of RegionProperties` Each item describes one labeled region, and can be accessed using the attributes listed below. See also [`label`](#skimage.measure.label "skimage.measure.label") #### Notes The following properties can be accessed as attributes or keys: `areaint` Number of pixels of the region. `bboxtuple` Bounding box `(min_row, min_col, max_row, max_col)`. Pixels belonging to the bounding box are in the half-open interval `[min_row; max_row)` and `[min_col; max_col)`. `bbox_areaint` Number of pixels of bounding box. `centroidarray` Centroid coordinate tuple `(row, col)`. `convex_areaint` Number of pixels of convex hull image, which is the smallest convex polygon that encloses the region. `convex_image(H, J) ndarray` Binary convex hull image which has the same size as bounding box. `coords(N, 2) ndarray` Coordinate list `(row, col)` of the region. `eccentricityfloat` Eccentricity of the ellipse that has the same second-moments as the region. The eccentricity is the ratio of the focal distance (distance between focal points) over the major axis length. The value is in the interval [0, 1). When it is 0, the ellipse becomes a circle. `equivalent_diameterfloat` The diameter of a circle with the same area as the region. `euler_numberint` Euler characteristic of the set of non-zero pixels. Computed as number of connected components subtracted by number of holes (input.ndim connectivity). In 3D, number of connected components plus number of holes subtracted by number of tunnels. `extentfloat` Ratio of pixels in the region to pixels in the total bounding box. Computed as `area / (rows * cols)` `feret_diameter_maxfloat` Maximum Feret’s diameter computed as the longest distance between points around a region’s convex hull contour as determined by `find_contours`. [[5]](#r4a29d8446b4f-5) `filled_areaint` Number of pixels of the region will all the holes filled in. Describes the area of the filled\_image. `filled_image(H, J) ndarray` Binary region image with filled holes which has the same size as bounding box. `image(H, J) ndarray` Sliced binary region image which has the same size as bounding box. `inertia_tensorndarray` Inertia tensor of the region for the rotation around its mass. `inertia_tensor_eigvalstuple` The eigenvalues of the inertia tensor in decreasing order. `intensity_imagendarray` Image inside region bounding box. `labelint` The label in the labeled input image. `local_centroidarray` Centroid coordinate tuple `(row, col)`, relative to region bounding box. `major_axis_lengthfloat` The length of the major axis of the ellipse that has the same normalized second central moments as the region. `max_intensityfloat` Value with the greatest intensity in the region. `mean_intensityfloat` Value with the mean intensity in the region. `min_intensityfloat` Value with the least intensity in the region. `minor_axis_lengthfloat` The length of the minor axis of the ellipse that has the same normalized second central moments as the region. `moments(3, 3) ndarray` Spatial moments up to 3rd order: ``` m_ij = sum{ array(row, col) * row^i * col^j } ``` where the sum is over the `row`, `col` coordinates of the region. `moments_central(3, 3) ndarray` Central moments (translation invariant) up to 3rd order: ``` mu_ij = sum{ array(row, col) * (row - row_c)^i * (col - col_c)^j } ``` where the sum is over the `row`, `col` coordinates of the region, and `row_c` and `col_c` are the coordinates of the region’s centroid. `moments_hutuple` Hu moments (translation, scale and rotation invariant). `moments_normalized(3, 3) ndarray` Normalized moments (translation and scale invariant) up to 3rd order: ``` nu_ij = mu_ij / m_00^[(i+j)/2 + 1] ``` where `m_00` is the zeroth spatial moment. `orientationfloat` Angle between the 0th axis (rows) and the major axis of the ellipse that has the same second moments as the region, ranging from `-pi/2` to `pi/2` counter-clockwise. `perimeterfloat` Perimeter of object which approximates the contour as a line through the centers of border pixels using a 4-connectivity. `perimeter_croftonfloat` Perimeter of object approximated by the Crofton formula in 4 directions. `slicetuple of slices` A slice to extract the object from the source image. `solidityfloat` Ratio of pixels in the region to pixels of the convex hull image. `weighted_centroidarray` Centroid coordinate tuple `(row, col)` weighted with intensity image. `weighted_local_centroidarray` Centroid coordinate tuple `(row, col)`, relative to region bounding box, weighted with intensity image. `weighted_moments(3, 3) ndarray` Spatial moments of intensity image up to 3rd order: ``` wm_ij = sum{ array(row, col) * row^i * col^j } ``` where the sum is over the `row`, `col` coordinates of the region. `weighted_moments_central(3, 3) ndarray` Central moments (translation invariant) of intensity image up to 3rd order: ``` wmu_ij = sum{ array(row, col) * (row - row_c)^i * (col - col_c)^j } ``` where the sum is over the `row`, `col` coordinates of the region, and `row_c` and `col_c` are the coordinates of the region’s weighted centroid. `weighted_moments_hutuple` Hu moments (translation, scale and rotation invariant) of intensity image. `weighted_moments_normalized(3, 3) ndarray` Normalized moments (translation and scale invariant) of intensity image up to 3rd order: ``` wnu_ij = wmu_ij / wm_00^[(i+j)/2 + 1] ``` where `wm_00` is the zeroth spatial moment (intensity-weighted area). Each region also supports iteration, so that you can do: ``` for prop in region: print(prop, region[prop]) ``` #### References `1` Wilhelm Burger, Mark Burge. Principles of Digital Image Processing: Core Algorithms. Springer-Verlag, London, 2009. `2` B. JΓ€hne. Digital Image Processing. Springer-Verlag, Berlin-Heidelberg, 6. edition, 2005. `3` T. H. Reiss. Recognizing Planar Objects Using Invariant Image Features, from Lecture notes in computer science, p. 676. Springer, Berlin, 1993. `4` <https://en.wikipedia.org/wiki/Image_moment> `5` W. Pabst, E. GregorovΓ‘. Characterization of particles and particle systems, pp. 27-28. ICT Prague, 2007. <https://old.vscht.cz/sil/keramika/Characterization_of_particles/CPPS%20_English%20version_.pdf> #### Examples ``` >>> from skimage import data, util >>> from skimage.measure import label, regionprops >>> img = util.img_as_ubyte(data.coins()) > 110 >>> label_img = label(img, connectivity=img.ndim) >>> props = regionprops(label_img) >>> # centroid of first labeled object >>> props[0].centroid (22.72987986048314, 81.91228523446583) >>> # centroid of first labeled object >>> props[0]['centroid'] (22.72987986048314, 81.91228523446583) ``` Add custom measurements by passing functions as `extra_properties` ``` >>> from skimage import data, util >>> from skimage.measure import label, regionprops >>> import numpy as np >>> img = util.img_as_ubyte(data.coins()) > 110 >>> label_img = label(img, connectivity=img.ndim) >>> def pixelcount(regionmask): ... return np.sum(regionmask) >>> props = regionprops(label_img, extra_properties=(pixelcount,)) >>> props[0].pixelcount 7741 >>> props[1]['pixelcount'] 42 ``` ### Examples using `skimage.measure.regionprops` [Measure region properties](https://scikit-image.org/docs/0.18.x/auto_examples/segmentation/plot_regionprops.html#sphx-glr-auto-examples-segmentation-plot-regionprops-py) regionprops\_table ------------------ `skimage.measure.regionprops_table(label_image, intensity_image=None, properties=('label', 'bbox'), *, cache=True, separator='-', extra_properties=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/_regionprops.py#L705-L864) Compute image properties and return them as a pandas-compatible table. The table is a dictionary mapping column names to value arrays. See Notes section below for details. New in version 0.16. Parameters `label_image(N, M[, P]) ndarray` Labeled input image. Labels with value 0 are ignored. `intensity_image(M, N[, P][, C]) ndarray, optional` Intensity (i.e., input) image with same size as labeled image, plus optionally an extra dimension for multichannel data. Default is None. Changed in version 0.18.0: The ability to provide an extra dimension for channels was added. `propertiestuple or list of str, optional` Properties that will be included in the resulting dictionary For a list of available properties, please see [`regionprops()`](#skimage.measure.regionprops "skimage.measure.regionprops"). Users should remember to add β€œlabel” to keep track of region identities. `cachebool, optional` Determine whether to cache calculated properties. The computation is much faster for cached properties, whereas the memory consumption increases. `separatorstr, optional` For non-scalar properties not listed in OBJECT\_COLUMNS, each element will appear in its own column, with the index of that element separated from the property name by this separator. For example, the inertia tensor of a 2D region will appear in four columns: `inertia_tensor-0-0`, `inertia_tensor-0-1`, `inertia_tensor-1-0`, and `inertia_tensor-1-1` (where the separator is `-`). Object columns are those that cannot be split in this way because the number of columns would change depending on the object. For example, `image` and `coords`. `extra_propertiesIterable of callables` Add extra property computation functions that are not included with skimage. The name of the property is derived from the function name, the dtype is inferred by calling the function on a small sample. If the name of an extra property clashes with the name of an existing property the extra property wil not be visible and a UserWarning is issued. A property computation function must take a region mask as its first argument. If the property requires an intensity image, it must accept the intensity image as the second argument. Returns `out_dictdict` Dictionary mapping property names to an array of values of that property, one value per region. This dictionary can be used as input to pandas `DataFrame` to map property names to columns in the frame and regions to rows. If the image has no regions, the arrays will have length 0, but the correct type. #### Notes Each column contains either a scalar property, an object property, or an element in a multidimensional array. Properties with scalar values for each region, such as β€œeccentricity”, will appear as a float or int array with that property name as key. Multidimensional properties *of fixed size* for a given image dimension, such as β€œcentroid” (every centroid will have three elements in a 3D image, no matter the region size), will be split into that many columns, with the name {property\_name}{separator}{element\_num} (for 1D properties), {property\_name}{separator}{elem\_num0}{separator}{elem\_num1} (for 2D properties), and so on. For multidimensional properties that don’t have a fixed size, such as β€œimage” (the image of a region varies in size depending on the region size), an object array will be used, with the corresponding property name as the key. #### Examples ``` >>> from skimage import data, util, measure >>> image = data.coins() >>> label_image = measure.label(image > 110, connectivity=image.ndim) >>> props = measure.regionprops_table(label_image, image, ... properties=['label', 'inertia_tensor', ... 'inertia_tensor_eigvals']) >>> props {'label': array([ 1, 2, ...]), ... 'inertia_tensor-0-0': array([ 4.012...e+03, 8.51..., ...]), ... ..., 'inertia_tensor_eigvals-1': array([ 2.67...e+02, 2.83..., ...])} ``` The resulting dictionary can be directly passed to pandas, if installed, to obtain a clean DataFrame: ``` >>> import pandas as pd >>> data = pd.DataFrame(props) >>> data.head() label inertia_tensor-0-0 ... inertia_tensor_eigvals-1 0 1 4012.909888 ... 267.065503 1 2 8.514739 ... 2.834806 2 3 0.666667 ... 0.000000 3 4 0.000000 ... 0.000000 4 5 0.222222 ... 0.111111 ``` [5 rows x 7 columns] If we want to measure a feature that does not come as a built-in property, we can define custom functions and pass them as `extra_properties`. For example, we can create a custom function that measures the intensity quartiles in a region: ``` >>> from skimage import data, util, measure >>> import numpy as np >>> def quartiles(regionmask, intensity): ... return np.percentile(intensity[regionmask], q=(25, 50, 75)) >>> >>> image = data.coins() >>> label_image = measure.label(image > 110, connectivity=image.ndim) >>> props = measure.regionprops_table(label_image, intensity_image=image, ... properties=('label',), ... extra_properties=(quartiles,)) >>> import pandas as pd >>> pd.DataFrame(props).head() label quartiles-0 quartiles-1 quartiles-2 0 1 117.00 123.0 130.0 1 2 111.25 112.0 114.0 2 3 111.00 111.0 111.0 3 4 111.00 111.5 112.5 4 5 112.50 113.0 114.0 ``` ### Examples using `skimage.measure.regionprops_table` [Measure region properties](https://scikit-image.org/docs/0.18.x/auto_examples/segmentation/plot_regionprops.html#sphx-glr-auto-examples-segmentation-plot-regionprops-py) shannon\_entropy ---------------- `skimage.measure.shannon_entropy(image, base=2)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/entropy.py#L5-L41) Calculate the Shannon entropy of an image. The Shannon entropy is defined as S = -sum(pk \* log(pk)), where pk are frequency/probability of pixels of value k. Parameters `image(N, M) ndarray` Grayscale input image. `basefloat, optional` The logarithmic base to use. Returns `entropyfloat` #### Notes The returned value is measured in bits or shannon (Sh) for base=2, natural unit (nat) for base=np.e and hartley (Hart) for base=10. #### References `1` <https://en.wikipedia.org/wiki/Entropy_(information_theory)> `2` <https://en.wiktionary.org/wiki/Shannon_entropy> #### Examples ``` >>> from skimage import data >>> from skimage.measure import shannon_entropy >>> shannon_entropy(data.camera()) 7.231695011055706 ``` subdivide\_polygon ------------------ `skimage.measure.subdivide_polygon(coords, degree=2, preserve_ends=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/_polygon.py#L109-L168) Subdivision of polygonal curves using B-Splines. Note that the resulting curve is always within the convex hull of the original polygon. Circular polygons stay closed after subdivision. Parameters `coords(N, 2) array` Coordinate array. `degree{1, 2, 3, 4, 5, 6, 7}, optional` Degree of B-Spline. Default is 2. `preserve_endsbool, optional` Preserve first and last coordinate of non-circular polygon. Default is False. Returns `coords(M, 2) array` Subdivided coordinate array. #### References `1` <http://mrl.nyu.edu/publications/subdiv-course2000/coursenotes00.pdf> CircleModel ----------- `class skimage.measure.CircleModel` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/fit.py#L221-L347) Bases: `skimage.measure.fit.BaseModel` Total least squares estimator for 2D circles. The functional model of the circle is: ``` r**2 = (x - xc)**2 + (y - yc)**2 ``` This estimator minimizes the squared distances from all points to the circle: ``` min{ sum((r - sqrt((x_i - xc)**2 + (y_i - yc)**2))**2) } ``` A minimum number of 3 points is required to solve for the parameters. #### Examples ``` >>> t = np.linspace(0, 2 * np.pi, 25) >>> xy = CircleModel().predict_xy(t, params=(2, 3, 4)) >>> model = CircleModel() >>> model.estimate(xy) True >>> tuple(np.round(model.params, 5)) (2.0, 3.0, 4.0) >>> res = model.residuals(xy) >>> np.abs(np.round(res, 9)) array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]) ``` Attributes `paramstuple` Circle model parameters in the following order `xc`, `yc`, `r`. `__init__()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/fit.py#L26-L27) Initialize self. See help(type(self)) for accurate signature. `estimate(data)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/fit.py#L256-L295) Estimate circle model from data using total least squares. Parameters `data(N, 2) array` N points with `(x, y)` coordinates, respectively. Returns `successbool` True, if model estimation succeeds. `predict_xy(t, params=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/fit.py#L323-L347) Predict x- and y-coordinates using the estimated model. Parameters `tarray` Angles in circle in radians. Angles start to count from positive x-axis to positive y-axis in a right-handed system. `params(3, ) array, optional` Optional custom parameter set. Returns `xy(…, 2) array` Predicted x- and y-coordinates. `residuals(data)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/fit.py#L297-L321) Determine residuals of data to model. For each point the shortest distance to the circle is returned. Parameters `data(N, 2) array` N points with `(x, y)` coordinates, respectively. Returns `residuals(N, ) array` Residual for each data point. EllipseModel ------------ `class skimage.measure.EllipseModel` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/fit.py#L350-L578) Bases: `skimage.measure.fit.BaseModel` Total least squares estimator for 2D ellipses. The functional model of the ellipse is: ``` xt = xc + a*cos(theta)*cos(t) - b*sin(theta)*sin(t) yt = yc + a*sin(theta)*cos(t) + b*cos(theta)*sin(t) d = sqrt((x - xt)**2 + (y - yt)**2) ``` where `(xt, yt)` is the closest point on the ellipse to `(x, y)`. Thus d is the shortest distance from the point to the ellipse. The estimator is based on a least squares minimization. The optimal solution is computed directly, no iterations are required. This leads to a simple, stable and robust fitting method. The `params` attribute contains the parameters in the following order: ``` xc, yc, a, b, theta ``` #### Examples ``` >>> xy = EllipseModel().predict_xy(np.linspace(0, 2 * np.pi, 25), ... params=(10, 15, 4, 8, np.deg2rad(30))) >>> ellipse = EllipseModel() >>> ellipse.estimate(xy) True >>> np.round(ellipse.params, 2) array([10. , 15. , 4. , 8. , 0.52]) >>> np.round(abs(ellipse.residuals(xy)), 5) array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]) ``` Attributes `paramstuple` Ellipse model parameters in the following order `xc`, `yc`, `a`, `b`, `theta`. `__init__()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/fit.py#L26-L27) Initialize self. See help(type(self)) for accurate signature. `estimate(data)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/fit.py#L391-L483) Estimate circle model from data using total least squares. Parameters `data(N, 2) array` N points with `(x, y)` coordinates, respectively. Returns `successbool` True, if model estimation succeeds. #### References `1` Halir, R.; Flusser, J. β€œNumerically stable direct least squares fitting of ellipses”. In Proc. 6th International Conference in Central Europe on Computer Graphics and Visualization. WSCG (Vol. 98, pp. 125-132). `predict_xy(t, params=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/fit.py#L547-L578) Predict x- and y-coordinates using the estimated model. Parameters `tarray` Angles in circle in radians. Angles start to count from positive x-axis to positive y-axis in a right-handed system. `params(5, ) array, optional` Optional custom parameter set. Returns `xy(…, 2) array` Predicted x- and y-coordinates. `residuals(data)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/fit.py#L485-L545) Determine residuals of data to model. For each point the shortest distance to the ellipse is returned. Parameters `data(N, 2) array` N points with `(x, y)` coordinates, respectively. Returns `residuals(N, ) array` Residual for each data point. LineModelND ----------- `class skimage.measure.LineModelND` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/fit.py#L30-L218) Bases: `skimage.measure.fit.BaseModel` Total least squares estimator for N-dimensional lines. In contrast to ordinary least squares line estimation, this estimator minimizes the orthogonal distances of points to the estimated line. Lines are defined by a point (origin) and a unit vector (direction) according to the following vector equation: ``` X = origin + lambda * direction ``` #### Examples ``` >>> x = np.linspace(1, 2, 25) >>> y = 1.5 * x + 3 >>> lm = LineModelND() >>> lm.estimate(np.stack([x, y], axis=-1)) True >>> tuple(np.round(lm.params, 5)) (array([1.5 , 5.25]), array([0.5547 , 0.83205])) >>> res = lm.residuals(np.stack([x, y], axis=-1)) >>> np.abs(np.round(res, 9)) array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.]) >>> np.round(lm.predict_y(x[:5]), 3) array([4.5 , 4.562, 4.625, 4.688, 4.75 ]) >>> np.round(lm.predict_x(y[:5]), 3) array([1. , 1.042, 1.083, 1.125, 1.167]) ``` Attributes `paramstuple` Line model parameters in the following order `origin`, `direction`. `__init__()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/fit.py#L26-L27) Initialize self. See help(type(self)) for accurate signature. `estimate(data)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/fit.py#L66-L101) Estimate line model from data. This minimizes the sum of shortest (orthogonal) distances from the given data points to the estimated line. Parameters `data(N, dim) array` N points in a space of dimensionality dim >= 2. Returns `successbool` True, if model estimation succeeds. `predict(x, axis=0, params=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/fit.py#L134-L172) Predict intersection of the estimated line model with a hyperplane orthogonal to a given axis. Parameters `x(n, 1) array` Coordinates along an axis. `axisint` Axis orthogonal to the hyperplane intersecting the line. `params(2, ) array, optional` Optional custom parameter set in the form (`origin`, `direction`). Returns `data(n, m) array` Predicted coordinates. Raises ValueError If the line is parallel to the given axis. `predict_x(y, params=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/fit.py#L174-L195) Predict x-coordinates for 2D lines using the estimated model. Alias for: ``` predict(y, axis=1)[:, 0] ``` Parameters `yarray` y-coordinates. `params(2, ) array, optional` Optional custom parameter set in the form (`origin`, `direction`). Returns `xarray` Predicted x-coordinates. `predict_y(x, params=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/fit.py#L197-L218) Predict y-coordinates for 2D lines using the estimated model. Alias for: ``` predict(x, axis=0)[:, 1] ``` Parameters `xarray` x-coordinates. `params(2, ) array, optional` Optional custom parameter set in the form (`origin`, `direction`). Returns `yarray` Predicted y-coordinates. `residuals(data, params=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/fit.py#L103-L132) Determine residuals of data to model. For each point, the shortest (orthogonal) distance to the line is returned. It is obtained by projecting the data onto the line. Parameters `data(N, dim) array` N points in a space of dimension dim. `params(2, ) array, optional` Optional custom parameter set in the form (`origin`, `direction`). Returns `residuals(N, ) array` Residual for each data point.
programming_docs
scikit_image Module: viewer.canvastools Module: viewer.canvastools ========================== | | | | --- | --- | | [`skimage.viewer.canvastools.LineTool`](#skimage.viewer.canvastools.LineTool "skimage.viewer.canvastools.LineTool")(manager) | Widget for line selection in a plot. | | [`skimage.viewer.canvastools.PaintTool`](#skimage.viewer.canvastools.PaintTool "skimage.viewer.canvastools.PaintTool")(…[, …]) | Widget for painting on top of a plot. | | [`skimage.viewer.canvastools.RectangleTool`](#skimage.viewer.canvastools.RectangleTool "skimage.viewer.canvastools.RectangleTool")(manager) | Widget for selecting a rectangular region in a plot. | | [`skimage.viewer.canvastools.ThickLineTool`](#skimage.viewer.canvastools.ThickLineTool "skimage.viewer.canvastools.ThickLineTool")(manager) | Widget for line selection in a plot. | | `skimage.viewer.canvastools.base` | | | `skimage.viewer.canvastools.linetool` | | | `skimage.viewer.canvastools.painttool` | | | `skimage.viewer.canvastools.recttool` | | LineTool -------- `class skimage.viewer.canvastools.LineTool(manager, on_move=None, on_release=None, on_enter=None, maxdist=10, line_props=None, handle_props=None, **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/canvastools/linetool.py#L9-L124) Bases: `skimage.viewer.canvastools.base.CanvasToolBase` Widget for line selection in a plot. Parameters `managerViewer or PlotPlugin.` Skimage viewer or plot plugin object. `on_movefunction` Function called whenever a control handle is moved. This function must accept the end points of line as the only argument. `on_releasefunction` Function called whenever the control handle is released. `on_enterfunction` Function called whenever the β€œenter” key is pressed. `maxdistfloat` Maximum pixel distance allowed when selecting control handle. `line_propsdict` Properties for [`matplotlib.lines.Line2D`](https://matplotlib.org/api/_as_gen/matplotlib.lines.Line2D.html#matplotlib.lines.Line2D "(in Matplotlib v3.3.3)"). `handle_propsdict` Marker properties for the handles (also see [`matplotlib.lines.Line2D`](https://matplotlib.org/api/_as_gen/matplotlib.lines.Line2D.html#matplotlib.lines.Line2D "(in Matplotlib v3.3.3)")). Attributes `end_points2D array` End points of line ((x1, y1), (x2, y2)). `__init__(manager, on_move=None, on_release=None, on_enter=None, maxdist=10, line_props=None, handle_props=None, **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/canvastools/linetool.py#L36-L67) Initialize self. See help(type(self)) for accurate signature. `property end_points` `property geometry` Geometry information that gets passed to callback functions. `hit_test(event)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/canvastools/linetool.py#L84-L93) `on_mouse_press(event)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/canvastools/linetool.py#L95-L100) `on_mouse_release(event)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/canvastools/linetool.py#L102-L107) `on_move(event)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/canvastools/linetool.py#L109-L115) `update(x=None, y=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/canvastools/linetool.py#L117-L120) PaintTool --------- `class skimage.viewer.canvastools.PaintTool(manager, overlay_shape, radius=5, alpha=0.3, on_move=None, on_release=None, on_enter=None, rect_props=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/canvastools/painttool.py#L12-L186) Bases: `skimage.viewer.canvastools.base.CanvasToolBase` Widget for painting on top of a plot. Parameters `managerViewer or PlotPlugin.` Skimage viewer or plot plugin object. `overlay_shapeshape tuple` 2D shape tuple used to initialize overlay image. `radiusint` The size of the paint cursor. `alphafloat (between [0, 1])` Opacity of overlay. `on_movefunction` Function called whenever a control handle is moved. This function must accept the end points of line as the only argument. `on_releasefunction` Function called whenever the control handle is released. `on_enterfunction` Function called whenever the β€œenter” key is pressed. `rect_propsdict` Properties for [`matplotlib.patches.Rectangle`](https://matplotlib.org/api/_as_gen/matplotlib.patches.Rectangle.html#matplotlib.patches.Rectangle "(in Matplotlib v3.3.3)"). This class redefines defaults in [`matplotlib.widgets.RectangleSelector`](https://matplotlib.org/api/widgets_api.html#matplotlib.widgets.RectangleSelector "(in Matplotlib v3.3.3)"). #### Examples ``` >>> from skimage.data import camera >>> import matplotlib.pyplot as plt >>> from skimage.viewer.canvastools import PaintTool >>> import numpy as np ``` ``` >>> img = camera() ``` ``` >>> ax = plt.subplot(111) >>> plt.imshow(img, cmap=plt.cm.gray) >>> p = PaintTool(ax,np.shape(img[:-1]),10,0.2) >>> plt.show() ``` ``` >>> mask = p.overlay >>> plt.imshow(mask,cmap=plt.cm.gray) >>> plt.show() ``` Attributes `overlayarray` Overlay of painted labels displayed on top of image. `labelint` Current paint color. `__init__(manager, overlay_shape, radius=5, alpha=0.3, on_move=None, on_release=None, on_enter=None, rect_props=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/canvastools/painttool.py#L61-L86) Initialize self. See help(type(self)) for accurate signature. `property geometry` Geometry information that gets passed to callback functions. `property label` `on_key_press(event)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/canvastools/painttool.py#L143-L146) `on_mouse_press(event)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/canvastools/painttool.py#L148-L152) `on_mouse_release(event)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/canvastools/painttool.py#L154-L157) `on_move(event)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/canvastools/painttool.py#L159-L171) `property overlay` `property radius` `property shape` `update_cursor(x, y)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/canvastools/painttool.py#L179-L182) `update_overlay(x, y)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/canvastools/painttool.py#L173-L177) RectangleTool ------------- `class skimage.viewer.canvastools.RectangleTool(manager, on_move=None, on_release=None, on_enter=None, maxdist=10, rect_props=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/canvastools/recttool.py#L9-L233) Bases: `skimage.viewer.canvastools.base.CanvasToolBase`, [`matplotlib.widgets.RectangleSelector`](https://matplotlib.org/api/widgets_api.html#matplotlib.widgets.RectangleSelector "(in Matplotlib v3.3.3)") Widget for selecting a rectangular region in a plot. After making the desired selection, press β€œEnter” to accept the selection and call the `on_enter` callback function. Parameters `managerViewer or PlotPlugin.` Skimage viewer or plot plugin object. `on_movefunction` Function called whenever a control handle is moved. This function must accept the rectangle extents as the only argument. `on_releasefunction` Function called whenever the control handle is released. `on_enterfunction` Function called whenever the β€œenter” key is pressed. `maxdistfloat` Maximum pixel distance allowed when selecting control handle. `rect_propsdict` Properties for [`matplotlib.patches.Rectangle`](https://matplotlib.org/api/_as_gen/matplotlib.patches.Rectangle.html#matplotlib.patches.Rectangle "(in Matplotlib v3.3.3)"). This class redefines defaults in [`matplotlib.widgets.RectangleSelector`](https://matplotlib.org/api/widgets_api.html#matplotlib.widgets.RectangleSelector "(in Matplotlib v3.3.3)"). #### Examples ``` >>> from skimage import data >>> from skimage.viewer import ImageViewer >>> from skimage.viewer.canvastools import RectangleTool >>> from skimage.draw import line >>> from skimage.draw import set_color ``` ``` >>> viewer = ImageViewer(data.coffee()) ``` ``` >>> def print_the_rect(extents): ... global viewer ... im = viewer.image ... coord = np.int64(extents) ... [rr1, cc1] = line(coord[2],coord[0],coord[2],coord[1]) ... [rr2, cc2] = line(coord[2],coord[1],coord[3],coord[1]) ... [rr3, cc3] = line(coord[3],coord[1],coord[3],coord[0]) ... [rr4, cc4] = line(coord[3],coord[0],coord[2],coord[0]) ... set_color(im, (rr1, cc1), [255, 255, 0]) ... set_color(im, (rr2, cc2), [0, 255, 255]) ... set_color(im, (rr3, cc3), [255, 0, 255]) ... set_color(im, (rr4, cc4), [0, 0, 0]) ... viewer.image=im ``` ``` >>> rect_tool = RectangleTool(viewer, on_enter=print_the_rect) >>> viewer.show() ``` Attributes `extentstuple` Return (xmin, xmax, ymin, ymax). `__init__(manager, on_move=None, on_release=None, on_enter=None, maxdist=10, rect_props=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/canvastools/recttool.py#L65-L110) Parameters `axAxes` The parent axes for the widget. `onselectfunction` A callback function that is called after a selection is completed. It must have the signature: ``` def onselect(eclick: MouseEvent, erelease: MouseEvent) ``` where *eclick* and *erelease* are the mouse click and release `MouseEvent`s that start and complete the selection. `drawtype{β€œbox”, β€œline”, β€œnone”}, default: β€œbox”` Whether to draw the full rectangle box, the diagonal line of the rectangle, or nothing at all. `minspanxfloat, default: 0` Selections with an x-span less than *minspanx* are ignored. `minspanyfloat, default: 0` Selections with an y-span less than *minspany* are ignored. `useblitbool, default: False` Whether to use blitting for faster drawing (if supported by the backend). `linepropsdict, optional` Properties with which the line is drawn, if `drawtype == "line"`. Default: ``` dict(color="black", linestyle="-", linewidth=2, alpha=0.5) ``` `rectpropsdict, optional` Properties with which the rectangle is drawn, if `drawtype == "box"`. Default: ``` dict(facecolor="red", edgecolor="black", alpha=0.2, fill=True) ``` `spancoords{β€œdata”, β€œpixels”}, default: β€œdata”` Whether to interpret *minspanx* and *minspany* in data or in pixel coordinates. `buttonMouseButton, list of MouseButton, default: all buttons` Button(s) that trigger rectangle selection. `maxdistfloat, default: 10` Distance in pixels within which the interactive tool handles can be activated. `marker_propsdict` Properties with which the interactive handles are drawn. Currently not implemented and ignored. `interactivebool, default: False` Whether to draw a set of handles that allow interaction with the widget after it is drawn. `state_modifier_keysdict, optional` Keyboard modifiers which affect the widget’s behavior. Values amend the defaults. * β€œmove”: Move the existing shape, default: no modifier. * β€œclear”: Clear the current shape, default: β€œescape”. * β€œsquare”: Makes the shape square, default: β€œshift”. * β€œcenter”: Make the initial point the center of the shape, default: β€œctrl”. β€œsquare” and β€œcenter” can be combined. `property corners` Corners of rectangle from lower left, moving clockwise. `property edge_centers` Midpoint of rectangle edges from left, moving clockwise. `property extents` Return (xmin, xmax, ymin, ymax). `property geometry` Geometry information that gets passed to callback functions. `on_mouse_press(event)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/canvastools/recttool.py#L178-L187) `on_mouse_release(event)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/canvastools/recttool.py#L165-L176) `on_move(event)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/canvastools/recttool.py#L213-L229) ThickLineTool ------------- `class skimage.viewer.canvastools.ThickLineTool(manager, on_move=None, on_enter=None, on_release=None, on_change=None, maxdist=10, line_props=None, handle_props=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/canvastools/linetool.py#L127-L198) Bases: `skimage.viewer.canvastools.linetool.LineTool` Widget for line selection in a plot. The thickness of the line can be varied using the mouse scroll wheel, or with the β€˜+’ and β€˜-β€˜ keys. Parameters `managerViewer or PlotPlugin.` Skimage viewer or plot plugin object. `on_movefunction` Function called whenever a control handle is moved. This function must accept the end points of line as the only argument. `on_releasefunction` Function called whenever the control handle is released. `on_enterfunction` Function called whenever the β€œenter” key is pressed. `on_changefunction` Function called whenever the line thickness is changed. `maxdistfloat` Maximum pixel distance allowed when selecting control handle. `line_propsdict` Properties for [`matplotlib.lines.Line2D`](https://matplotlib.org/api/_as_gen/matplotlib.lines.Line2D.html#matplotlib.lines.Line2D "(in Matplotlib v3.3.3)"). `handle_propsdict` Marker properties for the handles (also see [`matplotlib.lines.Line2D`](https://matplotlib.org/api/_as_gen/matplotlib.lines.Line2D.html#matplotlib.lines.Line2D "(in Matplotlib v3.3.3)")). Attributes `end_points2D array` End points of line ((x1, y1), (x2, y2)). `__init__(manager, on_move=None, on_enter=None, on_release=None, on_change=None, maxdist=10, line_props=None, handle_props=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/canvastools/linetool.py#L160-L173) Initialize self. See help(type(self)) for accurate signature. `on_key_press(event)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/canvastools/linetool.py#L183-L187) `on_scroll(event)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/canvastools/linetool.py#L175-L181) scikit_image Module: morphology Module: morphology ================== | | | | --- | --- | | [`skimage.morphology.area_closing`](#skimage.morphology.area_closing "skimage.morphology.area_closing")(image[, …]) | Perform an area closing of the image. | | [`skimage.morphology.area_opening`](#skimage.morphology.area_opening "skimage.morphology.area_opening")(image[, …]) | Perform an area opening of the image. | | [`skimage.morphology.ball`](#skimage.morphology.ball "skimage.morphology.ball")(radius[, dtype]) | Generates a ball-shaped structuring element. | | [`skimage.morphology.binary_closing`](#skimage.morphology.binary_closing "skimage.morphology.binary_closing")(image[, …]) | Return fast binary morphological closing of an image. | | [`skimage.morphology.binary_dilation`](#skimage.morphology.binary_dilation "skimage.morphology.binary_dilation")(image[, …]) | Return fast binary morphological dilation of an image. | | [`skimage.morphology.binary_erosion`](#skimage.morphology.binary_erosion "skimage.morphology.binary_erosion")(image[, …]) | Return fast binary morphological erosion of an image. | | [`skimage.morphology.binary_opening`](#skimage.morphology.binary_opening "skimage.morphology.binary_opening")(image[, …]) | Return fast binary morphological opening of an image. | | [`skimage.morphology.black_tophat`](#skimage.morphology.black_tophat "skimage.morphology.black_tophat")(image[, …]) | Return black top hat of an image. | | [`skimage.morphology.closing`](#skimage.morphology.closing "skimage.morphology.closing")(image[, selem, out]) | Return greyscale morphological closing of an image. | | [`skimage.morphology.convex_hull_image`](#skimage.morphology.convex_hull_image "skimage.morphology.convex_hull_image")(image) | Compute the convex hull image of a binary image. | | [`skimage.morphology.convex_hull_object`](#skimage.morphology.convex_hull_object "skimage.morphology.convex_hull_object")(image, \*) | Compute the convex hull image of individual objects in a binary image. | | [`skimage.morphology.cube`](#skimage.morphology.cube "skimage.morphology.cube")(width[, dtype]) | Generates a cube-shaped structuring element. | | [`skimage.morphology.diameter_closing`](#skimage.morphology.diameter_closing "skimage.morphology.diameter_closing")(image[, …]) | Perform a diameter closing of the image. | | [`skimage.morphology.diameter_opening`](#skimage.morphology.diameter_opening "skimage.morphology.diameter_opening")(image[, …]) | Perform a diameter opening of the image. | | [`skimage.morphology.diamond`](#skimage.morphology.diamond "skimage.morphology.diamond")(radius[, dtype]) | Generates a flat, diamond-shaped structuring element. | | [`skimage.morphology.dilation`](#skimage.morphology.dilation "skimage.morphology.dilation")(image[, selem, …]) | Return greyscale morphological dilation of an image. | | [`skimage.morphology.disk`](#skimage.morphology.disk "skimage.morphology.disk")(radius[, dtype]) | Generates a flat, disk-shaped structuring element. | | [`skimage.morphology.erosion`](#skimage.morphology.erosion "skimage.morphology.erosion")(image[, selem, …]) | Return greyscale morphological erosion of an image. | | [`skimage.morphology.flood`](#skimage.morphology.flood "skimage.morphology.flood")(image, seed\_point, \*) | Mask corresponding to a flood fill. | | [`skimage.morphology.flood_fill`](#skimage.morphology.flood_fill "skimage.morphology.flood_fill")(image, …[, …]) | Perform flood filling on an image. | | [`skimage.morphology.h_maxima`](#skimage.morphology.h_maxima "skimage.morphology.h_maxima")(image, h[, selem]) | Determine all maxima of the image with height >= h. | | [`skimage.morphology.h_minima`](#skimage.morphology.h_minima "skimage.morphology.h_minima")(image, h[, selem]) | Determine all minima of the image with depth >= h. | | [`skimage.morphology.label`](#skimage.morphology.label "skimage.morphology.label")(input[, …]) | Label connected regions of an integer array. | | [`skimage.morphology.local_maxima`](#skimage.morphology.local_maxima "skimage.morphology.local_maxima")(image[, …]) | Find local maxima of n-dimensional array. | | [`skimage.morphology.local_minima`](#skimage.morphology.local_minima "skimage.morphology.local_minima")(image[, …]) | Find local minima of n-dimensional array. | | [`skimage.morphology.max_tree`](#skimage.morphology.max_tree "skimage.morphology.max_tree")(image[, …]) | Build the max tree from an image. | | [`skimage.morphology.max_tree_local_maxima`](#skimage.morphology.max_tree_local_maxima "skimage.morphology.max_tree_local_maxima")(image) | Determine all local maxima of the image. | | [`skimage.morphology.medial_axis`](#skimage.morphology.medial_axis "skimage.morphology.medial_axis")(image[, …]) | Compute the medial axis transform of a binary image | | [`skimage.morphology.octagon`](#skimage.morphology.octagon "skimage.morphology.octagon")(m, n[, dtype]) | Generates an octagon shaped structuring element. | | [`skimage.morphology.octahedron`](#skimage.morphology.octahedron "skimage.morphology.octahedron")(radius[, dtype]) | Generates a octahedron-shaped structuring element. | | [`skimage.morphology.opening`](#skimage.morphology.opening "skimage.morphology.opening")(image[, selem, out]) | Return greyscale morphological opening of an image. | | [`skimage.morphology.reconstruction`](#skimage.morphology.reconstruction "skimage.morphology.reconstruction")(seed, mask) | Perform a morphological reconstruction of an image. | | [`skimage.morphology.rectangle`](#skimage.morphology.rectangle "skimage.morphology.rectangle")(nrows, ncols[, …]) | Generates a flat, rectangular-shaped structuring element. | | [`skimage.morphology.remove_small_holes`](#skimage.morphology.remove_small_holes "skimage.morphology.remove_small_holes")(ar[, …]) | Remove contiguous holes smaller than the specified size. | | [`skimage.morphology.remove_small_objects`](#skimage.morphology.remove_small_objects "skimage.morphology.remove_small_objects")(ar) | Remove objects smaller than the specified size. | | [`skimage.morphology.skeletonize`](#skimage.morphology.skeletonize "skimage.morphology.skeletonize")(image, \*[, …]) | Compute the skeleton of a binary image. | | [`skimage.morphology.skeletonize_3d`](#skimage.morphology.skeletonize_3d "skimage.morphology.skeletonize_3d")(image) | Compute the skeleton of a binary image. | | [`skimage.morphology.square`](#skimage.morphology.square "skimage.morphology.square")(width[, dtype]) | Generates a flat, square-shaped structuring element. | | [`skimage.morphology.star`](#skimage.morphology.star "skimage.morphology.star")(a[, dtype]) | Generates a star shaped structuring element. | | [`skimage.morphology.thin`](#skimage.morphology.thin "skimage.morphology.thin")(image[, max\_iter]) | Perform morphological thinning of a binary image. | | [`skimage.morphology.watershed`](#skimage.morphology.watershed "skimage.morphology.watershed")(image[, …]) | **Deprecated function**. | | [`skimage.morphology.white_tophat`](#skimage.morphology.white_tophat "skimage.morphology.white_tophat")(image[, …]) | Return white top hat of an image. | area\_closing ------------- `skimage.morphology.area_closing(image, area_threshold=64, connectivity=1, parent=None, tree_traverser=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/max_tree.py#L349-L472) Perform an area closing of the image. Area closing removes all dark structures of an image with a surface smaller than area\_threshold. The output image is larger than or equal to the input image for every pixel and all local minima have at least a surface of area\_threshold pixels. Area closings are similar to morphological closings, but they do not use a fixed structuring element, but rather a deformable one, with surface = area\_threshold. In the binary case, area closings are equivalent to remove\_small\_holes; this operator is thus extended to gray-level images. Technically, this operator is based on the max-tree representation of the image. Parameters `imagendarray` The input image for which the area\_closing is to be calculated. This image can be of any type. `area_thresholdunsigned int` The size parameter (number of pixels). The default value is arbitrarily chosen to be 64. `connectivityunsigned int, optional` The neighborhood connectivity. The integer represents the maximum number of orthogonal steps to reach a neighbor. In 2D, it is 1 for a 4-neighborhood and 2 for a 8-neighborhood. Default value is 1. `parentndarray, int64, optional` Parent image representing the max tree of the inverted image. The value of each pixel is the index of its parent in the ravelled array. See Note for further details. `tree_traverser1D array, int64, optional` The ordered pixel indices (referring to the ravelled array). The pixels are ordered such that every pixel is preceded by its parent (except for the root which has no parent). Returns `outputndarray` Output image of the same shape and type as input image. See also [`skimage.morphology.area_opening`](#skimage.morphology.area_opening "skimage.morphology.area_opening") [`skimage.morphology.diameter_opening`](#skimage.morphology.diameter_opening "skimage.morphology.diameter_opening") [`skimage.morphology.diameter_closing`](#skimage.morphology.diameter_closing "skimage.morphology.diameter_closing") [`skimage.morphology.max_tree`](#skimage.morphology.max_tree "skimage.morphology.max_tree") [`skimage.morphology.remove_small_objects`](#skimage.morphology.remove_small_objects "skimage.morphology.remove_small_objects") [`skimage.morphology.remove_small_holes`](#skimage.morphology.remove_small_holes "skimage.morphology.remove_small_holes") #### Notes If a max-tree representation (parent and tree\_traverser) are given to the function, they must be calculated from the inverted image for this function, i.e.: >>> P, S = max\_tree(invert(f)) >>> closed = diameter\_closing(f, 3, parent=P, tree\_traverser=S) #### References `1` Vincent L., Proc. β€œGrayscale area openings and closings, their efficient implementation and applications”, EURASIP Workshop on Mathematical Morphology and its Applications to Signal Processing, Barcelona, Spain, pp.22-27, May 1993. `2` Soille, P., β€œMorphological Image Analysis: Principles and Applications” (Chapter 6), 2nd edition (2003), ISBN 3540429883. [DOI:10.1007/978-3-662-05088-0](https://doi.org/10.1007/978-3-662-05088-0) `3` Salembier, P., Oliveras, A., & Garrido, L. (1998). Antiextensive Connected Operators for Image and Sequence Processing. IEEE Transactions on Image Processing, 7(4), 555-570. [DOI:10.1109/83.663500](https://doi.org/10.1109/83.663500) `4` Najman, L., & Couprie, M. (2006). Building the component tree in quasi-linear time. IEEE Transactions on Image Processing, 15(11), 3531-3539. [DOI:10.1109/TIP.2006.877518](https://doi.org/10.1109/TIP.2006.877518) `5` Carlinet, E., & Geraud, T. (2014). A Comparative Review of Component Tree Computation Algorithms. IEEE Transactions on Image Processing, 23(9), 3885-3895. [DOI:10.1109/TIP.2014.2336551](https://doi.org/10.1109/TIP.2014.2336551) #### Examples We create an image (quadratic function with a minimum in the center and 4 additional local minima. ``` >>> w = 12 >>> x, y = np.mgrid[0:w,0:w] >>> f = 180 + 0.2*((x - w/2)**2 + (y-w/2)**2) >>> f[2:3,1:5] = 160; f[2:4,9:11] = 140; f[9:11,2:4] = 120 >>> f[9:10,9:11] = 100; f[10,10] = 100 >>> f = f.astype(int) ``` We can calculate the area closing: ``` >>> closed = area_closing(f, 8, connectivity=1) ``` All small minima are removed, and the remaining minima have at least a size of 8. area\_opening ------------- `skimage.morphology.area_opening(image, area_threshold=64, connectivity=1, parent=None, tree_traverser=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/max_tree.py#L146-L254) Perform an area opening of the image. Area opening removes all bright structures of an image with a surface smaller than area\_threshold. The output image is thus the largest image smaller than the input for which all local maxima have at least a surface of area\_threshold pixels. Area openings are similar to morphological openings, but they do not use a fixed structuring element, but rather a deformable one, with surface = area\_threshold. Consequently, the area\_opening with area\_threshold=1 is the identity. In the binary case, area openings are equivalent to remove\_small\_objects; this operator is thus extended to gray-level images. Technically, this operator is based on the max-tree representation of the image. Parameters `imagendarray` The input image for which the area\_opening is to be calculated. This image can be of any type. `area_thresholdunsigned int` The size parameter (number of pixels). The default value is arbitrarily chosen to be 64. `connectivityunsigned int, optional` The neighborhood connectivity. The integer represents the maximum number of orthogonal steps to reach a neighbor. In 2D, it is 1 for a 4-neighborhood and 2 for a 8-neighborhood. Default value is 1. `parentndarray, int64, optional` Parent image representing the max tree of the image. The value of each pixel is the index of its parent in the ravelled array. `tree_traverser1D array, int64, optional` The ordered pixel indices (referring to the ravelled array). The pixels are ordered such that every pixel is preceded by its parent (except for the root which has no parent). Returns `outputndarray` Output image of the same shape and type as the input image. See also [`skimage.morphology.area_closing`](#skimage.morphology.area_closing "skimage.morphology.area_closing") [`skimage.morphology.diameter_opening`](#skimage.morphology.diameter_opening "skimage.morphology.diameter_opening") [`skimage.morphology.diameter_closing`](#skimage.morphology.diameter_closing "skimage.morphology.diameter_closing") [`skimage.morphology.max_tree`](#skimage.morphology.max_tree "skimage.morphology.max_tree") [`skimage.morphology.remove_small_objects`](#skimage.morphology.remove_small_objects "skimage.morphology.remove_small_objects") [`skimage.morphology.remove_small_holes`](#skimage.morphology.remove_small_holes "skimage.morphology.remove_small_holes") #### References `1` Vincent L., Proc. β€œGrayscale area openings and closings, their efficient implementation and applications”, EURASIP Workshop on Mathematical Morphology and its Applications to Signal Processing, Barcelona, Spain, pp.22-27, May 1993. `2` Soille, P., β€œMorphological Image Analysis: Principles and Applications” (Chapter 6), 2nd edition (2003), ISBN 3540429883. :DOI:10.1007/978-3-662-05088-0 `3` Salembier, P., Oliveras, A., & Garrido, L. (1998). Antiextensive Connected Operators for Image and Sequence Processing. IEEE Transactions on Image Processing, 7(4), 555-570. :DOI:10.1109/83.663500 `4` Najman, L., & Couprie, M. (2006). Building the component tree in quasi-linear time. IEEE Transactions on Image Processing, 15(11), 3531-3539. :DOI:10.1109/TIP.2006.877518 `5` Carlinet, E., & Geraud, T. (2014). A Comparative Review of Component Tree Computation Algorithms. IEEE Transactions on Image Processing, 23(9), 3885-3895. :DOI:10.1109/TIP.2014.2336551 #### Examples We create an image (quadratic function with a maximum in the center and 4 additional local maxima. ``` >>> w = 12 >>> x, y = np.mgrid[0:w,0:w] >>> f = 20 - 0.2*((x - w/2)**2 + (y-w/2)**2) >>> f[2:3,1:5] = 40; f[2:4,9:11] = 60; f[9:11,2:4] = 80 >>> f[9:10,9:11] = 100; f[10,10] = 100 >>> f = f.astype(int) ``` We can calculate the area opening: ``` >>> open = area_opening(f, 8, connectivity=1) ``` The peaks with a surface smaller than 8 are removed. ball ---- `skimage.morphology.ball(radius, dtype=<class 'numpy.uint8'>)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/selem.py#L231-L259) Generates a ball-shaped structuring element. This is the 3D equivalent of a disk. A pixel is within the neighborhood if the Euclidean distance between it and the origin is no greater than radius. Parameters `radiusint` The radius of the ball-shaped structuring element. Returns `selemndarray` The structuring element where elements of the neighborhood are 1 and 0 otherwise. Other Parameters `dtypedata-type` The data type of the structuring element. ### Examples using `skimage.morphology.ball` [Local Histogram Equalization](https://scikit-image.org/docs/0.18.x/auto_examples/color_exposure/plot_local_equalize.html#sphx-glr-auto-examples-color-exposure-plot-local-equalize-py) [Rank filters](https://scikit-image.org/docs/0.18.x/auto_examples/applications/plot_rank_filters.html#sphx-glr-auto-examples-applications-plot-rank-filters-py) binary\_closing --------------- `skimage.morphology.binary_closing(image, selem=None, out=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/binary.py#L115-L146) Return fast binary morphological closing of an image. This function returns the same result as greyscale closing but performs faster for binary images. The morphological closing on an image is defined as a dilation followed by an erosion. Closing can remove small dark spots (i.e. β€œpepper”) and connect small bright cracks. This tends to β€œclose” up (dark) gaps between (bright) features. Parameters `imagendarray` Binary input image. `selemndarray, optional` The neighborhood expressed as a 2-D array of 1’s and 0’s. If None, use a cross-shaped structuring element (connectivity=1). `outndarray of bool, optional` The array to store the result of the morphology. If None, is passed, a new array will be allocated. Returns `closingndarray of bool` The result of the morphological closing. ### Examples using `skimage.morphology.binary_closing` [Flood Fill](https://scikit-image.org/docs/0.18.x/auto_examples/segmentation/plot_floodfill.html#sphx-glr-auto-examples-segmentation-plot-floodfill-py) binary\_dilation ---------------- `skimage.morphology.binary_dilation(image, selem=None, out=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/binary.py#L46-L78) Return fast binary morphological dilation of an image. This function returns the same result as greyscale dilation but performs faster for binary images. Morphological dilation sets a pixel at `(i,j)` to the maximum over all pixels in the neighborhood centered at `(i,j)`. Dilation enlarges bright regions and shrinks dark regions. Parameters `imagendarray` Binary input image. `selemndarray, optional` The neighborhood expressed as a 2-D array of 1’s and 0’s. If None, use a cross-shaped structuring element (connectivity=1). `outndarray of bool, optional` The array to store the result of the morphology. If None is passed, a new array will be allocated. Returns `dilatedndarray of bool or uint` The result of the morphological dilation with values in `[False, True]`. binary\_erosion --------------- `skimage.morphology.binary_erosion(image, selem=None, out=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/binary.py#L11-L43) Return fast binary morphological erosion of an image. This function returns the same result as greyscale erosion but performs faster for binary images. Morphological erosion sets a pixel at `(i,j)` to the minimum over all pixels in the neighborhood centered at `(i,j)`. Erosion shrinks bright regions and enlarges dark regions. Parameters `imagendarray` Binary input image. `selemndarray, optional` The neighborhood expressed as a 2-D array of 1’s and 0’s. If None, use a cross-shaped structuring element (connectivity=1). `outndarray of bool, optional` The array to store the result of the morphology. If None is passed, a new array will be allocated. Returns `erodedndarray of bool or uint` The result of the morphological erosion taking values in `[False, True]`. binary\_opening --------------- `skimage.morphology.binary_opening(image, selem=None, out=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/binary.py#L81-L112) Return fast binary morphological opening of an image. This function returns the same result as greyscale opening but performs faster for binary images. The morphological opening on an image is defined as an erosion followed by a dilation. Opening can remove small bright spots (i.e. β€œsalt”) and connect small dark cracks. This tends to β€œopen” up (dark) gaps between (bright) features. Parameters `imagendarray` Binary input image. `selemndarray, optional` The neighborhood expressed as a 2-D array of 1’s and 0’s. If None, use a cross-shaped structuring element (connectivity=1). `outndarray of bool, optional` The array to store the result of the morphology. If None is passed, a new array will be allocated. Returns `openingndarray of bool` The result of the morphological opening. ### Examples using `skimage.morphology.binary_opening` [Flood Fill](https://scikit-image.org/docs/0.18.x/auto_examples/segmentation/plot_floodfill.html#sphx-glr-auto-examples-segmentation-plot-floodfill-py) black\_tophat ------------- `skimage.morphology.black_tophat(image, selem=None, out=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/grey.py#L429-L489) Return black top hat of an image. The black top hat of an image is defined as its morphological closing minus the original image. This operation returns the dark spots of the image that are smaller than the structuring element. Note that dark spots in the original image are bright spots after the black top hat. Parameters `imagendarray` Image array. `selemndarray, optional` The neighborhood expressed as a 2-D array of 1’s and 0’s. If None, use cross-shaped structuring element (connectivity=1). `outndarray, optional` The array to store the result of the morphology. If None is passed, a new array will be allocated. Returns `outarray, same shape and type as image` The result of the morphological black top hat. See also [`white_tophat`](#skimage.morphology.white_tophat "skimage.morphology.white_tophat") #### References `1` <https://en.wikipedia.org/wiki/Top-hat_transform> #### Examples ``` >>> # Change dark peak to bright peak and subtract background >>> import numpy as np >>> from skimage.morphology import square >>> dark_on_grey = np.array([[7, 6, 6, 6, 7], ... [6, 5, 4, 5, 6], ... [6, 4, 0, 4, 6], ... [6, 5, 4, 5, 6], ... [7, 6, 6, 6, 7]], dtype=np.uint8) >>> black_tophat(dark_on_grey, square(3)) array([[0, 0, 0, 0, 0], [0, 0, 1, 0, 0], [0, 1, 5, 1, 0], [0, 0, 1, 0, 0], [0, 0, 0, 0, 0]], dtype=uint8) ``` closing ------- `skimage.morphology.closing(image, selem=None, out=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/grey.py#L305-L352) Return greyscale morphological closing of an image. The morphological closing on an image is defined as a dilation followed by an erosion. Closing can remove small dark spots (i.e. β€œpepper”) and connect small bright cracks. This tends to β€œclose” up (dark) gaps between (bright) features. Parameters `imagendarray` Image array. `selemndarray, optional` The neighborhood expressed as an array of 1’s and 0’s. If None, use cross-shaped structuring element (connectivity=1). `outndarray, optional` The array to store the result of the morphology. If None, is passed, a new array will be allocated. Returns `closingarray, same shape and type as image` The result of the morphological closing. #### Examples ``` >>> # Close a gap between two bright lines >>> import numpy as np >>> from skimage.morphology import square >>> broken_line = np.array([[0, 0, 0, 0, 0], ... [0, 0, 0, 0, 0], ... [1, 1, 0, 1, 1], ... [0, 0, 0, 0, 0], ... [0, 0, 0, 0, 0]], dtype=np.uint8) >>> closing(broken_line, square(3)) array([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [1, 1, 1, 1, 1], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]], dtype=uint8) ``` convex\_hull\_image ------------------- `skimage.morphology.convex_hull_image(image, offset_coordinates=True, tolerance=1e-10)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/convex_hull.py#L73-L145) Compute the convex hull image of a binary image. The convex hull is the set of pixels included in the smallest convex polygon that surround all white pixels in the input image. Parameters `imagearray` Binary input image. This array is cast to bool before processing. `offset_coordinatesbool, optional` If `True`, a pixel at coordinate, e.g., (4, 7) will be represented by coordinates (3.5, 7), (4.5, 7), (4, 6.5), and (4, 7.5). This adds some β€œextent” to a pixel when computing the hull. `tolerancefloat, optional` Tolerance when determining whether a point is inside the hull. Due to numerical floating point errors, a tolerance of 0 can result in some points erroneously being classified as being outside the hull. Returns `hull(M, N) array of bool` Binary image with pixels in convex hull set to True. #### References `1` <https://blogs.mathworks.com/steve/2011/10/04/binary-image-convex-hull-algorithm-notes/> convex\_hull\_object -------------------- `skimage.morphology.convex_hull_object(image, *, connectivity=2)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/convex_hull.py#L148-L197) Compute the convex hull image of individual objects in a binary image. The convex hull is the set of pixels included in the smallest convex polygon that surround all white pixels in the input image. Parameters `image(M, N) ndarray` Binary input image. `connectivity{1, 2}, int, optional` Determines the neighbors of each pixel. Adjacent elements within a squared distance of `connectivity` from pixel center are considered neighbors.: ``` 1-connectivity 2-connectivity [ ] [ ] [ ] [ ] | \ | / [ ]--[x]--[ ] [ ]--[x]--[ ] | / | \ [ ] [ ] [ ] [ ] ``` Returns `hullndarray of bool` Binary image with pixels inside convex hull set to `True`. #### Notes This function uses `skimage.morphology.label` to define unique objects, finds the convex hull of each using `convex_hull_image`, and combines these regions with logical OR. Be aware the convex hulls of unconnected objects may overlap in the result. If this is suspected, consider using convex\_hull\_image separately on each object or adjust `connectivity`. cube ---- `skimage.morphology.cube(width, dtype=<class 'numpy.uint8'>)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/selem.py#L170-L194) Generates a cube-shaped structuring element. This is the 3D equivalent of a square. Every pixel along the perimeter has a chessboard distance no greater than radius (radius=floor(width/2)) pixels. Parameters `widthint` The width, height and depth of the cube. Returns `selemndarray` A structuring element consisting only of ones, i.e. every pixel belongs to the neighborhood. Other Parameters `dtypedata-type` The data type of the structuring element. diameter\_closing ----------------- `skimage.morphology.diameter_closing(image, diameter_threshold=8, connectivity=1, parent=None, tree_traverser=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/max_tree.py#L475-L579) Perform a diameter closing of the image. Diameter closing removes all dark structures of an image with maximal extension smaller than diameter\_threshold. The maximal extension is defined as the maximal extension of the bounding box. The operator is also called Bounding Box Closing. In practice, the result is similar to a morphological closing, but long and thin structures are not removed. Technically, this operator is based on the max-tree representation of the image. Parameters `imagendarray` The input image for which the diameter\_closing is to be calculated. This image can be of any type. `diameter_thresholdunsigned int` The maximal extension parameter (number of pixels). The default value is 8. `connectivityunsigned int, optional` The neighborhood connectivity. The integer represents the maximum number of orthogonal steps to reach a neighbor. In 2D, it is 1 for a 4-neighborhood and 2 for a 8-neighborhood. Default value is 1. `parentndarray, int64, optional` Precomputed parent image representing the max tree of the inverted image. This function is fast, if precomputed parent and tree\_traverser are provided. See Note for further details. `tree_traverser1D array, int64, optional` Precomputed traverser, where the pixels are ordered such that every pixel is preceded by its parent (except for the root which has no parent). This function is fast, if precomputed parent and tree\_traverser are provided. See Note for further details. Returns `outputndarray` Output image of the same shape and type as input image. See also [`skimage.morphology.area_opening`](#skimage.morphology.area_opening "skimage.morphology.area_opening") [`skimage.morphology.area_closing`](#skimage.morphology.area_closing "skimage.morphology.area_closing") [`skimage.morphology.diameter_opening`](#skimage.morphology.diameter_opening "skimage.morphology.diameter_opening") [`skimage.morphology.max_tree`](#skimage.morphology.max_tree "skimage.morphology.max_tree") #### Notes If a max-tree representation (parent and tree\_traverser) are given to the function, they must be calculated from the inverted image for this function, i.e.: >>> P, S = max\_tree(invert(f)) >>> closed = diameter\_closing(f, 3, parent=P, tree\_traverser=S) #### References `1` Walter, T., & Klein, J.-C. (2002). Automatic Detection of Microaneurysms in Color Fundus Images of the Human Retina by Means of the Bounding Box Closing. In A. Colosimo, P. Sirabella, A. Giuliani (Eds.), Medical Data Analysis. Lecture Notes in Computer Science, vol 2526, pp. 210-220. Springer Berlin Heidelberg. [DOI:10.1007/3-540-36104-9\_23](https://doi.org/10.1007/3-540-36104-9_23) `2` Carlinet, E., & Geraud, T. (2014). A Comparative Review of Component Tree Computation Algorithms. IEEE Transactions on Image Processing, 23(9), 3885-3895. [DOI:10.1109/TIP.2014.2336551](https://doi.org/10.1109/TIP.2014.2336551) #### Examples We create an image (quadratic function with a minimum in the center and 4 additional local minima. ``` >>> w = 12 >>> x, y = np.mgrid[0:w,0:w] >>> f = 180 + 0.2*((x - w/2)**2 + (y-w/2)**2) >>> f[2:3,1:5] = 160; f[2:4,9:11] = 140; f[9:11,2:4] = 120 >>> f[9:10,9:11] = 100; f[10,10] = 100 >>> f = f.astype(int) ``` We can calculate the diameter closing: ``` >>> closed = diameter_closing(f, 3, connectivity=1) ``` All small minima with a maximal extension of 2 or less are removed. The remaining minima have all a maximal extension of at least 3. diameter\_opening ----------------- `skimage.morphology.diameter_opening(image, diameter_threshold=8, connectivity=1, parent=None, tree_traverser=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/max_tree.py#L257-L346) Perform a diameter opening of the image. Diameter opening removes all bright structures of an image with maximal extension smaller than diameter\_threshold. The maximal extension is defined as the maximal extension of the bounding box. The operator is also called Bounding Box Opening. In practice, the result is similar to a morphological opening, but long and thin structures are not removed. Technically, this operator is based on the max-tree representation of the image. Parameters `imagendarray` The input image for which the area\_opening is to be calculated. This image can be of any type. `diameter_thresholdunsigned int` The maximal extension parameter (number of pixels). The default value is 8. `connectivityunsigned int, optional` The neighborhood connectivity. The integer represents the maximum number of orthogonal steps to reach a neighbor. In 2D, it is 1 for a 4-neighborhood and 2 for a 8-neighborhood. Default value is 1. `parentndarray, int64, optional` Parent image representing the max tree of the image. The value of each pixel is the index of its parent in the ravelled array. `tree_traverser1D array, int64, optional` The ordered pixel indices (referring to the ravelled array). The pixels are ordered such that every pixel is preceded by its parent (except for the root which has no parent). Returns `outputndarray` Output image of the same shape and type as the input image. See also [`skimage.morphology.area_opening`](#skimage.morphology.area_opening "skimage.morphology.area_opening") [`skimage.morphology.area_closing`](#skimage.morphology.area_closing "skimage.morphology.area_closing") [`skimage.morphology.diameter_closing`](#skimage.morphology.diameter_closing "skimage.morphology.diameter_closing") [`skimage.morphology.max_tree`](#skimage.morphology.max_tree "skimage.morphology.max_tree") #### References `1` Walter, T., & Klein, J.-C. (2002). Automatic Detection of Microaneurysms in Color Fundus Images of the Human Retina by Means of the Bounding Box Closing. In A. Colosimo, P. Sirabella, A. Giuliani (Eds.), Medical Data Analysis. Lecture Notes in Computer Science, vol 2526, pp. 210-220. Springer Berlin Heidelberg. [DOI:10.1007/3-540-36104-9\_23](https://doi.org/10.1007/3-540-36104-9_23) `2` Carlinet, E., & Geraud, T. (2014). A Comparative Review of Component Tree Computation Algorithms. IEEE Transactions on Image Processing, 23(9), 3885-3895. [DOI:10.1109/TIP.2014.2336551](https://doi.org/10.1109/TIP.2014.2336551) #### Examples We create an image (quadratic function with a maximum in the center and 4 additional local maxima. ``` >>> w = 12 >>> x, y = np.mgrid[0:w,0:w] >>> f = 20 - 0.2*((x - w/2)**2 + (y-w/2)**2) >>> f[2:3,1:5] = 40; f[2:4,9:11] = 60; f[9:11,2:4] = 80 >>> f[9:10,9:11] = 100; f[10,10] = 100 >>> f = f.astype(int) ``` We can calculate the diameter opening: ``` >>> open = diameter_opening(f, 3, connectivity=1) ``` The peaks with a maximal extension of 2 or less are removed. The remaining peaks have all a maximal extension of at least 3. diamond ------- `skimage.morphology.diamond(radius, dtype=<class 'numpy.uint8'>)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/selem.py#L70-L97) Generates a flat, diamond-shaped structuring element. A pixel is part of the neighborhood (i.e. labeled 1) if the city block/Manhattan distance between it and the center of the neighborhood is no greater than radius. Parameters `radiusint` The radius of the diamond-shaped structuring element. Returns `selemndarray` The structuring element where elements of the neighborhood are 1 and 0 otherwise. Other Parameters `dtypedata-type` The data type of the structuring element. dilation -------- `skimage.morphology.dilation(image, selem=None, out=None, shift_x=False, shift_y=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/grey.py#L189-L252) Return greyscale morphological dilation of an image. Morphological dilation sets a pixel at (i,j) to the maximum over all pixels in the neighborhood centered at (i,j). Dilation enlarges bright regions and shrinks dark regions. Parameters `imagendarray` Image array. `selemndarray, optional` The neighborhood expressed as a 2-D array of 1’s and 0’s. If None, use cross-shaped structuring element (connectivity=1). `outndarray, optional` The array to store the result of the morphology. If None, is passed, a new array will be allocated. `shift_x, shift_ybool, optional` shift structuring element about center point. This only affects eccentric structuring elements (i.e. selem with even numbered sides). Returns `dilateduint8 array, same shape and type as image` The result of the morphological dilation. #### Notes For `uint8` (and `uint16` up to a certain bit-depth) data, the lower algorithm complexity makes the [`skimage.filters.rank.maximum`](skimage.filters.rank#skimage.filters.rank.maximum "skimage.filters.rank.maximum") function more efficient for larger images and structuring elements. #### Examples ``` >>> # Dilation enlarges bright regions >>> import numpy as np >>> from skimage.morphology import square >>> bright_pixel = np.array([[0, 0, 0, 0, 0], ... [0, 0, 0, 0, 0], ... [0, 0, 1, 0, 0], ... [0, 0, 0, 0, 0], ... [0, 0, 0, 0, 0]], dtype=np.uint8) >>> dilation(bright_pixel, square(3)) array([[0, 0, 0, 0, 0], [0, 1, 1, 1, 0], [0, 1, 1, 1, 0], [0, 1, 1, 1, 0], [0, 0, 0, 0, 0]], dtype=uint8) ``` ### Examples using `skimage.morphology.dilation` [Rank filters](https://scikit-image.org/docs/0.18.x/auto_examples/applications/plot_rank_filters.html#sphx-glr-auto-examples-applications-plot-rank-filters-py) disk ---- `skimage.morphology.disk(radius, dtype=<class 'numpy.uint8'>)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/selem.py#L100-L124) Generates a flat, disk-shaped structuring element. A pixel is within the neighborhood if the Euclidean distance between it and the origin is no greater than radius. Parameters `radiusint` The radius of the disk-shaped structuring element. Returns `selemndarray` The structuring element where elements of the neighborhood are 1 and 0 otherwise. Other Parameters `dtypedata-type` The data type of the structuring element. ### Examples using `skimage.morphology.disk` [Local Histogram Equalization](https://scikit-image.org/docs/0.18.x/auto_examples/color_exposure/plot_local_equalize.html#sphx-glr-auto-examples-color-exposure-plot-local-equalize-py) [Entropy](https://scikit-image.org/docs/0.18.x/auto_examples/filters/plot_entropy.html#sphx-glr-auto-examples-filters-plot-entropy-py) [Markers for watershed transform](https://scikit-image.org/docs/0.18.x/auto_examples/segmentation/plot_marked_watershed.html#sphx-glr-auto-examples-segmentation-plot-marked-watershed-py) [Flood Fill](https://scikit-image.org/docs/0.18.x/auto_examples/segmentation/plot_floodfill.html#sphx-glr-auto-examples-segmentation-plot-floodfill-py) [Segment human cells (in mitosis)](https://scikit-image.org/docs/0.18.x/auto_examples/applications/plot_human_mitosis.html#sphx-glr-auto-examples-applications-plot-human-mitosis-py) [Rank filters](https://scikit-image.org/docs/0.18.x/auto_examples/applications/plot_rank_filters.html#sphx-glr-auto-examples-applications-plot-rank-filters-py) erosion ------- `skimage.morphology.erosion(image, selem=None, out=None, shift_x=False, shift_y=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/grey.py#L130-L186) Return greyscale morphological erosion of an image. Morphological erosion sets a pixel at (i,j) to the minimum over all pixels in the neighborhood centered at (i,j). Erosion shrinks bright regions and enlarges dark regions. Parameters `imagendarray` Image array. `selemndarray, optional` The neighborhood expressed as an array of 1’s and 0’s. If None, use cross-shaped structuring element (connectivity=1). `outndarrays, optional` The array to store the result of the morphology. If None is passed, a new array will be allocated. `shift_x, shift_ybool, optional` shift structuring element about center point. This only affects eccentric structuring elements (i.e. selem with even numbered sides). Returns `erodedarray, same shape as image` The result of the morphological erosion. #### Notes For `uint8` (and `uint16` up to a certain bit-depth) data, the lower algorithm complexity makes the [`skimage.filters.rank.minimum`](skimage.filters.rank#skimage.filters.rank.minimum "skimage.filters.rank.minimum") function more efficient for larger images and structuring elements. #### Examples ``` >>> # Erosion shrinks bright regions >>> import numpy as np >>> from skimage.morphology import square >>> bright_square = np.array([[0, 0, 0, 0, 0], ... [0, 1, 1, 1, 0], ... [0, 1, 1, 1, 0], ... [0, 1, 1, 1, 0], ... [0, 0, 0, 0, 0]], dtype=np.uint8) >>> erosion(bright_square, square(3)) array([[0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]], dtype=uint8) ``` flood ----- `skimage.morphology.flood(image, seed_point, *, selem=None, connectivity=None, tolerance=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/_flood_fill.py#L124-L290) Mask corresponding to a flood fill. Starting at a specific `seed_point`, connected points equal or within `tolerance` of the seed value are found. Parameters `imagendarray` An n-dimensional array. `seed_pointtuple or int` The point in `image` used as the starting point for the flood fill. If the image is 1D, this point may be given as an integer. `selemndarray, optional` A structuring element used to determine the neighborhood of each evaluated pixel. It must contain only 1’s and 0’s, have the same number of dimensions as `image`. If not given, all adjacent pixels are considered as part of the neighborhood (fully connected). `connectivityint, optional` A number used to determine the neighborhood of each evaluated pixel. Adjacent pixels whose squared distance from the center is larger or equal to `connectivity` are considered neighbors. Ignored if `selem` is not None. `tolerancefloat or int, optional` If None (default), adjacent values must be strictly equal to the initial value of `image` at `seed_point`. This is fastest. If a value is given, a comparison will be done at every point and if within tolerance of the initial value will also be filled (inclusive). Returns `maskndarray` A Boolean array with the same shape as `image` is returned, with True values for areas connected to and equal (or within tolerance of) the seed point. All other values are False. #### Notes The conceptual analogy of this operation is the β€˜paint bucket’ tool in many raster graphics programs. This function returns just the mask representing the fill. If indices are desired rather than masks for memory reasons, the user can simply run [`numpy.nonzero`](https://numpy.org/doc/stable/reference/generated/numpy.nonzero.html#numpy.nonzero "(in NumPy v1.19)") on the result, save the indices, and discard this mask. #### Examples ``` >>> from skimage.morphology import flood >>> image = np.zeros((4, 7), dtype=int) >>> image[1:3, 1:3] = 1 >>> image[3, 0] = 1 >>> image[1:3, 4:6] = 2 >>> image[3, 6] = 3 >>> image array([[0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 0, 2, 2, 0], [0, 1, 1, 0, 2, 2, 0], [1, 0, 0, 0, 0, 0, 3]]) ``` Fill connected ones with 5, with full connectivity (diagonals included): ``` >>> mask = flood(image, (1, 1)) >>> image_flooded = image.copy() >>> image_flooded[mask] = 5 >>> image_flooded array([[0, 0, 0, 0, 0, 0, 0], [0, 5, 5, 0, 2, 2, 0], [0, 5, 5, 0, 2, 2, 0], [5, 0, 0, 0, 0, 0, 3]]) ``` Fill connected ones with 5, excluding diagonal points (connectivity 1): ``` >>> mask = flood(image, (1, 1), connectivity=1) >>> image_flooded = image.copy() >>> image_flooded[mask] = 5 >>> image_flooded array([[0, 0, 0, 0, 0, 0, 0], [0, 5, 5, 0, 2, 2, 0], [0, 5, 5, 0, 2, 2, 0], [1, 0, 0, 0, 0, 0, 3]]) ``` Fill with a tolerance: ``` >>> mask = flood(image, (0, 0), tolerance=1) >>> image_flooded = image.copy() >>> image_flooded[mask] = 5 >>> image_flooded array([[5, 5, 5, 5, 5, 5, 5], [5, 5, 5, 5, 2, 2, 5], [5, 5, 5, 5, 2, 2, 5], [5, 5, 5, 5, 5, 5, 3]]) ``` flood\_fill ----------- `skimage.morphology.flood_fill(image, seed_point, new_value, *, selem=None, connectivity=None, tolerance=None, in_place=False, inplace=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/_flood_fill.py#L15-L121) Perform flood filling on an image. Starting at a specific `seed_point`, connected points equal or within `tolerance` of the seed value are found, then set to `new_value`. Parameters `imagendarray` An n-dimensional array. `seed_pointtuple or int` The point in `image` used as the starting point for the flood fill. If the image is 1D, this point may be given as an integer. `new_valueimage type` New value to set the entire fill. This must be chosen in agreement with the dtype of `image`. `selemndarray, optional` A structuring element used to determine the neighborhood of each evaluated pixel. It must contain only 1’s and 0’s, have the same number of dimensions as `image`. If not given, all adjacent pixels are considered as part of the neighborhood (fully connected). `connectivityint, optional` A number used to determine the neighborhood of each evaluated pixel. Adjacent pixels whose squared distance from the center is less than or equal to `connectivity` are considered neighbors. Ignored if `selem` is not None. `tolerancefloat or int, optional` If None (default), adjacent values must be strictly equal to the value of `image` at `seed_point` to be filled. This is fastest. If a tolerance is provided, adjacent points with values within plus or minus tolerance from the seed point are filled (inclusive). `in_placebool, optional` If True, flood filling is applied to `image` in place. If False, the flood filled result is returned without modifying the input `image` (default). `inplacebool, optional` This parameter is deprecated and will be removed in version 0.19.0 in favor of in\_place. If True, flood filling is applied to `image` inplace. If False, the flood filled result is returned without modifying the input `image` (default). Returns `filledndarray` An array with the same shape as `image` is returned, with values in areas connected to and equal (or within tolerance of) the seed point replaced with `new_value`. #### Notes The conceptual analogy of this operation is the β€˜paint bucket’ tool in many raster graphics programs. #### Examples ``` >>> from skimage.morphology import flood_fill >>> image = np.zeros((4, 7), dtype=int) >>> image[1:3, 1:3] = 1 >>> image[3, 0] = 1 >>> image[1:3, 4:6] = 2 >>> image[3, 6] = 3 >>> image array([[0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 0, 2, 2, 0], [0, 1, 1, 0, 2, 2, 0], [1, 0, 0, 0, 0, 0, 3]]) ``` Fill connected ones with 5, with full connectivity (diagonals included): ``` >>> flood_fill(image, (1, 1), 5) array([[0, 0, 0, 0, 0, 0, 0], [0, 5, 5, 0, 2, 2, 0], [0, 5, 5, 0, 2, 2, 0], [5, 0, 0, 0, 0, 0, 3]]) ``` Fill connected ones with 5, excluding diagonal points (connectivity 1): ``` >>> flood_fill(image, (1, 1), 5, connectivity=1) array([[0, 0, 0, 0, 0, 0, 0], [0, 5, 5, 0, 2, 2, 0], [0, 5, 5, 0, 2, 2, 0], [1, 0, 0, 0, 0, 0, 3]]) ``` Fill with a tolerance: ``` >>> flood_fill(image, (0, 0), 5, tolerance=1) array([[5, 5, 5, 5, 5, 5, 5], [5, 5, 5, 5, 2, 2, 5], [5, 5, 5, 5, 2, 2, 5], [5, 5, 5, 5, 5, 5, 3]]) ``` h\_maxima --------- `skimage.morphology.h_maxima(image, h, selem=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/extrema.py#L48-L173) Determine all maxima of the image with height >= h. The local maxima are defined as connected sets of pixels with equal grey level strictly greater than the grey level of all pixels in direct neighborhood of the set. A local maximum M of height h is a local maximum for which there is at least one path joining M with an equal or higher local maximum on which the minimal value is f(M) - h (i.e. the values along the path are not decreasing by more than h with respect to the maximum’s value) and no path to an equal or higher local maximum for which the minimal value is greater. The global maxima of the image are also found by this function. Parameters `imagendarray` The input image for which the maxima are to be calculated. `hunsigned integer` The minimal height of all extracted maxima. `selemndarray, optional` The neighborhood expressed as an n-D array of 1’s and 0’s. Default is the ball of radius 1 according to the maximum norm (i.e. a 3x3 square for 2D images, a 3x3x3 cube for 3D images, etc.) Returns `h_maxndarray` The local maxima of height >= h and the global maxima. The resulting image is a binary image, where pixels belonging to the determined maxima take value 1, the others take value 0. See also `skimage.morphology.extrema.h_minima` `skimage.morphology.extrema.local_maxima` `skimage.morphology.extrema.local_minima` #### References `1` Soille, P., β€œMorphological Image Analysis: Principles and Applications” (Chapter 6), 2nd edition (2003), ISBN 3540429883. #### Examples ``` >>> import numpy as np >>> from skimage.morphology import extrema ``` We create an image (quadratic function with a maximum in the center and 4 additional constant maxima. The heights of the maxima are: 1, 21, 41, 61, 81 ``` >>> w = 10 >>> x, y = np.mgrid[0:w,0:w] >>> f = 20 - 0.2*((x - w/2)**2 + (y-w/2)**2) >>> f[2:4,2:4] = 40; f[2:4,7:9] = 60; f[7:9,2:4] = 80; f[7:9,7:9] = 100 >>> f = f.astype(int) ``` We can calculate all maxima with a height of at least 40: ``` >>> maxima = extrema.h_maxima(f, 40) ``` The resulting image will contain 3 local maxima. h\_minima --------- `skimage.morphology.h_minima(image, h, selem=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/extrema.py#L176-L269) Determine all minima of the image with depth >= h. The local minima are defined as connected sets of pixels with equal grey level strictly smaller than the grey levels of all pixels in direct neighborhood of the set. A local minimum M of depth h is a local minimum for which there is at least one path joining M with an equal or lower local minimum on which the maximal value is f(M) + h (i.e. the values along the path are not increasing by more than h with respect to the minimum’s value) and no path to an equal or lower local minimum for which the maximal value is smaller. The global minima of the image are also found by this function. Parameters `imagendarray` The input image for which the minima are to be calculated. `hunsigned integer` The minimal depth of all extracted minima. `selemndarray, optional` The neighborhood expressed as an n-D array of 1’s and 0’s. Default is the ball of radius 1 according to the maximum norm (i.e. a 3x3 square for 2D images, a 3x3x3 cube for 3D images, etc.) Returns `h_minndarray` The local minima of depth >= h and the global minima. The resulting image is a binary image, where pixels belonging to the determined minima take value 1, the others take value 0. See also `skimage.morphology.extrema.h_maxima` `skimage.morphology.extrema.local_maxima` `skimage.morphology.extrema.local_minima` #### References `1` Soille, P., β€œMorphological Image Analysis: Principles and Applications” (Chapter 6), 2nd edition (2003), ISBN 3540429883. #### Examples ``` >>> import numpy as np >>> from skimage.morphology import extrema ``` We create an image (quadratic function with a minimum in the center and 4 additional constant maxima. The depth of the minima are: 1, 21, 41, 61, 81 ``` >>> w = 10 >>> x, y = np.mgrid[0:w,0:w] >>> f = 180 + 0.2*((x - w/2)**2 + (y-w/2)**2) >>> f[2:4,2:4] = 160; f[2:4,7:9] = 140; f[7:9,2:4] = 120; f[7:9,7:9] = 100 >>> f = f.astype(int) ``` We can calculate all minima with a depth of at least 40: ``` >>> minima = extrema.h_minima(f, 40) ``` The resulting image will contain 3 local minima. label ----- `skimage.morphology.label(input, background=None, return_num=False, connectivity=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/measure/_label.py#L32-L120) Label connected regions of an integer array. Two pixels are connected when they are neighbors and have the same value. In 2D, they can be neighbors either in a 1- or 2-connected sense. The value refers to the maximum number of orthogonal hops to consider a pixel/voxel a neighbor: ``` 1-connectivity 2-connectivity diagonal connection close-up [ ] [ ] [ ] [ ] [ ] | \ | / | <- hop 2 [ ]--[x]--[ ] [ ]--[x]--[ ] [x]--[ ] | / | \ hop 1 [ ] [ ] [ ] [ ] ``` Parameters `inputndarray of dtype int` Image to label. `backgroundint, optional` Consider all pixels with this value as background pixels, and label them as 0. By default, 0-valued pixels are considered as background pixels. `return_numbool, optional` Whether to return the number of assigned labels. `connectivityint, optional` Maximum number of orthogonal hops to consider a pixel/voxel as a neighbor. Accepted values are ranging from 1 to input.ndim. If `None`, a full connectivity of `input.ndim` is used. Returns `labelsndarray of dtype int` Labeled array, where all connected regions are assigned the same integer value. `numint, optional` Number of labels, which equals the maximum label index and is only returned if return\_num is `True`. See also `regionprops` `regionprops_table` #### References `1` Christophe Fiorio and Jens Gustedt, β€œTwo linear time Union-Find strategies for image processing”, Theoretical Computer Science 154 (1996), pp. 165-181. `2` Kensheng Wu, Ekow Otoo and Arie Shoshani, β€œOptimizing connected component labeling algorithms”, Paper LBNL-56864, 2005, Lawrence Berkeley National Laboratory (University of California), <http://repositories.cdlib.org/lbnl/LBNL-56864> #### Examples ``` >>> import numpy as np >>> x = np.eye(3).astype(int) >>> print(x) [[1 0 0] [0 1 0] [0 0 1]] >>> print(label(x, connectivity=1)) [[1 0 0] [0 2 0] [0 0 3]] >>> print(label(x, connectivity=2)) [[1 0 0] [0 1 0] [0 0 1]] >>> print(label(x, background=-1)) [[1 2 2] [2 1 2] [2 2 1]] >>> x = np.array([[1, 0, 0], ... [1, 1, 5], ... [0, 0, 0]]) >>> print(label(x)) [[1 0 0] [1 1 2] [0 0 0]] ``` local\_maxima ------------- `skimage.morphology.local_maxima(image, selem=None, connectivity=None, indices=False, allow_borders=True)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/extrema.py#L272-L432) Find local maxima of n-dimensional array. The local maxima are defined as connected sets of pixels with equal gray level (plateaus) strictly greater than the gray levels of all pixels in the neighborhood. Parameters `imagendarray` An n-dimensional array. `selemndarray, optional` A structuring element used to determine the neighborhood of each evaluated pixel (`True` denotes a connected pixel). It must be a boolean array and have the same number of dimensions as `image`. If neither `selem` nor `connectivity` are given, all adjacent pixels are considered as part of the neighborhood. `connectivityint, optional` A number used to determine the neighborhood of each evaluated pixel. Adjacent pixels whose squared distance from the center is less than or equal to `connectivity` are considered neighbors. Ignored if `selem` is not None. `indicesbool, optional` If True, the output will be a tuple of one-dimensional arrays representing the indices of local maxima in each dimension. If False, the output will be a boolean array with the same shape as `image`. `allow_bordersbool, optional` If true, plateaus that touch the image border are valid maxima. Returns `maximandarray or tuple[ndarray]` If `indices` is false, a boolean array with the same shape as `image` is returned with `True` indicating the position of local maxima (`False` otherwise). If `indices` is true, a tuple of one-dimensional arrays containing the coordinates (indices) of all found maxima. Warns UserWarning If `allow_borders` is false and any dimension of the given `image` is shorter than 3 samples, maxima can’t exist and a warning is shown. See also [`skimage.morphology.local_minima`](#skimage.morphology.local_minima "skimage.morphology.local_minima") [`skimage.morphology.h_maxima`](#skimage.morphology.h_maxima "skimage.morphology.h_maxima") [`skimage.morphology.h_minima`](#skimage.morphology.h_minima "skimage.morphology.h_minima") #### Notes This function operates on the following ideas: 1. Make a first pass over the image’s last dimension and flag candidates for local maxima by comparing pixels in only one direction. If the pixels aren’t connected in the last dimension all pixels are flagged as candidates instead. For each candidate: 2. Perform a flood-fill to find all connected pixels that have the same gray value and are part of the plateau. 3. Consider the connected neighborhood of a plateau: if no bordering sample has a higher gray level, mark the plateau as a definite local maximum. #### Examples ``` >>> from skimage.morphology import local_maxima >>> image = np.zeros((4, 7), dtype=int) >>> image[1:3, 1:3] = 1 >>> image[3, 0] = 1 >>> image[1:3, 4:6] = 2 >>> image[3, 6] = 3 >>> image array([[0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 0, 2, 2, 0], [0, 1, 1, 0, 2, 2, 0], [1, 0, 0, 0, 0, 0, 3]]) ``` Find local maxima by comparing to all neighboring pixels (maximal connectivity): ``` >>> local_maxima(image) array([[False, False, False, False, False, False, False], [False, True, True, False, False, False, False], [False, True, True, False, False, False, False], [ True, False, False, False, False, False, True]]) >>> local_maxima(image, indices=True) (array([1, 1, 2, 2, 3, 3]), array([1, 2, 1, 2, 0, 6])) ``` Find local maxima without comparing to diagonal pixels (connectivity 1): ``` >>> local_maxima(image, connectivity=1) array([[False, False, False, False, False, False, False], [False, True, True, False, True, True, False], [False, True, True, False, True, True, False], [ True, False, False, False, False, False, True]]) ``` and exclude maxima that border the image edge: ``` >>> local_maxima(image, connectivity=1, allow_borders=False) array([[False, False, False, False, False, False, False], [False, True, True, False, True, True, False], [False, True, True, False, True, True, False], [False, False, False, False, False, False, False]]) ``` local\_minima ------------- `skimage.morphology.local_minima(image, selem=None, connectivity=None, indices=False, allow_borders=True)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/extrema.py#L435-L542) Find local minima of n-dimensional array. The local minima are defined as connected sets of pixels with equal gray level (plateaus) strictly smaller than the gray levels of all pixels in the neighborhood. Parameters `imagendarray` An n-dimensional array. `selemndarray, optional` A structuring element used to determine the neighborhood of each evaluated pixel (`True` denotes a connected pixel). It must be a boolean array and have the same number of dimensions as `image`. If neither `selem` nor `connectivity` are given, all adjacent pixels are considered as part of the neighborhood. `connectivityint, optional` A number used to determine the neighborhood of each evaluated pixel. Adjacent pixels whose squared distance from the center is less than or equal to `connectivity` are considered neighbors. Ignored if `selem` is not None. `indicesbool, optional` If True, the output will be a tuple of one-dimensional arrays representing the indices of local minima in each dimension. If False, the output will be a boolean array with the same shape as `image`. `allow_bordersbool, optional` If true, plateaus that touch the image border are valid minima. Returns `minimandarray or tuple[ndarray]` If `indices` is false, a boolean array with the same shape as `image` is returned with `True` indicating the position of local minima (`False` otherwise). If `indices` is true, a tuple of one-dimensional arrays containing the coordinates (indices) of all found minima. See also [`skimage.morphology.local_maxima`](#skimage.morphology.local_maxima "skimage.morphology.local_maxima") [`skimage.morphology.h_maxima`](#skimage.morphology.h_maxima "skimage.morphology.h_maxima") [`skimage.morphology.h_minima`](#skimage.morphology.h_minima "skimage.morphology.h_minima") #### Notes This function operates on the following ideas: 1. Make a first pass over the image’s last dimension and flag candidates for local minima by comparing pixels in only one direction. If the pixels aren’t connected in the last dimension all pixels are flagged as candidates instead. For each candidate: 2. Perform a flood-fill to find all connected pixels that have the same gray value and are part of the plateau. 3. Consider the connected neighborhood of a plateau: if no bordering sample has a smaller gray level, mark the plateau as a definite local minimum. #### Examples ``` >>> from skimage.morphology import local_minima >>> image = np.zeros((4, 7), dtype=int) >>> image[1:3, 1:3] = -1 >>> image[3, 0] = -1 >>> image[1:3, 4:6] = -2 >>> image[3, 6] = -3 >>> image array([[ 0, 0, 0, 0, 0, 0, 0], [ 0, -1, -1, 0, -2, -2, 0], [ 0, -1, -1, 0, -2, -2, 0], [-1, 0, 0, 0, 0, 0, -3]]) ``` Find local minima by comparing to all neighboring pixels (maximal connectivity): ``` >>> local_minima(image) array([[False, False, False, False, False, False, False], [False, True, True, False, False, False, False], [False, True, True, False, False, False, False], [ True, False, False, False, False, False, True]]) >>> local_minima(image, indices=True) (array([1, 1, 2, 2, 3, 3]), array([1, 2, 1, 2, 0, 6])) ``` Find local minima without comparing to diagonal pixels (connectivity 1): ``` >>> local_minima(image, connectivity=1) array([[False, False, False, False, False, False, False], [False, True, True, False, True, True, False], [False, True, True, False, True, True, False], [ True, False, False, False, False, False, True]]) ``` and exclude minima that border the image edge: ``` >>> local_minima(image, connectivity=1, allow_borders=False) array([[False, False, False, False, False, False, False], [False, True, True, False, True, True, False], [False, True, True, False, True, True, False], [False, False, False, False, False, False, False]]) ``` max\_tree --------- `skimage.morphology.max_tree(image, connectivity=1)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/max_tree.py#L53-L143) Build the max tree from an image. Component trees represent the hierarchical structure of the connected components resulting from sequential thresholding operations applied to an image. A connected component at one level is parent of a component at a higher level if the latter is included in the first. A max-tree is an efficient representation of a component tree. A connected component at one level is represented by one reference pixel at this level, which is parent to all other pixels at that level and to the reference pixel at the level above. The max-tree is the basis for many morphological operators, namely connected operators. Parameters `imagendarray` The input image for which the max-tree is to be calculated. This image can be of any type. `connectivityunsigned int, optional` The neighborhood connectivity. The integer represents the maximum number of orthogonal steps to reach a neighbor. In 2D, it is 1 for a 4-neighborhood and 2 for a 8-neighborhood. Default value is 1. Returns `parentndarray, int64` Array of same shape as image. The value of each pixel is the index of its parent in the ravelled array. `tree_traverser1D array, int64` The ordered pixel indices (referring to the ravelled array). The pixels are ordered such that every pixel is preceded by its parent (except for the root which has no parent). #### References `1` Salembier, P., Oliveras, A., & Garrido, L. (1998). Antiextensive Connected Operators for Image and Sequence Processing. IEEE Transactions on Image Processing, 7(4), 555-570. [DOI:10.1109/83.663500](https://doi.org/10.1109/83.663500) `2` Berger, C., Geraud, T., Levillain, R., Widynski, N., Baillard, A., Bertin, E. (2007). Effective Component Tree Computation with Application to Pattern Recognition in Astronomical Imaging. In International Conference on Image Processing (ICIP) (pp. 41-44). [DOI:10.1109/ICIP.2007.4379949](https://doi.org/10.1109/ICIP.2007.4379949) `3` Najman, L., & Couprie, M. (2006). Building the component tree in quasi-linear time. IEEE Transactions on Image Processing, 15(11), 3531-3539. [DOI:10.1109/TIP.2006.877518](https://doi.org/10.1109/TIP.2006.877518) `4` Carlinet, E., & Geraud, T. (2014). A Comparative Review of Component Tree Computation Algorithms. IEEE Transactions on Image Processing, 23(9), 3885-3895. [DOI:10.1109/TIP.2014.2336551](https://doi.org/10.1109/TIP.2014.2336551) #### Examples We create a small sample image (Figure 1 from [4]) and build the max-tree. ``` >>> image = np.array([[15, 13, 16], [12, 12, 10], [16, 12, 14]]) >>> P, S = max_tree(image, connectivity=2) ``` max\_tree\_local\_maxima ------------------------ `skimage.morphology.max_tree_local_maxima(image, connectivity=1, parent=None, tree_traverser=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/max_tree.py#L582-L670) Determine all local maxima of the image. The local maxima are defined as connected sets of pixels with equal gray level strictly greater than the gray levels of all pixels in direct neighborhood of the set. The function labels the local maxima. Technically, the implementation is based on the max-tree representation of an image. The function is very efficient if the max-tree representation has already been computed. Otherwise, it is preferable to use the function local\_maxima. Parameters `imagendarray` The input image for which the maxima are to be calculated. **connectivity: unsigned int, optional** The neighborhood connectivity. The integer represents the maximum number of orthogonal steps to reach a neighbor. In 2D, it is 1 for a 4-neighborhood and 2 for a 8-neighborhood. Default value is 1. **parent: ndarray, int64, optional** The value of each pixel is the index of its parent in the ravelled array. **tree\_traverser: 1D array, int64, optional** The ordered pixel indices (referring to the ravelled array). The pixels are ordered such that every pixel is preceded by its parent (except for the root which has no parent). Returns `local_maxndarray, uint64` Labeled local maxima of the image. See also [`skimage.morphology.local_maxima`](#skimage.morphology.local_maxima "skimage.morphology.local_maxima") [`skimage.morphology.max_tree`](#skimage.morphology.max_tree "skimage.morphology.max_tree") #### References `1` Vincent L., Proc. β€œGrayscale area openings and closings, their efficient implementation and applications”, EURASIP Workshop on Mathematical Morphology and its Applications to Signal Processing, Barcelona, Spain, pp.22-27, May 1993. `2` Soille, P., β€œMorphological Image Analysis: Principles and Applications” (Chapter 6), 2nd edition (2003), ISBN 3540429883. [DOI:10.1007/978-3-662-05088-0](https://doi.org/10.1007/978-3-662-05088-0) `3` Salembier, P., Oliveras, A., & Garrido, L. (1998). Antiextensive Connected Operators for Image and Sequence Processing. IEEE Transactions on Image Processing, 7(4), 555-570. [DOI:10.1109/83.663500](https://doi.org/10.1109/83.663500) `4` Najman, L., & Couprie, M. (2006). Building the component tree in quasi-linear time. IEEE Transactions on Image Processing, 15(11), 3531-3539. [DOI:10.1109/TIP.2006.877518](https://doi.org/10.1109/TIP.2006.877518) `5` Carlinet, E., & Geraud, T. (2014). A Comparative Review of Component Tree Computation Algorithms. IEEE Transactions on Image Processing, 23(9), 3885-3895. [DOI:10.1109/TIP.2014.2336551](https://doi.org/10.1109/TIP.2014.2336551) #### Examples We create an image (quadratic function with a maximum in the center and 4 additional constant maxima. ``` >>> w = 10 >>> x, y = np.mgrid[0:w,0:w] >>> f = 20 - 0.2*((x - w/2)**2 + (y-w/2)**2) >>> f[2:4,2:4] = 40; f[2:4,7:9] = 60; f[7:9,2:4] = 80; f[7:9,7:9] = 100 >>> f = f.astype(int) ``` We can calculate all local maxima: ``` >>> maxima = max_tree_local_maxima(f) ``` The resulting image contains the labeled local maxima. medial\_axis ------------ `skimage.morphology.medial_axis(image, mask=None, return_distance=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/_skeletonize.py#L364-L510) Compute the medial axis transform of a binary image Parameters `imagebinary ndarray, shape (M, N)` The image of the shape to be skeletonized. `maskbinary ndarray, shape (M, N), optional` If a mask is given, only those elements in `image` with a true value in `mask` are used for computing the medial axis. `return_distancebool, optional` If true, the distance transform is returned as well as the skeleton. Returns `outndarray of bools` Medial axis transform of the image `distndarray of ints, optional` Distance transform of the image (only returned if `return_distance` is True) See also [`skeletonize`](#skimage.morphology.skeletonize "skimage.morphology.skeletonize") #### Notes This algorithm computes the medial axis transform of an image as the ridges of its distance transform. The different steps of the algorithm are as follows * A lookup table is used, that assigns 0 or 1 to each configuration of the 3x3 binary square, whether the central pixel should be removed or kept. We want a point to be removed if it has more than one neighbor and if removing it does not change the number of connected components. * The distance transform to the background is computed, as well as the cornerness of the pixel. * The foreground (value of 1) points are ordered by the distance transform, then the cornerness. * A cython function is called to reduce the image to its skeleton. It processes pixels in the order determined at the previous step, and removes or maintains a pixel according to the lookup table. Because of the ordering, it is possible to process all pixels in only one pass. #### Examples ``` >>> square = np.zeros((7, 7), dtype=np.uint8) >>> square[1:-1, 2:-2] = 1 >>> square array([[0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0]], dtype=uint8) >>> medial_axis(square).astype(np.uint8) array([[0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 1, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 1, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0]], dtype=uint8) ``` octagon ------- `skimage.morphology.octagon(m, n, dtype=<class 'numpy.uint8'>)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/selem.py#L262-L300) Generates an octagon shaped structuring element. For a given size of (m) horizontal and vertical sides and a given (n) height or width of slanted sides octagon is generated. The slanted sides are 45 or 135 degrees to the horizontal axis and hence the widths and heights are equal. Parameters `mint` The size of the horizontal and vertical sides. `nint` The height or width of the slanted sides. Returns `selemndarray` The structuring element where elements of the neighborhood are 1 and 0 otherwise. Other Parameters `dtypedata-type` The data type of the structuring element. octahedron ---------- `skimage.morphology.octahedron(radius, dtype=<class 'numpy.uint8'>)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/selem.py#L197-L228) Generates a octahedron-shaped structuring element. This is the 3D equivalent of a diamond. A pixel is part of the neighborhood (i.e. labeled 1) if the city block/Manhattan distance between it and the center of the neighborhood is no greater than radius. Parameters `radiusint` The radius of the octahedron-shaped structuring element. Returns `selemndarray` The structuring element where elements of the neighborhood are 1 and 0 otherwise. Other Parameters `dtypedata-type` The data type of the structuring element. opening ------- `skimage.morphology.opening(image, selem=None, out=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/grey.py#L255-L302) Return greyscale morphological opening of an image. The morphological opening on an image is defined as an erosion followed by a dilation. Opening can remove small bright spots (i.e. β€œsalt”) and connect small dark cracks. This tends to β€œopen” up (dark) gaps between (bright) features. Parameters `imagendarray` Image array. `selemndarray, optional` The neighborhood expressed as an array of 1’s and 0’s. If None, use cross-shaped structuring element (connectivity=1). `outndarray, optional` The array to store the result of the morphology. If None is passed, a new array will be allocated. Returns `openingarray, same shape and type as image` The result of the morphological opening. #### Examples ``` >>> # Open up gap between two bright regions (but also shrink regions) >>> import numpy as np >>> from skimage.morphology import square >>> bad_connection = np.array([[1, 0, 0, 0, 1], ... [1, 1, 0, 1, 1], ... [1, 1, 1, 1, 1], ... [1, 1, 0, 1, 1], ... [1, 0, 0, 0, 1]], dtype=np.uint8) >>> opening(bad_connection, square(3)) array([[0, 0, 0, 0, 0], [1, 1, 0, 1, 1], [1, 1, 0, 1, 1], [1, 1, 0, 1, 1], [0, 0, 0, 0, 0]], dtype=uint8) ``` reconstruction -------------- `skimage.morphology.reconstruction(seed, mask, method='dilation', selem=None, offset=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/greyreconstruct.py#L17-L211) Perform a morphological reconstruction of an image. Morphological reconstruction by dilation is similar to basic morphological dilation: high-intensity values will replace nearby low-intensity values. The basic dilation operator, however, uses a structuring element to determine how far a value in the input image can spread. In contrast, reconstruction uses two images: a β€œseed” image, which specifies the values that spread, and a β€œmask” image, which gives the maximum allowed value at each pixel. The mask image, like the structuring element, limits the spread of high-intensity values. Reconstruction by erosion is simply the inverse: low-intensity values spread from the seed image and are limited by the mask image, which represents the minimum allowed value. Alternatively, you can think of reconstruction as a way to isolate the connected regions of an image. For dilation, reconstruction connects regions marked by local maxima in the seed image: neighboring pixels less-than-or-equal-to those seeds are connected to the seeded region. Local maxima with values larger than the seed image will get truncated to the seed value. Parameters `seedndarray` The seed image (a.k.a. marker image), which specifies the values that are dilated or eroded. `maskndarray` The maximum (dilation) / minimum (erosion) allowed value at each pixel. `method{β€˜dilation’|’erosion’}, optional` Perform reconstruction by dilation or erosion. In dilation (or erosion), the seed image is dilated (or eroded) until limited by the mask image. For dilation, each seed value must be less than or equal to the corresponding mask value; for erosion, the reverse is true. Default is β€˜dilation’. `selemndarray, optional` The neighborhood expressed as an n-D array of 1’s and 0’s. Default is the n-D square of radius equal to 1 (i.e. a 3x3 square for 2D images, a 3x3x3 cube for 3D images, etc.) `offsetndarray, optional` The coordinates of the center of the structuring element. Default is located on the geometrical center of the selem, in that case selem dimensions must be odd. Returns `reconstructedndarray` The result of morphological reconstruction. #### Notes The algorithm is taken from [[1]](#r4e1a5d6f491d-1). Applications for greyscale reconstruction are discussed in [[2]](#r4e1a5d6f491d-2) and [[3]](#r4e1a5d6f491d-3). #### References `1` Robinson, β€œEfficient morphological reconstruction: a downhill filter”, Pattern Recognition Letters 25 (2004) 1759-1767. `2` Vincent, L., β€œMorphological Grayscale Reconstruction in Image Analysis: Applications and Efficient Algorithms”, IEEE Transactions on Image Processing (1993) `3` Soille, P., β€œMorphological Image Analysis: Principles and Applications”, Chapter 6, 2nd edition (2003), ISBN 3540429883. #### Examples ``` >>> import numpy as np >>> from skimage.morphology import reconstruction ``` First, we create a sinusoidal mask image with peaks at middle and ends. ``` >>> x = np.linspace(0, 4 * np.pi) >>> y_mask = np.cos(x) ``` Then, we create a seed image initialized to the minimum mask value (for reconstruction by dilation, min-intensity values don’t spread) and add β€œseeds” to the left and right peak, but at a fraction of peak value (1). ``` >>> y_seed = y_mask.min() * np.ones_like(x) >>> y_seed[0] = 0.5 >>> y_seed[-1] = 0 >>> y_rec = reconstruction(y_seed, y_mask) ``` The reconstructed image (or curve, in this case) is exactly the same as the mask image, except that the peaks are truncated to 0.5 and 0. The middle peak disappears completely: Since there were no seed values in this peak region, its reconstructed value is truncated to the surrounding value (-1). As a more practical example, we try to extract the bright features of an image by subtracting a background image created by reconstruction. ``` >>> y, x = np.mgrid[:20:0.5, :20:0.5] >>> bumps = np.sin(x) + np.sin(y) ``` To create the background image, set the mask image to the original image, and the seed image to the original image with an intensity offset, `h`. ``` >>> h = 0.3 >>> seed = bumps - h >>> background = reconstruction(seed, bumps) ``` The resulting reconstructed image looks exactly like the original image, but with the peaks of the bumps cut off. Subtracting this reconstructed image from the original image leaves just the peaks of the bumps ``` >>> hdome = bumps - background ``` This operation is known as the h-dome of the image and leaves features of height `h` in the subtracted image. rectangle --------- `skimage.morphology.rectangle(nrows, ncols, dtype=<class 'numpy.uint8'>)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/selem.py#L34-L67) Generates a flat, rectangular-shaped structuring element. Every pixel in the rectangle generated for a given width and given height belongs to the neighborhood. Parameters `nrowsint` The number of rows of the rectangle. `ncolsint` The number of columns of the rectangle. Returns `selemndarray` A structuring element consisting only of ones, i.e. every pixel belongs to the neighborhood. Other Parameters `dtypedata-type` The data type of the structuring element. #### Notes * The use of `width` and `height` has been deprecated in version 0.18.0. Use `nrows` and `ncols` instead. remove\_small\_holes -------------------- `skimage.morphology.remove_small_holes(ar, area_threshold=64, connectivity=1, in_place=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/misc.py#L142-L227) Remove contiguous holes smaller than the specified size. Parameters `arndarray (arbitrary shape, int or bool type)` The array containing the connected components of interest. `area_thresholdint, optional (default: 64)` The maximum area, in pixels, of a contiguous hole that will be filled. Replaces `min_size`. `connectivityint, {1, 2, …, ar.ndim}, optional (default: 1)` The connectivity defining the neighborhood of a pixel. `in_placebool, optional (default: False)` If `True`, remove the connected components in the input array itself. Otherwise, make a copy. Returns `outndarray, same shape and type as input ar` The input array with small holes within connected components removed. Raises TypeError If the input array is of an invalid type, such as float or string. ValueError If the input array contains negative values. #### Notes If the array type is int, it is assumed that it contains already-labeled objects. The labels are not kept in the output image (this function always outputs a bool image). It is suggested that labeling is completed after using this function. #### Examples ``` >>> from skimage import morphology >>> a = np.array([[1, 1, 1, 1, 1, 0], ... [1, 1, 1, 0, 1, 0], ... [1, 0, 0, 1, 1, 0], ... [1, 1, 1, 1, 1, 0]], bool) >>> b = morphology.remove_small_holes(a, 2) >>> b array([[ True, True, True, True, True, False], [ True, True, True, True, True, False], [ True, False, False, True, True, False], [ True, True, True, True, True, False]]) >>> c = morphology.remove_small_holes(a, 2, connectivity=2) >>> c array([[ True, True, True, True, True, False], [ True, True, True, False, True, False], [ True, False, False, True, True, False], [ True, True, True, True, True, False]]) >>> d = morphology.remove_small_holes(a, 2, in_place=True) >>> d is a True ``` ### Examples using `skimage.morphology.remove_small_holes` [Measure region properties](https://scikit-image.org/docs/0.18.x/auto_examples/segmentation/plot_regionprops.html#sphx-glr-auto-examples-segmentation-plot-regionprops-py) remove\_small\_objects ---------------------- `skimage.morphology.remove_small_objects(ar, min_size=64, connectivity=1, in_place=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/misc.py#L51-L139) Remove objects smaller than the specified size. Expects ar to be an array with labeled objects, and removes objects smaller than min\_size. If `ar` is bool, the image is first labeled. This leads to potentially different behavior for bool and 0-and-1 arrays. Parameters `arndarray (arbitrary shape, int or bool type)` The array containing the objects of interest. If the array type is int, the ints must be non-negative. `min_sizeint, optional (default: 64)` The smallest allowable object size. `connectivityint, {1, 2, …, ar.ndim}, optional (default: 1)` The connectivity defining the neighborhood of a pixel. Used during labelling if `ar` is bool. `in_placebool, optional (default: False)` If `True`, remove the objects in the input array itself. Otherwise, make a copy. Returns `outndarray, same shape and type as input ar` The input array with small connected components removed. Raises TypeError If the input array is of an invalid type, such as float or string. ValueError If the input array contains negative values. #### Examples ``` >>> from skimage import morphology >>> a = np.array([[0, 0, 0, 1, 0], ... [1, 1, 1, 0, 0], ... [1, 1, 1, 0, 1]], bool) >>> b = morphology.remove_small_objects(a, 6) >>> b array([[False, False, False, False, False], [ True, True, True, False, False], [ True, True, True, False, False]]) >>> c = morphology.remove_small_objects(a, 7, connectivity=2) >>> c array([[False, False, False, True, False], [ True, True, True, False, False], [ True, True, True, False, False]]) >>> d = morphology.remove_small_objects(a, 6, in_place=True) >>> d is a True ``` ### Examples using `skimage.morphology.remove_small_objects` [Measure region properties](https://scikit-image.org/docs/0.18.x/auto_examples/segmentation/plot_regionprops.html#sphx-glr-auto-examples-segmentation-plot-regionprops-py) skeletonize ----------- `skimage.morphology.skeletonize(image, *, method=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/_skeletonize.py#L16-L90) Compute the skeleton of a binary image. Thinning is used to reduce each connected component in a binary image to a single-pixel wide skeleton. Parameters `imagendarray, 2D or 3D` A binary image containing the objects to be skeletonized. Zeros represent background, nonzero values are foreground. `method{β€˜zhang’, β€˜lee’}, optional` Which algorithm to use. Zhang’s algorithm [[Zha84]](#rc75910d539e3-zha84) only works for 2D images, and is the default for 2D. Lee’s algorithm [[Lee94]](#rc75910d539e3-lee94) works for 2D or 3D images and is the default for 3D. Returns `skeletonndarray` The thinned image. See also [`medial_axis`](#skimage.morphology.medial_axis "skimage.morphology.medial_axis") #### References `Lee94` T.-C. Lee, R.L. Kashyap and C.-N. Chu, Building skeleton models via 3-D medial surface/axis thinning algorithms. Computer Vision, Graphics, and Image Processing, 56(6):462-478, 1994. `Zha84` A fast parallel algorithm for thinning digital patterns, T. Y. Zhang and C. Y. Suen, Communications of the ACM, March 1984, Volume 27, Number 3. #### Examples ``` >>> X, Y = np.ogrid[0:9, 0:9] >>> ellipse = (1./3 * (X - 4)**2 + (Y - 4)**2 < 3**2).astype(np.uint8) >>> ellipse array([[0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0]], dtype=uint8) >>> skel = skeletonize(ellipse) >>> skel.astype(np.uint8) array([[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8) ``` skeletonize\_3d --------------- `skimage.morphology.skeletonize_3d(image)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/_skeletonize.py#L579-L647) Compute the skeleton of a binary image. Thinning is used to reduce each connected component in a binary image to a single-pixel wide skeleton. Parameters `imagendarray, 2D or 3D` A binary image containing the objects to be skeletonized. Zeros represent background, nonzero values are foreground. Returns `skeletonndarray` The thinned image. See also `skeletonize,` [`medial_axis`](#skimage.morphology.medial_axis "skimage.morphology.medial_axis") #### Notes The method of [[Lee94]](#rc9cdb497d267-lee94) uses an octree data structure to examine a 3x3x3 neighborhood of a pixel. The algorithm proceeds by iteratively sweeping over the image, and removing pixels at each iteration until the image stops changing. Each iteration consists of two steps: first, a list of candidates for removal is assembled; then pixels from this list are rechecked sequentially, to better preserve connectivity of the image. The algorithm this function implements is different from the algorithms used by either [`skeletonize`](#skimage.morphology.skeletonize "skimage.morphology.skeletonize") or [`medial_axis`](#skimage.morphology.medial_axis "skimage.morphology.medial_axis"), thus for 2D images the results produced by this function are generally different. #### References `Lee94` T.-C. Lee, R.L. Kashyap and C.-N. Chu, Building skeleton models via 3-D medial surface/axis thinning algorithms. Computer Vision, Graphics, and Image Processing, 56(6):462-478, 1994. square ------ `skimage.morphology.square(width, dtype=<class 'numpy.uint8'>)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/selem.py#L8-L31) Generates a flat, square-shaped structuring element. Every pixel along the perimeter has a chessboard distance no greater than radius (radius=floor(width/2)) pixels. Parameters `widthint` The width and height of the square. Returns `selemndarray` A structuring element consisting only of ones, i.e. every pixel belongs to the neighborhood. Other Parameters `dtypedata-type` The data type of the structuring element. star ---- `skimage.morphology.star(a, dtype=<class 'numpy.uint8'>)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/selem.py#L303-L349) Generates a star shaped structuring element. Start has 8 vertices and is an overlap of square of size `2*a + 1` with its 45 degree rotated version. The slanted sides are 45 or 135 degrees to the horizontal axis. Parameters `aint` Parameter deciding the size of the star structural element. The side of the square array returned is `2*a + 1 + 2*floor(a / 2)`. Returns `selemndarray` The structuring element where elements of the neighborhood are 1 and 0 otherwise. Other Parameters `dtypedata-type` The data type of the structuring element. thin ---- `skimage.morphology.thin(image, max_iter=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/_skeletonize.py#L259-L356) Perform morphological thinning of a binary image. Parameters `imagebinary (M, N) ndarray` The image to be thinned. `max_iterint, number of iterations, optional` Regardless of the value of this parameter, the thinned image is returned immediately if an iteration produces no change. If this parameter is specified it thus sets an upper bound on the number of iterations performed. Returns `outndarray of bool` Thinned image. See also `skeletonize,` [`medial_axis`](#skimage.morphology.medial_axis "skimage.morphology.medial_axis") #### Notes This algorithm [[1]](#r2b353e29d473-1) works by making multiple passes over the image, removing pixels matching a set of criteria designed to thin connected regions while preserving eight-connected components and 2 x 2 squares [[2]](#r2b353e29d473-2). In each of the two sub-iterations the algorithm correlates the intermediate skeleton image with a neighborhood mask, then looks up each neighborhood in a lookup table indicating whether the central pixel should be deleted in that sub-iteration. #### References `1` Z. Guo and R. W. Hall, β€œParallel thinning with two-subiteration algorithms,” Comm. ACM, vol. 32, no. 3, pp. 359-373, 1989. [DOI:10.1145/62065.62074](https://doi.org/10.1145/62065.62074) `2` Lam, L., Seong-Whan Lee, and Ching Y. Suen, β€œThinning Methodologies-A Comprehensive Survey,” IEEE Transactions on Pattern Analysis and Machine Intelligence, Vol 14, No. 9, p. 879, 1992. [DOI:10.1109/34.161346](https://doi.org/10.1109/34.161346) #### Examples ``` >>> square = np.zeros((7, 7), dtype=np.uint8) >>> square[1:-1, 2:-2] = 1 >>> square[0, 1] = 1 >>> square array([[0, 1, 0, 0, 0, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0]], dtype=uint8) >>> skel = thin(square) >>> skel.astype(np.uint8) array([[0, 1, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]], dtype=uint8) ``` watershed --------- `skimage.morphology.watershed(image, markers=None, connectivity=1, offset=None, mask=None, compactness=0, watershed_line=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/_deprecated.py#L4-L111) **Deprecated function**. Use `skimage.segmentation.watershed` instead. Find watershed basins in `image` flooded from given `markers`. Parameters `imagendarray (2-D, 3-D, …) of integers` Data array where the lowest value points are labeled first. `markersint, or ndarray of int, same shape as image, optional` The desired number of markers, or an array marking the basins with the values to be assigned in the label matrix. Zero means not a marker. If `None` (no markers given), the local minima of the image are used as markers. `connectivityndarray, optional` An array with the same number of dimensions as `image` whose non-zero elements indicate neighbors for connection. Following the scipy convention, default is a one-connected array of the dimension of the image. `offsetarray_like of shape image.ndim, optional` offset of the connectivity (one offset per dimension) `maskndarray of bools or 0s and 1s, optional` Array of same shape as `image`. Only points at which mask == True will be labeled. `compactnessfloat, optional` Use compact watershed [[3]](#r91cba7b06893-3) with given compactness parameter. Higher values result in more regularly-shaped watershed basins. `watershed_linebool, optional` If watershed\_line is True, a one-pixel wide line separates the regions obtained by the watershed algorithm. The line has the label 0. Returns out: ndarray A labeled matrix of the same type and shape as markers See also [`skimage.segmentation.random_walker`](skimage.segmentation#skimage.segmentation.random_walker "skimage.segmentation.random_walker") random walker segmentation A segmentation algorithm based on anisotropic diffusion, usually slower than the watershed but with good results on noisy data and boundaries with holes. #### Notes This function implements a watershed algorithm [[1]](#r91cba7b06893-1) [[2]](#r91cba7b06893-2) that apportions pixels into marked basins. The algorithm uses a priority queue to hold the pixels with the metric for the priority queue being pixel value, then the time of entry into the queue - this settles ties in favor of the closest marker. Some ideas taken from Soille, β€œAutomated Basin Delineation from Digital Elevation Models Using Mathematical Morphology”, Signal Processing 20 (1990) 171-182 The most important insight in the paper is that entry time onto the queue solves two problems: a pixel should be assigned to the neighbor with the largest gradient or, if there is no gradient, pixels on a plateau should be split between markers on opposite sides. This implementation converts all arguments to specific, lowest common denominator types, then passes these to a C algorithm. Markers can be determined manually, or automatically using for example the local minima of the gradient of the image, or the local maxima of the distance function to the background for separating overlapping objects (see example). #### References `1` <https://en.wikipedia.org/wiki/Watershed_%28image_processing%29> `2` <http://cmm.ensmp.fr/~beucher/wtshed.html> `3` Peer Neubert & Peter Protzel (2014). Compact Watershed and Preemptive SLIC: On Improving Trade-offs of Superpixel Segmentation Algorithms. ICPR 2014, pp 996-1001. [DOI:10.1109/ICPR.2014.181](https://doi.org/10.1109/ICPR.2014.181) <https://www.tu-chemnitz.de/etit/proaut/publications/cws_pSLIC_ICPR.pdf> #### Examples The watershed algorithm is useful to separate overlapping objects. We first generate an initial image with two overlapping circles: ``` >>> import numpy as np >>> x, y = np.indices((80, 80)) >>> x1, y1, x2, y2 = 28, 28, 44, 52 >>> r1, r2 = 16, 20 >>> mask_circle1 = (x - x1)**2 + (y - y1)**2 < r1**2 >>> mask_circle2 = (x - x2)**2 + (y - y2)**2 < r2**2 >>> image = np.logical_or(mask_circle1, mask_circle2) ``` Next, we want to separate the two circles. We generate markers at the maxima of the distance to the background: ``` >>> from scipy import ndimage as ndi >>> distance = ndi.distance_transform_edt(image) >>> from skimage.feature import peak_local_max >>> local_maxi = peak_local_max(distance, labels=image, ... footprint=np.ones((3, 3)), ... indices=False) >>> markers = ndi.label(local_maxi)[0] ``` Finally, we run the watershed on the image and markers: ``` >>> labels = watershed(-distance, markers, mask=image) ``` The algorithm works also for 3-D images, and can be used for example to separate overlapping spheres. white\_tophat ------------- `skimage.morphology.white_tophat(image, selem=None, out=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/grey.py#L355-L426) Return white top hat of an image. The white top hat of an image is defined as the image minus its morphological opening. This operation returns the bright spots of the image that are smaller than the structuring element. Parameters `imagendarray` Image array. `selemndarray, optional` The neighborhood expressed as an array of 1’s and 0’s. If None, use cross-shaped structuring element (connectivity=1). `outndarray, optional` The array to store the result of the morphology. If None is passed, a new array will be allocated. Returns `outarray, same shape and type as image` The result of the morphological white top hat. See also [`black_tophat`](#skimage.morphology.black_tophat "skimage.morphology.black_tophat") #### References `1` <https://en.wikipedia.org/wiki/Top-hat_transform> #### Examples ``` >>> # Subtract grey background from bright peak >>> import numpy as np >>> from skimage.morphology import square >>> bright_on_grey = np.array([[2, 3, 3, 3, 2], ... [3, 4, 5, 4, 3], ... [3, 5, 9, 5, 3], ... [3, 4, 5, 4, 3], ... [2, 3, 3, 3, 2]], dtype=np.uint8) >>> white_tophat(bright_on_grey, square(3)) array([[0, 0, 0, 0, 0], [0, 0, 1, 0, 0], [0, 1, 5, 1, 0], [0, 0, 1, 0, 0], [0, 0, 0, 0, 0]], dtype=uint8) ```
programming_docs
scikit_image Module: viewer.viewers Module: viewer.viewers ====================== | | | | --- | --- | | [`skimage.viewer.viewers.CollectionViewer`](#skimage.viewer.viewers.CollectionViewer "skimage.viewer.viewers.CollectionViewer")(…) | Viewer for displaying image collections. | | [`skimage.viewer.viewers.ImageViewer`](#skimage.viewer.viewers.ImageViewer "skimage.viewer.viewers.ImageViewer")(image[, …]) | Viewer for displaying images. | | `skimage.viewer.viewers.core` | ImageViewer class for viewing and interacting with images. | CollectionViewer ---------------- `class skimage.viewer.viewers.CollectionViewer(image_collection, update_on='move', **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L331-L407) Bases: `skimage.viewer.viewers.core.ImageViewer` Viewer for displaying image collections. Select the displayed frame of the image collection using the slider or with the following keyboard shortcuts: left/right arrows Previous/next image in collection. number keys, 0–9 0% to 90% of collection. For example, β€œ5” goes to the image in the middle (i.e. 50%) of the collection. home/end keys First/last image in collection. Parameters `image_collectionlist of images` List of images to be displayed. `update_on{β€˜move’ | β€˜release’}` Control whether image is updated on slide or release of the image slider. Using β€˜on\_release’ will give smoother behavior when displaying large images or when writing a plugin/subclass that requires heavy computation. `__init__(image_collection, update_on='move', **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L356-L379) Initialize self. See help(type(self)) for accurate signature. `keyPressEvent(event)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L396-L407) `update_index(name, index)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L381-L394) Select image on display using index into image collection. ImageViewer ----------- `class skimage.viewer.viewers.ImageViewer(image, useblit=True)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L49-L328) Bases: [`object`](https://docs.python.org/3.9/library/functions.html#object "(in Python v3.9)") Viewer for displaying images. This viewer is a simple container object that holds a Matplotlib axes for showing images. [`ImageViewer`](#skimage.viewer.viewers.ImageViewer "skimage.viewer.viewers.ImageViewer") doesn’t subclass the Matplotlib axes (or figure) because of the high probability of name collisions. Subclasses and plugins will likely extend the [`update_image`](#skimage.viewer.viewers.ImageViewer.update_image "skimage.viewer.viewers.ImageViewer.update_image") method to add custom overlays or filter the displayed image. Parameters `imagearray` Image being viewed. #### Examples ``` >>> from skimage import data >>> image = data.coins() >>> viewer = ImageViewer(image) >>> viewer.show() ``` Attributes `canvas, fig, axMatplotlib canvas, figure, and axes` Matplotlib canvas, figure, and axes used to display image. `imagearray` Image being viewed. Setting this value will update the displayed frame. `original_imagearray` Plugins typically operate on (but don’t change) the *original* image. `pluginslist` List of attached plugins. `__init__(image, useblit=True)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L92-L151) Initialize self. See help(type(self)) for accurate signature. `add_tool(tool)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L307-L311) `closeEvent(event)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L237-L238) `connect_event(event, callback)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L292-L295) Connect callback function to matplotlib event and return id. `disconnect_event(callback_id)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L297-L299) Disconnect callback by its id (returned by [`connect_event`](#skimage.viewer.viewers.ImageViewer.connect_event "skimage.viewer.viewers.ImageViewer.connect_event")). `dock_areas = {'bottom': None, 'left': None, 'right': None, 'top': None}` `property image` `open_file(filename=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L186-L193) Open image file and display in viewer. `original_image_changed = None` `redraw()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L258-L262) `remove_tool(tool)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L313-L319) `reset_image()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L289-L290) `save_to_file(filename=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L208-L235) Save current image to file. The current behavior is not ideal: It saves the image displayed on screen, so all images will be converted to RGB, and the image size is not preserved (resizing the viewer window will alter the size of the saved image). `show(main_window=True)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L248-L256) Show ImageViewer and attached plugins. This behaves much like [`matplotlib.pyplot.show`](https://matplotlib.org/api/_as_gen/matplotlib.pyplot.show.html#matplotlib.pyplot.show "(in Matplotlib v3.3.3)") and `QWidget.show`. `update_image(image)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/viewers/core.py#L195-L201) Update displayed image. This method can be overridden or extended in subclasses and plugins to react to image changes. scikit_image Module: draw Module: draw ============ | | | | --- | --- | | [`skimage.draw.bezier_curve`](#skimage.draw.bezier_curve "skimage.draw.bezier_curve")(r0, c0, r1, c1, …) | Generate Bezier curve coordinates. | | [`skimage.draw.circle`](#skimage.draw.circle "skimage.draw.circle")(r, c, radius[, shape]) | Generate coordinates of pixels within circle. | | [`skimage.draw.circle_perimeter`](#skimage.draw.circle_perimeter "skimage.draw.circle_perimeter")(r, c, radius) | Generate circle perimeter coordinates. | | [`skimage.draw.circle_perimeter_aa`](#skimage.draw.circle_perimeter_aa "skimage.draw.circle_perimeter_aa")(r, c, radius) | Generate anti-aliased circle perimeter coordinates. | | [`skimage.draw.disk`](#skimage.draw.disk "skimage.draw.disk")(center, radius, \*[, shape]) | Generate coordinates of pixels within circle. | | [`skimage.draw.ellipse`](#skimage.draw.ellipse "skimage.draw.ellipse")(r, c, r\_radius, c\_radius) | Generate coordinates of pixels within ellipse. | | [`skimage.draw.ellipse_perimeter`](#skimage.draw.ellipse_perimeter "skimage.draw.ellipse_perimeter")(r, c, …[, …]) | Generate ellipse perimeter coordinates. | | [`skimage.draw.ellipsoid`](#skimage.draw.ellipsoid "skimage.draw.ellipsoid")(a, b, c[, spacing, …]) | Generates ellipsoid with semimajor axes aligned with grid dimensions on grid with specified `spacing`. | | [`skimage.draw.ellipsoid_stats`](#skimage.draw.ellipsoid_stats "skimage.draw.ellipsoid_stats")(a, b, c) | Calculates analytical surface area and volume for ellipsoid with semimajor axes aligned with grid dimensions of specified `spacing`. | | [`skimage.draw.line`](#skimage.draw.line "skimage.draw.line")(r0, c0, r1, c1) | Generate line pixel coordinates. | | [`skimage.draw.line_aa`](#skimage.draw.line_aa "skimage.draw.line_aa")(r0, c0, r1, c1) | Generate anti-aliased line pixel coordinates. | | [`skimage.draw.line_nd`](#skimage.draw.line_nd "skimage.draw.line_nd")(start, stop, \*[, …]) | Draw a single-pixel thick line in n dimensions. | | [`skimage.draw.polygon`](#skimage.draw.polygon "skimage.draw.polygon")(r, c[, shape]) | Generate coordinates of pixels within polygon. | | [`skimage.draw.polygon2mask`](#skimage.draw.polygon2mask "skimage.draw.polygon2mask")(image\_shape, polygon) | Compute a mask from polygon. | | [`skimage.draw.polygon_perimeter`](#skimage.draw.polygon_perimeter "skimage.draw.polygon_perimeter")(r, c[, …]) | Generate polygon perimeter coordinates. | | [`skimage.draw.random_shapes`](#skimage.draw.random_shapes "skimage.draw.random_shapes")(image\_shape, …) | Generate an image with random shapes, labeled with bounding boxes. | | [`skimage.draw.rectangle`](#skimage.draw.rectangle "skimage.draw.rectangle")(start[, end, extent, …]) | Generate coordinates of pixels within a rectangle. | | [`skimage.draw.rectangle_perimeter`](#skimage.draw.rectangle_perimeter "skimage.draw.rectangle_perimeter")(start[, …]) | Generate coordinates of pixels that are exactly around a rectangle. | | [`skimage.draw.set_color`](#skimage.draw.set_color "skimage.draw.set_color")(image, coords, color) | Set pixel color in the image at the given coordinates. | bezier\_curve ------------- `skimage.draw.bezier_curve(r0, c0, r1, c1, r2, c2, weight, shape=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/draw/draw.py#L697-L751) Generate Bezier curve coordinates. Parameters `r0, c0int` Coordinates of the first control point. `r1, c1int` Coordinates of the middle control point. `r2, c2int` Coordinates of the last control point. `weightdouble` Middle control point weight, it describes the line tension. `shapetuple, optional` Image shape which is used to determine the maximum extent of output pixel coordinates. This is useful for curves that exceed the image size. If None, the full extent of the curve is used. Returns `rr, cc(N,) ndarray of int` Indices of pixels that belong to the Bezier curve. May be used to directly index into an array, e.g. `img[rr, cc] = 1`. #### Notes The algorithm is the rational quadratic algorithm presented in reference [[1]](#r275489368e51-1). #### References `1` A Rasterizing Algorithm for Drawing Curves, A. Zingl, 2012 <http://members.chello.at/easyfilter/Bresenham.pdf> #### Examples ``` >>> import numpy as np >>> from skimage.draw import bezier_curve >>> img = np.zeros((10, 10), dtype=np.uint8) >>> rr, cc = bezier_curve(1, 5, 5, -2, 8, 8, 2) >>> img[rr, cc] = 1 >>> img array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 1, 1, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8) ``` circle ------ `skimage.draw.circle(r, c, radius, shape=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/draw/draw.py#L146-L180) Generate coordinates of pixels within circle. Parameters `r, cdouble` Center coordinate of disk. `radiusdouble` Radius of disk. `shapetuple, optional` Image shape which is used to determine the maximum extent of output pixel coordinates. This is useful for disks that exceed the image size. If None, the full extent of the disk is used. Must be at least length 2. Only the first two values are used to determine the extent of the input image. Returns `rr, ccndarray of int` Pixel coordinates of disk. May be used to directly index into an array, e.g. `img[rr, cc] = 1`. Warns Deprecated: New in version 0.17: This function is deprecated and will be removed in scikit-image 0.19. Please use the function named `disk` instead. circle\_perimeter ----------------- `skimage.draw.circle_perimeter(r, c, radius, method='bresenham', shape=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/draw/draw.py#L502-L562) Generate circle perimeter coordinates. Parameters `r, cint` Centre coordinate of circle. `radiusint` Radius of circle. `method{β€˜bresenham’, β€˜andres’}, optional` bresenham : Bresenham method (default) andres : Andres method `shapetuple, optional` Image shape which is used to determine the maximum extent of output pixel coordinates. This is useful for circles that exceed the image size. If None, the full extent of the circle is used. Must be at least length 2. Only the first two values are used to determine the extent of the input image. Returns `rr, cc(N,) ndarray of int` Bresenham and Andres’ method: Indices of pixels that belong to the circle perimeter. May be used to directly index into an array, e.g. `img[rr, cc] = 1`. #### Notes Andres method presents the advantage that concentric circles create a disc whereas Bresenham can make holes. There is also less distortions when Andres circles are rotated. Bresenham method is also known as midpoint circle algorithm. Anti-aliased circle generator is available with [`circle_perimeter_aa`](#skimage.draw.circle_perimeter_aa "skimage.draw.circle_perimeter_aa"). #### References `1` J.E. Bresenham, β€œAlgorithm for computer control of a digital plotter”, IBM Systems journal, 4 (1965) 25-30. `2` E. Andres, β€œDiscrete circles, rings and spheres”, Computers & Graphics, 18 (1994) 695-706. #### Examples ``` >>> from skimage.draw import circle_perimeter >>> img = np.zeros((10, 10), dtype=np.uint8) >>> rr, cc = circle_perimeter(4, 4, 3) >>> img[rr, cc] = 1 >>> img array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 1, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 1, 0, 0], [0, 1, 0, 0, 0, 0, 0, 1, 0, 0], [0, 1, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8) ``` circle\_perimeter\_aa --------------------- `skimage.draw.circle_perimeter_aa(r, c, radius, shape=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/draw/draw.py#L565-L623) Generate anti-aliased circle perimeter coordinates. Parameters `r, cint` Centre coordinate of circle. `radiusint` Radius of circle. `shapetuple, optional` Image shape which is used to determine the maximum extent of output pixel coordinates. This is useful for circles that exceed the image size. If None, the full extent of the circle is used. Must be at least length 2. Only the first two values are used to determine the extent of the input image. Returns `rr, cc, val(N,) ndarray (int, int, float)` Indices of pixels (`rr`, `cc`) and intensity values (`val`). `img[rr, cc] = val`. #### Notes Wu’s method draws anti-aliased circle. This implementation doesn’t use lookup table optimization. Use the function `draw.set_color` to apply `circle_perimeter_aa` results to color images. #### References `1` X. Wu, β€œAn efficient antialiasing technique”, In ACM SIGGRAPH Computer Graphics, 25 (1991) 143-152. #### Examples ``` >>> from skimage.draw import circle_perimeter_aa >>> img = np.zeros((10, 10), dtype=np.uint8) >>> rr, cc, val = circle_perimeter_aa(4, 4, 3) >>> img[rr, cc] = val * 255 >>> img array([[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 60, 211, 255, 211, 60, 0, 0, 0], [ 0, 60, 194, 43, 0, 43, 194, 60, 0, 0], [ 0, 211, 43, 0, 0, 0, 43, 211, 0, 0], [ 0, 255, 0, 0, 0, 0, 0, 255, 0, 0], [ 0, 211, 43, 0, 0, 0, 43, 211, 0, 0], [ 0, 60, 194, 43, 0, 43, 194, 60, 0, 0], [ 0, 0, 60, 211, 255, 211, 60, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8) ``` ``` >>> from skimage import data, draw >>> image = data.chelsea() >>> rr, cc, val = draw.circle_perimeter_aa(r=100, c=100, radius=75) >>> draw.set_color(image, (rr, cc), [1, 0, 0], alpha=val) ``` disk ---- `skimage.draw.disk(center, radius, *, shape=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/draw/draw.py#L183-L225) Generate coordinates of pixels within circle. Parameters `centertuple` Center coordinate of disk. `radiusdouble` Radius of disk. `shapetuple, optional` Image shape which is used to determine the maximum extent of output pixel coordinates. This is useful for disks that exceed the image size. If None, the full extent of the disk is used. Must be at least length 2. Only the first two values are used to determine the extent of the input image. Returns `rr, ccndarray of int` Pixel coordinates of disk. May be used to directly index into an array, e.g. `img[rr, cc] = 1`. #### Examples ``` >>> from skimage.draw import disk >>> img = np.zeros((10, 10), dtype=np.uint8) >>> rr, cc = disk((4, 4), 5) >>> img[rr, cc] = 1 >>> img array([[0, 0, 1, 1, 1, 1, 1, 0, 0, 0], [0, 1, 1, 1, 1, 1, 1, 1, 0, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8) ``` ellipse ------- `skimage.draw.ellipse(r, c, r_radius, c_radius, shape=None, rotation=0.0)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/draw/draw.py#L46-L143) Generate coordinates of pixels within ellipse. Parameters `r, cdouble` Centre coordinate of ellipse. `r_radius, c_radiusdouble` Minor and major semi-axes. `(r/r_radius)**2 + (c/c_radius)**2 = 1`. `shapetuple, optional` Image shape which is used to determine the maximum extent of output pixel coordinates. This is useful for ellipses which exceed the image size. By default the full extent of the ellipse are used. Must be at least length 2. Only the first two values are used to determine the extent. `rotationfloat, optional (default 0.)` Set the ellipse rotation (rotation) in range (-PI, PI) in contra clock wise direction, so PI/2 degree means swap ellipse axis Returns `rr, ccndarray of int` Pixel coordinates of ellipse. May be used to directly index into an array, e.g. `img[rr, cc] = 1`. #### Notes The ellipse equation: ``` ((x * cos(alpha) + y * sin(alpha)) / x_radius) ** 2 + ((x * sin(alpha) - y * cos(alpha)) / y_radius) ** 2 = 1 ``` Note that the positions of [`ellipse`](#skimage.draw.ellipse "skimage.draw.ellipse") without specified `shape` can have also, negative values, as this is correct on the plane. On the other hand using these ellipse positions for an image afterwards may lead to appearing on the other side of image, because `image[-1, -1] = image[end-1, end-1]` ``` >>> rr, cc = ellipse(1, 2, 3, 6) >>> img = np.zeros((6, 12), dtype=np.uint8) >>> img[rr, cc] = 1 >>> img array([[1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1]], dtype=uint8) ``` #### Examples ``` >>> from skimage.draw import ellipse >>> img = np.zeros((10, 12), dtype=np.uint8) >>> rr, cc = ellipse(5, 6, 3, 5, rotation=np.deg2rad(30)) >>> img[rr, cc] = 1 >>> img array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 0], [0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0], [0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0], [0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8) ``` ### Examples using `skimage.draw.ellipse` [Masked Normalized Cross-Correlation](https://scikit-image.org/docs/0.18.x/auto_examples/registration/plot_masked_register_translation.html#sphx-glr-auto-examples-registration-plot-masked-register-translation-py) [Measure region properties](https://scikit-image.org/docs/0.18.x/auto_examples/segmentation/plot_regionprops.html#sphx-glr-auto-examples-segmentation-plot-regionprops-py) ellipse\_perimeter ------------------ `skimage.draw.ellipse_perimeter(r, c, r_radius, c_radius, orientation=0, shape=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/draw/draw.py#L626-L694) Generate ellipse perimeter coordinates. Parameters `r, cint` Centre coordinate of ellipse. `r_radius, c_radiusint` Minor and major semi-axes. `(r/r_radius)**2 + (c/c_radius)**2 = 1`. `orientationdouble, optional` Major axis orientation in clockwise direction as radians. `shapetuple, optional` Image shape which is used to determine the maximum extent of output pixel coordinates. This is useful for ellipses that exceed the image size. If None, the full extent of the ellipse is used. Must be at least length 2. Only the first two values are used to determine the extent of the input image. Returns `rr, cc(N,) ndarray of int` Indices of pixels that belong to the ellipse perimeter. May be used to directly index into an array, e.g. `img[rr, cc] = 1`. #### References `1` A Rasterizing Algorithm for Drawing Curves, A. Zingl, 2012 <http://members.chello.at/easyfilter/Bresenham.pdf> #### Examples ``` >>> from skimage.draw import ellipse_perimeter >>> img = np.zeros((10, 10), dtype=np.uint8) >>> rr, cc = ellipse_perimeter(5, 5, 3, 4) >>> img[rr, cc] = 1 >>> img array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 1, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 1], [0, 1, 0, 0, 0, 0, 0, 0, 0, 1], [0, 1, 0, 0, 0, 0, 0, 0, 0, 1], [0, 0, 1, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8) ``` Note that the positions of [`ellipse`](#skimage.draw.ellipse "skimage.draw.ellipse") without specified `shape` can have also, negative values, as this is correct on the plane. On the other hand using these ellipse positions for an image afterwards may lead to appearing on the other side of image, because `image[-1, -1] = image[end-1, end-1]` ``` >>> rr, cc = ellipse_perimeter(2, 3, 4, 5) >>> img = np.zeros((9, 12), dtype=np.uint8) >>> img[rr, cc] = 1 >>> img array([[0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1], [0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0], [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0]], dtype=uint8) ``` ellipsoid --------- `skimage.draw.ellipsoid(a, b, c, spacing=(1.0, 1.0, 1.0), levelset=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/draw/draw3d.py#L5-L63) Generates ellipsoid with semimajor axes aligned with grid dimensions on grid with specified `spacing`. Parameters `afloat` Length of semimajor axis aligned with x-axis. `bfloat` Length of semimajor axis aligned with y-axis. `cfloat` Length of semimajor axis aligned with z-axis. `spacingtuple of floats, length 3` Spacing in (x, y, z) spatial dimensions. `levelsetbool` If True, returns the level set for this ellipsoid (signed level set about zero, with positive denoting interior) as np.float64. False returns a binarized version of said level set. Returns `ellip(N, M, P) array` Ellipsoid centered in a correctly sized array for given `spacing`. Boolean dtype unless `levelset=True`, in which case a float array is returned with the level set above 0.0 representing the ellipsoid. ellipsoid\_stats ---------------- `skimage.draw.ellipsoid_stats(a, b, c)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/draw/draw3d.py#L66-L114) Calculates analytical surface area and volume for ellipsoid with semimajor axes aligned with grid dimensions of specified `spacing`. Parameters `afloat` Length of semimajor axis aligned with x-axis. `bfloat` Length of semimajor axis aligned with y-axis. `cfloat` Length of semimajor axis aligned with z-axis. Returns `volfloat` Calculated volume of ellipsoid. `surffloat` Calculated surface area of ellipsoid. line ---- `skimage.draw.line(r0, c0, r1, c1)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/draw/draw.py#L371-L410) Generate line pixel coordinates. Parameters `r0, c0int` Starting position (row, column). `r1, c1int` End position (row, column). Returns `rr, cc(N,) ndarray of int` Indices of pixels that belong to the line. May be used to directly index into an array, e.g. `img[rr, cc] = 1`. #### Notes Anti-aliased line generator is available with [`line_aa`](#skimage.draw.line_aa "skimage.draw.line_aa"). #### Examples ``` >>> from skimage.draw import line >>> img = np.zeros((10, 10), dtype=np.uint8) >>> rr, cc = line(1, 1, 8, 8) >>> img[rr, cc] = 1 >>> img array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8) ``` line\_aa -------- `skimage.draw.line_aa(r0, c0, r1, c1)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/draw/draw.py#L413-L452) Generate anti-aliased line pixel coordinates. Parameters `r0, c0int` Starting position (row, column). `r1, c1int` End position (row, column). Returns `rr, cc, val(N,) ndarray (int, int, float)` Indices of pixels (`rr`, `cc`) and intensity values (`val`). `img[rr, cc] = val`. #### References `1` A Rasterizing Algorithm for Drawing Curves, A. Zingl, 2012 <http://members.chello.at/easyfilter/Bresenham.pdf> #### Examples ``` >>> from skimage.draw import line_aa >>> img = np.zeros((10, 10), dtype=np.uint8) >>> rr, cc, val = line_aa(1, 1, 8, 8) >>> img[rr, cc] = val * 255 >>> img array([[ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [ 0, 255, 74, 0, 0, 0, 0, 0, 0, 0], [ 0, 74, 255, 74, 0, 0, 0, 0, 0, 0], [ 0, 0, 74, 255, 74, 0, 0, 0, 0, 0], [ 0, 0, 0, 74, 255, 74, 0, 0, 0, 0], [ 0, 0, 0, 0, 74, 255, 74, 0, 0, 0], [ 0, 0, 0, 0, 0, 74, 255, 74, 0, 0], [ 0, 0, 0, 0, 0, 0, 74, 255, 74, 0], [ 0, 0, 0, 0, 0, 0, 0, 74, 255, 0], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8) ``` line\_nd -------- `skimage.draw.line_nd(start, stop, *, endpoint=False, integer=True)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/draw/draw_nd.py#L54-L108) Draw a single-pixel thick line in n dimensions. The line produced will be ndim-connected. That is, two subsequent pixels in the line will be either direct or diagonal neighbours in n dimensions. Parameters `startarray-like, shape (N,)` The start coordinates of the line. `stoparray-like, shape (N,)` The end coordinates of the line. `endpointbool, optional` Whether to include the endpoint in the returned line. Defaults to False, which allows for easy drawing of multi-point paths. `integerbool, optional` Whether to round the coordinates to integer. If True (default), the returned coordinates can be used to directly index into an array. `False` could be used for e.g. vector drawing. Returns `coordstuple of arrays` The coordinates of points on the line. #### Examples ``` >>> lin = line_nd((1, 1), (5, 2.5), endpoint=False) >>> lin (array([1, 2, 3, 4]), array([1, 1, 2, 2])) >>> im = np.zeros((6, 5), dtype=int) >>> im[lin] = 1 >>> im array([[0, 0, 0, 0, 0], [0, 1, 0, 0, 0], [0, 1, 0, 0, 0], [0, 0, 1, 0, 0], [0, 0, 1, 0, 0], [0, 0, 0, 0, 0]]) >>> line_nd([2, 1, 1], [5, 5, 2.5], endpoint=True) (array([2, 3, 4, 4, 5]), array([1, 2, 3, 4, 5]), array([1, 1, 2, 2, 2])) ``` polygon ------- `skimage.draw.polygon(r, c, shape=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/draw/draw.py#L455-L499) Generate coordinates of pixels within polygon. Parameters `r(N,) ndarray` Row coordinates of vertices of polygon. `c(N,) ndarray` Column coordinates of vertices of polygon. `shapetuple, optional` Image shape which is used to determine the maximum extent of output pixel coordinates. This is useful for polygons that exceed the image size. If None, the full extent of the polygon is used. Must be at least length 2. Only the first two values are used to determine the extent of the input image. Returns `rr, ccndarray of int` Pixel coordinates of polygon. May be used to directly index into an array, e.g. `img[rr, cc] = 1`. #### Examples ``` >>> from skimage.draw import polygon >>> img = np.zeros((10, 10), dtype=np.uint8) >>> r = np.array([1, 2, 8]) >>> c = np.array([1, 7, 4]) >>> rr, cc = polygon(r, c) >>> img[rr, cc] = 1 >>> img array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0, 0], [0, 0, 0, 1, 1, 1, 1, 0, 0, 0], [0, 0, 0, 1, 1, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 1, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8) ``` polygon2mask ------------ `skimage.draw.polygon2mask(image_shape, polygon)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/draw/_polygon2mask.py#L6-L41) Compute a mask from polygon. Parameters `image_shapetuple of size 2.` The shape of the mask. `polygonarray_like.` The polygon coordinates of shape (N, 2) where N is the number of points. Returns `mask2-D ndarray of type β€˜bool’.` The mask that corresponds to the input polygon. #### Notes This function does not do any border checking, so that all the vertices need to be within the given shape. #### Examples ``` >>> image_shape = (128, 128) >>> polygon = np.array([[60, 100], [100, 40], [40, 40]]) >>> mask = polygon2mask(image_shape, polygon) >>> mask.shape (128, 128) ``` polygon\_perimeter ------------------ `skimage.draw.polygon_perimeter(r, c, shape=None, clip=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/draw/draw.py#L228-L304) Generate polygon perimeter coordinates. Parameters `r(N,) ndarray` Row coordinates of vertices of polygon. `c(N,) ndarray` Column coordinates of vertices of polygon. `shapetuple, optional` Image shape which is used to determine maximum extents of output pixel coordinates. This is useful for polygons that exceed the image size. If None, the full extents of the polygon is used. Must be at least length 2. Only the first two values are used to determine the extent of the input image. `clipbool, optional` Whether to clip the polygon to the provided shape. If this is set to True, the drawn figure will always be a closed polygon with all edges visible. Returns `rr, ccndarray of int` Pixel coordinates of polygon. May be used to directly index into an array, e.g. `img[rr, cc] = 1`. #### Examples ``` >>> from skimage.draw import polygon_perimeter >>> img = np.zeros((10, 10), dtype=np.uint8) >>> rr, cc = polygon_perimeter([5, -1, 5, 10], ... [-1, 5, 11, 5], ... shape=img.shape, clip=True) >>> img[rr, cc] = 1 >>> img array([[0, 0, 0, 0, 1, 1, 1, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 1, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 1, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], [1, 0, 0, 0, 0, 0, 0, 0, 0, 1], [0, 1, 1, 0, 0, 0, 0, 0, 0, 1], [0, 0, 0, 1, 0, 0, 0, 1, 1, 0], [0, 0, 0, 0, 1, 1, 1, 0, 0, 0]], dtype=uint8) ``` random\_shapes -------------- `skimage.draw.random_shapes(image_shape, max_shapes, min_shapes=1, min_size=2, max_size=None, multichannel=True, num_channels=3, shape=None, intensity_range=None, allow_overlap=False, num_trials=100, random_seed=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/draw/_random_shapes.py#L293-L437) Generate an image with random shapes, labeled with bounding boxes. The image is populated with random shapes with random sizes, random locations, and random colors, with or without overlap. Shapes have random (row, col) starting coordinates and random sizes bounded by `min_size` and `max_size`. It can occur that a randomly generated shape will not fit the image at all. In that case, the algorithm will try again with new starting coordinates a certain number of times. However, it also means that some shapes may be skipped altogether. In that case, this function will generate fewer shapes than requested. Parameters `image_shapetuple` The number of rows and columns of the image to generate. `max_shapesint` The maximum number of shapes to (attempt to) fit into the shape. `min_shapesint, optional` The minimum number of shapes to (attempt to) fit into the shape. `min_sizeint, optional` The minimum dimension of each shape to fit into the image. `max_sizeint, optional` The maximum dimension of each shape to fit into the image. `multichannelbool, optional` If True, the generated image has `num_channels` color channels, otherwise generates grayscale image. `num_channelsint, optional` Number of channels in the generated image. If 1, generate monochrome images, else color images with multiple channels. Ignored if `multichannel` is set to False. `shape{rectangle, circle, triangle, ellipse, None} str, optional` The name of the shape to generate or `None` to pick random ones. `intensity_range{tuple of tuples of uint8, tuple of uint8}, optional` The range of values to sample pixel values from. For grayscale images the format is (min, max). For multichannel - ((min, max),) if the ranges are equal across the channels, and ((min\_0, max\_0), … (min\_N, max\_N)) if they differ. As the function supports generation of uint8 arrays only, the maximum range is (0, 255). If None, set to (0, 254) for each channel reserving color of intensity = 255 for background. `allow_overlapbool, optional` If `True`, allow shapes to overlap. `num_trialsint, optional` How often to attempt to fit a shape into the image before skipping it. `random_seedint, optional` Seed to initialize the random number generator. If `None`, a random seed from the operating system is used. Returns `imageuint8 array` An image with the fitted shapes. `labelslist` A list of labels, one per shape in the image. Each label is a (category, ((r0, r1), (c0, c1))) tuple specifying the category and bounding box coordinates of the shape. #### Examples ``` >>> import skimage.draw >>> image, labels = skimage.draw.random_shapes((32, 32), max_shapes=3) >>> image array([ [[255, 255, 255], [255, 255, 255], [255, 255, 255], ..., [255, 255, 255], [255, 255, 255], [255, 255, 255]]], dtype=uint8) >>> labels [('circle', ((22, 18), (25, 21))), ('triangle', ((5, 6), (13, 13)))] ``` rectangle --------- `skimage.draw.rectangle(start, end=None, extent=None, shape=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/draw/draw.py#L754-L847) Generate coordinates of pixels within a rectangle. Parameters `starttuple` Origin point of the rectangle, e.g., `([plane,] row, column)`. `endtuple` End point of the rectangle `([plane,] row, column)`. For a 2D matrix, the slice defined by the rectangle is `[start:(end+1)]`. Either `end` or `extent` must be specified. `extenttuple` The extent (size) of the drawn rectangle. E.g., `([num_planes,] num_rows, num_cols)`. Either `end` or `extent` must be specified. A negative extent is valid, and will result in a rectangle going along the opposite direction. If extent is negative, the `start` point is not included. `shapetuple, optional` Image shape used to determine the maximum bounds of the output coordinates. This is useful for clipping rectangles that exceed the image size. By default, no clipping is done. Returns `coordsarray of int, shape (Ndim, Npoints)` The coordinates of all pixels in the rectangle. #### Notes This function can be applied to N-dimensional images, by passing `start` and `end` or `extent` as tuples of length N. #### Examples ``` >>> import numpy as np >>> from skimage.draw import rectangle >>> img = np.zeros((5, 5), dtype=np.uint8) >>> start = (1, 1) >>> extent = (3, 3) >>> rr, cc = rectangle(start, extent=extent, shape=img.shape) >>> img[rr, cc] = 1 >>> img array([[0, 0, 0, 0, 0], [0, 1, 1, 1, 0], [0, 1, 1, 1, 0], [0, 1, 1, 1, 0], [0, 0, 0, 0, 0]], dtype=uint8) ``` ``` >>> img = np.zeros((5, 5), dtype=np.uint8) >>> start = (0, 1) >>> end = (3, 3) >>> rr, cc = rectangle(start, end=end, shape=img.shape) >>> img[rr, cc] = 1 >>> img array([[0, 1, 1, 1, 0], [0, 1, 1, 1, 0], [0, 1, 1, 1, 0], [0, 1, 1, 1, 0], [0, 0, 0, 0, 0]], dtype=uint8) ``` ``` >>> import numpy as np >>> from skimage.draw import rectangle >>> img = np.zeros((6, 6), dtype=np.uint8) >>> start = (3, 3) >>> >>> rr, cc = rectangle(start, extent=(2, 2)) >>> img[rr, cc] = 1 >>> rr, cc = rectangle(start, extent=(-2, 2)) >>> img[rr, cc] = 2 >>> rr, cc = rectangle(start, extent=(-2, -2)) >>> img[rr, cc] = 3 >>> rr, cc = rectangle(start, extent=(2, -2)) >>> img[rr, cc] = 4 >>> print(img) [[0 0 0 0 0 0] [0 3 3 2 2 0] [0 3 3 2 2 0] [0 4 4 1 1 0] [0 4 4 1 1 0] [0 0 0 0 0 0]] ``` rectangle\_perimeter -------------------- `skimage.draw.rectangle_perimeter(start, end=None, extent=None, shape=None, clip=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/draw/draw.py#L850-L920) Generate coordinates of pixels that are exactly around a rectangle. Parameters `starttuple` Origin point of the inner rectangle, e.g., `(row, column)`. `endtuple` End point of the inner rectangle `(row, column)`. For a 2D matrix, the slice defined by inner the rectangle is `[start:(end+1)]`. Either `end` or `extent` must be specified. `extenttuple` The extent (size) of the inner rectangle. E.g., `(num_rows, num_cols)`. Either `end` or `extent` must be specified. Negative extents are permitted. See [`rectangle`](#skimage.draw.rectangle "skimage.draw.rectangle") to better understand how they behave. `shapetuple, optional` Image shape used to determine the maximum bounds of the output coordinates. This is useful for clipping perimeters that exceed the image size. By default, no clipping is done. Must be at least length 2. Only the first two values are used to determine the extent of the input image. `clipbool, optional` Whether to clip the perimeter to the provided shape. If this is set to True, the drawn figure will always be a closed polygon with all edges visible. Returns `coordsarray of int, shape (2, Npoints)` The coordinates of all pixels in the rectangle. #### Examples ``` >>> import numpy as np >>> from skimage.draw import rectangle_perimeter >>> img = np.zeros((5, 6), dtype=np.uint8) >>> start = (2, 3) >>> end = (3, 4) >>> rr, cc = rectangle_perimeter(start, end=end, shape=img.shape) >>> img[rr, cc] = 1 >>> img array([[0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 1, 1], [0, 0, 1, 0, 0, 1], [0, 0, 1, 0, 0, 1], [0, 0, 1, 1, 1, 1]], dtype=uint8) ``` ``` >>> img = np.zeros((5, 5), dtype=np.uint8) >>> r, c = rectangle_perimeter(start, (10, 10), shape=img.shape, clip=True) >>> img[r, c] = 1 >>> img array([[0, 0, 0, 0, 0], [0, 0, 1, 1, 1], [0, 0, 1, 0, 1], [0, 0, 1, 0, 1], [0, 0, 1, 1, 1]], dtype=uint8) ``` set\_color ---------- `skimage.draw.set_color(image, coords, color, alpha=1)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/draw/draw.py#L307-L368) Set pixel color in the image at the given coordinates. Note that this function modifies the color of the image in-place. Coordinates that exceed the shape of the image will be ignored. Parameters `image(M, N, D) ndarray` Image `coordstuple of ((P,) ndarray, (P,) ndarray)` Row and column coordinates of pixels to be colored. `color(D,) ndarray` Color to be assigned to coordinates in the image. `alphascalar or (N,) ndarray` Alpha values used to blend color with image. 0 is transparent, 1 is opaque. #### Examples ``` >>> from skimage.draw import line, set_color >>> img = np.zeros((10, 10), dtype=np.uint8) >>> rr, cc = line(1, 1, 20, 20) >>> set_color(img, (rr, cc), 1) >>> img array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 1]], dtype=uint8) ```
programming_docs
scikit_image Module: transform Module: transform ================= | | | | --- | --- | | [`skimage.transform.downscale_local_mean`](#skimage.transform.downscale_local_mean "skimage.transform.downscale_local_mean")(…) | Down-sample N-dimensional image by local averaging. | | [`skimage.transform.estimate_transform`](#skimage.transform.estimate_transform "skimage.transform.estimate_transform")(ttype, …) | Estimate 2D geometric transformation parameters. | | [`skimage.transform.frt2`](#skimage.transform.frt2 "skimage.transform.frt2")(a) | Compute the 2-dimensional finite radon transform (FRT) for an n x n integer array. | | [`skimage.transform.hough_circle`](#skimage.transform.hough_circle "skimage.transform.hough_circle")(image, radius) | Perform a circular Hough transform. | | [`skimage.transform.hough_circle_peaks`](#skimage.transform.hough_circle_peaks "skimage.transform.hough_circle_peaks")(…[, …]) | Return peaks in a circle Hough transform. | | [`skimage.transform.hough_ellipse`](#skimage.transform.hough_ellipse "skimage.transform.hough_ellipse")(image[, …]) | Perform an elliptical Hough transform. | | [`skimage.transform.hough_line`](#skimage.transform.hough_line "skimage.transform.hough_line")(image[, theta]) | Perform a straight line Hough transform. | | [`skimage.transform.hough_line_peaks`](#skimage.transform.hough_line_peaks "skimage.transform.hough_line_peaks")(hspace, …) | Return peaks in a straight line Hough transform. | | [`skimage.transform.ifrt2`](#skimage.transform.ifrt2 "skimage.transform.ifrt2")(a) | Compute the 2-dimensional inverse finite radon transform (iFRT) for an (n+1) x n integer array. | | [`skimage.transform.integral_image`](#skimage.transform.integral_image "skimage.transform.integral_image")(image) | Integral image / summed area table. | | [`skimage.transform.integrate`](#skimage.transform.integrate "skimage.transform.integrate")(ii, start, end) | Use an integral image to integrate over a given window. | | [`skimage.transform.iradon`](#skimage.transform.iradon "skimage.transform.iradon")(radon\_image[, …]) | Inverse radon transform. | | [`skimage.transform.iradon_sart`](#skimage.transform.iradon_sart "skimage.transform.iradon_sart")(radon\_image[, …]) | Inverse radon transform. | | [`skimage.transform.matrix_transform`](#skimage.transform.matrix_transform "skimage.transform.matrix_transform")(coords, …) | Apply 2D matrix transform. | | [`skimage.transform.order_angles_golden_ratio`](#skimage.transform.order_angles_golden_ratio "skimage.transform.order_angles_golden_ratio")(theta) | Order angles to reduce the amount of correlated information in subsequent projections. | | [`skimage.transform.probabilistic_hough_line`](#skimage.transform.probabilistic_hough_line "skimage.transform.probabilistic_hough_line")(image) | Return lines from a progressive probabilistic line Hough transform. | | [`skimage.transform.pyramid_expand`](#skimage.transform.pyramid_expand "skimage.transform.pyramid_expand")(image[, …]) | Upsample and then smooth image. | | [`skimage.transform.pyramid_gaussian`](#skimage.transform.pyramid_gaussian "skimage.transform.pyramid_gaussian")(image[, …]) | Yield images of the Gaussian pyramid formed by the input image. | | [`skimage.transform.pyramid_laplacian`](#skimage.transform.pyramid_laplacian "skimage.transform.pyramid_laplacian")(image[, …]) | Yield images of the laplacian pyramid formed by the input image. | | [`skimage.transform.pyramid_reduce`](#skimage.transform.pyramid_reduce "skimage.transform.pyramid_reduce")(image[, …]) | Smooth and then downsample image. | | [`skimage.transform.radon`](#skimage.transform.radon "skimage.transform.radon")(image[, theta, …]) | Calculates the radon transform of an image given specified projection angles. | | [`skimage.transform.rescale`](#skimage.transform.rescale "skimage.transform.rescale")(image, scale[, …]) | Scale image by a certain factor. | | [`skimage.transform.resize`](#skimage.transform.resize "skimage.transform.resize")(image, output\_shape) | Resize image to match a certain size. | | [`skimage.transform.rotate`](#skimage.transform.rotate "skimage.transform.rotate")(image, angle[, …]) | Rotate image by a certain angle around its center. | | [`skimage.transform.swirl`](#skimage.transform.swirl "skimage.transform.swirl")(image[, center, …]) | Perform a swirl transformation. | | [`skimage.transform.warp`](#skimage.transform.warp "skimage.transform.warp")(image, inverse\_map[, …]) | Warp an image according to a given coordinate transformation. | | [`skimage.transform.warp_coords`](#skimage.transform.warp_coords "skimage.transform.warp_coords")(coord\_map, shape) | Build the source coordinates for the output of a 2-D image warp. | | [`skimage.transform.warp_polar`](#skimage.transform.warp_polar "skimage.transform.warp_polar")(image[, …]) | Remap image to polar or log-polar coordinates space. | | [`skimage.transform.AffineTransform`](#skimage.transform.AffineTransform "skimage.transform.AffineTransform")([matrix, …]) | 2D affine transformation. | | [`skimage.transform.EssentialMatrixTransform`](#skimage.transform.EssentialMatrixTransform "skimage.transform.EssentialMatrixTransform")([…]) | Essential matrix transformation. | | [`skimage.transform.EuclideanTransform`](#skimage.transform.EuclideanTransform "skimage.transform.EuclideanTransform")([…]) | 2D Euclidean transformation. | | [`skimage.transform.FundamentalMatrixTransform`](#skimage.transform.FundamentalMatrixTransform "skimage.transform.FundamentalMatrixTransform")([…]) | Fundamental matrix transformation. | | [`skimage.transform.PiecewiseAffineTransform`](#skimage.transform.PiecewiseAffineTransform "skimage.transform.PiecewiseAffineTransform")() | 2D piecewise affine transformation. | | [`skimage.transform.PolynomialTransform`](#skimage.transform.PolynomialTransform "skimage.transform.PolynomialTransform")([params]) | 2D polynomial transformation. | | [`skimage.transform.ProjectiveTransform`](#skimage.transform.ProjectiveTransform "skimage.transform.ProjectiveTransform")([matrix]) | Projective transformation. | | [`skimage.transform.SimilarityTransform`](#skimage.transform.SimilarityTransform "skimage.transform.SimilarityTransform")([…]) | 2D similarity transformation. | downscale\_local\_mean ---------------------- `skimage.transform.downscale_local_mean(image, factors, cval=0, clip=True)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_warps.py#L407-L451) Down-sample N-dimensional image by local averaging. The image is padded with `cval` if it is not perfectly divisible by the integer factors. In contrast to interpolation in [`skimage.transform.resize`](#skimage.transform.resize "skimage.transform.resize") and [`skimage.transform.rescale`](#skimage.transform.rescale "skimage.transform.rescale") this function calculates the local mean of elements in each block of size `factors` in the input image. Parameters `imagendarray` N-dimensional input image. `factorsarray_like` Array containing down-sampling integer factor along each axis. `cvalfloat, optional` Constant padding value if image is not perfectly divisible by the integer factors. `clipbool, optional` Unused, but kept here for API consistency with the other transforms in this module. (The local mean will never fall outside the range of values in the input image, assuming the provided `cval` also falls within that range.) Returns `imagendarray` Down-sampled image with same number of dimensions as input image. For integer inputs, the output dtype will be `float64`. See [`numpy.mean()`](https://numpy.org/doc/stable/reference/generated/numpy.mean.html#numpy.mean "(in NumPy v1.19)") for details. #### Examples ``` >>> a = np.arange(15).reshape(3, 5) >>> a array([[ 0, 1, 2, 3, 4], [ 5, 6, 7, 8, 9], [10, 11, 12, 13, 14]]) >>> downscale_local_mean(a, (2, 3)) array([[3.5, 4. ], [5.5, 4.5]]) ``` estimate\_transform ------------------- `skimage.transform.estimate_transform(ttype, src, dst, **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L1342-L1413) Estimate 2D geometric transformation parameters. You can determine the over-, well- and under-determined parameters with the total least-squares method. Number of source and destination coordinates must match. Parameters `ttype{β€˜euclidean’, similarity’, β€˜affine’, β€˜piecewise-affine’, β€˜projective’, β€˜polynomial’}` Type of transform. `kwargsarray or int` Function parameters (src, dst, n, angle): ``` NAME / TTYPE FUNCTION PARAMETERS 'euclidean' `src, `dst` 'similarity' `src, `dst` 'affine' `src, `dst` 'piecewise-affine' `src, `dst` 'projective' `src, `dst` 'polynomial' `src, `dst`, `order` (polynomial order, default order is 2) ``` Also see examples below. Returns `tformGeometricTransform` Transform object containing the transformation parameters and providing access to forward and inverse transformation functions. #### Examples ``` >>> import numpy as np >>> from skimage import transform ``` ``` >>> # estimate transformation parameters >>> src = np.array([0, 0, 10, 10]).reshape((2, 2)) >>> dst = np.array([12, 14, 1, -20]).reshape((2, 2)) ``` ``` >>> tform = transform.estimate_transform('similarity', src, dst) ``` ``` >>> np.allclose(tform.inverse(tform(src)), src) True ``` ``` >>> # warp image using the estimated transformation >>> from skimage import data >>> image = data.camera() ``` ``` >>> warp(image, inverse_map=tform.inverse) ``` ``` >>> # create transformation with explicit parameters >>> tform2 = transform.SimilarityTransform(scale=1.1, rotation=1, ... translation=(10, 20)) ``` ``` >>> # unite transformations, applied in order from left to right >>> tform3 = tform + tform2 >>> np.allclose(tform3(src), tform2(tform(src))) True ``` frt2 ---- `skimage.transform.frt2(a)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/finite_radon_transform.py#L12-L68) Compute the 2-dimensional finite radon transform (FRT) for an n x n integer array. Parameters `aarray_like` A 2-D square n x n integer array. Returns `FRT2-D ndarray` Finite Radon Transform array of (n+1) x n integer coefficients. See also [`ifrt2`](#skimage.transform.ifrt2 "skimage.transform.ifrt2") The two-dimensional inverse FRT. #### Notes The FRT has a unique inverse if and only if n is prime. [FRT] The idea for this algorithm is due to Vlad Negnevitski. #### References `FRT` A. Kingston and I. Svalbe, β€œProjective transforms on periodic discrete image arrays,” in P. Hawkes (Ed), Advances in Imaging and Electron Physics, 139 (2006) #### Examples Generate a test image: Use a prime number for the array dimensions ``` >>> SIZE = 59 >>> img = np.tri(SIZE, dtype=np.int32) ``` Apply the Finite Radon Transform: ``` >>> f = frt2(img) ``` hough\_circle ------------- `skimage.transform.hough_circle(image, radius, normalize=True, full_output=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/hough_transform.py#L72-L113) Perform a circular Hough transform. Parameters `image(M, N) ndarray` Input image with nonzero values representing edges. `radiusscalar or sequence of scalars` Radii at which to compute the Hough transform. Floats are converted to integers. `normalizeboolean, optional (default True)` Normalize the accumulator with the number of pixels used to draw the radius. `full_outputboolean, optional (default False)` Extend the output size by twice the largest radius in order to detect centers outside the input picture. Returns `H3D ndarray (radius index, (M + 2R, N + 2R) ndarray)` Hough transform accumulator for each radius. R designates the larger radius if full\_output is True. Otherwise, R = 0. #### Examples ``` >>> from skimage.transform import hough_circle >>> from skimage.draw import circle_perimeter >>> img = np.zeros((100, 100), dtype=bool) >>> rr, cc = circle_perimeter(25, 35, 23) >>> img[rr, cc] = 1 >>> try_radii = np.arange(5, 50) >>> res = hough_circle(img, try_radii) >>> ridx, r, c = np.unravel_index(np.argmax(res), res.shape) >>> r, c, try_radii[ridx] (25, 35, 23) ``` hough\_circle\_peaks -------------------- `skimage.transform.hough_circle_peaks(hspaces, radii, min_xdistance=1, min_ydistance=1, threshold=None, num_peaks=inf, total_num_peaks=inf, normalize=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/hough_transform.py#L271-L377) Return peaks in a circle Hough transform. Identifies most prominent circles separated by certain distances in given Hough spaces. Non-maximum suppression with different sizes is applied separately in the first and second dimension of the Hough space to identify peaks. For circles with different radius but close in distance, only the one with highest peak is kept. Parameters `hspaces(N, M) array` Hough spaces returned by the [`hough_circle`](#skimage.transform.hough_circle "skimage.transform.hough_circle") function. `radii(M,) array` Radii corresponding to Hough spaces. `min_xdistanceint, optional` Minimum distance separating centers in the x dimension. `min_ydistanceint, optional` Minimum distance separating centers in the y dimension. `thresholdfloat, optional` Minimum intensity of peaks in each Hough space. Default is `0.5 * max(hspace)`. `num_peaksint, optional` Maximum number of peaks in each Hough space. When the number of peaks exceeds `num_peaks`, only `num_peaks` coordinates based on peak intensity are considered for the corresponding radius. `total_num_peaksint, optional` Maximum number of peaks. When the number of peaks exceeds `num_peaks`, return `num_peaks` coordinates based on peak intensity. `normalizebool, optional` If True, normalize the accumulator by the radius to sort the prominent peaks. Returns `accum, cx, cy, radtuple of array` Peak values in Hough space, x and y center coordinates and radii. #### Notes Circles with bigger radius have higher peaks in Hough space. If larger circles are preferred over smaller ones, `normalize` should be False. Otherwise, circles will be returned in the order of decreasing voting number. #### Examples ``` >>> from skimage import transform, draw >>> img = np.zeros((120, 100), dtype=int) >>> radius, x_0, y_0 = (20, 99, 50) >>> y, x = draw.circle_perimeter(y_0, x_0, radius) >>> img[x, y] = 1 >>> hspaces = transform.hough_circle(img, radius) >>> accum, cx, cy, rad = hough_circle_peaks(hspaces, [radius,]) ``` hough\_ellipse -------------- `skimage.transform.hough_ellipse(image, threshold=4, accuracy=1, min_size=4, max_size=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/hough_transform.py#L116-L165) Perform an elliptical Hough transform. Parameters `image(M, N) ndarray` Input image with nonzero values representing edges. `thresholdint, optional` Accumulator threshold value. `accuracydouble, optional` Bin size on the minor axis used in the accumulator. `min_sizeint, optional` Minimal major axis length. `max_sizeint, optional` Maximal minor axis length. If None, the value is set to the half of the smaller image dimension. Returns `resultndarray with fields [(accumulator, yc, xc, a, b, orientation)].` Where `(yc, xc)` is the center, `(a, b)` the major and minor axes, respectively. The `orientation` value follows [`skimage.draw.ellipse_perimeter`](skimage.draw#skimage.draw.ellipse_perimeter "skimage.draw.ellipse_perimeter") convention. #### Notes The accuracy must be chosen to produce a peak in the accumulator distribution. In other words, a flat accumulator distribution with low values may be caused by a too low bin size. #### References `1` Xie, Yonghong, and Qiang Ji. β€œA new efficient ellipse detection method.” Pattern Recognition, 2002. Proceedings. 16th International Conference on. Vol. 2. IEEE, 2002 #### Examples ``` >>> from skimage.transform import hough_ellipse >>> from skimage.draw import ellipse_perimeter >>> img = np.zeros((25, 25), dtype=np.uint8) >>> rr, cc = ellipse_perimeter(10, 10, 6, 8) >>> img[cc, rr] = 1 >>> result = hough_ellipse(img, threshold=8) >>> result.tolist() [(10, 10.0, 10.0, 8.0, 6.0, 0.0)] ``` hough\_line ----------- `skimage.transform.hough_line(image, theta=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/hough_transform.py#L168-L223) Perform a straight line Hough transform. Parameters `image(M, N) ndarray` Input image with nonzero values representing edges. `theta1D ndarray of double, optional` Angles at which to compute the transform, in radians. Defaults to a vector of 180 angles evenly spaced from -pi/2 to pi/2. Returns `hspace2-D ndarray of uint64` Hough transform accumulator. `anglesndarray` Angles at which the transform is computed, in radians. `distancesndarray` Distance values. #### Notes The origin is the top left corner of the original image. X and Y axis are horizontal and vertical edges respectively. The distance is the minimal algebraic distance from the origin to the detected line. The angle accuracy can be improved by decreasing the step size in the `theta` array. #### Examples Generate a test image: ``` >>> img = np.zeros((100, 150), dtype=bool) >>> img[30, :] = 1 >>> img[:, 65] = 1 >>> img[35:45, 35:50] = 1 >>> for i in range(90): ... img[i, i] = 1 >>> img += np.random.random(img.shape) > 0.95 ``` Apply the Hough transform: ``` >>> out, angles, d = hough_line(img) ``` ``` import numpy as np import matplotlib.pyplot as plt from skimage.transform import hough_line from skimage.draw import line img = np.zeros((100, 150), dtype=bool) img[30, :] = 1 img[:, 65] = 1 img[35:45, 35:50] = 1 rr, cc = line(60, 130, 80, 10) img[rr, cc] = 1 img += np.random.random(img.shape) > 0.95 out, angles, d = hough_line(img) fix, axes = plt.subplots(1, 2, figsize=(7, 4)) axes[0].imshow(img, cmap=plt.cm.gray) axes[0].set_title('Input image') axes[1].imshow( out, cmap=plt.cm.bone, extent=(np.rad2deg(angles[-1]), np.rad2deg(angles[0]), d[-1], d[0])) axes[1].set_title('Hough transform') axes[1].set_xlabel('Angle (degree)') axes[1].set_ylabel('Distance (pixel)') plt.tight_layout() plt.show() ``` ([Source code](https://scikit-image.org/docs/0.18.x/plots/hough_tf.py), [png](https://scikit-image.org/docs/0.18.x/plots/hough_tf.png), [pdf](https://scikit-image.org/docs/0.18.x/plots/hough_tf.pdf)) hough\_line\_peaks ------------------ `skimage.transform.hough_line_peaks(hspace, angles, dists, min_distance=9, min_angle=10, threshold=None, num_peaks=inf)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/hough_transform.py#L9-L69) Return peaks in a straight line Hough transform. Identifies most prominent lines separated by a certain angle and distance in a Hough transform. Non-maximum suppression with different sizes is applied separately in the first (distances) and second (angles) dimension of the Hough space to identify peaks. Parameters `hspace(N, M) array` Hough space returned by the [`hough_line`](#skimage.transform.hough_line "skimage.transform.hough_line") function. `angles(M,) array` Angles returned by the [`hough_line`](#skimage.transform.hough_line "skimage.transform.hough_line") function. Assumed to be continuous. (`angles[-1] - angles[0] == PI`). `dists(N, ) array` Distances returned by the [`hough_line`](#skimage.transform.hough_line "skimage.transform.hough_line") function. `min_distanceint, optional` Minimum distance separating lines (maximum filter size for first dimension of hough space). `min_angleint, optional` Minimum angle separating lines (maximum filter size for second dimension of hough space). `thresholdfloat, optional` Minimum intensity of peaks. Default is `0.5 * max(hspace)`. `num_peaksint, optional` Maximum number of peaks. When the number of peaks exceeds `num_peaks`, return `num_peaks` coordinates based on peak intensity. Returns `accum, angles, diststuple of array` Peak values in Hough space, angles and distances. #### Examples ``` >>> from skimage.transform import hough_line, hough_line_peaks >>> from skimage.draw import line >>> img = np.zeros((15, 15), dtype=bool) >>> rr, cc = line(0, 0, 14, 14) >>> img[rr, cc] = 1 >>> rr, cc = line(0, 14, 14, 0) >>> img[cc, rr] = 1 >>> hspace, angles, dists = hough_line(img) >>> hspace, angles, dists = hough_line_peaks(hspace, angles, dists) >>> len(angles) 2 ``` ifrt2 ----- `skimage.transform.ifrt2(a)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/finite_radon_transform.py#L71-L134) Compute the 2-dimensional inverse finite radon transform (iFRT) for an (n+1) x n integer array. Parameters `aarray_like` A 2-D (n+1) row x n column integer array. Returns `iFRT2-D n x n ndarray` Inverse Finite Radon Transform array of n x n integer coefficients. See also [`frt2`](#skimage.transform.frt2 "skimage.transform.frt2") The two-dimensional FRT #### Notes The FRT has a unique inverse if and only if n is prime. See [[1]](#r3b76f892cb20-1) for an overview. The idea for this algorithm is due to Vlad Negnevitski. #### References `1` A. Kingston and I. Svalbe, β€œProjective transforms on periodic discrete image arrays,” in P. Hawkes (Ed), Advances in Imaging and Electron Physics, 139 (2006) #### Examples ``` >>> SIZE = 59 >>> img = np.tri(SIZE, dtype=np.int32) ``` Apply the Finite Radon Transform: ``` >>> f = frt2(img) ``` Apply the Inverse Finite Radon Transform to recover the input ``` >>> fi = ifrt2(f) ``` Check that it’s identical to the original ``` >>> assert len(np.nonzero(img-fi)[0]) == 0 ``` integral\_image --------------- `skimage.transform.integral_image(image)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/integral.py#L4-L33) Integral image / summed area table. The integral image contains the sum of all elements above and to the left of it, i.e.: \[S[m, n] = \sum\_{i \leq m} \sum\_{j \leq n} X[i, j]\] Parameters `imagendarray` Input image. Returns `Sndarray` Integral image/summed area table of same shape as input image. #### References `1` F.C. Crow, β€œSummed-area tables for texture mapping,” ACM SIGGRAPH Computer Graphics, vol. 18, 1984, pp. 207-212. integrate --------- `skimage.transform.integrate(ii, start, end)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/integral.py#L36-L128) Use an integral image to integrate over a given window. Parameters `iindarray` Integral image. `startList of tuples, each tuple of length equal to dimension of ii` Coordinates of top left corner of window(s). Each tuple in the list contains the starting row, col, … index i.e `[(row_win1, col_win1, …), (row_win2, col_win2,…), …]`. `endList of tuples, each tuple of length equal to dimension of ii` Coordinates of bottom right corner of window(s). Each tuple in the list containing the end row, col, … index i.e `[(row_win1, col_win1, …), (row_win2, col_win2, …), …]`. Returns `Sscalar or ndarray` Integral (sum) over the given window(s). #### Examples ``` >>> arr = np.ones((5, 6), dtype=float) >>> ii = integral_image(arr) >>> integrate(ii, (1, 0), (1, 2)) # sum from (1, 0) to (1, 2) array([3.]) >>> integrate(ii, [(3, 3)], [(4, 5)]) # sum from (3, 3) to (4, 5) array([6.]) >>> # sum from (1, 0) to (1, 2) and from (3, 3) to (4, 5) >>> integrate(ii, [(1, 0), (3, 3)], [(1, 2), (4, 5)]) array([3., 6.]) ``` iradon ------ `skimage.transform.iradon(radon_image, theta=None, output_size=None, filter_name='ramp', interpolation='linear', circle=True, preserve_range=True)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/radon_transform.py#L184-L314) Inverse radon transform. Reconstruct an image from the radon transform, using the filtered back projection algorithm. Parameters `radon_imagearray` Image containing radon transform (sinogram). Each column of the image corresponds to a projection along a different angle. The tomography rotation axis should lie at the pixel index `radon_image.shape[0] // 2` along the 0th dimension of `radon_image`. `thetaarray_like, optional` Reconstruction angles (in degrees). Default: m angles evenly spaced between 0 and 180 (if the shape of `radon_image` is (N, M)). `output_sizeint, optional` Number of rows and columns in the reconstruction. `filter_namestr, optional` Filter used in frequency domain filtering. Ramp filter used by default. Filters available: ramp, shepp-logan, cosine, hamming, hann. Assign None to use no filter. `interpolationstr, optional` Interpolation method used in reconstruction. Methods available: β€˜linear’, β€˜nearest’, and β€˜cubic’ (β€˜cubic’ is slow). `circleboolean, optional` Assume the reconstructed image is zero outside the inscribed circle. Also changes the default output\_size to match the behaviour of `radon` called with `circle=True`. `preserve_rangebool, optional` Whether to keep the original range of values. Otherwise, the input image is converted according to the conventions of `img_as_float`. Also see <https://scikit-image.org/docs/dev/user_guide/data_types.html> Returns `reconstructedndarray` Reconstructed image. The rotation axis will be located in the pixel with indices `(reconstructed.shape[0] // 2, reconstructed.shape[1] // 2)`. Changed in version 0.19: In `iradon`, `filter` argument is deprecated in favor of `filter_name`. #### Notes It applies the Fourier slice theorem to reconstruct an image by multiplying the frequency domain of the filter with the FFT of the projection data. This algorithm is called filtered back projection. #### References `1` AC Kak, M Slaney, β€œPrinciples of Computerized Tomographic Imaging”, IEEE Press 1988. `2` B.R. Ramesh, N. Srinivasa, K. Rajgopal, β€œAn Algorithm for Computing the Discrete Radon Transform With Some Applications”, Proceedings of the Fourth IEEE Region 10 International Conference, TENCON β€˜89, 1989 iradon\_sart ------------ `skimage.transform.iradon_sart(radon_image, theta=None, image=None, projection_shifts=None, clip=None, relaxation=0.15, dtype=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/radon_transform.py#L376-L515) Inverse radon transform. Reconstruct an image from the radon transform, using a single iteration of the Simultaneous Algebraic Reconstruction Technique (SART) algorithm. Parameters `radon_image2D array` Image containing radon transform (sinogram). Each column of the image corresponds to a projection along a different angle. The tomography rotation axis should lie at the pixel index `radon_image.shape[0] // 2` along the 0th dimension of `radon_image`. `theta1D array, optional` Reconstruction angles (in degrees). Default: m angles evenly spaced between 0 and 180 (if the shape of `radon_image` is (N, M)). `image2D array, optional` Image containing an initial reconstruction estimate. Shape of this array should be `(radon_image.shape[0], radon_image.shape[0])`. The default is an array of zeros. `projection_shifts1D array, optional` Shift the projections contained in `radon_image` (the sinogram) by this many pixels before reconstructing the image. The i’th value defines the shift of the i’th column of `radon_image`. `cliplength-2 sequence of floats, optional` Force all values in the reconstructed tomogram to lie in the range `[clip[0], clip[1]]` `relaxationfloat, optional` Relaxation parameter for the update step. A higher value can improve the convergence rate, but one runs the risk of instabilities. Values close to or higher than 1 are not recommended. `dtypedtype, optional` Output data type, must be floating point. By default, if input data type is not float, input is cast to double, otherwise dtype is set to input data type. Returns `reconstructedndarray` Reconstructed image. The rotation axis will be located in the pixel with indices `(reconstructed.shape[0] // 2, reconstructed.shape[1] // 2)`. #### Notes Algebraic Reconstruction Techniques are based on formulating the tomography reconstruction problem as a set of linear equations. Along each ray, the projected value is the sum of all the values of the cross section along the ray. A typical feature of SART (and a few other variants of algebraic techniques) is that it samples the cross section at equidistant points along the ray, using linear interpolation between the pixel values of the cross section. The resulting set of linear equations are then solved using a slightly modified Kaczmarz method. When using SART, a single iteration is usually sufficient to obtain a good reconstruction. Further iterations will tend to enhance high-frequency information, but will also often increase the noise. #### References `1` AC Kak, M Slaney, β€œPrinciples of Computerized Tomographic Imaging”, IEEE Press 1988. `2` AH Andersen, AC Kak, β€œSimultaneous algebraic reconstruction technique (SART): a superior implementation of the ART algorithm”, Ultrasonic Imaging 6 pp 81–94 (1984) `3` S Kaczmarz, β€œAngenΓ€herte auflΓΆsung von systemen linearer gleichungen”, Bulletin International de l’Academie Polonaise des Sciences et des Lettres 35 pp 355–357 (1937) `4` Kohler, T. β€œA projection access scheme for iterative reconstruction based on the golden section.” Nuclear Science Symposium Conference Record, 2004 IEEE. Vol. 6. IEEE, 2004. `5` Kaczmarz’ method, Wikipedia, <https://en.wikipedia.org/wiki/Kaczmarz_method> matrix\_transform ----------------- `skimage.transform.matrix_transform(coords, matrix)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L1416-L1432) Apply 2D matrix transform. Parameters `coords(N, 2) array` x, y coordinates to transform `matrix(3, 3) array` Homogeneous transformation matrix. Returns `coords(N, 2) array` Transformed coordinates. order\_angles\_golden\_ratio ---------------------------- `skimage.transform.order_angles_golden_ratio(theta)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/radon_transform.py#L317-L373) Order angles to reduce the amount of correlated information in subsequent projections. Parameters `theta1D array of floats` Projection angles in degrees. Duplicate angles are not allowed. Returns `indices_generatorgenerator yielding unsigned integers` The returned generator yields indices into `theta` such that `theta[indices]` gives the approximate golden ratio ordering of the projections. In total, `len(theta)` indices are yielded. All non-negative integers < `len(theta)` are yielded exactly once. #### Notes The method used here is that of the golden ratio introduced by T. Kohler. #### References `1` Kohler, T. β€œA projection access scheme for iterative reconstruction based on the golden section.” Nuclear Science Symposium Conference Record, 2004 IEEE. Vol. 6. IEEE, 2004. `2` Winkelmann, Stefanie, et al. β€œAn optimal radial profile order based on the Golden Ratio for time-resolved MRI.” Medical Imaging, IEEE Transactions on 26.1 (2007): 68-76. probabilistic\_hough\_line -------------------------- `skimage.transform.probabilistic_hough_line(image, threshold=10, line_length=50, line_gap=10, theta=None, seed=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/hough_transform.py#L226-L268) Return lines from a progressive probabilistic line Hough transform. Parameters `image(M, N) ndarray` Input image with nonzero values representing edges. `thresholdint, optional` Threshold `line_lengthint, optional` Minimum accepted length of detected lines. Increase the parameter to extract longer lines. `line_gapint, optional` Maximum gap between pixels to still form a line. Increase the parameter to merge broken lines more aggressively. `theta1D ndarray, dtype=double, optional` Angles at which to compute the transform, in radians. If None, use a range from -pi/2 to pi/2. `seedint, optional` Seed to initialize the random number generator. Returns `lineslist` List of lines identified, lines in format ((x0, y0), (x1, y1)), indicating line start and end. #### References `1` C. Galamhos, J. Matas and J. Kittler, β€œProgressive probabilistic Hough transform for line detection”, in IEEE Computer Society Conference on Computer Vision and Pattern Recognition, 1999. pyramid\_expand --------------- `skimage.transform.pyramid_expand(image, upscale=2, sigma=None, order=1, mode='reflect', cval=0, multichannel=False, preserve_range=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/pyramids.py#L85-L142) Upsample and then smooth image. Parameters `imagendarray` Input image. `upscalefloat, optional` Upscale factor. `sigmafloat, optional` Sigma for Gaussian filter. Default is `2 * upscale / 6.0` which corresponds to a filter mask twice the size of the scale factor that covers more than 99% of the Gaussian distribution. `orderint, optional` Order of splines used in interpolation of upsampling. See [`skimage.transform.warp`](#skimage.transform.warp "skimage.transform.warp") for detail. `mode{β€˜reflect’, β€˜constant’, β€˜edge’, β€˜symmetric’, β€˜wrap’}, optional` The mode parameter determines how the array borders are handled, where cval is the value when mode is equal to β€˜constant’. `cvalfloat, optional` Value to fill past edges of input if mode is β€˜constant’. `multichannelbool, optional` Whether the last axis of the image is to be interpreted as multiple channels or another spatial dimension. `preserve_rangebool, optional` Whether to keep the original range of values. Otherwise, the input image is converted according to the conventions of `img_as_float`. Also see <https://scikit-image.org/docs/dev/user_guide/data_types.html> Returns `outarray` Upsampled and smoothed float image. #### References `1` <http://persci.mit.edu/pub_pdfs/pyramid83.pdf> pyramid\_gaussian ----------------- `skimage.transform.pyramid_gaussian(image, max_layer=-1, downscale=2, sigma=None, order=1, mode='reflect', cval=0, multichannel=False, preserve_range=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/pyramids.py#L145-L224) Yield images of the Gaussian pyramid formed by the input image. Recursively applies the [`pyramid_reduce`](#skimage.transform.pyramid_reduce "skimage.transform.pyramid_reduce") function to the image, and yields the downscaled images. Note that the first image of the pyramid will be the original, unscaled image. The total number of images is `max_layer + 1`. In case all layers are computed, the last image is either a one-pixel image or the image where the reduction does not change its shape. Parameters `imagendarray` Input image. `max_layerint, optional` Number of layers for the pyramid. 0th layer is the original image. Default is -1 which builds all possible layers. `downscalefloat, optional` Downscale factor. `sigmafloat, optional` Sigma for Gaussian filter. Default is `2 * downscale / 6.0` which corresponds to a filter mask twice the size of the scale factor that covers more than 99% of the Gaussian distribution. `orderint, optional` Order of splines used in interpolation of downsampling. See [`skimage.transform.warp`](#skimage.transform.warp "skimage.transform.warp") for detail. `mode{β€˜reflect’, β€˜constant’, β€˜edge’, β€˜symmetric’, β€˜wrap’}, optional` The mode parameter determines how the array borders are handled, where cval is the value when mode is equal to β€˜constant’. `cvalfloat, optional` Value to fill past edges of input if mode is β€˜constant’. `multichannelbool, optional` Whether the last axis of the image is to be interpreted as multiple channels or another spatial dimension. `preserve_rangebool, optional` Whether to keep the original range of values. Otherwise, the input image is converted according to the conventions of `img_as_float`. Also see <https://scikit-image.org/docs/dev/user_guide/data_types.html> Returns `pyramidgenerator` Generator yielding pyramid layers as float images. #### References `1` <http://persci.mit.edu/pub_pdfs/pyramid83.pdf> pyramid\_laplacian ------------------ `skimage.transform.pyramid_laplacian(image, max_layer=-1, downscale=2, sigma=None, order=1, mode='reflect', cval=0, multichannel=False, preserve_range=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/pyramids.py#L227-L317) Yield images of the laplacian pyramid formed by the input image. Each layer contains the difference between the downsampled and the downsampled, smoothed image: ``` layer = resize(prev_layer) - smooth(resize(prev_layer)) ``` Note that the first image of the pyramid will be the difference between the original, unscaled image and its smoothed version. The total number of images is `max_layer + 1`. In case all layers are computed, the last image is either a one-pixel image or the image where the reduction does not change its shape. Parameters `imagendarray` Input image. `max_layerint, optional` Number of layers for the pyramid. 0th layer is the original image. Default is -1 which builds all possible layers. `downscalefloat, optional` Downscale factor. `sigmafloat, optional` Sigma for Gaussian filter. Default is `2 * downscale / 6.0` which corresponds to a filter mask twice the size of the scale factor that covers more than 99% of the Gaussian distribution. `orderint, optional` Order of splines used in interpolation of downsampling. See [`skimage.transform.warp`](#skimage.transform.warp "skimage.transform.warp") for detail. `mode{β€˜reflect’, β€˜constant’, β€˜edge’, β€˜symmetric’, β€˜wrap’}, optional` The mode parameter determines how the array borders are handled, where cval is the value when mode is equal to β€˜constant’. `cvalfloat, optional` Value to fill past edges of input if mode is β€˜constant’. `multichannelbool, optional` Whether the last axis of the image is to be interpreted as multiple channels or another spatial dimension. `preserve_rangebool, optional` Whether to keep the original range of values. Otherwise, the input image is converted according to the conventions of `img_as_float`. Also see <https://scikit-image.org/docs/dev/user_guide/data_types.html> Returns `pyramidgenerator` Generator yielding pyramid layers as float images. #### References `1` <http://persci.mit.edu/pub_pdfs/pyramid83.pdf> `2` <http://sepwww.stanford.edu/data/media/public/sep/morgan/texturematch/paper_html/node3.html> pyramid\_reduce --------------- `skimage.transform.pyramid_reduce(image, downscale=2, sigma=None, order=1, mode='reflect', cval=0, multichannel=False, preserve_range=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/pyramids.py#L25-L82) Smooth and then downsample image. Parameters `imagendarray` Input image. `downscalefloat, optional` Downscale factor. `sigmafloat, optional` Sigma for Gaussian filter. Default is `2 * downscale / 6.0` which corresponds to a filter mask twice the size of the scale factor that covers more than 99% of the Gaussian distribution. `orderint, optional` Order of splines used in interpolation of downsampling. See [`skimage.transform.warp`](#skimage.transform.warp "skimage.transform.warp") for detail. `mode{β€˜reflect’, β€˜constant’, β€˜edge’, β€˜symmetric’, β€˜wrap’}, optional` The mode parameter determines how the array borders are handled, where cval is the value when mode is equal to β€˜constant’. `cvalfloat, optional` Value to fill past edges of input if mode is β€˜constant’. `multichannelbool, optional` Whether the last axis of the image is to be interpreted as multiple channels or another spatial dimension. `preserve_rangebool, optional` Whether to keep the original range of values. Otherwise, the input image is converted according to the conventions of `img_as_float`. Also see <https://scikit-image.org/docs/dev/user_guide/data_types.html> Returns `outarray` Smoothed and downsampled float image. #### References `1` <http://persci.mit.edu/pub_pdfs/pyramid83.pdf> radon ----- `skimage.transform.radon(image, theta=None, circle=True, *, preserve_range=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/radon_transform.py#L24-L115) Calculates the radon transform of an image given specified projection angles. Parameters `imagearray_like` Input image. The rotation axis will be located in the pixel with indices `(image.shape[0] // 2, image.shape[1] // 2)`. `thetaarray_like, optional` Projection angles (in degrees). If `None`, the value is set to np.arange(180). `circleboolean, optional` Assume image is zero outside the inscribed circle, making the width of each projection (the first dimension of the sinogram) equal to `min(image.shape)`. `preserve_rangebool, optional` Whether to keep the original range of values. Otherwise, the input image is converted according to the conventions of `img_as_float`. Also see <https://scikit-image.org/docs/dev/user_guide/data_types.html> Returns `radon_imagendarray` Radon transform (sinogram). The tomography rotation axis will lie at the pixel index `radon_image.shape[0] // 2` along the 0th dimension of `radon_image`. #### Notes Based on code of Justin K. Romberg (<https://www.clear.rice.edu/elec431/projects96/DSP/bpanalysis.html>) #### References `1` AC Kak, M Slaney, β€œPrinciples of Computerized Tomographic Imaging”, IEEE Press 1988. `2` B.R. Ramesh, N. Srinivasa, K. Rajgopal, β€œAn Algorithm for Computing the Discrete Radon Transform With Some Applications”, Proceedings of the Fourth IEEE Region 10 International Conference, TENCON β€˜89, 1989 rescale ------- `skimage.transform.rescale(image, scale, order=None, mode='reflect', cval=0, clip=True, preserve_range=False, multichannel=False, anti_aliasing=None, anti_aliasing_sigma=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_warps.py#L201-L293) Scale image by a certain factor. Performs interpolation to up-scale or down-scale N-dimensional images. Note that anti-aliasing should be enabled when down-sizing images to avoid aliasing artifacts. For down-sampling with an integer factor also see [`skimage.transform.downscale_local_mean`](#skimage.transform.downscale_local_mean "skimage.transform.downscale_local_mean"). Parameters `imagendarray` Input image. `scale{float, tuple of floats}` Scale factors. Separate scale factors can be defined as `(rows, cols[, …][, dim])`. Returns `scaledndarray` Scaled version of the input. Other Parameters `orderint, optional` The order of the spline interpolation, default is 0 if image.dtype is bool and 1 otherwise. The order has to be in the range 0-5. See [`skimage.transform.warp`](#skimage.transform.warp "skimage.transform.warp") for detail. `mode{β€˜constant’, β€˜edge’, β€˜symmetric’, β€˜reflect’, β€˜wrap’}, optional` Points outside the boundaries of the input are filled according to the given mode. Modes match the behaviour of [`numpy.pad`](https://numpy.org/doc/stable/reference/generated/numpy.pad.html#numpy.pad "(in NumPy v1.19)"). `cvalfloat, optional` Used in conjunction with mode β€˜constant’, the value outside the image boundaries. `clipbool, optional` Whether to clip the output to the range of values of the input image. This is enabled by default, since higher order interpolation may produce values outside the given input range. `preserve_rangebool, optional` Whether to keep the original range of values. Otherwise, the input image is converted according to the conventions of `img_as_float`. Also see <https://scikit-image.org/docs/dev/user_guide/data_types.html> `multichannelbool, optional` Whether the last axis of the image is to be interpreted as multiple channels or another spatial dimension. `anti_aliasingbool, optional` Whether to apply a Gaussian filter to smooth the image prior to down-scaling. It is crucial to filter when down-sampling the image to avoid aliasing artifacts. If input image data type is bool, no anti-aliasing is applied. `anti_aliasing_sigma{float, tuple of floats}, optional` Standard deviation for Gaussian filtering to avoid aliasing artifacts. By default, this value is chosen as (s - 1) / 2 where s is the down-scaling factor. #### Notes Modes β€˜reflect’ and β€˜symmetric’ are similar, but differ in whether the edge pixels are duplicated during the reflection. As an example, if an array has values [0, 1, 2] and was padded to the right by four values using symmetric, the result would be [0, 1, 2, 2, 1, 0, 0], while for reflect it would be [0, 1, 2, 1, 0, 1, 2]. #### Examples ``` >>> from skimage import data >>> from skimage.transform import rescale >>> image = data.camera() >>> rescale(image, 0.1).shape (51, 51) >>> rescale(image, 0.5).shape (256, 256) ``` resize ------ `skimage.transform.resize(image, output_shape, order=None, mode='reflect', cval=0, clip=True, preserve_range=False, anti_aliasing=None, anti_aliasing_sigma=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_warps.py#L19-L198) Resize image to match a certain size. Performs interpolation to up-size or down-size N-dimensional images. Note that anti-aliasing should be enabled when down-sizing images to avoid aliasing artifacts. For down-sampling with an integer factor also see [`skimage.transform.downscale_local_mean`](#skimage.transform.downscale_local_mean "skimage.transform.downscale_local_mean"). Parameters `imagendarray` Input image. `output_shapetuple or ndarray` Size of the generated output image `(rows, cols[, …][, dim])`. If `dim` is not provided, the number of channels is preserved. In case the number of input channels does not equal the number of output channels a n-dimensional interpolation is applied. Returns `resizedndarray` Resized version of the input. Other Parameters `orderint, optional` The order of the spline interpolation, default is 0 if image.dtype is bool and 1 otherwise. The order has to be in the range 0-5. See [`skimage.transform.warp`](#skimage.transform.warp "skimage.transform.warp") for detail. `mode{β€˜constant’, β€˜edge’, β€˜symmetric’, β€˜reflect’, β€˜wrap’}, optional` Points outside the boundaries of the input are filled according to the given mode. Modes match the behaviour of [`numpy.pad`](https://numpy.org/doc/stable/reference/generated/numpy.pad.html#numpy.pad "(in NumPy v1.19)"). `cvalfloat, optional` Used in conjunction with mode β€˜constant’, the value outside the image boundaries. `clipbool, optional` Whether to clip the output to the range of values of the input image. This is enabled by default, since higher order interpolation may produce values outside the given input range. `preserve_rangebool, optional` Whether to keep the original range of values. Otherwise, the input image is converted according to the conventions of `img_as_float`. Also see <https://scikit-image.org/docs/dev/user_guide/data_types.html> `anti_aliasingbool, optional` Whether to apply a Gaussian filter to smooth the image prior to down-scaling. It is crucial to filter when down-sampling the image to avoid aliasing artifacts. If input image data type is bool, no anti-aliasing is applied. `anti_aliasing_sigma{float, tuple of floats}, optional` Standard deviation for Gaussian filtering to avoid aliasing artifacts. By default, this value is chosen as (s - 1) / 2 where s is the down-scaling factor, where s > 1. For the up-size case, s < 1, no anti-aliasing is performed prior to rescaling. #### Notes Modes β€˜reflect’ and β€˜symmetric’ are similar, but differ in whether the edge pixels are duplicated during the reflection. As an example, if an array has values [0, 1, 2] and was padded to the right by four values using symmetric, the result would be [0, 1, 2, 2, 1, 0, 0], while for reflect it would be [0, 1, 2, 1, 0, 1, 2]. #### Examples ``` >>> from skimage import data >>> from skimage.transform import resize >>> image = data.camera() >>> resize(image, (100, 100)).shape (100, 100) ``` rotate ------ `skimage.transform.rotate(image, angle, resize=False, center=None, order=None, mode='constant', cval=0, clip=True, preserve_range=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_warps.py#L296-L404) Rotate image by a certain angle around its center. Parameters `imagendarray` Input image. `anglefloat` Rotation angle in degrees in counter-clockwise direction. `resizebool, optional` Determine whether the shape of the output image will be automatically calculated, so the complete rotated image exactly fits. Default is False. `centeriterable of length 2` The rotation center. If `center=None`, the image is rotated around its center, i.e. `center=(cols / 2 - 0.5, rows / 2 - 0.5)`. Please note that this parameter is (cols, rows), contrary to normal skimage ordering. Returns `rotatedndarray` Rotated version of the input. Other Parameters `orderint, optional` The order of the spline interpolation, default is 0 if image.dtype is bool and 1 otherwise. The order has to be in the range 0-5. See [`skimage.transform.warp`](#skimage.transform.warp "skimage.transform.warp") for detail. `mode{β€˜constant’, β€˜edge’, β€˜symmetric’, β€˜reflect’, β€˜wrap’}, optional` Points outside the boundaries of the input are filled according to the given mode. Modes match the behaviour of [`numpy.pad`](https://numpy.org/doc/stable/reference/generated/numpy.pad.html#numpy.pad "(in NumPy v1.19)"). `cvalfloat, optional` Used in conjunction with mode β€˜constant’, the value outside the image boundaries. `clipbool, optional` Whether to clip the output to the range of values of the input image. This is enabled by default, since higher order interpolation may produce values outside the given input range. `preserve_rangebool, optional` Whether to keep the original range of values. Otherwise, the input image is converted according to the conventions of `img_as_float`. Also see <https://scikit-image.org/docs/dev/user_guide/data_types.html> #### Notes Modes β€˜reflect’ and β€˜symmetric’ are similar, but differ in whether the edge pixels are duplicated during the reflection. As an example, if an array has values [0, 1, 2] and was padded to the right by four values using symmetric, the result would be [0, 1, 2, 2, 1, 0, 0], while for reflect it would be [0, 1, 2, 1, 0, 1, 2]. #### Examples ``` >>> from skimage import data >>> from skimage.transform import rotate >>> image = data.camera() >>> rotate(image, 2).shape (512, 512) >>> rotate(image, 2, resize=True).shape (530, 530) >>> rotate(image, 90, resize=True).shape (512, 512) ``` ### Examples using `skimage.transform.rotate` [Different perimeters](https://scikit-image.org/docs/0.18.x/auto_examples/segmentation/plot_perimeters.html#sphx-glr-auto-examples-segmentation-plot-perimeters-py) [Measure region properties](https://scikit-image.org/docs/0.18.x/auto_examples/segmentation/plot_regionprops.html#sphx-glr-auto-examples-segmentation-plot-regionprops-py) swirl ----- `skimage.transform.swirl(image, center=None, strength=1, radius=100, rotation=0, output_shape=None, order=None, mode='reflect', cval=0, clip=True, preserve_range=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_warps.py#L473-L534) Perform a swirl transformation. Parameters `imagendarray` Input image. `center(column, row) tuple or (2,) ndarray, optional` Center coordinate of transformation. `strengthfloat, optional` The amount of swirling applied. `radiusfloat, optional` The extent of the swirl in pixels. The effect dies out rapidly beyond `radius`. `rotationfloat, optional` Additional rotation applied to the image. Returns `swirledndarray` Swirled version of the input. Other Parameters `output_shapetuple (rows, cols), optional` Shape of the output image generated. By default the shape of the input image is preserved. `orderint, optional` The order of the spline interpolation, default is 0 if image.dtype is bool and 1 otherwise. The order has to be in the range 0-5. See [`skimage.transform.warp`](#skimage.transform.warp "skimage.transform.warp") for detail. `mode{β€˜constant’, β€˜edge’, β€˜symmetric’, β€˜reflect’, β€˜wrap’}, optional` Points outside the boundaries of the input are filled according to the given mode, with β€˜constant’ used as the default. Modes match the behaviour of [`numpy.pad`](https://numpy.org/doc/stable/reference/generated/numpy.pad.html#numpy.pad "(in NumPy v1.19)"). `cvalfloat, optional` Used in conjunction with mode β€˜constant’, the value outside the image boundaries. `clipbool, optional` Whether to clip the output to the range of values of the input image. This is enabled by default, since higher order interpolation may produce values outside the given input range. `preserve_rangebool, optional` Whether to keep the original range of values. Otherwise, the input image is converted according to the conventions of `img_as_float`. Also see <https://scikit-image.org/docs/dev/user_guide/data_types.html> warp ---- `skimage.transform.warp(image, inverse_map, map_args={}, output_shape=None, order=None, mode='constant', cval=0.0, clip=True, preserve_range=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_warps.py#L684-L932) Warp an image according to a given coordinate transformation. Parameters `imagendarray` Input image. `inverse_maptransformation object, callable cr = f(cr, **kwargs), or ndarray` Inverse coordinate map, which transforms coordinates in the output images into their corresponding coordinates in the input image. There are a number of different options to define this map, depending on the dimensionality of the input image. A 2-D image can have 2 dimensions for gray-scale images, or 3 dimensions with color information. * For 2-D images, you can directly pass a transformation object, e.g. [`skimage.transform.SimilarityTransform`](#skimage.transform.SimilarityTransform "skimage.transform.SimilarityTransform"), or its inverse. * For 2-D images, you can pass a `(3, 3)` homogeneous transformation matrix, e.g. `skimage.transform.SimilarityTransform.params`. * For 2-D images, a function that transforms a `(M, 2)` array of `(col, row)` coordinates in the output image to their corresponding coordinates in the input image. Extra parameters to the function can be specified through `map_args`. * For N-D images, you can directly pass an array of coordinates. The first dimension specifies the coordinates in the input image, while the subsequent dimensions determine the position in the output image. E.g. in case of 2-D images, you need to pass an array of shape `(2, rows, cols)`, where `rows` and `cols` determine the shape of the output image, and the first dimension contains the `(row, col)` coordinate in the input image. See [`scipy.ndimage.map_coordinates`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.map_coordinates.html#scipy.ndimage.map_coordinates "(in SciPy v1.5.4)") for further documentation. Note, that a `(3, 3)` matrix is interpreted as a homogeneous transformation matrix, so you cannot interpolate values from a 3-D input, if the output is of shape `(3,)`. See example section for usage. `map_argsdict, optional` Keyword arguments passed to `inverse_map`. `output_shapetuple (rows, cols), optional` Shape of the output image generated. By default the shape of the input image is preserved. Note that, even for multi-band images, only rows and columns need to be specified. `orderint, optional` The order of interpolation. The order has to be in the range 0-5: * 0: Nearest-neighbor * 1: Bi-linear (default) * 2: Bi-quadratic * 3: Bi-cubic * 4: Bi-quartic * 5: Bi-quintic Default is 0 if image.dtype is bool and 1 otherwise. `mode{β€˜constant’, β€˜edge’, β€˜symmetric’, β€˜reflect’, β€˜wrap’}, optional` Points outside the boundaries of the input are filled according to the given mode. Modes match the behaviour of [`numpy.pad`](https://numpy.org/doc/stable/reference/generated/numpy.pad.html#numpy.pad "(in NumPy v1.19)"). `cvalfloat, optional` Used in conjunction with mode β€˜constant’, the value outside the image boundaries. `clipbool, optional` Whether to clip the output to the range of values of the input image. This is enabled by default, since higher order interpolation may produce values outside the given input range. `preserve_rangebool, optional` Whether to keep the original range of values. Otherwise, the input image is converted according to the conventions of `img_as_float`. Also see <https://scikit-image.org/docs/dev/user_guide/data_types.html> Returns `warpeddouble ndarray` The warped input image. #### Notes * The input image is converted to a `double` image. * In case of a [`SimilarityTransform`](#skimage.transform.SimilarityTransform "skimage.transform.SimilarityTransform"), [`AffineTransform`](#skimage.transform.AffineTransform "skimage.transform.AffineTransform") and [`ProjectiveTransform`](#skimage.transform.ProjectiveTransform "skimage.transform.ProjectiveTransform") and `order` in [0, 3] this function uses the underlying transformation matrix to warp the image with a much faster routine. #### Examples ``` >>> from skimage.transform import warp >>> from skimage import data >>> image = data.camera() ``` The following image warps are all equal but differ substantially in execution time. The image is shifted to the bottom. Use a geometric transform to warp an image (fast): ``` >>> from skimage.transform import SimilarityTransform >>> tform = SimilarityTransform(translation=(0, -10)) >>> warped = warp(image, tform) ``` Use a callable (slow): ``` >>> def shift_down(xy): ... xy[:, 1] -= 10 ... return xy >>> warped = warp(image, shift_down) ``` Use a transformation matrix to warp an image (fast): ``` >>> matrix = np.array([[1, 0, 0], [0, 1, -10], [0, 0, 1]]) >>> warped = warp(image, matrix) >>> from skimage.transform import ProjectiveTransform >>> warped = warp(image, ProjectiveTransform(matrix=matrix)) ``` You can also use the inverse of a geometric transformation (fast): ``` >>> warped = warp(image, tform.inverse) ``` For N-D images you can pass a coordinate array, that specifies the coordinates in the input image for every element in the output image. E.g. if you want to rescale a 3-D cube, you can do: ``` >>> cube_shape = np.array([30, 30, 30]) >>> cube = np.random.rand(*cube_shape) ``` Setup the coordinate array, that defines the scaling: ``` >>> scale = 0.1 >>> output_shape = (scale * cube_shape).astype(int) >>> coords0, coords1, coords2 = np.mgrid[:output_shape[0], ... :output_shape[1], :output_shape[2]] >>> coords = np.array([coords0, coords1, coords2]) ``` Assume that the cube contains spatial data, where the first array element center is at coordinate (0.5, 0.5, 0.5) in real space, i.e. we have to account for this extra offset when scaling the image: ``` >>> coords = (coords + 0.5) / scale - 0.5 >>> warped = warp(cube, coords) ``` ### Examples using `skimage.transform.warp` [Registration using optical flow](https://scikit-image.org/docs/0.18.x/auto_examples/registration/plot_opticalflow.html#sphx-glr-auto-examples-registration-plot-opticalflow-py) warp\_coords ------------ `skimage.transform.warp_coords(coord_map, shape, dtype=<class 'numpy.float64'>)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_warps.py#L560-L635) Build the source coordinates for the output of a 2-D image warp. Parameters `coord_mapcallable like GeometricTransform.inverse` Return input coordinates for given output coordinates. Coordinates are in the shape (P, 2), where P is the number of coordinates and each element is a `(row, col)` pair. `shapetuple` Shape of output image `(rows, cols[, bands])`. `dtypenp.dtype or string` dtype for return value (sane choices: float32 or float64). Returns `coords(ndim, rows, cols[, bands]) array of dtype dtype` Coordinates for [`scipy.ndimage.map_coordinates`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.map_coordinates.html#scipy.ndimage.map_coordinates "(in SciPy v1.5.4)"), that will yield an image of shape (orows, ocols, bands) by drawing from source points according to the `coord_transform_fn`. #### Notes This is a lower-level routine that produces the source coordinates for 2-D images used by `warp()`. It is provided separately from [`warp`](#skimage.transform.warp "skimage.transform.warp") to give additional flexibility to users who would like, for example, to re-use a particular coordinate mapping, to use specific dtypes at various points along the the image-warping process, or to implement different post-processing logic than [`warp`](#skimage.transform.warp "skimage.transform.warp") performs after the call to `ndi.map_coordinates`. #### Examples Produce a coordinate map that shifts an image up and to the right: ``` >>> from skimage import data >>> from scipy.ndimage import map_coordinates >>> >>> def shift_up10_left20(xy): ... return xy - np.array([-20, 10])[None, :] >>> >>> image = data.astronaut().astype(np.float32) >>> coords = warp_coords(shift_up10_left20, image.shape) >>> warped_image = map_coordinates(image, coords) ``` warp\_polar ----------- `skimage.transform.warp_polar(image, center=None, *, radius=None, output_shape=None, scaling='linear', multichannel=False, **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_warps.py#L997-L1095) Remap image to polar or log-polar coordinates space. Parameters `imagendarray` Input image. Only 2-D arrays are accepted by default. If `multichannel=True`, 3-D arrays are accepted and the last axis is interpreted as multiple channels. `centertuple (row, col), optional` Point in image that represents the center of the transformation (i.e., the origin in cartesian space). Values can be of type `float`. If no value is given, the center is assumed to be the center point of the image. `radiusfloat, optional` Radius of the circle that bounds the area to be transformed. `output_shapetuple (row, col), optional` `scaling{β€˜linear’, β€˜log’}, optional` Specify whether the image warp is polar or log-polar. Defaults to β€˜linear’. `multichannelbool, optional` Whether the image is a 3-D array in which the third axis is to be interpreted as multiple channels. If set to `False` (default), only 2-D arrays are accepted. `**kwargskeyword arguments` Passed to `transform.warp`. Returns `warpedndarray` The polar or log-polar warped image. #### Examples Perform a basic polar warp on a grayscale image: ``` >>> from skimage import data >>> from skimage.transform import warp_polar >>> image = data.checkerboard() >>> warped = warp_polar(image) ``` Perform a log-polar warp on a grayscale image: ``` >>> warped = warp_polar(image, scaling='log') ``` Perform a log-polar warp on a grayscale image while specifying center, radius, and output shape: ``` >>> warped = warp_polar(image, (100,100), radius=100, ... output_shape=image.shape, scaling='log') ``` Perform a log-polar warp on a color image: ``` >>> image = data.astronaut() >>> warped = warp_polar(image, scaling='log', multichannel=True) ``` AffineTransform --------------- `class skimage.transform.AffineTransform(matrix=None, scale=None, rotation=None, shear=None, translation=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L746-L844) Bases: `skimage.transform._geometric.ProjectiveTransform` 2D affine transformation. Has the following form: ``` X = a0*x + a1*y + a2 = = sx*x*cos(rotation) - sy*y*sin(rotation + shear) + a2 Y = b0*x + b1*y + b2 = = sx*x*sin(rotation) + sy*y*cos(rotation + shear) + b2 ``` where `sx` and `sy` are scale factors in the x and y directions, and the homogeneous transformation matrix is: ``` [[a0 a1 a2] [b0 b1 b2] [0 0 1]] ``` Parameters `matrix(3, 3) array, optional` Homogeneous transformation matrix. `scale{s as float or (sx, sy) as array, list or tuple}, optional` Scale factor(s). If a single value, it will be assigned to both sx and sy. New in version 0.17: Added support for supplying a single scalar value. `rotationfloat, optional` Rotation angle in counter-clockwise direction as radians. `shearfloat, optional` Shear angle in counter-clockwise direction as radians. `translation(tx, ty) as array, list or tuple, optional` Translation parameters. Attributes `params(3, 3) array` Homogeneous transformation matrix. `__init__(matrix=None, scale=None, rotation=None, shear=None, translation=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L790-L825) Initialize self. See help(type(self)) for accurate signature. `property rotation` `property scale` `property shear` `property translation` EssentialMatrixTransform ------------------------ `class skimage.transform.EssentialMatrixTransform(rotation=None, translation=None, matrix=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L399-L494) Bases: `skimage.transform._geometric.FundamentalMatrixTransform` Essential matrix transformation. The essential matrix relates corresponding points between a pair of calibrated images. The matrix transforms normalized, homogeneous image points in one image to epipolar lines in the other image. The essential matrix is only defined for a pair of moving images capturing a non-planar scene. In the case of pure rotation or planar scenes, the homography describes the geometric relation between two images ([`ProjectiveTransform`](#skimage.transform.ProjectiveTransform "skimage.transform.ProjectiveTransform")). If the intrinsic calibration of the images is unknown, the fundamental matrix describes the projective relation between the two images ([`FundamentalMatrixTransform`](#skimage.transform.FundamentalMatrixTransform "skimage.transform.FundamentalMatrixTransform")). Parameters `rotation(3, 3) array, optional` Rotation matrix of the relative camera motion. `translation(3, 1) array, optional` Translation vector of the relative camera motion. The vector must have unit length. `matrix(3, 3) array, optional` Essential matrix. #### References `1` Hartley, Richard, and Andrew Zisserman. Multiple view geometry in computer vision. Cambridge university press, 2003. Attributes `params(3, 3) array` Essential matrix. `__init__(rotation=None, translation=None, matrix=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L435-L458) Initialize self. See help(type(self)) for accurate signature. `estimate(src, dst)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L460-L494) Estimate essential matrix using 8-point algorithm. The 8-point algorithm requires at least 8 corresponding point pairs for a well-conditioned solution, otherwise the over-determined solution is estimated. Parameters `src(N, 2) array` Source coordinates. `dst(N, 2) array` Destination coordinates. Returns `successbool` True, if model estimation succeeds. EuclideanTransform ------------------ `class skimage.transform.EuclideanTransform(matrix=None, rotation=None, translation=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L981-L1077) Bases: `skimage.transform._geometric.ProjectiveTransform` 2D Euclidean transformation. Has the following form: ``` X = a0 * x - b0 * y + a1 = = x * cos(rotation) - y * sin(rotation) + a1 Y = b0 * x + a0 * y + b1 = = x * sin(rotation) + y * cos(rotation) + b1 ``` where the homogeneous transformation matrix is: ``` [[a0 b0 a1] [b0 a0 b1] [0 0 1]] ``` The Euclidean transformation is a rigid transformation with rotation and translation parameters. The similarity transformation extends the Euclidean transformation with a single scaling factor. Parameters `matrix(3, 3) array, optional` Homogeneous transformation matrix. `rotationfloat, optional` Rotation angle in counter-clockwise direction as radians. `translation(tx, ty) as array, list or tuple, optional` x, y translation parameters. Attributes `params(3, 3) array` Homogeneous transformation matrix. `__init__(matrix=None, rotation=None, translation=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L1018-L1043) Initialize self. See help(type(self)) for accurate signature. `estimate(src, dst)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L1045-L1069) Estimate the transformation from a set of corresponding points. You can determine the over-, well- and under-determined parameters with the total least-squares method. Number of source and destination coordinates must match. Parameters `src(N, 2) array` Source coordinates. `dst(N, 2) array` Destination coordinates. Returns `successbool` True, if model estimation succeeds. `property rotation` `property translation` FundamentalMatrixTransform -------------------------- `class skimage.transform.FundamentalMatrixTransform(matrix=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L211-L396) Bases: `skimage.transform._geometric.GeometricTransform` Fundamental matrix transformation. The fundamental matrix relates corresponding points between a pair of uncalibrated images. The matrix transforms homogeneous image points in one image to epipolar lines in the other image. The fundamental matrix is only defined for a pair of moving images. In the case of pure rotation or planar scenes, the homography describes the geometric relation between two images ([`ProjectiveTransform`](#skimage.transform.ProjectiveTransform "skimage.transform.ProjectiveTransform")). If the intrinsic calibration of the images is known, the essential matrix describes the metric relation between the two images ([`EssentialMatrixTransform`](#skimage.transform.EssentialMatrixTransform "skimage.transform.EssentialMatrixTransform")). Parameters `matrix(3, 3) array, optional` Fundamental matrix. #### References `1` Hartley, Richard, and Andrew Zisserman. Multiple view geometry in computer vision. Cambridge university press, 2003. Attributes `params(3, 3) array` Fundamental matrix. `__init__(matrix=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L241-L247) Initialize self. See help(type(self)) for accurate signature. `estimate(src, dst)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L335-L367) Estimate fundamental matrix using 8-point algorithm. The 8-point algorithm requires at least 8 corresponding point pairs for a well-conditioned solution, otherwise the over-determined solution is estimated. Parameters `src(N, 2) array` Source coordinates. `dst(N, 2) array` Destination coordinates. Returns `successbool` True, if model estimation succeeds. `inverse(coords)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L266-L281) Apply inverse transformation. Parameters `coords(N, 2) array` Destination coordinates. Returns `coords(N, 3) array` Epipolar lines in the source image. `residuals(src, dst)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L369-L396) Compute the Sampson distance. The Sampson distance is the first approximation to the geometric error. Parameters `src(N, 2) array` Source coordinates. `dst(N, 2) array` Destination coordinates. Returns `residuals(N, ) array` Sampson distance. PiecewiseAffineTransform ------------------------ `class skimage.transform.PiecewiseAffineTransform` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L847-L978) Bases: `skimage.transform._geometric.GeometricTransform` 2D piecewise affine transformation. Control points are used to define the mapping. The transform is based on a Delaunay triangulation of the points to form a mesh. Each triangle is used to find a local affine transform. Attributes `affineslist of AffineTransform objects` Affine transformations for each triangle in the mesh. `inverse_affineslist of AffineTransform objects` Inverse affine transformations for each triangle in the mesh. `__init__()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L863-L867) Initialize self. See help(type(self)) for accurate signature. `estimate(src, dst)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L869-L908) Estimate the transformation from a set of corresponding points. Number of source and destination coordinates must match. Parameters `src(N, 2) array` Source coordinates. `dst(N, 2) array` Destination coordinates. Returns `successbool` True, if model estimation succeeds. `inverse(coords)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L945-L978) Apply inverse transformation. Coordinates outside of the mesh will be set to `- 1`. Parameters `coords(N, 2) array` Source coordinates. Returns `coords(N, 2) array` Transformed coordinates. PolynomialTransform ------------------- `class skimage.transform.PolynomialTransform(params=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L1182-L1327) Bases: `skimage.transform._geometric.GeometricTransform` 2D polynomial transformation. Has the following form: ``` X = sum[j=0:order]( sum[i=0:j]( a_ji * x**(j - i) * y**i )) Y = sum[j=0:order]( sum[i=0:j]( b_ji * x**(j - i) * y**i )) ``` Parameters `params(2, N) array, optional` Polynomial coefficients where `N * 2 = (order + 1) * (order + 2)`. So, a\_ji is defined in `params[0, :]` and b\_ji in `params[1, :]`. Attributes `params(2, N) array` Polynomial coefficients where `N * 2 = (order + 1) * (order + 2)`. So, a\_ji is defined in `params[0, :]` and b\_ji in `params[1, :]`. `__init__(params=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L1204-L1210) Initialize self. See help(type(self)) for accurate signature. `estimate(src, dst, order=2)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L1212-L1290) Estimate the transformation from a set of corresponding points. You can determine the over-, well- and under-determined parameters with the total least-squares method. Number of source and destination coordinates must match. The transformation is defined as: ``` X = sum[j=0:order]( sum[i=0:j]( a_ji * x**(j - i) * y**i )) Y = sum[j=0:order]( sum[i=0:j]( b_ji * x**(j - i) * y**i )) ``` These equations can be transformed to the following form: ``` 0 = sum[j=0:order]( sum[i=0:j]( a_ji * x**(j - i) * y**i )) - X 0 = sum[j=0:order]( sum[i=0:j]( b_ji * x**(j - i) * y**i )) - Y ``` which exist for each set of corresponding points, so we have a set of N \* 2 equations. The coefficients appear linearly so we can write A x = 0, where: ``` A = [[1 x y x**2 x*y y**2 ... 0 ... 0 -X] [0 ... 0 1 x y x**2 x*y y**2 -Y] ... ... ] x.T = [a00 a10 a11 a20 a21 a22 ... ann b00 b10 b11 b20 b21 b22 ... bnn c3] ``` In case of total least-squares the solution of this homogeneous system of equations is the right singular vector of A which corresponds to the smallest singular value normed by the coefficient c3. Parameters `src(N, 2) array` Source coordinates. `dst(N, 2) array` Destination coordinates. `orderint, optional` Polynomial order (number of coefficients is order + 1). Returns `successbool` True, if model estimation succeeds. `inverse(coords)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L1322-L1327) Apply inverse transformation. Parameters `coords(N, 2) array` Destination coordinates. Returns `coords(N, 2) array` Source coordinates. ProjectiveTransform ------------------- `class skimage.transform.ProjectiveTransform(matrix=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L497-L743) Bases: `skimage.transform._geometric.GeometricTransform` Projective transformation. Apply a projective transformation (homography) on coordinates. For each homogeneous coordinate \(\mathbf{x} = [x, y, 1]^T\), its target position is calculated by multiplying with the given matrix, \(H\), to give \(H \mathbf{x}\): ``` [[a0 a1 a2] [b0 b1 b2] [c0 c1 1 ]]. ``` E.g., to rotate by theta degrees clockwise, the matrix should be: ``` [[cos(theta) -sin(theta) 0] [sin(theta) cos(theta) 0] [0 0 1]] ``` or, to translate x by 10 and y by 20: ``` [[1 0 10] [0 1 20] [0 0 1 ]]. ``` Parameters `matrix(3, 3) array, optional` Homogeneous transformation matrix. Attributes `params(3, 3) array` Homogeneous transformation matrix. `__init__(matrix=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L536-L542) Initialize self. See help(type(self)) for accurate signature. `estimate(src, dst)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L596-L703) Estimate the transformation from a set of corresponding points. You can determine the over-, well- and under-determined parameters with the total least-squares method. Number of source and destination coordinates must match. The transformation is defined as: ``` X = (a0*x + a1*y + a2) / (c0*x + c1*y + 1) Y = (b0*x + b1*y + b2) / (c0*x + c1*y + 1) ``` These equations can be transformed to the following form: ``` 0 = a0*x + a1*y + a2 - c0*x*X - c1*y*X - X 0 = b0*x + b1*y + b2 - c0*x*Y - c1*y*Y - Y ``` which exist for each set of corresponding points, so we have a set of N \* 2 equations. The coefficients appear linearly so we can write A x = 0, where: ``` A = [[x y 1 0 0 0 -x*X -y*X -X] [0 0 0 x y 1 -x*Y -y*Y -Y] ... ... ] x.T = [a0 a1 a2 b0 b1 b2 c0 c1 c3] ``` In case of total least-squares the solution of this homogeneous system of equations is the right singular vector of A which corresponds to the smallest singular value normed by the coefficient c3. In case of the affine transformation the coefficients c0 and c1 are 0. Thus the system of equations is: ``` A = [[x y 1 0 0 0 -X] [0 0 0 x y 1 -Y] ... ... ] x.T = [a0 a1 a2 b0 b1 b2 c3] ``` Parameters `src(N, 2) array` Source coordinates. `dst(N, 2) array` Destination coordinates. Returns `successbool` True, if model estimation succeeds. `inverse(coords)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L580-L594) Apply inverse transformation. Parameters `coords(N, 2) array` Destination coordinates. Returns `coords(N, 2) array` Source coordinates. SimilarityTransform ------------------- `class skimage.transform.SimilarityTransform(matrix=None, scale=None, rotation=None, translation=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L1080-L1179) Bases: `skimage.transform._geometric.EuclideanTransform` 2D similarity transformation. Has the following form: ``` X = a0 * x - b0 * y + a1 = = s * x * cos(rotation) - s * y * sin(rotation) + a1 Y = b0 * x + a0 * y + b1 = = s * x * sin(rotation) + s * y * cos(rotation) + b1 ``` where `s` is a scale factor and the homogeneous transformation matrix is: ``` [[a0 b0 a1] [b0 a0 b1] [0 0 1]] ``` The similarity transformation extends the Euclidean transformation with a single scaling factor in addition to the rotation and translation parameters. Parameters `matrix(3, 3) array, optional` Homogeneous transformation matrix. `scalefloat, optional` Scale factor. `rotationfloat, optional` Rotation angle in counter-clockwise direction as radians. `translation(tx, ty) as array, list or tuple, optional` x, y translation parameters. Attributes `params(3, 3) array` Homogeneous transformation matrix. `__init__(matrix=None, scale=None, rotation=None, translation=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L1119-L1148) Initialize self. See help(type(self)) for accurate signature. `estimate(src, dst)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/transform/_geometric.py#L1150-L1174) Estimate the transformation from a set of corresponding points. You can determine the over-, well- and under-determined parameters with the total least-squares method. Number of source and destination coordinates must match. Parameters `src(N, 2) array` Source coordinates. `dst(N, 2) array` Destination coordinates. Returns `successbool` True, if model estimation succeeds. `property scale`
programming_docs
scikit_image skimage skimage ======= Image Processing for Python `scikit-image` (a.k.a. `skimage`) is a collection of algorithms for image processing and computer vision. The main package of `skimage` only provides a few utilities for converting between image data types; for most features, you need to import one of the following subpackages: Subpackages ----------- color Color space conversion. data Test images and example data. draw Drawing primitives (lines, text, etc.) that operate on NumPy arrays. exposure Image intensity adjustment, e.g., histogram equalization, etc. feature Feature detection and extraction, e.g., texture analysis corners, etc. filters Sharpening, edge finding, rank filters, thresholding, etc. graph Graph-theoretic operations, e.g., shortest paths. io Reading, saving, and displaying images and video. measure Measurement of image properties, e.g., region properties and contours. metrics Metrics corresponding to images, e.g. distance metrics, similarity, etc. morphology Morphological operations, e.g., opening or skeletonization. restoration Restoration algorithms, e.g., deconvolution algorithms, denoising, etc. segmentation Partitioning an image into multiple regions. transform Geometric and other transforms, e.g., rotation or the Radon transform. util Generic utilities. viewer A simple graphical user interface for visualizing results and exploring parameters. Utility Functions ----------------- img\_as\_float Convert an image to floating point format, with values in [0, 1]. Is similar to [`img_as_float64`](#skimage.img_as_float64 "skimage.img_as_float64"), but will not convert lower-precision floating point arrays to `float64`. img\_as\_float32 Convert an image to single-precision (32-bit) floating point format, with values in [0, 1]. img\_as\_float64 Convert an image to double-precision (64-bit) floating point format, with values in [0, 1]. img\_as\_uint Convert an image to unsigned integer format, with values in [0, 65535]. img\_as\_int Convert an image to signed integer format, with values in [-32768, 32767]. img\_as\_ubyte Convert an image to unsigned byte format, with values in [0, 255]. img\_as\_bool Convert an image to boolean format, with values either True or False. dtype\_limits Return intensity limits, i.e. (min, max) tuple, of the image’s dtype. | | | | --- | --- | | [`skimage.dtype_limits`](#skimage.dtype_limits "skimage.dtype_limits")(image[, clip\_negative]) | Return intensity limits, i.e. | | [`skimage.ensure_python_version`](#skimage.ensure_python_version "skimage.ensure_python_version")(min\_version) | | | [`skimage.img_as_bool`](#skimage.img_as_bool "skimage.img_as_bool")(image[, force\_copy]) | Convert an image to boolean format. | | [`skimage.img_as_float`](#skimage.img_as_float "skimage.img_as_float")(image[, force\_copy]) | Convert an image to floating point format. | | [`skimage.img_as_float32`](#skimage.img_as_float32 "skimage.img_as_float32")(image[, force\_copy]) | Convert an image to single-precision (32-bit) floating point format. | | [`skimage.img_as_float64`](#skimage.img_as_float64 "skimage.img_as_float64")(image[, force\_copy]) | Convert an image to double-precision (64-bit) floating point format. | | [`skimage.img_as_int`](#skimage.img_as_int "skimage.img_as_int")(image[, force\_copy]) | Convert an image to 16-bit signed integer format. | | [`skimage.img_as_ubyte`](#skimage.img_as_ubyte "skimage.img_as_ubyte")(image[, force\_copy]) | Convert an image to 8-bit unsigned integer format. | | [`skimage.img_as_uint`](#skimage.img_as_uint "skimage.img_as_uint")(image[, force\_copy]) | Convert an image to 16-bit unsigned integer format. | | [`skimage.lookfor`](#skimage.lookfor "skimage.lookfor")(what) | Do a keyword search on scikit-image docstrings. | | [`skimage.data`](skimage.data#module-skimage.data "skimage.data") | Standard test images. | | [`skimage.util`](skimage.util#module-skimage.util "skimage.util") | | dtype\_limits ------------- `skimage.dtype_limits(image, clip_negative=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/util/dtype.py#L38-L57) Return intensity limits, i.e. (min, max) tuple, of the image’s dtype. Parameters `imagendarray` Input image. `clip_negativebool, optional` If True, clip the negative range (i.e. return 0 for min intensity) even if the image dtype allows negative values. Returns `imin, imaxtuple` Lower and upper intensity limits. ensure\_python\_version ----------------------- `skimage.ensure_python_version(min_version)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/_shared/version_requirements.py#L4-L30) img\_as\_bool ------------- `skimage.img_as_bool(image, force_copy=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/util/dtype.py#L534-L555) Convert an image to boolean format. Parameters `imagendarray` Input image. `force_copybool, optional` Force a copy of the data, irrespective of its current dtype. Returns `outndarray of bool (bool_)` Output image. #### Notes The upper half of the input dtype’s positive range is True, and the lower half is False. All negative values (if present) are False. img\_as\_float -------------- `skimage.img_as_float(image, force_copy=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/util/dtype.py#L432-L458) Convert an image to floating point format. This function is similar to [`img_as_float64`](#skimage.img_as_float64 "skimage.img_as_float64"), but will not convert lower-precision floating point arrays to `float64`. Parameters `imagendarray` Input image. `force_copybool, optional` Force a copy of the data, irrespective of its current dtype. Returns `outndarray of float` Output image. #### Notes The range of a floating point image is [0.0, 1.0] or [-1.0, 1.0] when converting from unsigned or signed datatypes, respectively. If the input image has a float type, intensity values are not modified and can be outside the ranges [0.0, 1.0] or [-1.0, 1.0]. ### Examples using `skimage.img_as_float` [Tinting gray-scale images](https://scikit-image.org/docs/0.18.x/auto_examples/color_exposure/plot_tinting_grayscale_images.html#sphx-glr-auto-examples-color-exposure-plot-tinting-grayscale-images-py) [3D adaptive histogram equalization](https://scikit-image.org/docs/0.18.x/auto_examples/color_exposure/plot_adapt_hist_eq_3d.html#sphx-glr-auto-examples-color-exposure-plot-adapt-hist-eq-3d-py) [Phase Unwrapping](https://scikit-image.org/docs/0.18.x/auto_examples/filters/plot_phase_unwrap.html#sphx-glr-auto-examples-filters-plot-phase-unwrap-py) [Finding local maxima](https://scikit-image.org/docs/0.18.x/auto_examples/segmentation/plot_peak_local_max.html#sphx-glr-auto-examples-segmentation-plot-peak-local-max-py) [Use rolling-ball algorithm for estimating background intensity](https://scikit-image.org/docs/0.18.x/auto_examples/segmentation/plot_rolling_ball.html#sphx-glr-auto-examples-segmentation-plot-rolling-ball-py) [Explore 3D images (of cells)](https://scikit-image.org/docs/0.18.x/auto_examples/applications/plot_3d_image_processing.html#sphx-glr-auto-examples-applications-plot-3d-image-processing-py) img\_as\_float32 ---------------- `skimage.img_as_float32(image, force_copy=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/util/dtype.py#L380-L403) Convert an image to single-precision (32-bit) floating point format. Parameters `imagendarray` Input image. `force_copybool, optional` Force a copy of the data, irrespective of its current dtype. Returns `outndarray of float32` Output image. #### Notes The range of a floating point image is [0.0, 1.0] or [-1.0, 1.0] when converting from unsigned or signed datatypes, respectively. If the input image has a float type, intensity values are not modified and can be outside the ranges [0.0, 1.0] or [-1.0, 1.0]. img\_as\_float64 ---------------- `skimage.img_as_float64(image, force_copy=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/util/dtype.py#L406-L429) Convert an image to double-precision (64-bit) floating point format. Parameters `imagendarray` Input image. `force_copybool, optional` Force a copy of the data, irrespective of its current dtype. Returns `outndarray of float64` Output image. #### Notes The range of a floating point image is [0.0, 1.0] or [-1.0, 1.0] when converting from unsigned or signed datatypes, respectively. If the input image has a float type, intensity values are not modified and can be outside the ranges [0.0, 1.0] or [-1.0, 1.0]. img\_as\_int ------------ `skimage.img_as_int(image, force_copy=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/util/dtype.py#L485-L507) Convert an image to 16-bit signed integer format. Parameters `imagendarray` Input image. `force_copybool, optional` Force a copy of the data, irrespective of its current dtype. Returns `outndarray of int16` Output image. #### Notes The values are scaled between -32768 and 32767. If the input data-type is positive-only (e.g., uint8), then the output image will still only have positive values. img\_as\_ubyte -------------- `skimage.img_as_ubyte(image, force_copy=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/util/dtype.py#L510-L531) Convert an image to 8-bit unsigned integer format. Parameters `imagendarray` Input image. `force_copybool, optional` Force a copy of the data, irrespective of its current dtype. Returns `outndarray of ubyte (uint8)` Output image. #### Notes Negative input values will be clipped. Positive values are scaled between 0 and 255. ### Examples using `skimage.img_as_ubyte` [Local Histogram Equalization](https://scikit-image.org/docs/0.18.x/auto_examples/color_exposure/plot_local_equalize.html#sphx-glr-auto-examples-color-exposure-plot-local-equalize-py) [Entropy](https://scikit-image.org/docs/0.18.x/auto_examples/filters/plot_entropy.html#sphx-glr-auto-examples-filters-plot-entropy-py) [Markers for watershed transform](https://scikit-image.org/docs/0.18.x/auto_examples/segmentation/plot_marked_watershed.html#sphx-glr-auto-examples-segmentation-plot-marked-watershed-py) [Segment human cells (in mitosis)](https://scikit-image.org/docs/0.18.x/auto_examples/applications/plot_human_mitosis.html#sphx-glr-auto-examples-applications-plot-human-mitosis-py) [Rank filters](https://scikit-image.org/docs/0.18.x/auto_examples/applications/plot_rank_filters.html#sphx-glr-auto-examples-applications-plot-rank-filters-py) img\_as\_uint ------------- `skimage.img_as_uint(image, force_copy=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/util/dtype.py#L461-L482) Convert an image to 16-bit unsigned integer format. Parameters `imagendarray` Input image. `force_copybool, optional` Force a copy of the data, irrespective of its current dtype. Returns `outndarray of uint16` Output image. #### Notes Negative input values will be clipped. Positive values are scaled between 0 and 65535. lookfor ------- `skimage.lookfor(what)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/util/lookfor.py#L5-L24) Do a keyword search on scikit-image docstrings. Parameters `whatstr` Words to look for. #### Examples ``` >>> import skimage >>> skimage.lookfor('regular_grid') Search results for 'regular_grid' --------------------------------- skimage.lookfor Do a keyword search on scikit-image docstrings. skimage.util.regular_grid Find `n_points` regularly spaced along `ar_shape`. ``` scikit_image Module: viewer.widgets Module: viewer.widgets ====================== Widgets for interacting with ImageViewer. These widgets should be added to a Plugin subclass using its `add_widget` method or calling: ``` plugin += Widget(...) ``` on a Plugin instance. The Plugin will delegate action based on the widget’s parameter type specified by its `ptype` attribute, which can be: ``` 'arg' : positional argument passed to Plugin's `filter_image` method. 'kwarg' : keyword argument passed to Plugin's `filter_image` method. 'plugin' : attribute of Plugin. You'll probably need to add a class property of the same name that updates the display. ``` | | | | --- | --- | | [`skimage.viewer.widgets.BaseWidget`](#skimage.viewer.widgets.BaseWidget "skimage.viewer.widgets.BaseWidget")(name[, …]) | | | [`skimage.viewer.widgets.Button`](#skimage.viewer.widgets.Button "skimage.viewer.widgets.Button")(name, callback) | Button which calls callback upon click. | | [`skimage.viewer.widgets.CheckBox`](#skimage.viewer.widgets.CheckBox "skimage.viewer.widgets.CheckBox")(name[, …]) | CheckBox widget | | [`skimage.viewer.widgets.ComboBox`](#skimage.viewer.widgets.ComboBox "skimage.viewer.widgets.ComboBox")(name, items) | ComboBox widget for selecting among a list of choices. | | [`skimage.viewer.widgets.OKCancelButtons`](#skimage.viewer.widgets.OKCancelButtons "skimage.viewer.widgets.OKCancelButtons")([…]) | Buttons that close the parent plugin. | | [`skimage.viewer.widgets.SaveButtons`](#skimage.viewer.widgets.SaveButtons "skimage.viewer.widgets.SaveButtons")([name, …]) | Buttons to save image to io.stack or to a file. | | [`skimage.viewer.widgets.Slider`](#skimage.viewer.widgets.Slider "skimage.viewer.widgets.Slider")(name[, low, …]) | Slider widget for adjusting numeric parameters. | | [`skimage.viewer.widgets.Text`](#skimage.viewer.widgets.Text "skimage.viewer.widgets.Text")([name, text]) | | | `skimage.viewer.widgets.core` | | | `skimage.viewer.widgets.history` | | BaseWidget ---------- `class skimage.viewer.widgets.BaseWidget(name, ptype=None, callback=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/widgets/core.py#L8-L25) Bases: [`object`](https://docs.python.org/3.9/library/functions.html#object "(in Python v3.9)") `__init__(name, ptype=None, callback=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/widgets/core.py#L12-L17) Initialize self. See help(type(self)) for accurate signature. `plugin = 'Widget is not attached to a Plugin.'` `property val` Button ------ `class skimage.viewer.widgets.Button(name, callback)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/widgets/core.py#L292-L309) Bases: `skimage.viewer.widgets.core.BaseWidget` Button which calls callback upon click. Parameters `namestr` Name of button. `callbackcallable f()` Function to call when button is clicked. `__init__(name, callback)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/widgets/core.py#L303-L309) Initialize self. See help(type(self)) for accurate signature. CheckBox -------- `class skimage.viewer.widgets.CheckBox(name, value=False, alignment='center', ptype='kwarg', callback=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/widgets/core.py#L239-L289) Bases: `skimage.viewer.widgets.core.BaseWidget` CheckBox widget Parameters `namestr` Name of CheckBox parameter. If this parameter is passed as a keyword argument, it must match the name of that keyword argument (spaces are replaced with underscores). In addition, this name is displayed as the name of the CheckBox. **value: {False, True}, optional** Initial state of the CheckBox. **alignment: {β€˜center’,’left’,’right’}, optional** Checkbox alignment `ptype{β€˜arg’ | β€˜kwarg’ | β€˜plugin’}, optional` Parameter type `callbackcallable f(widget_name, value), optional` Callback function called in response to checkbox changes. *Note:* This function is typically set (overridden) when the widget is added to a plugin. `__init__(name, value=False, alignment='center', ptype='kwarg', callback=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/widgets/core.py#L261-L281) Initialize self. See help(type(self)) for accurate signature. `property val` ComboBox -------- `class skimage.viewer.widgets.ComboBox(name, items, ptype='kwarg', callback=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/widgets/core.py#L190-L236) Bases: `skimage.viewer.widgets.core.BaseWidget` ComboBox widget for selecting among a list of choices. Parameters `namestr` Name of ComboBox parameter. If this parameter is passed as a keyword argument, it must match the name of that keyword argument (spaces are replaced with underscores). In addition, this name is displayed as the name of the ComboBox. **items: list of str** Allowed parameter values. `ptype{β€˜arg’ | β€˜kwarg’ | β€˜plugin’}, optional` Parameter type. `callbackcallable f(widget_name, value), optional` Callback function called in response to combobox changes. *Note:* This function is typically set (overridden) when the widget is added to a plugin. `__init__(name, items, ptype='kwarg', callback=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/widgets/core.py#L210-L224) Initialize self. See help(type(self)) for accurate signature. `property index` `property val` OKCancelButtons --------------- `class skimage.viewer.widgets.OKCancelButtons(button_width=80)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/widgets/history.py#L15-L47) Bases: `skimage.viewer.widgets.core.BaseWidget` Buttons that close the parent plugin. OK will replace the original image with the current (filtered) image. Cancel will just close the plugin. `__init__(button_width=80)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/widgets/history.py#L22-L38) Initialize self. See help(type(self)) for accurate signature. `close_plugin()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/widgets/history.py#L45-L47) `update_original_image()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/widgets/history.py#L40-L43) SaveButtons ----------- `class skimage.viewer.widgets.SaveButtons(name='Save to:', default_format='png')` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/widgets/history.py#L50-L92) Bases: `skimage.viewer.widgets.core.BaseWidget` Buttons to save image to io.stack or to a file. `__init__(name='Save to:', default_format='png')` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/widgets/history.py#L53-L71) Initialize self. See help(type(self)) for accurate signature. `save_to_file(filename=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/widgets/history.py#L83-L92) `save_to_stack()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/widgets/history.py#L73-L81) Slider ------ `class skimage.viewer.widgets.Slider(name, low=0.0, high=1.0, value=None, value_type='float', ptype='kwarg', callback=None, max_edit_width=60, orientation='horizontal', update_on='release')` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/widgets/core.py#L50-L187) Bases: `skimage.viewer.widgets.core.BaseWidget` Slider widget for adjusting numeric parameters. Parameters `namestr` Name of slider parameter. If this parameter is passed as a keyword argument, it must match the name of that keyword argument (spaces are replaced with underscores). In addition, this name is displayed as the name of the slider. `low, highfloat` Range of slider values. `valuefloat` Default slider value. If None, use midpoint between `low` and `high`. `value_type{β€˜float’ | β€˜int’}, optional` Numeric type of slider value. `ptype{β€˜kwarg’ | β€˜arg’ | β€˜plugin’}, optional` Parameter type. `callbackcallable f(widget_name, value), optional` Callback function called in response to slider changes. *Note:* This function is typically set (overridden) when the widget is added to a plugin. `orientation{β€˜horizontal’ | β€˜vertical’}, optional` Slider orientation. `update_on{β€˜release’ | β€˜move’}, optional` Control when callback function is called: on slider move or release. `__init__(name, low=0.0, high=1.0, value=None, value_type='float', ptype='kwarg', callback=None, max_edit_width=60, orientation='horizontal', update_on='release')` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/widgets/core.py#L78-L147) Initialize self. See help(type(self)) for accurate signature. `property val` Text ---- `class skimage.viewer.widgets.Text(name=None, text='')` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/widgets/core.py#L28-L47) Bases: `skimage.viewer.widgets.core.BaseWidget` `__init__(name=None, text='')` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/widgets/core.py#L30-L39) Initialize self. See help(type(self)) for accurate signature. `property text`
programming_docs
scikit_image Module: filters.rank Module: filters.rank ==================== | | | | --- | --- | | [`skimage.filters.rank.autolevel`](#skimage.filters.rank.autolevel "skimage.filters.rank.autolevel")(image, selem) | Auto-level image using local histogram. | | [`skimage.filters.rank.autolevel_percentile`](#skimage.filters.rank.autolevel_percentile "skimage.filters.rank.autolevel_percentile")(…) | Return greyscale local autolevel of an image. | | [`skimage.filters.rank.bottomhat`](#skimage.filters.rank.bottomhat "skimage.filters.rank.bottomhat")(image, selem) | Local bottom-hat of an image. | | [`skimage.filters.rank.enhance_contrast`](#skimage.filters.rank.enhance_contrast "skimage.filters.rank.enhance_contrast")(image, …) | Enhance contrast of an image. | | [`skimage.filters.rank.enhance_contrast_percentile`](#skimage.filters.rank.enhance_contrast_percentile "skimage.filters.rank.enhance_contrast_percentile")(…) | Enhance contrast of an image. | | [`skimage.filters.rank.entropy`](#skimage.filters.rank.entropy "skimage.filters.rank.entropy")(image, selem[, …]) | Local entropy. | | [`skimage.filters.rank.equalize`](#skimage.filters.rank.equalize "skimage.filters.rank.equalize")(image, selem) | Equalize image using local histogram. | | [`skimage.filters.rank.geometric_mean`](#skimage.filters.rank.geometric_mean "skimage.filters.rank.geometric_mean")(image, selem) | Return local geometric mean of an image. | | [`skimage.filters.rank.gradient`](#skimage.filters.rank.gradient "skimage.filters.rank.gradient")(image, selem) | Return local gradient of an image (i.e. | | [`skimage.filters.rank.gradient_percentile`](#skimage.filters.rank.gradient_percentile "skimage.filters.rank.gradient_percentile")(…) | Return local gradient of an image (i.e. | | [`skimage.filters.rank.majority`](#skimage.filters.rank.majority "skimage.filters.rank.majority")(image, selem, \*) | Majority filter assign to each pixel the most occuring value within its neighborhood. | | [`skimage.filters.rank.maximum`](#skimage.filters.rank.maximum "skimage.filters.rank.maximum")(image, selem[, …]) | Return local maximum of an image. | | [`skimage.filters.rank.mean`](#skimage.filters.rank.mean "skimage.filters.rank.mean")(image, selem[, …]) | Return local mean of an image. | | [`skimage.filters.rank.mean_bilateral`](#skimage.filters.rank.mean_bilateral "skimage.filters.rank.mean_bilateral")(image, selem) | Apply a flat kernel bilateral filter. | | [`skimage.filters.rank.mean_percentile`](#skimage.filters.rank.mean_percentile "skimage.filters.rank.mean_percentile")(image, …) | Return local mean of an image. | | [`skimage.filters.rank.median`](#skimage.filters.rank.median "skimage.filters.rank.median")(image[, selem, …]) | Return local median of an image. | | [`skimage.filters.rank.minimum`](#skimage.filters.rank.minimum "skimage.filters.rank.minimum")(image, selem[, …]) | Return local minimum of an image. | | [`skimage.filters.rank.modal`](#skimage.filters.rank.modal "skimage.filters.rank.modal")(image, selem[, …]) | Return local mode of an image. | | [`skimage.filters.rank.noise_filter`](#skimage.filters.rank.noise_filter "skimage.filters.rank.noise_filter")(image, selem) | Noise feature. | | [`skimage.filters.rank.otsu`](#skimage.filters.rank.otsu "skimage.filters.rank.otsu")(image, selem[, …]) | Local Otsu’s threshold value for each pixel. | | [`skimage.filters.rank.percentile`](#skimage.filters.rank.percentile "skimage.filters.rank.percentile")(image, selem) | Return local percentile of an image. | | [`skimage.filters.rank.pop`](#skimage.filters.rank.pop "skimage.filters.rank.pop")(image, selem[, …]) | Return the local number (population) of pixels. | | [`skimage.filters.rank.pop_bilateral`](#skimage.filters.rank.pop_bilateral "skimage.filters.rank.pop_bilateral")(image, selem) | Return the local number (population) of pixels. | | [`skimage.filters.rank.pop_percentile`](#skimage.filters.rank.pop_percentile "skimage.filters.rank.pop_percentile")(image, selem) | Return the local number (population) of pixels. | | [`skimage.filters.rank.subtract_mean`](#skimage.filters.rank.subtract_mean "skimage.filters.rank.subtract_mean")(image, selem) | Return image subtracted from its local mean. | | [`skimage.filters.rank.subtract_mean_percentile`](#skimage.filters.rank.subtract_mean_percentile "skimage.filters.rank.subtract_mean_percentile")(…) | Return image subtracted from its local mean. | | [`skimage.filters.rank.sum`](#skimage.filters.rank.sum "skimage.filters.rank.sum")(image, selem[, …]) | Return the local sum of pixels. | | [`skimage.filters.rank.sum_bilateral`](#skimage.filters.rank.sum_bilateral "skimage.filters.rank.sum_bilateral")(image, selem) | Apply a flat kernel bilateral filter. | | [`skimage.filters.rank.sum_percentile`](#skimage.filters.rank.sum_percentile "skimage.filters.rank.sum_percentile")(image, selem) | Return the local sum of pixels. | | [`skimage.filters.rank.threshold`](#skimage.filters.rank.threshold "skimage.filters.rank.threshold")(image, selem) | Local threshold of an image. | | [`skimage.filters.rank.threshold_percentile`](#skimage.filters.rank.threshold_percentile "skimage.filters.rank.threshold_percentile")(…) | Local threshold of an image. | | [`skimage.filters.rank.tophat`](#skimage.filters.rank.tophat "skimage.filters.rank.tophat")(image, selem[, …]) | Local top-hat of an image. | | [`skimage.filters.rank.windowed_histogram`](#skimage.filters.rank.windowed_histogram "skimage.filters.rank.windowed_histogram")(…) | Normalized sliding window histogram | autolevel --------- `skimage.filters.rank.autolevel(image, selem, out=None, mask=None, shift_x=False, shift_y=False, shift_z=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/generic.py#L337-L387) Auto-level image using local histogram. This filter locally stretches the histogram of gray values to cover the entire range of values from β€œwhite” to β€œblack”. Parameters `image([P,] M, N) ndarray (uint8, uint16)` Input image. `selemndarray` The neighborhood expressed as an ndarray of 1’s and 0’s. `out([P,] M, N) array (same dtype as input)` If None, a new array is allocated. `maskndarray (integer or float), optional` Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default). `shift_x, shift_y, shift_zint` Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element). Returns `out([P,] M, N) ndarray (same dtype as input image)` Output image. #### Examples ``` >>> from skimage import data >>> from skimage.morphology import disk, ball >>> from skimage.filters.rank import autolevel >>> import numpy as np >>> img = data.camera() >>> volume = np.random.randint(0, 255, size=(10,10,10), dtype=np.uint8) >>> auto = autolevel(img, disk(5)) >>> auto_vol = autolevel(volume, ball(5)) ``` ### Examples using `skimage.filters.rank.autolevel` [Rank filters](https://scikit-image.org/docs/0.18.x/auto_examples/applications/plot_rank_filters.html#sphx-glr-auto-examples-applications-plot-rank-filters-py) autolevel\_percentile --------------------- `skimage.filters.rank.autolevel_percentile(image, selem, out=None, mask=None, shift_x=False, shift_y=False, p0=0, p1=1)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/_percentile.py#L48-L85) Return greyscale local autolevel of an image. This filter locally stretches the histogram of greyvalues to cover the entire range of values from β€œwhite” to β€œblack”. Only greyvalues between percentiles [p0, p1] are considered in the filter. Parameters `image2-D array (uint8, uint16)` Input image. `selem2-D array` The neighborhood expressed as a 2-D array of 1’s and 0’s. `out2-D array (same dtype as input)` If None, a new array is allocated. `maskndarray` Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default). `shift_x, shift_yint` Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element). `p0, p1float in [0, …, 1]` Define the [p0, p1] percentile interval to be considered for computing the value. Returns `out2-D array (same dtype as input image)` Output image. ### Examples using `skimage.filters.rank.autolevel_percentile` [Rank filters](https://scikit-image.org/docs/0.18.x/auto_examples/applications/plot_rank_filters.html#sphx-glr-auto-examples-applications-plot-rank-filters-py) bottomhat --------- `skimage.filters.rank.bottomhat(image, selem, out=None, mask=None, shift_x=False, shift_y=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/generic.py#L390-L443) Local bottom-hat of an image. This filter computes the morphological closing of the image and then subtracts the result from the original image. Parameters `image2-D array (integer or float)` Input image. `selem2-D array (integer or float)` The neighborhood expressed as a 2-D array of 1’s and 0’s. `out2-D array (integer or float), optional` If None, a new array is allocated. `maskndarray (integer or float), optional` Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default). `shift_x, shift_yint, optional` Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element). Returns `out2-D array (same dtype as input image)` Output image. Warns Deprecated: New in version 0.17. This function is deprecated and will be removed in scikit-image 0.19. This filter was misnamed and we believe that the usefulness is narrow. #### Examples ``` >>> from skimage import data >>> from skimage.morphology import disk >>> from skimage.filters.rank import bottomhat >>> img = data.camera() >>> out = bottomhat(img, disk(5)) ``` enhance\_contrast ----------------- `skimage.filters.rank.enhance_contrast(image, selem, out=None, mask=None, shift_x=False, shift_y=False, shift_z=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/generic.py#L937-L988) Enhance contrast of an image. This replaces each pixel by the local maximum if the pixel gray value is closer to the local maximum than the local minimum. Otherwise it is replaced by the local minimum. Parameters `image([P,] M, N) ndarray (uint8, uint16)` Input image. `selemndarray` The neighborhood expressed as an ndarray of 1’s and 0’s. `out([P,] M, N) array (same dtype as input)` If None, a new array is allocated. `maskndarray (integer or float), optional` Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default). `shift_x, shift_y, shift_zint` Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element). Returns `out([P,] M, N) ndarray (same dtype as input image)` Output image #### Examples ``` >>> from skimage import data >>> from skimage.morphology import disk, ball >>> from skimage.filters.rank import enhance_contrast >>> import numpy as np >>> img = data.camera() >>> volume = np.random.randint(0, 255, size=(10,10,10), dtype=np.uint8) >>> out = enhance_contrast(img, disk(5)) >>> out_vol = enhance_contrast(volume, ball(5)) ``` ### Examples using `skimage.filters.rank.enhance_contrast` [Rank filters](https://scikit-image.org/docs/0.18.x/auto_examples/applications/plot_rank_filters.html#sphx-glr-auto-examples-applications-plot-rank-filters-py) enhance\_contrast\_percentile ----------------------------- `skimage.filters.rank.enhance_contrast_percentile(image, selem, out=None, mask=None, shift_x=False, shift_y=False, p0=0, p1=1)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/_percentile.py#L199-L237) Enhance contrast of an image. This replaces each pixel by the local maximum if the pixel greyvalue is closer to the local maximum than the local minimum. Otherwise it is replaced by the local minimum. Only greyvalues between percentiles [p0, p1] are considered in the filter. Parameters `image2-D array (uint8, uint16)` Input image. `selem2-D array` The neighborhood expressed as a 2-D array of 1’s and 0’s. `out2-D array (same dtype as input)` If None, a new array is allocated. `maskndarray` Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default). `shift_x, shift_yint` Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element). `p0, p1float in [0, …, 1]` Define the [p0, p1] percentile interval to be considered for computing the value. Returns `out2-D array (same dtype as input image)` Output image. ### Examples using `skimage.filters.rank.enhance_contrast_percentile` [Rank filters](https://scikit-image.org/docs/0.18.x/auto_examples/applications/plot_rank_filters.html#sphx-glr-auto-examples-applications-plot-rank-filters-py) entropy ------- `skimage.filters.rank.entropy(image, selem, out=None, mask=None, shift_x=False, shift_y=False, shift_z=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/generic.py#L1290-L1346) Local entropy. The entropy is computed using base 2 logarithm i.e. the filter returns the minimum number of bits needed to encode the local gray level distribution. Parameters `image([P,] M, N) ndarray (uint8, uint16)` Input image. `selemndarray` The neighborhood expressed as an ndarray of 1’s and 0’s. `out([P,] M, N) array (same dtype as input)` If None, a new array is allocated. `maskndarray (integer or float), optional` Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default). `shift_x, shift_y, shift_zint` Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element). Returns `out([P,] M, N) ndarray (float)` Output image. #### References `1` <https://en.wikipedia.org/wiki/Entropy_(information_theory)> #### Examples ``` >>> from skimage import data >>> from skimage.filters.rank import entropy >>> from skimage.morphology import disk, ball >>> import numpy as np >>> img = data.camera() >>> volume = np.random.randint(0, 255, size=(10,10,10), dtype=np.uint8) >>> ent = entropy(img, disk(5)) >>> ent_vol = entropy(volume, ball(5)) ``` ### Examples using `skimage.filters.rank.entropy` [Tinting gray-scale images](https://scikit-image.org/docs/0.18.x/auto_examples/color_exposure/plot_tinting_grayscale_images.html#sphx-glr-auto-examples-color-exposure-plot-tinting-grayscale-images-py) [Entropy](https://scikit-image.org/docs/0.18.x/auto_examples/filters/plot_entropy.html#sphx-glr-auto-examples-filters-plot-entropy-py) [Rank filters](https://scikit-image.org/docs/0.18.x/auto_examples/applications/plot_rank_filters.html#sphx-glr-auto-examples-applications-plot-rank-filters-py) equalize -------- `skimage.filters.rank.equalize(image, selem, out=None, mask=None, shift_x=False, shift_y=False, shift_z=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/generic.py#L446-L493) Equalize image using local histogram. Parameters `image([P,] M, N) ndarray (uint8, uint16)` Input image. `selemndarray` The neighborhood expressed as an ndarray of 1’s and 0’s. `out([P,] M, N) array (same dtype as input)` If None, a new array is allocated. `maskndarray (integer or float), optional` Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default). `shift_x, shift_y, shift_zint` Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element). Returns `out([P,] M, N) ndarray (same dtype as input image)` Output image. #### Examples ``` >>> from skimage import data >>> from skimage.morphology import disk, ball >>> from skimage.filters.rank import equalize >>> import numpy as np >>> img = data.camera() >>> volume = np.random.randint(0, 255, size=(10,10,10), dtype=np.uint8) >>> equ = equalize(img, disk(5)) >>> equ_vol = equalize(volume, ball(5)) ``` ### Examples using `skimage.filters.rank.equalize` [Local Histogram Equalization](https://scikit-image.org/docs/0.18.x/auto_examples/color_exposure/plot_local_equalize.html#sphx-glr-auto-examples-color-exposure-plot-local-equalize-py) [Rank filters](https://scikit-image.org/docs/0.18.x/auto_examples/applications/plot_rank_filters.html#sphx-glr-auto-examples-applications-plot-rank-filters-py) geometric\_mean --------------- `skimage.filters.rank.geometric_mean(image, selem, out=None, mask=None, shift_x=False, shift_y=False, shift_z=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/generic.py#L655-L707) Return local geometric mean of an image. Parameters `image([P,] M, N) ndarray (uint8, uint16)` Input image. `selemndarray` The neighborhood expressed as an ndarray of 1’s and 0’s. `out([P,] M, N) array (same dtype as input)` If None, a new array is allocated. `maskndarray (integer or float), optional` Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default). `shift_x, shift_y, shift_zint` Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element). Returns `out([P,] M, N) ndarray (same dtype as input image)` Output image. #### References `1` Gonzalez, R. C. and Wood, R. E. β€œDigital Image Processing (3rd Edition).” Prentice-Hall Inc, 2006. #### Examples ``` >>> from skimage import data >>> from skimage.morphology import disk, ball >>> from skimage.filters.rank import mean >>> import numpy as np >>> img = data.camera() >>> volume = np.random.randint(0, 255, size=(10,10,10), dtype=np.uint8) >>> avg = geometric_mean(img, disk(5)) >>> avg_vol = geometric_mean(volume, ball(5)) ``` gradient -------- `skimage.filters.rank.gradient(image, selem, out=None, mask=None, shift_x=False, shift_y=False, shift_z=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/generic.py#L496-L543) Return local gradient of an image (i.e. local maximum - local minimum). Parameters `image([P,] M, N) ndarray (uint8, uint16)` Input image. `selemndarray` The neighborhood expressed as an ndarray of 1’s and 0’s. `out([P,] M, N) array (same dtype as input)` If None, a new array is allocated. `maskndarray (integer or float), optional` Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default). `shift_x, shift_y, shift_zint` Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element). Returns `out([P,] M, N) ndarray (same dtype as input image)` Output image. #### Examples ``` >>> from skimage import data >>> from skimage.morphology import disk, ball >>> from skimage.filters.rank import gradient >>> import numpy as np >>> img = data.camera() >>> volume = np.random.randint(0, 255, size=(10,10,10), dtype=np.uint8) >>> out = gradient(img, disk(5)) >>> out_vol = gradient(volume, ball(5)) ``` ### Examples using `skimage.filters.rank.gradient` [Markers for watershed transform](https://scikit-image.org/docs/0.18.x/auto_examples/segmentation/plot_marked_watershed.html#sphx-glr-auto-examples-segmentation-plot-marked-watershed-py) [Rank filters](https://scikit-image.org/docs/0.18.x/auto_examples/applications/plot_rank_filters.html#sphx-glr-auto-examples-applications-plot-rank-filters-py) gradient\_percentile -------------------- `skimage.filters.rank.gradient_percentile(image, selem, out=None, mask=None, shift_x=False, shift_y=False, p0=0, p1=1)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/_percentile.py#L88-L122) Return local gradient of an image (i.e. local maximum - local minimum). Only greyvalues between percentiles [p0, p1] are considered in the filter. Parameters `image2-D array (uint8, uint16)` Input image. `selem2-D array` The neighborhood expressed as a 2-D array of 1’s and 0’s. `out2-D array (same dtype as input)` If None, a new array is allocated. `maskndarray` Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default). `shift_x, shift_yint` Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element). `p0, p1float in [0, …, 1]` Define the [p0, p1] percentile interval to be considered for computing the value. Returns `out2-D array (same dtype as input image)` Output image. majority -------- `skimage.filters.rank.majority(image, selem, *, out=None, mask=None, shift_x=False, shift_y=False, shift_z=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/generic.py#L1460-L1508) Majority filter assign to each pixel the most occuring value within its neighborhood. Parameters `imagendarray` Image array (uint8, uint16 array). `selem2-D array (integer or float)` The neighborhood expressed as a 2-D array of 1’s and 0’s. `outndarray (integer or float), optional` If None, a new array will be allocated. `maskndarray (integer or float), optional` Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default). `shift_x, shift_yint, optional` Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element). Returns `out2-D array (same dtype as input image)` Output image. #### Examples ``` >>> from skimage import data >>> from skimage.filters.rank import majority >>> from skimage.morphology import disk, ball >>> import numpy as np >>> img = data.camera() >>> volume = np.random.randint(0, 255, size=(10,10,10), dtype=np.uint8) >>> maj_img = majority(img, disk(5)) >>> maj_img_vol = majority(volume, ball(5)) ``` maximum ------- `skimage.filters.rank.maximum(image, selem, out=None, mask=None, shift_x=False, shift_y=False, shift_z=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/generic.py#L546-L602) Return local maximum of an image. Parameters `image([P,] M, N) ndarray (uint8, uint16)` Input image. `selemndarray` The neighborhood expressed as an ndarray of 1’s and 0’s. `out([P,] M, N) array (same dtype as input)` If None, a new array is allocated. `maskndarray (integer or float), optional` Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default). `shift_x, shift_y, shift_zint` Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element). Returns `out([P,] M, N) ndarray (same dtype as input image)` Output image. See also [`skimage.morphology.dilation`](skimage.morphology#skimage.morphology.dilation "skimage.morphology.dilation") #### Notes The lower algorithm complexity makes [`skimage.filters.rank.maximum`](#skimage.filters.rank.maximum "skimage.filters.rank.maximum") more efficient for larger images and structuring elements. #### Examples ``` >>> from skimage import data >>> from skimage.morphology import disk, ball >>> from skimage.filters.rank import maximum >>> import numpy as np >>> img = data.camera() >>> volume = np.random.randint(0, 255, size=(10,10,10), dtype=np.uint8) >>> out = maximum(img, disk(5)) >>> out_vol = maximum(volume, ball(5)) ``` ### Examples using `skimage.filters.rank.maximum` [Rank filters](https://scikit-image.org/docs/0.18.x/auto_examples/applications/plot_rank_filters.html#sphx-glr-auto-examples-applications-plot-rank-filters-py) mean ---- `skimage.filters.rank.mean(image, selem, out=None, mask=None, shift_x=False, shift_y=False, shift_z=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/generic.py#L605-L652) Return local mean of an image. Parameters `image([P,] M, N) ndarray (uint8, uint16)` Input image. `selemndarray` The neighborhood expressed as an ndarray of 1’s and 0’s. `out([P,] M, N) array (same dtype as input)` If None, a new array is allocated. `maskndarray (integer or float), optional` Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default). `shift_x, shift_y, shift_zint` Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element). Returns `out([P,] M, N) ndarray (same dtype as input image)` Output image. #### Examples ``` >>> from skimage import data >>> from skimage.morphology import disk, ball >>> from skimage.filters.rank import mean >>> import numpy as np >>> img = data.camera() >>> volume = np.random.randint(0, 255, size=(10,10,10), dtype=np.uint8) >>> avg = mean(img, disk(5)) >>> avg_vol = mean(volume, ball(5)) ``` ### Examples using `skimage.filters.rank.mean` [Segment human cells (in mitosis)](https://scikit-image.org/docs/0.18.x/auto_examples/applications/plot_human_mitosis.html#sphx-glr-auto-examples-applications-plot-human-mitosis-py) [Rank filters](https://scikit-image.org/docs/0.18.x/auto_examples/applications/plot_rank_filters.html#sphx-glr-auto-examples-applications-plot-rank-filters-py) mean\_bilateral --------------- `skimage.filters.rank.mean_bilateral(image, selem, out=None, mask=None, shift_x=False, shift_y=False, s0=10, s1=10)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/bilateral.py#L47-L102) Apply a flat kernel bilateral filter. This is an edge-preserving and noise reducing denoising filter. It averages pixels based on their spatial closeness and radiometric similarity. Spatial closeness is measured by considering only the local pixel neighborhood given by a structuring element. Radiometric similarity is defined by the greylevel interval [g-s0, g+s1] where g is the current pixel greylevel. Only pixels belonging to the structuring element and having a greylevel inside this interval are averaged. Parameters `image2-D array (uint8, uint16)` Input image. `selem2-D array` The neighborhood expressed as a 2-D array of 1’s and 0’s. `out2-D array (same dtype as input)` If None, a new array is allocated. `maskndarray` Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default). `shift_x, shift_yint` Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element). `s0, s1int` Define the [s0, s1] interval around the greyvalue of the center pixel to be considered for computing the value. Returns `out2-D array (same dtype as input image)` Output image. See also `denoise_bilateral` #### Examples ``` >>> from skimage import data >>> from skimage.morphology import disk >>> from skimage.filters.rank import mean_bilateral >>> img = data.camera().astype(np.uint16) >>> bilat_img = mean_bilateral(img, disk(20), s0=10,s1=10) ``` ### Examples using `skimage.filters.rank.mean_bilateral` [Rank filters](https://scikit-image.org/docs/0.18.x/auto_examples/applications/plot_rank_filters.html#sphx-glr-auto-examples-applications-plot-rank-filters-py) mean\_percentile ---------------- `skimage.filters.rank.mean_percentile(image, selem, out=None, mask=None, shift_x=False, shift_y=False, p0=0, p1=1)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/_percentile.py#L125-L159) Return local mean of an image. Only greyvalues between percentiles [p0, p1] are considered in the filter. Parameters `image2-D array (uint8, uint16)` Input image. `selem2-D array` The neighborhood expressed as a 2-D array of 1’s and 0’s. `out2-D array (same dtype as input)` If None, a new array is allocated. `maskndarray` Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default). `shift_x, shift_yint` Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element). `p0, p1float in [0, …, 1]` Define the [p0, p1] percentile interval to be considered for computing the value. Returns `out2-D array (same dtype as input image)` Output image. median ------ `skimage.filters.rank.median(image, selem=None, out=None, mask=None, shift_x=False, shift_y=False, shift_z=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/generic.py#L768-L823) Return local median of an image. Parameters `image([P,] M, N) ndarray (uint8, uint16)` Input image. `selemndarray` The neighborhood expressed as an ndarray of 1’s and 0’s. If None, a full square of size 3 is used. `out([P,] M, N) array (same dtype as input)` If None, a new array is allocated. `maskndarray (integer or float), optional` Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default). `shift_x, shift_y, shift_zint` Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element). Returns `out([P,] M, N) ndarray (same dtype as input image)` Output image. See also [`skimage.filters.median`](skimage.filters#skimage.filters.median "skimage.filters.median") Implementation of a median filtering which handles images with floating precision. #### Examples ``` >>> from skimage import data >>> from skimage.morphology import disk, ball >>> from skimage.filters.rank import median >>> import numpy as np >>> img = data.camera() >>> volume = np.random.randint(0, 255, size=(10,10,10), dtype=np.uint8) >>> med = median(img, disk(5)) >>> med_vol = median(volume, ball(5)) ``` ### Examples using `skimage.filters.rank.median` [Markers for watershed transform](https://scikit-image.org/docs/0.18.x/auto_examples/segmentation/plot_marked_watershed.html#sphx-glr-auto-examples-segmentation-plot-marked-watershed-py) [Rank filters](https://scikit-image.org/docs/0.18.x/auto_examples/applications/plot_rank_filters.html#sphx-glr-auto-examples-applications-plot-rank-filters-py) minimum ------- `skimage.filters.rank.minimum(image, selem, out=None, mask=None, shift_x=False, shift_y=False, shift_z=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/generic.py#L826-L882) Return local minimum of an image. Parameters `image([P,] M, N) ndarray (uint8, uint16)` Input image. `selemndarray` The neighborhood expressed as an ndarray of 1’s and 0’s. `out([P,] M, N) array (same dtype as input)` If None, a new array is allocated. `maskndarray (integer or float), optional` Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default). `shift_x, shift_y, shift_zint` Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element). Returns `out([P,] M, N) ndarray (same dtype as input image)` Output image. See also [`skimage.morphology.erosion`](skimage.morphology#skimage.morphology.erosion "skimage.morphology.erosion") #### Notes The lower algorithm complexity makes [`skimage.filters.rank.minimum`](#skimage.filters.rank.minimum "skimage.filters.rank.minimum") more efficient for larger images and structuring elements. #### Examples ``` >>> from skimage import data >>> from skimage.morphology import disk, ball >>> from skimage.filters.rank import minimum >>> import numpy as np >>> img = data.camera() >>> volume = np.random.randint(0, 255, size=(10,10,10), dtype=np.uint8) >>> out = minimum(img, disk(5)) >>> out_vol = minimum(volume, ball(5)) ``` ### Examples using `skimage.filters.rank.minimum` [Rank filters](https://scikit-image.org/docs/0.18.x/auto_examples/applications/plot_rank_filters.html#sphx-glr-auto-examples-applications-plot-rank-filters-py) modal ----- `skimage.filters.rank.modal(image, selem, out=None, mask=None, shift_x=False, shift_y=False, shift_z=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/generic.py#L885-L934) Return local mode of an image. The mode is the value that appears most often in the local histogram. Parameters `image([P,] M, N) ndarray (uint8, uint16)` Input image. `selemndarray` The neighborhood expressed as an ndarray of 1’s and 0’s. `out([P,] M, N) array (same dtype as input)` If None, a new array is allocated. `maskndarray (integer or float), optional` Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default). `shift_x, shift_y, shift_zint` Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element). Returns `out([P,] M, N) ndarray (same dtype as input image)` Output image. #### Examples ``` >>> from skimage import data >>> from skimage.morphology import disk, ball >>> from skimage.filters.rank import modal >>> import numpy as np >>> img = data.camera() >>> volume = np.random.randint(0, 255, size=(10,10,10), dtype=np.uint8) >>> out = modal(img, disk(5)) >>> out_vol = modal(volume, ball(5)) ``` noise\_filter ------------- `skimage.filters.rank.noise_filter(image, selem, out=None, mask=None, shift_x=False, shift_y=False, shift_z=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/generic.py#L1220-L1287) Noise feature. Parameters `image([P,] M, N) ndarray (uint8, uint16)` Input image. `selemndarray` The neighborhood expressed as an ndarray of 1’s and 0’s. `out([P,] M, N) array (same dtype as input)` If None, a new array is allocated. `maskndarray (integer or float), optional` Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default). `shift_x, shift_y, shift_zint` Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element). Returns `out([P,] M, N) ndarray (same dtype as input image)` Output image. #### References `1` N. Hashimoto et al. Referenceless image quality evaluation for whole slide imaging. J Pathol Inform 2012;3:9. #### Examples ``` >>> from skimage import data >>> from skimage.morphology import disk, ball >>> from skimage.filters.rank import noise_filter >>> import numpy as np >>> img = data.camera() >>> volume = np.random.randint(0, 255, size=(10,10,10), dtype=np.uint8) >>> out = noise_filter(img, disk(5)) >>> out_vol = noise_filter(volume, ball(5)) ``` otsu ---- `skimage.filters.rank.otsu(image, selem, out=None, mask=None, shift_x=False, shift_y=False, shift_z=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/generic.py#L1349-L1402) Local Otsu’s threshold value for each pixel. Parameters `image([P,] M, N) ndarray (uint8, uint16)` Input image. `selemndarray` The neighborhood expressed as an ndarray of 1’s and 0’s. `out([P,] M, N) array (same dtype as input)` If None, a new array is allocated. `maskndarray (integer or float), optional` Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default). `shift_x, shift_y, shift_zint` Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element). Returns `out([P,] M, N) ndarray (same dtype as input image)` Output image. #### References `1` [https://en.wikipedia.org/wiki/Otsu’s\_method](https://en.wikipedia.org/wiki/Otsu's_method) #### Examples ``` >>> from skimage import data >>> from skimage.filters.rank import otsu >>> from skimage.morphology import disk, ball >>> import numpy as np >>> img = data.camera() >>> volume = np.random.randint(0, 255, size=(10,10,10), dtype=np.uint8) >>> local_otsu = otsu(img, disk(5)) >>> thresh_image = img >= local_otsu >>> local_otsu_vol = otsu(volume, ball(5)) >>> thresh_image_vol = volume >= local_otsu_vol ``` ### Examples using `skimage.filters.rank.otsu` [Rank filters](https://scikit-image.org/docs/0.18.x/auto_examples/applications/plot_rank_filters.html#sphx-glr-auto-examples-applications-plot-rank-filters-py) percentile ---------- `skimage.filters.rank.percentile(image, selem, out=None, mask=None, shift_x=False, shift_y=False, p0=0)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/_percentile.py#L240-L276) Return local percentile of an image. Returns the value of the p0 lower percentile of the local greyvalue distribution. Only greyvalues between percentiles [p0, p1] are considered in the filter. Parameters `image2-D array (uint8, uint16)` Input image. `selem2-D array` The neighborhood expressed as a 2-D array of 1’s and 0’s. `out2-D array (same dtype as input)` If None, a new array is allocated. `maskndarray` Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default). `shift_x, shift_yint` Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element). `p0float in [0, …, 1]` Set the percentile value. Returns `out2-D array (same dtype as input image)` Output image. pop --- `skimage.filters.rank.pop(image, selem, out=None, mask=None, shift_x=False, shift_y=False, shift_z=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/generic.py#L991-L1046) Return the local number (population) of pixels. The number of pixels is defined as the number of pixels which are included in the structuring element and the mask. Parameters `image([P,] M, N) ndarray (uint8, uint16)` Input image. `selemndarray` The neighborhood expressed as an ndarray of 1’s and 0’s. `out([P,] M, N) array (same dtype as input)` If None, a new array is allocated. `maskndarray (integer or float), optional` Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default). `shift_x, shift_y, shift_zint` Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element). Returns `out([P,] M, N) ndarray (same dtype as input image)` Output image. #### Examples ``` >>> from skimage.morphology import square, cube # Need to add 3D example >>> import skimage.filters.rank as rank >>> img = 255 * np.array([[0, 0, 0, 0, 0], ... [0, 1, 1, 1, 0], ... [0, 1, 1, 1, 0], ... [0, 1, 1, 1, 0], ... [0, 0, 0, 0, 0]], dtype=np.uint8) >>> rank.pop(img, square(3)) array([[4, 6, 6, 6, 4], [6, 9, 9, 9, 6], [6, 9, 9, 9, 6], [6, 9, 9, 9, 6], [4, 6, 6, 6, 4]], dtype=uint8) ``` pop\_bilateral -------------- `skimage.filters.rank.pop_bilateral(image, selem, out=None, mask=None, shift_x=False, shift_y=False, s0=10, s1=10)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/bilateral.py#L105-L158) Return the local number (population) of pixels. The number of pixels is defined as the number of pixels which are included in the structuring element and the mask. Additionally pixels must have a greylevel inside the interval [g-s0, g+s1] where g is the greyvalue of the center pixel. Parameters `image2-D array (uint8, uint16)` Input image. `selem2-D array` The neighborhood expressed as a 2-D array of 1’s and 0’s. `out2-D array (same dtype as input)` If None, a new array is allocated. `maskndarray` Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default). `shift_x, shift_yint` Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element). `s0, s1int` Define the [s0, s1] interval around the greyvalue of the center pixel to be considered for computing the value. Returns `out2-D array (same dtype as input image)` Output image. #### Examples ``` >>> from skimage.morphology import square >>> import skimage.filters.rank as rank >>> img = 255 * np.array([[0, 0, 0, 0, 0], ... [0, 1, 1, 1, 0], ... [0, 1, 1, 1, 0], ... [0, 1, 1, 1, 0], ... [0, 0, 0, 0, 0]], dtype=np.uint16) >>> rank.pop_bilateral(img, square(3), s0=10, s1=10) array([[3, 4, 3, 4, 3], [4, 4, 6, 4, 4], [3, 6, 9, 6, 3], [4, 4, 6, 4, 4], [3, 4, 3, 4, 3]], dtype=uint16) ``` pop\_percentile --------------- `skimage.filters.rank.pop_percentile(image, selem, out=None, mask=None, shift_x=False, shift_y=False, p0=0, p1=1)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/_percentile.py#L279-L316) Return the local number (population) of pixels. The number of pixels is defined as the number of pixels which are included in the structuring element and the mask. Only greyvalues between percentiles [p0, p1] are considered in the filter. Parameters `image2-D array (uint8, uint16)` Input image. `selem2-D array` The neighborhood expressed as a 2-D array of 1’s and 0’s. `out2-D array (same dtype as input)` If None, a new array is allocated. `maskndarray` Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default). `shift_x, shift_yint` Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element). `p0, p1float in [0, …, 1]` Define the [p0, p1] percentile interval to be considered for computing the value. Returns `out2-D array (same dtype as input image)` Output image. subtract\_mean -------------- `skimage.filters.rank.subtract_mean(image, selem, out=None, mask=None, shift_x=False, shift_y=False, shift_z=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/generic.py#L710-L765) Return image subtracted from its local mean. Parameters `image([P,] M, N) ndarray (uint8, uint16)` Input image. `selemndarray` The neighborhood expressed as an ndarray of 1’s and 0’s. `out([P,] M, N) array (same dtype as input)` If None, a new array is allocated. `maskndarray (integer or float), optional` Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default). `shift_x, shift_y, shift_zint` Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element). Returns `out([P,] M, N) ndarray (same dtype as input image)` Output image. #### Notes Subtracting the mean value may introduce underflow. To compensate this potential underflow, the obtained difference is downscaled by a factor of 2 and shifted by `n_bins / 2 - 1`, the median value of the local histogram (`n_bins = max(3, image.max()) +1` for 16-bits images and 256 otherwise). #### Examples ``` >>> from skimage import data >>> from skimage.morphology import disk, ball >>> from skimage.filters.rank import subtract_mean >>> import numpy as np >>> img = data.camera() >>> volume = np.random.randint(0, 255, size=(10,10,10), dtype=np.uint8) >>> out = subtract_mean(img, disk(5)) >>> out_vol = subtract_mean(volume, ball(5)) ``` subtract\_mean\_percentile -------------------------- `skimage.filters.rank.subtract_mean_percentile(image, selem, out=None, mask=None, shift_x=False, shift_y=False, p0=0, p1=1)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/_percentile.py#L162-L196) Return image subtracted from its local mean. Only greyvalues between percentiles [p0, p1] are considered in the filter. Parameters `image2-D array (uint8, uint16)` Input image. `selem2-D array` The neighborhood expressed as a 2-D array of 1’s and 0’s. `out2-D array (same dtype as input)` If None, a new array is allocated. `maskndarray` Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default). `shift_x, shift_yint` Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element). `p0, p1float in [0, …, 1]` Define the [p0, p1] percentile interval to be considered for computing the value. Returns `out2-D array (same dtype as input image)` Output image. sum --- `skimage.filters.rank.sum(image, selem, out=None, mask=None, shift_x=False, shift_y=False, shift_z=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/generic.py#L1049-L1104) Return the local sum of pixels. Note that the sum may overflow depending on the data type of the input array. Parameters `image([P,] M, N) ndarray (uint8, uint16)` Input image. `selemndarray` The neighborhood expressed as an ndarray of 1’s and 0’s. `out([P,] M, N) array (same dtype as input)` If None, a new array is allocated. `maskndarray (integer or float), optional` Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default). `shift_x, shift_y, shift_zint` Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element). Returns `out([P,] M, N) ndarray (same dtype as input image)` Output image. #### Examples ``` >>> from skimage.morphology import square, cube # Need to add 3D example >>> import skimage.filters.rank as rank # Cube seems to fail but >>> img = np.array([[0, 0, 0, 0, 0], # Ball can pass ... [0, 1, 1, 1, 0], ... [0, 1, 1, 1, 0], ... [0, 1, 1, 1, 0], ... [0, 0, 0, 0, 0]], dtype=np.uint8) >>> rank.sum(img, square(3)) array([[1, 2, 3, 2, 1], [2, 4, 6, 4, 2], [3, 6, 9, 6, 3], [2, 4, 6, 4, 2], [1, 2, 3, 2, 1]], dtype=uint8) ``` sum\_bilateral -------------- `skimage.filters.rank.sum_bilateral(image, selem, out=None, mask=None, shift_x=False, shift_y=False, s0=10, s1=10)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/bilateral.py#L161-L219) Apply a flat kernel bilateral filter. This is an edge-preserving and noise reducing denoising filter. It averages pixels based on their spatial closeness and radiometric similarity. Spatial closeness is measured by considering only the local pixel neighborhood given by a structuring element (selem). Radiometric similarity is defined by the greylevel interval [g-s0, g+s1] where g is the current pixel greylevel. Only pixels belonging to the structuring element AND having a greylevel inside this interval are summed. Note that the sum may overflow depending on the data type of the input array. Parameters `image2-D array (uint8, uint16)` Input image. `selem2-D array` The neighborhood expressed as a 2-D array of 1’s and 0’s. `out2-D array (same dtype as input)` If None, a new array is allocated. `maskndarray` Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default). `shift_x, shift_yint` Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element). `s0, s1int` Define the [s0, s1] interval around the greyvalue of the center pixel to be considered for computing the value. Returns `out2-D array (same dtype as input image)` Output image. See also `denoise_bilateral` #### Examples ``` >>> from skimage import data >>> from skimage.morphology import disk >>> from skimage.filters.rank import sum_bilateral >>> img = data.camera().astype(np.uint16) >>> bilat_img = sum_bilateral(img, disk(10), s0=10, s1=10) ``` sum\_percentile --------------- `skimage.filters.rank.sum_percentile(image, selem, out=None, mask=None, shift_x=False, shift_y=False, p0=0, p1=1)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/_percentile.py#L319-L356) Return the local sum of pixels. Only greyvalues between percentiles [p0, p1] are considered in the filter. Note that the sum may overflow depending on the data type of the input array. Parameters `image2-D array (uint8, uint16)` Input image. `selem2-D array` The neighborhood expressed as a 2-D array of 1’s and 0’s. `out2-D array (same dtype as input)` If None, a new array is allocated. `maskndarray` Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default). `shift_x, shift_yint` Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element). `p0, p1float in [0, …, 1]` Define the [p0, p1] percentile interval to be considered for computing the value. Returns `out2-D array (same dtype as input image)` Output image. threshold --------- `skimage.filters.rank.threshold(image, selem, out=None, mask=None, shift_x=False, shift_y=False, shift_z=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/generic.py#L1107-L1162) Local threshold of an image. The resulting binary mask is True if the gray value of the center pixel is greater than the local mean. Parameters `image([P,] M, N) ndarray (uint8, uint16)` Input image. `selemndarray` The neighborhood expressed as an ndarray of 1’s and 0’s. `out([P,] M, N) array (same dtype as input)` If None, a new array is allocated. `maskndarray (integer or float), optional` Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default). `shift_x, shift_y, shift_zint` Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element). Returns `out([P,] M, N) ndarray (same dtype as input image)` Output image. #### Examples ``` >>> from skimage.morphology import square, cube # Need to add 3D example >>> from skimage.filters.rank import threshold >>> img = 255 * np.array([[0, 0, 0, 0, 0], ... [0, 1, 1, 1, 0], ... [0, 1, 1, 1, 0], ... [0, 1, 1, 1, 0], ... [0, 0, 0, 0, 0]], dtype=np.uint8) >>> threshold(img, square(3)) array([[0, 0, 0, 0, 0], [0, 1, 1, 1, 0], [0, 1, 0, 1, 0], [0, 1, 1, 1, 0], [0, 0, 0, 0, 0]], dtype=uint8) ``` threshold\_percentile --------------------- `skimage.filters.rank.threshold_percentile(image, selem, out=None, mask=None, shift_x=False, shift_y=False, p0=0)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/_percentile.py#L359-L395) Local threshold of an image. The resulting binary mask is True if the greyvalue of the center pixel is greater than the local mean. Only greyvalues between percentiles [p0, p1] are considered in the filter. Parameters `image2-D array (uint8, uint16)` Input image. `selem2-D array` The neighborhood expressed as a 2-D array of 1’s and 0’s. `out2-D array (same dtype as input)` If None, a new array is allocated. `maskndarray` Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default). `shift_x, shift_yint` Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element). `p0float in [0, …, 1]` Set the percentile value. Returns `out2-D array (same dtype as input image)` Output image. tophat ------ `skimage.filters.rank.tophat(image, selem, out=None, mask=None, shift_x=False, shift_y=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/generic.py#L1165-L1217) Local top-hat of an image. This filter computes the morphological opening of the image and then subtracts the result from the original image. Parameters `image2-D array (integer or float)` Input image. `selem2-D array (integer or float)` The neighborhood expressed as a 2-D array of 1’s and 0’s. `out2-D array (integer or float), optional` If None, a new array is allocated. `maskndarray (integer or float), optional` Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default). `shift_x, shift_yint, optional` Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element). Returns `out2-D array (same dtype as input image)` Output image. Warns Deprecated: New in version 0.17. This function is deprecated and will be removed in scikit-image 0.19. This filter was misnamed and we believe that the usefulness is narrow. #### Examples ``` >>> from skimage import data >>> from skimage.morphology import disk >>> from skimage.filters.rank import tophat >>> img = data.camera() >>> out = tophat(img, disk(5)) ``` windowed\_histogram ------------------- `skimage.filters.rank.windowed_histogram(image, selem, out=None, mask=None, shift_x=False, shift_y=False, n_bins=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/rank/generic.py#L1405-L1457) Normalized sliding window histogram Parameters `image2-D array (integer or float)` Input image. `selem2-D array (integer or float)` The neighborhood expressed as a 2-D array of 1’s and 0’s. `out2-D array (integer or float), optional` If None, a new array is allocated. `maskndarray (integer or float), optional` Mask array that defines (>0) area of the image included in the local neighborhood. If None, the complete image is used (default). `shift_x, shift_yint, optional` Offset added to the structuring element center point. Shift is bounded to the structuring element sizes (center must be inside the given structuring element). `n_binsint or None` The number of histogram bins. Will default to `image.max() + 1` if None is passed. Returns `out3-D array (float)` Array of dimensions (H,W,N), where (H,W) are the dimensions of the input image and N is n\_bins or `image.max() + 1` if no value is provided as a parameter. Effectively, each pixel is a N-D feature vector that is the histogram. The sum of the elements in the feature vector will be 1, unless no pixels in the window were covered by both selem and mask, in which case all elements will be 0. #### Examples ``` >>> from skimage import data >>> from skimage.filters.rank import windowed_histogram >>> from skimage.morphology import disk, ball >>> import numpy as np >>> img = data.camera() >>> volume = np.random.randint(0, 255, size=(10,10,10), dtype=np.uint8) >>> hist_img = windowed_histogram(img, disk(5)) ```
programming_docs
scikit_image Module: viewer.utils Module: viewer.utils ==================== | | | | --- | --- | | [`skimage.viewer.utils.figimage`](#skimage.viewer.utils.figimage "skimage.viewer.utils.figimage")(image[, …]) | Return figure and axes with figure tightly surrounding image. | | [`skimage.viewer.utils.init_qtapp`](#skimage.viewer.utils.init_qtapp "skimage.viewer.utils.init_qtapp")() | Initialize QAppliction. | | [`skimage.viewer.utils.new_plot`](#skimage.viewer.utils.new_plot "skimage.viewer.utils.new_plot")([parent, …]) | Return new figure and axes. | | [`skimage.viewer.utils.start_qtapp`](#skimage.viewer.utils.start_qtapp "skimage.viewer.utils.start_qtapp")([app]) | Start Qt mainloop | | [`skimage.viewer.utils.update_axes_image`](#skimage.viewer.utils.update_axes_image "skimage.viewer.utils.update_axes_image")(…) | Update the image displayed by an image plot. | | [`skimage.viewer.utils.ClearColormap`](#skimage.viewer.utils.ClearColormap "skimage.viewer.utils.ClearColormap")(rgb[, …]) | Color map that varies linearly from alpha = 0 to 1 | | [`skimage.viewer.utils.FigureCanvas`](#skimage.viewer.utils.FigureCanvas "skimage.viewer.utils.FigureCanvas")(figure, …) | Canvas for displaying images. | | [`skimage.viewer.utils.LinearColormap`](#skimage.viewer.utils.LinearColormap "skimage.viewer.utils.LinearColormap")(name, …) | LinearSegmentedColormap in which color varies smoothly. | | [`skimage.viewer.utils.RequiredAttr`](#skimage.viewer.utils.RequiredAttr "skimage.viewer.utils.RequiredAttr")([init\_val]) | A class attribute that must be set before use. | | `skimage.viewer.utils.canvas` | | | `skimage.viewer.utils.core` | | | `skimage.viewer.utils.dialogs` | | figimage -------- `skimage.viewer.utils.figimage(image, scale=1, dpi=None, **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/utils/core.py#L163-L193) Return figure and axes with figure tightly surrounding image. Unlike pyplot.figimage, this actually plots onto an axes object, which fills the figure. Plotting the image onto an axes allows for subsequent overlays of axes artists. Parameters `imagearray` image to plot `scalefloat` If scale is 1, the figure and axes have the same dimension as the image. Smaller values of `scale` will shrink the figure. `dpiint` Dots per inch for figure. If None, use the default rcParam. init\_qtapp ----------- `skimage.viewer.utils.init_qtapp()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/utils/core.py#L22-L31) Initialize QAppliction. The QApplication needs to be initialized before creating any QWidgets new\_plot --------- `skimage.viewer.utils.new_plot(parent=None, subplot_kw=None, **fig_kw)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/utils/core.py#L140-L160) Return new figure and axes. Parameters `parentQtWidget` Qt widget that displays the plot objects. If None, you must manually call `canvas.setParent` and pass the parent widget. `subplot_kwdict` Keyword arguments passed `matplotlib.figure.Figure.add_subplot`. `fig_kwdict` Keyword arguments passed `matplotlib.figure.Figure`. start\_qtapp ------------ `skimage.viewer.utils.start_qtapp(app=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/utils/core.py#L44-L53) Start Qt mainloop update\_axes\_image ------------------- `skimage.viewer.utils.update_axes_image(image_axes, image)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/utils/core.py#L196-L212) Update the image displayed by an image plot. This sets the image plot’s array and updates its shape appropriately Parameters `image_axesmatplotlib.image.AxesImage` Image axes to update. `imagearray` Image array. ClearColormap ------------- `class skimage.viewer.utils.ClearColormap(rgb, max_alpha=1, name='clear_color')` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/utils/core.py#L99-L108) Bases: `skimage.viewer.utils.core.LinearColormap` Color map that varies linearly from alpha = 0 to 1 `__init__(rgb, max_alpha=1, name='clear_color')` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/utils/core.py#L102-L108) Create color map from linear mapping segments segmentdata argument is a dictionary with a red, green and blue entries. Each entry should be a list of *x*, *y0*, *y1* tuples, forming rows in a table. Entries for alpha are optional. Example: suppose you want red to increase from 0 to 1 over the bottom half, green to do the same over the middle half, and blue over the top half. Then you would use: ``` cdict = {'red': [(0.0, 0.0, 0.0), (0.5, 1.0, 1.0), (1.0, 1.0, 1.0)], 'green': [(0.0, 0.0, 0.0), (0.25, 0.0, 0.0), (0.75, 1.0, 1.0), (1.0, 1.0, 1.0)], 'blue': [(0.0, 0.0, 0.0), (0.5, 0.0, 0.0), (1.0, 1.0, 1.0)]} ``` Each row in the table for a given color is a sequence of *x*, *y0*, *y1* tuples. In each sequence, *x* must increase monotonically from 0 to 1. For any input value *z* falling between *x[i]* and *x[i+1]*, the output value of a given color will be linearly interpolated between *y1[i]* and *y0[i+1]*: ``` row i: x y0 y1 / / row i+1: x y0 y1 ``` Hence y0 in the first row and y1 in the last row are never used. See also `LinearSegmentedColormap.from_list` Static method; factory function for generating a smoothly-varying LinearSegmentedColormap. `makeMappingArray` For information about making a mapping array. FigureCanvas ------------ `class skimage.viewer.utils.FigureCanvas(figure, **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/utils/core.py#L111-L125) Bases: [`object`](https://docs.python.org/3.9/library/functions.html#object "(in Python v3.9)") Canvas for displaying images. `__init__(figure, **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/utils/core.py#L113-L119) Initialize self. See help(type(self)) for accurate signature. `resizeEvent(event)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/utils/core.py#L121-L125) LinearColormap -------------- `class skimage.viewer.utils.LinearColormap(name, segmented_data, **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/utils/core.py#L74-L96) Bases: [`matplotlib.colors.LinearSegmentedColormap`](https://matplotlib.org/api/_as_gen/matplotlib.colors.LinearSegmentedColormap.html#matplotlib.colors.LinearSegmentedColormap "(in Matplotlib v3.3.3)") LinearSegmentedColormap in which color varies smoothly. This class is a simplification of LinearSegmentedColormap, which doesn’t support jumps in color intensities. Parameters `namestr` Name of colormap. `segmented_datadict` Dictionary of β€˜red’, β€˜green’, β€˜blue’, and (optionally) β€˜alpha’ values. Each color key contains a list of `x`, `y` tuples. `x` must increase monotonically from 0 to 1 and corresponds to input values for a mappable object (e.g. an image). `y` corresponds to the color intensity. `__init__(name, segmented_data, **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/utils/core.py#L93-L96) Create color map from linear mapping segments segmentdata argument is a dictionary with a red, green and blue entries. Each entry should be a list of *x*, *y0*, *y1* tuples, forming rows in a table. Entries for alpha are optional. Example: suppose you want red to increase from 0 to 1 over the bottom half, green to do the same over the middle half, and blue over the top half. Then you would use: ``` cdict = {'red': [(0.0, 0.0, 0.0), (0.5, 1.0, 1.0), (1.0, 1.0, 1.0)], 'green': [(0.0, 0.0, 0.0), (0.25, 0.0, 0.0), (0.75, 1.0, 1.0), (1.0, 1.0, 1.0)], 'blue': [(0.0, 0.0, 0.0), (0.5, 0.0, 0.0), (1.0, 1.0, 1.0)]} ``` Each row in the table for a given color is a sequence of *x*, *y0*, *y1* tuples. In each sequence, *x* must increase monotonically from 0 to 1. For any input value *z* falling between *x[i]* and *x[i+1]*, the output value of a given color will be linearly interpolated between *y1[i]* and *y0[i+1]*: ``` row i: x y0 y1 / / row i+1: x y0 y1 ``` Hence y0 in the first row and y1 in the last row are never used. See also `LinearSegmentedColormap.from_list` Static method; factory function for generating a smoothly-varying LinearSegmentedColormap. `makeMappingArray` For information about making a mapping array. RequiredAttr ------------ `class skimage.viewer.utils.RequiredAttr(init_val=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/utils/core.py#L56-L71) Bases: [`object`](https://docs.python.org/3.9/library/functions.html#object "(in Python v3.9)") A class attribute that must be set before use. `__init__(init_val=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/utils/core.py#L61-L62) Initialize self. See help(type(self)) for accurate signature. `instances = {(<skimage.viewer.utils.core.RequiredAttr object>, None): 'Widget is not attached to a Plugin.', (<skimage.viewer.utils.core.RequiredAttr object>, None): 'Plugin is not attached to ImageViewer'}` scikit_image Module: segmentation Module: segmentation ==================== | | | | --- | --- | | [`skimage.segmentation.active_contour`](#skimage.segmentation.active_contour "skimage.segmentation.active_contour")(image, snake) | Active contour model. | | [`skimage.segmentation.chan_vese`](#skimage.segmentation.chan_vese "skimage.segmentation.chan_vese")(image[, mu, …]) | Chan-Vese segmentation algorithm. | | [`skimage.segmentation.checkerboard_level_set`](#skimage.segmentation.checkerboard_level_set "skimage.segmentation.checkerboard_level_set")(…) | Create a checkerboard level set with binary values. | | [`skimage.segmentation.circle_level_set`](#skimage.segmentation.circle_level_set "skimage.segmentation.circle_level_set")(…[, …]) | Create a circle level set with binary values. | | [`skimage.segmentation.clear_border`](#skimage.segmentation.clear_border "skimage.segmentation.clear_border")(labels[, …]) | Clear objects connected to the label image border. | | [`skimage.segmentation.disk_level_set`](#skimage.segmentation.disk_level_set "skimage.segmentation.disk_level_set")(…[, …]) | Create a disk level set with binary values. | | [`skimage.segmentation.expand_labels`](#skimage.segmentation.expand_labels "skimage.segmentation.expand_labels")(label\_image) | Expand labels in label image by `distance` pixels without overlapping. | | [`skimage.segmentation.felzenszwalb`](#skimage.segmentation.felzenszwalb "skimage.segmentation.felzenszwalb")(image[, …]) | Computes Felsenszwalb’s efficient graph based image segmentation. | | [`skimage.segmentation.find_boundaries`](#skimage.segmentation.find_boundaries "skimage.segmentation.find_boundaries")(label\_img) | Return bool array where boundaries between labeled regions are True. | | [`skimage.segmentation.flood`](#skimage.segmentation.flood "skimage.segmentation.flood")(image, seed\_point, \*) | Mask corresponding to a flood fill. | | [`skimage.segmentation.flood_fill`](#skimage.segmentation.flood_fill "skimage.segmentation.flood_fill")(image, …) | Perform flood filling on an image. | | [`skimage.segmentation.inverse_gaussian_gradient`](#skimage.segmentation.inverse_gaussian_gradient "skimage.segmentation.inverse_gaussian_gradient")(image) | Inverse of gradient magnitude. | | [`skimage.segmentation.join_segmentations`](#skimage.segmentation.join_segmentations "skimage.segmentation.join_segmentations")(s1, s2) | Return the join of the two input segmentations. | | [`skimage.segmentation.mark_boundaries`](#skimage.segmentation.mark_boundaries "skimage.segmentation.mark_boundaries")(image, …) | Return image with boundaries between labeled regions highlighted. | | [`skimage.segmentation.morphological_chan_vese`](#skimage.segmentation.morphological_chan_vese "skimage.segmentation.morphological_chan_vese")(…) | Morphological Active Contours without Edges (MorphACWE) | | [`skimage.segmentation.morphological_geodesic_active_contour`](#skimage.segmentation.morphological_geodesic_active_contour "skimage.segmentation.morphological_geodesic_active_contour")(…) | Morphological Geodesic Active Contours (MorphGAC). | | [`skimage.segmentation.quickshift`](#skimage.segmentation.quickshift "skimage.segmentation.quickshift")(image[, …]) | Segments image using quickshift clustering in Color-(x,y) space. | | [`skimage.segmentation.random_walker`](#skimage.segmentation.random_walker "skimage.segmentation.random_walker")(data, labels) | Random walker algorithm for segmentation from markers. | | [`skimage.segmentation.relabel_sequential`](#skimage.segmentation.relabel_sequential "skimage.segmentation.relabel_sequential")(…) | Relabel arbitrary labels to {`offset`, … | | [`skimage.segmentation.slic`](#skimage.segmentation.slic "skimage.segmentation.slic")(image[, …]) | Segments image using k-means clustering in Color-(x,y,z) space. | | [`skimage.segmentation.watershed`](#skimage.segmentation.watershed "skimage.segmentation.watershed")(image[, …]) | Find watershed basins in `image` flooded from given `markers`. | active\_contour --------------- `skimage.segmentation.active_contour(image, snake, alpha=0.01, beta=0.1, w_line=0, w_edge=1, gamma=0.01, max_px_move=1.0, max_iterations=2500, convergence=0.1, *, boundary_condition='periodic', coordinates='rc')` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/segmentation/active_contour_model.py#L7-L227) Active contour model. Active contours by fitting snakes to features of images. Supports single and multichannel 2D images. Snakes can be periodic (for segmentation) or have fixed and/or free ends. The output snake has the same length as the input boundary. As the number of points is constant, make sure that the initial snake has enough points to capture the details of the final contour. Parameters `image(N, M) or (N, M, 3) ndarray` Input image. `snake(N, 2) ndarray` Initial snake coordinates. For periodic boundary conditions, endpoints must not be duplicated. `alphafloat, optional` Snake length shape parameter. Higher values makes snake contract faster. `betafloat, optional` Snake smoothness shape parameter. Higher values makes snake smoother. `w_linefloat, optional` Controls attraction to brightness. Use negative values to attract toward dark regions. `w_edgefloat, optional` Controls attraction to edges. Use negative values to repel snake from edges. `gammafloat, optional` Explicit time stepping parameter. `max_px_movefloat, optional` Maximum pixel distance to move per iteration. `max_iterationsint, optional` Maximum iterations to optimize snake shape. `convergencefloat, optional` Convergence criteria. `boundary_conditionstring, optional` Boundary conditions for the contour. Can be one of β€˜periodic’, β€˜free’, β€˜fixed’, β€˜free-fixed’, or β€˜fixed-free’. β€˜periodic’ attaches the two ends of the snake, β€˜fixed’ holds the end-points in place, and β€˜free’ allows free movement of the ends. β€˜fixed’ and β€˜free’ can be combined by parsing β€˜fixed-free’, β€˜free-fixed’. Parsing β€˜fixed-fixed’ or β€˜free-free’ yields same behaviour as β€˜fixed’ and β€˜free’, respectively. `coordinates{β€˜rc’}, optional` This option remains for compatibility purpose only and has no effect. It was introduced in 0.16 with the `'xy'` option, but since 0.18, only the `'rc'` option is valid. Coordinates must be set in a row-column format. Returns `snake(N, 2) ndarray` Optimised snake, same shape as input parameter. #### References `1` Kass, M.; Witkin, A.; Terzopoulos, D. β€œSnakes: Active contour models”. International Journal of Computer Vision 1 (4): 321 (1988). [DOI:10.1007/BF00133570](https://doi.org/10.1007/BF00133570) #### Examples ``` >>> from skimage.draw import circle_perimeter >>> from skimage.filters import gaussian ``` Create and smooth image: ``` >>> img = np.zeros((100, 100)) >>> rr, cc = circle_perimeter(35, 45, 25) >>> img[rr, cc] = 1 >>> img = gaussian(img, 2) ``` Initialize spline: ``` >>> s = np.linspace(0, 2*np.pi, 100) >>> init = 50 * np.array([np.sin(s), np.cos(s)]).T + 50 ``` Fit spline to image: ``` >>> snake = active_contour(img, init, w_edge=0, w_line=1, coordinates='rc') >>> dist = np.sqrt((45-snake[:, 0])**2 + (35-snake[:, 1])**2) >>> int(np.mean(dist)) 25 ``` chan\_vese ---------- `skimage.segmentation.chan_vese(image, mu=0.25, lambda1=1.0, lambda2=1.0, tol=0.001, max_iter=500, dt=0.5, init_level_set='checkerboard', extended_output=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/segmentation/_chan_vese.py#L170-L338) Chan-Vese segmentation algorithm. Active contour model by evolving a level set. Can be used to segment objects without clearly defined boundaries. Parameters `image(M, N) ndarray` Grayscale image to be segmented. `mufloat, optional` β€˜edge length’ weight parameter. Higher `mu` values will produce a β€˜round’ edge, while values closer to zero will detect smaller objects. `lambda1float, optional` β€˜difference from average’ weight parameter for the output region with value β€˜True’. If it is lower than `lambda2`, this region will have a larger range of values than the other. `lambda2float, optional` β€˜difference from average’ weight parameter for the output region with value β€˜False’. If it is lower than `lambda1`, this region will have a larger range of values than the other. `tolfloat, positive, optional` Level set variation tolerance between iterations. If the L2 norm difference between the level sets of successive iterations normalized by the area of the image is below this value, the algorithm will assume that the solution was reached. `max_iteruint, optional` Maximum number of iterations allowed before the algorithm interrupts itself. `dtfloat, optional` A multiplication factor applied at calculations for each step, serves to accelerate the algorithm. While higher values may speed up the algorithm, they may also lead to convergence problems. `init_level_setstr or (M, N) ndarray, optional` Defines the starting level set used by the algorithm. If a string is inputted, a level set that matches the image size will automatically be generated. Alternatively, it is possible to define a custom level set, which should be an array of float values, with the same shape as β€˜image’. Accepted string values are as follows. β€˜checkerboard’ the starting level set is defined as sin(x/5\*pi)\*sin(y/5\*pi), where x and y are pixel coordinates. This level set has fast convergence, but may fail to detect implicit edges. β€˜disk’ the starting level set is defined as the opposite of the distance from the center of the image minus half of the minimum value between image width and image height. This is somewhat slower, but is more likely to properly detect implicit edges. β€˜small disk’ the starting level set is defined as the opposite of the distance from the center of the image minus a quarter of the minimum value between image width and image height. `extended_outputbool, optional` If set to True, the return value will be a tuple containing the three return values (see below). If set to False which is the default value, only the β€˜segmentation’ array will be returned. Returns `segmentation(M, N) ndarray, bool` Segmentation produced by the algorithm. `phi(M, N) ndarray of floats` Final level set computed by the algorithm. `energieslist of floats` Shows the evolution of the β€˜energy’ for each step of the algorithm. This should allow to check whether the algorithm converged. #### Notes The Chan-Vese Algorithm is designed to segment objects without clearly defined boundaries. This algorithm is based on level sets that are evolved iteratively to minimize an energy, which is defined by weighted values corresponding to the sum of differences intensity from the average value outside the segmented region, the sum of differences from the average value inside the segmented region, and a term which is dependent on the length of the boundary of the segmented region. This algorithm was first proposed by Tony Chan and Luminita Vese, in a publication entitled β€œAn Active Contour Model Without Edges” [[1]](#rb5da2c114fc8-1). This implementation of the algorithm is somewhat simplified in the sense that the area factor β€˜nu’ described in the original paper is not implemented, and is only suitable for grayscale images. Typical values for `lambda1` and `lambda2` are 1. If the β€˜background’ is very different from the segmented object in terms of distribution (for example, a uniform black image with figures of varying intensity), then these values should be different from each other. Typical values for mu are between 0 and 1, though higher values can be used when dealing with shapes with very ill-defined contours. The β€˜energy’ which this algorithm tries to minimize is defined as the sum of the differences from the average within the region squared and weighed by the β€˜lambda’ factors to which is added the length of the contour multiplied by the β€˜mu’ factor. Supports 2D grayscale images only, and does not implement the area term described in the original article. #### References `1` An Active Contour Model without Edges, Tony Chan and Luminita Vese, Scale-Space Theories in Computer Vision, 1999, [DOI:10.1007/3-540-48236-9\_13](https://doi.org/10.1007/3-540-48236-9_13) `2` Chan-Vese Segmentation, Pascal Getreuer Image Processing On Line, 2 (2012), pp. 214-224, [DOI:10.5201/ipol.2012.g-cv](https://doi.org/10.5201/ipol.2012.g-cv) `3` The Chan-Vese Algorithm - Project Report, Rami Cohen, 2011 [arXiv:1107.2782](https://arxiv.org/abs/1107.2782) checkerboard\_level\_set ------------------------ `skimage.segmentation.checkerboard_level_set(image_shape, square_size=5)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/segmentation/morphsnakes.py#L193-L221) Create a checkerboard level set with binary values. Parameters `image_shapetuple of positive integers` Shape of the image. `square_sizeint, optional` Size of the squares of the checkerboard. It defaults to 5. Returns `outarray with shape image_shape` Binary level set of the checkerboard. See also [`circle_level_set`](#skimage.segmentation.circle_level_set "skimage.segmentation.circle_level_set") circle\_level\_set ------------------ `skimage.segmentation.circle_level_set(image_shape, center=None, radius=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/segmentation/morphsnakes.py#L117-L153) Create a circle level set with binary values. Parameters `image_shapetuple of positive integers` Shape of the image `centertuple of positive integers, optional` Coordinates of the center of the circle given in (row, column). If not given, it defaults to the center of the image. `radiusfloat, optional` Radius of the circle. If not given, it is set to the 75% of the smallest image dimension. Returns `outarray with shape image_shape` Binary level set of the circle with the given `radius` and `center`. Warns Deprecated: New in version 0.17: This function is deprecated and will be removed in scikit-image 0.19. Please use the function named `disk_level_set` instead. See also [`checkerboard_level_set`](#skimage.segmentation.checkerboard_level_set "skimage.segmentation.checkerboard_level_set") clear\_border ------------- `skimage.segmentation.clear_border(labels, buffer_size=0, bgval=0, in_place=False, mask=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/segmentation/_clear_border.py#L5-L106) Clear objects connected to the label image border. Parameters `labels(M[, N[, …, P]]) array of int or bool` Imaging data labels. `buffer_sizeint, optional` The width of the border examined. By default, only objects that touch the outside of the image are removed. `bgvalfloat or int, optional` Cleared objects are set to this value. `in_placebool, optional` Whether or not to manipulate the labels array in-place. `maskndarray of bool, same shape as image, optional.` Image data mask. Objects in labels image overlapping with False pixels of mask will be removed. If defined, the argument buffer\_size will be ignored. Returns `out(M[, N[, …, P]]) array` Imaging data labels with cleared borders #### Examples ``` >>> import numpy as np >>> from skimage.segmentation import clear_border >>> labels = np.array([[0, 0, 0, 0, 0, 0, 0, 1, 0], ... [1, 1, 0, 0, 1, 0, 0, 1, 0], ... [1, 1, 0, 1, 0, 1, 0, 0, 0], ... [0, 0, 0, 1, 1, 1, 1, 0, 0], ... [0, 1, 1, 1, 1, 1, 1, 1, 0], ... [0, 0, 0, 0, 0, 0, 0, 0, 0]]) >>> clear_border(labels) array([[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 1, 0, 0, 0, 0], [0, 0, 0, 1, 0, 1, 0, 0, 0], [0, 0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]]) >>> mask = np.array([[0, 0, 1, 1, 1, 1, 1, 1, 1], ... [0, 0, 1, 1, 1, 1, 1, 1, 1], ... [1, 1, 1, 1, 1, 1, 1, 1, 1], ... [1, 1, 1, 1, 1, 1, 1, 1, 1], ... [1, 1, 1, 1, 1, 1, 1, 1, 1], ... [1, 1, 1, 1, 1, 1, 1, 1, 1]]).astype(bool) >>> clear_border(labels, mask=mask) array([[0, 0, 0, 0, 0, 0, 0, 1, 0], [0, 0, 0, 0, 1, 0, 0, 1, 0], [0, 0, 0, 1, 0, 1, 0, 0, 0], [0, 0, 0, 1, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]]) ``` disk\_level\_set ---------------- `skimage.segmentation.disk_level_set(image_shape, *, center=None, radius=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/segmentation/morphsnakes.py#L156-L190) Create a disk level set with binary values. Parameters `image_shapetuple of positive integers` Shape of the image `centertuple of positive integers, optional` Coordinates of the center of the disk given in (row, column). If not given, it defaults to the center of the image. `radiusfloat, optional` Radius of the disk. If not given, it is set to the 75% of the smallest image dimension. Returns `outarray with shape image_shape` Binary level set of the disk with the given `radius` and `center`. See also [`checkerboard_level_set`](#skimage.segmentation.checkerboard_level_set "skimage.segmentation.checkerboard_level_set") expand\_labels -------------- `skimage.segmentation.expand_labels(label_image, distance=1)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/segmentation/_expand_labels.py#L16-L106) Expand labels in label image by `distance` pixels without overlapping. Given a label image, `expand_labels` grows label regions (connected components) outwards by up to `distance` pixels without overflowing into neighboring regions. More specifically, each background pixel that is within Euclidean distance of <= `distance` pixels of a connected component is assigned the label of that connected component. Where multiple connected components are within `distance` pixels of a background pixel, the label value of the closest connected component will be assigned (see Notes for the case of multiple labels at equal distance). Parameters `label_imagendarray of dtype int` label image `distancefloat` Euclidean distance in pixels by which to grow the labels. Default is one. Returns `enlarged_labelsndarray of dtype int` Labeled array, where all connected regions have been enlarged See also `skimage.measure.label(), skimage.segmentation.watershed(),` [`skimage.morphology.dilation()`](skimage.morphology#skimage.morphology.dilation "skimage.morphology.dilation") #### Notes Where labels are spaced more than `distance` pixels are apart, this is equivalent to a morphological dilation with a disc or hyperball of radius `distance`. However, in contrast to a morphological dilation, `expand_labels` will not expand a label region into a neighboring region. This implementation of `expand_labels` is derived from CellProfiler [[1]](#r700ff08b53f4-1), where it is known as module β€œIdentifySecondaryObjects (Distance-N)” [[2]](#r700ff08b53f4-2). There is an important edge case when a pixel has the same distance to multiple regions, as it is not defined which region expands into that space. Here, the exact behavior depends on the upstream implementation of `scipy.ndimage.distance_transform_edt`. #### References `1` <https://cellprofiler.org> `2` <https://github.com/CellProfiler/CellProfiler/blob/082930ea95add7b72243a4fa3d39ae5145995e9c/cellprofiler/modules/identifysecondaryobjects.py#L559> #### Examples ``` >>> labels = np.array([0, 1, 0, 0, 0, 0, 2]) >>> expand_labels(labels, distance=1) array([1, 1, 1, 0, 0, 2, 2]) ``` Labels will not overwrite each other: ``` >>> expand_labels(labels, distance=3) array([1, 1, 1, 1, 2, 2, 2]) ``` In case of ties, behavior is undefined, but currently resolves to the label closest to `(0,) * ndim` in lexicographical order. ``` >>> labels_tied = np.array([0, 1, 0, 2, 0]) >>> expand_labels(labels_tied, 1) array([1, 1, 1, 2, 2]) >>> labels2d = np.array( ... [[0, 1, 0, 0], ... [2, 0, 0, 0], ... [0, 3, 0, 0]] ... ) >>> expand_labels(labels2d, 1) array([[2, 1, 1, 0], [2, 2, 0, 0], [2, 3, 3, 0]]) ``` felzenszwalb ------------ `skimage.segmentation.felzenszwalb(image, scale=1, sigma=0.8, min_size=20, multichannel=True)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/segmentation/_felzenszwalb.py#L6-L64) Computes Felsenszwalb’s efficient graph based image segmentation. Produces an oversegmentation of a multichannel (i.e. RGB) image using a fast, minimum spanning tree based clustering on the image grid. The parameter `scale` sets an observation level. Higher scale means less and larger segments. `sigma` is the diameter of a Gaussian kernel, used for smoothing the image prior to segmentation. The number of produced segments as well as their size can only be controlled indirectly through `scale`. Segment size within an image can vary greatly depending on local contrast. For RGB images, the algorithm uses the euclidean distance between pixels in color space. Parameters `image(width, height, 3) or (width, height) ndarray` Input image. `scalefloat` Free parameter. Higher means larger clusters. `sigmafloat` Width (standard deviation) of Gaussian kernel used in preprocessing. `min_sizeint` Minimum component size. Enforced using postprocessing. `multichannelbool, optional (default: True)` Whether the last axis of the image is to be interpreted as multiple channels. A value of False, for a 3D image, is not currently supported. Returns `segment_mask(width, height) ndarray` Integer mask indicating segment labels. #### Notes The `k` parameter used in the original paper renamed to `scale` here. #### References `1` Efficient graph-based image segmentation, Felzenszwalb, P.F. and Huttenlocher, D.P. International Journal of Computer Vision, 2004 #### Examples ``` >>> from skimage.segmentation import felzenszwalb >>> from skimage.data import coffee >>> img = coffee() >>> segments = felzenszwalb(img, scale=3.0, sigma=0.95, min_size=5) ``` find\_boundaries ---------------- `skimage.segmentation.find_boundaries(label_img, connectivity=1, mode='thick', background=0)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/segmentation/boundaries.py#L48-L181) Return bool array where boundaries between labeled regions are True. Parameters `label_imgarray of int or bool` An array in which different regions are labeled with either different integers or boolean values. `connectivityint in {1, …, label_img.ndim}, optional` A pixel is considered a boundary pixel if any of its neighbors has a different label. `connectivity` controls which pixels are considered neighbors. A connectivity of 1 (default) means pixels sharing an edge (in 2D) or a face (in 3D) will be considered neighbors. A connectivity of `label_img.ndim` means pixels sharing a corner will be considered neighbors. `modestring in {β€˜thick’, β€˜inner’, β€˜outer’, β€˜subpixel’}` How to mark the boundaries: * thick: any pixel not completely surrounded by pixels of the same label (defined by `connectivity`) is marked as a boundary. This results in boundaries that are 2 pixels thick. * inner: outline the pixels *just inside* of objects, leaving background pixels untouched. * outer: outline pixels in the background around object boundaries. When two objects touch, their boundary is also marked. * subpixel: return a doubled image, with pixels *between* the original pixels marked as boundary where appropriate. `backgroundint, optional` For modes β€˜inner’ and β€˜outer’, a definition of a background label is required. See `mode` for descriptions of these two. Returns `boundariesarray of bool, same shape as label_img` A bool image where `True` represents a boundary pixel. For `mode` equal to β€˜subpixel’, `boundaries.shape[i]` is equal to `2 * label_img.shape[i] - 1` for all `i` (a pixel is inserted in between all other pairs of pixels). #### Examples ``` >>> labels = np.array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ... [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ... [0, 0, 0, 0, 0, 5, 5, 5, 0, 0], ... [0, 0, 1, 1, 1, 5, 5, 5, 0, 0], ... [0, 0, 1, 1, 1, 5, 5, 5, 0, 0], ... [0, 0, 1, 1, 1, 5, 5, 5, 0, 0], ... [0, 0, 0, 0, 0, 5, 5, 5, 0, 0], ... [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], ... [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=np.uint8) >>> find_boundaries(labels, mode='thick').astype(np.uint8) array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 1, 0], [0, 1, 1, 1, 1, 1, 0, 1, 1, 0], [0, 1, 1, 0, 1, 1, 0, 1, 1, 0], [0, 1, 1, 1, 1, 1, 0, 1, 1, 0], [0, 0, 1, 1, 1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8) >>> find_boundaries(labels, mode='inner').astype(np.uint8) array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 0, 1, 0, 0], [0, 0, 1, 0, 1, 1, 0, 1, 0, 0], [0, 0, 1, 1, 1, 1, 0, 1, 0, 0], [0, 0, 0, 0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8) >>> find_boundaries(labels, mode='outer').astype(np.uint8) array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0, 1, 0], [0, 1, 0, 0, 1, 1, 0, 0, 1, 0], [0, 1, 0, 0, 1, 1, 0, 0, 1, 0], [0, 1, 0, 0, 1, 1, 0, 0, 1, 0], [0, 0, 1, 1, 1, 1, 0, 0, 1, 0], [0, 0, 0, 0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=uint8) >>> labels_small = labels[::2, ::3] >>> labels_small array([[0, 0, 0, 0], [0, 0, 5, 0], [0, 1, 5, 0], [0, 0, 5, 0], [0, 0, 0, 0]], dtype=uint8) >>> find_boundaries(labels_small, mode='subpixel').astype(np.uint8) array([[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 0], [0, 0, 0, 1, 0, 1, 0], [0, 1, 1, 1, 0, 1, 0], [0, 1, 0, 1, 0, 1, 0], [0, 1, 1, 1, 0, 1, 0], [0, 0, 0, 1, 0, 1, 0], [0, 0, 0, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0, 0]], dtype=uint8) >>> bool_image = np.array([[False, False, False, False, False], ... [False, False, False, False, False], ... [False, False, True, True, True], ... [False, False, True, True, True], ... [False, False, True, True, True]], ... dtype=bool) >>> find_boundaries(bool_image) array([[False, False, False, False, False], [False, False, True, True, True], [False, True, True, True, True], [False, True, True, False, False], [False, True, True, False, False]]) ``` flood ----- `skimage.segmentation.flood(image, seed_point, *, selem=None, connectivity=None, tolerance=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/_flood_fill.py#L124-L290) Mask corresponding to a flood fill. Starting at a specific `seed_point`, connected points equal or within `tolerance` of the seed value are found. Parameters `imagendarray` An n-dimensional array. `seed_pointtuple or int` The point in `image` used as the starting point for the flood fill. If the image is 1D, this point may be given as an integer. `selemndarray, optional` A structuring element used to determine the neighborhood of each evaluated pixel. It must contain only 1’s and 0’s, have the same number of dimensions as `image`. If not given, all adjacent pixels are considered as part of the neighborhood (fully connected). `connectivityint, optional` A number used to determine the neighborhood of each evaluated pixel. Adjacent pixels whose squared distance from the center is larger or equal to `connectivity` are considered neighbors. Ignored if `selem` is not None. `tolerancefloat or int, optional` If None (default), adjacent values must be strictly equal to the initial value of `image` at `seed_point`. This is fastest. If a value is given, a comparison will be done at every point and if within tolerance of the initial value will also be filled (inclusive). Returns `maskndarray` A Boolean array with the same shape as `image` is returned, with True values for areas connected to and equal (or within tolerance of) the seed point. All other values are False. #### Notes The conceptual analogy of this operation is the β€˜paint bucket’ tool in many raster graphics programs. This function returns just the mask representing the fill. If indices are desired rather than masks for memory reasons, the user can simply run [`numpy.nonzero`](https://numpy.org/doc/stable/reference/generated/numpy.nonzero.html#numpy.nonzero "(in NumPy v1.19)") on the result, save the indices, and discard this mask. #### Examples ``` >>> from skimage.morphology import flood >>> image = np.zeros((4, 7), dtype=int) >>> image[1:3, 1:3] = 1 >>> image[3, 0] = 1 >>> image[1:3, 4:6] = 2 >>> image[3, 6] = 3 >>> image array([[0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 0, 2, 2, 0], [0, 1, 1, 0, 2, 2, 0], [1, 0, 0, 0, 0, 0, 3]]) ``` Fill connected ones with 5, with full connectivity (diagonals included): ``` >>> mask = flood(image, (1, 1)) >>> image_flooded = image.copy() >>> image_flooded[mask] = 5 >>> image_flooded array([[0, 0, 0, 0, 0, 0, 0], [0, 5, 5, 0, 2, 2, 0], [0, 5, 5, 0, 2, 2, 0], [5, 0, 0, 0, 0, 0, 3]]) ``` Fill connected ones with 5, excluding diagonal points (connectivity 1): ``` >>> mask = flood(image, (1, 1), connectivity=1) >>> image_flooded = image.copy() >>> image_flooded[mask] = 5 >>> image_flooded array([[0, 0, 0, 0, 0, 0, 0], [0, 5, 5, 0, 2, 2, 0], [0, 5, 5, 0, 2, 2, 0], [1, 0, 0, 0, 0, 0, 3]]) ``` Fill with a tolerance: ``` >>> mask = flood(image, (0, 0), tolerance=1) >>> image_flooded = image.copy() >>> image_flooded[mask] = 5 >>> image_flooded array([[5, 5, 5, 5, 5, 5, 5], [5, 5, 5, 5, 2, 2, 5], [5, 5, 5, 5, 2, 2, 5], [5, 5, 5, 5, 5, 5, 3]]) ``` ### Examples using `skimage.segmentation.flood` [Flood Fill](https://scikit-image.org/docs/0.18.x/auto_examples/segmentation/plot_floodfill.html#sphx-glr-auto-examples-segmentation-plot-floodfill-py) flood\_fill ----------- `skimage.segmentation.flood_fill(image, seed_point, new_value, *, selem=None, connectivity=None, tolerance=None, in_place=False, inplace=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/morphology/_flood_fill.py#L15-L121) Perform flood filling on an image. Starting at a specific `seed_point`, connected points equal or within `tolerance` of the seed value are found, then set to `new_value`. Parameters `imagendarray` An n-dimensional array. `seed_pointtuple or int` The point in `image` used as the starting point for the flood fill. If the image is 1D, this point may be given as an integer. `new_valueimage type` New value to set the entire fill. This must be chosen in agreement with the dtype of `image`. `selemndarray, optional` A structuring element used to determine the neighborhood of each evaluated pixel. It must contain only 1’s and 0’s, have the same number of dimensions as `image`. If not given, all adjacent pixels are considered as part of the neighborhood (fully connected). `connectivityint, optional` A number used to determine the neighborhood of each evaluated pixel. Adjacent pixels whose squared distance from the center is less than or equal to `connectivity` are considered neighbors. Ignored if `selem` is not None. `tolerancefloat or int, optional` If None (default), adjacent values must be strictly equal to the value of `image` at `seed_point` to be filled. This is fastest. If a tolerance is provided, adjacent points with values within plus or minus tolerance from the seed point are filled (inclusive). `in_placebool, optional` If True, flood filling is applied to `image` in place. If False, the flood filled result is returned without modifying the input `image` (default). `inplacebool, optional` This parameter is deprecated and will be removed in version 0.19.0 in favor of in\_place. If True, flood filling is applied to `image` inplace. If False, the flood filled result is returned without modifying the input `image` (default). Returns `filledndarray` An array with the same shape as `image` is returned, with values in areas connected to and equal (or within tolerance of) the seed point replaced with `new_value`. #### Notes The conceptual analogy of this operation is the β€˜paint bucket’ tool in many raster graphics programs. #### Examples ``` >>> from skimage.morphology import flood_fill >>> image = np.zeros((4, 7), dtype=int) >>> image[1:3, 1:3] = 1 >>> image[3, 0] = 1 >>> image[1:3, 4:6] = 2 >>> image[3, 6] = 3 >>> image array([[0, 0, 0, 0, 0, 0, 0], [0, 1, 1, 0, 2, 2, 0], [0, 1, 1, 0, 2, 2, 0], [1, 0, 0, 0, 0, 0, 3]]) ``` Fill connected ones with 5, with full connectivity (diagonals included): ``` >>> flood_fill(image, (1, 1), 5) array([[0, 0, 0, 0, 0, 0, 0], [0, 5, 5, 0, 2, 2, 0], [0, 5, 5, 0, 2, 2, 0], [5, 0, 0, 0, 0, 0, 3]]) ``` Fill connected ones with 5, excluding diagonal points (connectivity 1): ``` >>> flood_fill(image, (1, 1), 5, connectivity=1) array([[0, 0, 0, 0, 0, 0, 0], [0, 5, 5, 0, 2, 2, 0], [0, 5, 5, 0, 2, 2, 0], [1, 0, 0, 0, 0, 0, 3]]) ``` Fill with a tolerance: ``` >>> flood_fill(image, (0, 0), 5, tolerance=1) array([[5, 5, 5, 5, 5, 5, 5], [5, 5, 5, 5, 2, 2, 5], [5, 5, 5, 5, 2, 2, 5], [5, 5, 5, 5, 5, 5, 3]]) ``` ### Examples using `skimage.segmentation.flood_fill` [Flood Fill](https://scikit-image.org/docs/0.18.x/auto_examples/segmentation/plot_floodfill.html#sphx-glr-auto-examples-segmentation-plot-floodfill-py) inverse\_gaussian\_gradient --------------------------- `skimage.segmentation.inverse_gaussian_gradient(image, alpha=100.0, sigma=5.0)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/segmentation/morphsnakes.py#L224-L253) Inverse of gradient magnitude. Compute the magnitude of the gradients in the image and then inverts the result in the range [0, 1]. Flat areas are assigned values close to 1, while areas close to borders are assigned values close to 0. This function or a similar one defined by the user should be applied over the image as a preprocessing step before calling [`morphological_geodesic_active_contour`](#skimage.segmentation.morphological_geodesic_active_contour "skimage.segmentation.morphological_geodesic_active_contour"). Parameters `image(M, N) or (L, M, N) array` Grayscale image or volume. `alphafloat, optional` Controls the steepness of the inversion. A larger value will make the transition between the flat areas and border areas steeper in the resulting array. `sigmafloat, optional` Standard deviation of the Gaussian filter applied over the image. Returns `gimage(M, N) or (L, M, N) array` Preprocessed image (or volume) suitable for [`morphological_geodesic_active_contour`](#skimage.segmentation.morphological_geodesic_active_contour "skimage.segmentation.morphological_geodesic_active_contour"). join\_segmentations ------------------- `skimage.segmentation.join_segmentations(s1, s2)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/segmentation/_join.py#L5-L43) Return the join of the two input segmentations. The join J of S1 and S2 is defined as the segmentation in which two voxels are in the same segment if and only if they are in the same segment in *both* S1 and S2. Parameters `s1, s2numpy arrays` s1 and s2 are label fields of the same shape. Returns `jnumpy array` The join segmentation of s1 and s2. #### Examples ``` >>> from skimage.segmentation import join_segmentations >>> s1 = np.array([[0, 0, 1, 1], ... [0, 2, 1, 1], ... [2, 2, 2, 1]]) >>> s2 = np.array([[0, 1, 1, 0], ... [0, 1, 1, 0], ... [0, 1, 1, 1]]) >>> join_segmentations(s1, s2) array([[0, 1, 3, 2], [0, 5, 3, 2], [4, 5, 5, 3]]) ``` mark\_boundaries ---------------- `skimage.segmentation.mark_boundaries(image, label_img, color=(1, 1, 0), outline_color=None, mode='outer', background_label=0)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/segmentation/boundaries.py#L184-L231) Return image with boundaries between labeled regions highlighted. Parameters `image(M, N[, 3]) array` Grayscale or RGB image. `label_img(M, N) array of int` Label array where regions are marked by different integer values. `colorlength-3 sequence, optional` RGB color of boundaries in the output image. `outline_colorlength-3 sequence, optional` RGB color surrounding boundaries in the output image. If None, no outline is drawn. `modestring in {β€˜thick’, β€˜inner’, β€˜outer’, β€˜subpixel’}, optional` The mode for finding boundaries. `background_labelint, optional` Which label to consider background (this is only useful for modes `inner` and `outer`). Returns `marked(M, N, 3) array of float` An image in which the boundaries between labels are superimposed on the original image. See also [`find_boundaries`](#skimage.segmentation.find_boundaries "skimage.segmentation.find_boundaries") ### Examples using `skimage.segmentation.mark_boundaries` [Trainable segmentation using local features and random forests](https://scikit-image.org/docs/0.18.x/auto_examples/segmentation/plot_trainable_segmentation.html#sphx-glr-auto-examples-segmentation-plot-trainable-segmentation-py) morphological\_chan\_vese ------------------------- `skimage.segmentation.morphological_chan_vese(image, iterations, init_level_set='checkerboard', smoothing=1, lambda1=1, lambda2=1, iter_callback=<function <lambda>>)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/segmentation/morphsnakes.py#L256-L356) Morphological Active Contours without Edges (MorphACWE) Active contours without edges implemented with morphological operators. It can be used to segment objects in images and volumes without well defined borders. It is required that the inside of the object looks different on average than the outside (i.e., the inner area of the object should be darker or lighter than the outer area on average). Parameters `image(M, N) or (L, M, N) array` Grayscale image or volume to be segmented. `iterationsuint` Number of iterations to run `init_level_setstr, (M, N) array, or (L, M, N) array` Initial level set. If an array is given, it will be binarized and used as the initial level set. If a string is given, it defines the method to generate a reasonable initial level set with the shape of the `image`. Accepted values are β€˜checkerboard’ and β€˜circle’. See the documentation of [`checkerboard_level_set`](#skimage.segmentation.checkerboard_level_set "skimage.segmentation.checkerboard_level_set") and [`circle_level_set`](#skimage.segmentation.circle_level_set "skimage.segmentation.circle_level_set") respectively for details about how these level sets are created. `smoothinguint, optional` Number of times the smoothing operator is applied per iteration. Reasonable values are around 1-4. Larger values lead to smoother segmentations. `lambda1float, optional` Weight parameter for the outer region. If `lambda1` is larger than `lambda2`, the outer region will contain a larger range of values than the inner region. `lambda2float, optional` Weight parameter for the inner region. If `lambda2` is larger than `lambda1`, the inner region will contain a larger range of values than the outer region. `iter_callbackfunction, optional` If given, this function is called once per iteration with the current level set as the only argument. This is useful for debugging or for plotting intermediate results during the evolution. Returns `out(M, N) or (L, M, N) array` Final segmentation (i.e., the final level set) See also `circle_level_set,` [`checkerboard_level_set`](#skimage.segmentation.checkerboard_level_set "skimage.segmentation.checkerboard_level_set") #### Notes This is a version of the Chan-Vese algorithm that uses morphological operators instead of solving a partial differential equation (PDE) for the evolution of the contour. The set of morphological operators used in this algorithm are proved to be infinitesimally equivalent to the Chan-Vese PDE (see [[1]](#r81c856a3d0d3-1)). However, morphological operators are do not suffer from the numerical stability issues typically found in PDEs (it is not necessary to find the right time step for the evolution), and are computationally faster. The algorithm and its theoretical derivation are described in [[1]](#r81c856a3d0d3-1). #### References `1(1,2)` A Morphological Approach to Curvature-based Evolution of Curves and Surfaces, Pablo MΓ‘rquez-Neila, Luis Baumela, Luis Álvarez. In IEEE Transactions on Pattern Analysis and Machine Intelligence (PAMI), 2014, [DOI:10.1109/TPAMI.2013.106](https://doi.org/10.1109/TPAMI.2013.106) morphological\_geodesic\_active\_contour ---------------------------------------- `skimage.segmentation.morphological_geodesic_active_contour(gimage, iterations, init_level_set='circle', smoothing=1, threshold='auto', balloon=0, iter_callback=<function <lambda>>)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/segmentation/morphsnakes.py#L359-L482) Morphological Geodesic Active Contours (MorphGAC). Geodesic active contours implemented with morphological operators. It can be used to segment objects with visible but noisy, cluttered, broken borders. Parameters `gimage(M, N) or (L, M, N) array` Preprocessed image or volume to be segmented. This is very rarely the original image. Instead, this is usually a preprocessed version of the original image that enhances and highlights the borders (or other structures) of the object to segment. [`morphological_geodesic_active_contour`](#skimage.segmentation.morphological_geodesic_active_contour "skimage.segmentation.morphological_geodesic_active_contour") will try to stop the contour evolution in areas where `gimage` is small. See `morphsnakes.inverse_gaussian_gradient` as an example function to perform this preprocessing. Note that the quality of [`morphological_geodesic_active_contour`](#skimage.segmentation.morphological_geodesic_active_contour "skimage.segmentation.morphological_geodesic_active_contour") might greatly depend on this preprocessing. `iterationsuint` Number of iterations to run. `init_level_setstr, (M, N) array, or (L, M, N) array` Initial level set. If an array is given, it will be binarized and used as the initial level set. If a string is given, it defines the method to generate a reasonable initial level set with the shape of the `image`. Accepted values are β€˜checkerboard’ and β€˜circle’. See the documentation of [`checkerboard_level_set`](#skimage.segmentation.checkerboard_level_set "skimage.segmentation.checkerboard_level_set") and [`circle_level_set`](#skimage.segmentation.circle_level_set "skimage.segmentation.circle_level_set") respectively for details about how these level sets are created. `smoothinguint, optional` Number of times the smoothing operator is applied per iteration. Reasonable values are around 1-4. Larger values lead to smoother segmentations. `thresholdfloat, optional` Areas of the image with a value smaller than this threshold will be considered borders. The evolution of the contour will stop in this areas. `balloonfloat, optional` Balloon force to guide the contour in non-informative areas of the image, i.e., areas where the gradient of the image is too small to push the contour towards a border. A negative value will shrink the contour, while a positive value will expand the contour in these areas. Setting this to zero will disable the balloon force. `iter_callbackfunction, optional` If given, this function is called once per iteration with the current level set as the only argument. This is useful for debugging or for plotting intermediate results during the evolution. Returns `out(M, N) or (L, M, N) array` Final segmentation (i.e., the final level set) See also `inverse_gaussian_gradient, circle_level_set,` [`checkerboard_level_set`](#skimage.segmentation.checkerboard_level_set "skimage.segmentation.checkerboard_level_set") #### Notes This is a version of the Geodesic Active Contours (GAC) algorithm that uses morphological operators instead of solving partial differential equations (PDEs) for the evolution of the contour. The set of morphological operators used in this algorithm are proved to be infinitesimally equivalent to the GAC PDEs (see [[1]](#rb6daaf5d7730-1)). However, morphological operators are do not suffer from the numerical stability issues typically found in PDEs (e.g., it is not necessary to find the right time step for the evolution), and are computationally faster. The algorithm and its theoretical derivation are described in [[1]](#rb6daaf5d7730-1). #### References `1(1,2)` A Morphological Approach to Curvature-based Evolution of Curves and Surfaces, Pablo MΓ‘rquez-Neila, Luis Baumela, Luis Álvarez. In IEEE Transactions on Pattern Analysis and Machine Intelligence (PAMI), 2014, [DOI:10.1109/TPAMI.2013.106](https://doi.org/10.1109/TPAMI.2013.106) quickshift ---------- `skimage.segmentation.quickshift(image, ratio=1.0, kernel_size=5, max_dist=10, return_tree=False, sigma=0, convert2lab=True, random_seed=42)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/segmentation/_quickshift.py#L11-L74) Segments image using quickshift clustering in Color-(x,y) space. Produces an oversegmentation of the image using the quickshift mode-seeking algorithm. Parameters `image(width, height, channels) ndarray` Input image. `ratiofloat, optional, between 0 and 1` Balances color-space proximity and image-space proximity. Higher values give more weight to color-space. `kernel_sizefloat, optional` Width of Gaussian kernel used in smoothing the sample density. Higher means fewer clusters. `max_distfloat, optional` Cut-off point for data distances. Higher means fewer clusters. `return_treebool, optional` Whether to return the full segmentation hierarchy tree and distances. `sigmafloat, optional` Width for Gaussian smoothing as preprocessing. Zero means no smoothing. `convert2labbool, optional` Whether the input should be converted to Lab colorspace prior to segmentation. For this purpose, the input is assumed to be RGB. `random_seedint, optional` Random seed used for breaking ties. Returns `segment_mask(width, height) ndarray` Integer mask indicating segment labels. #### Notes The authors advocate to convert the image to Lab color space prior to segmentation, though this is not strictly necessary. For this to work, the image must be given in RGB format. #### References `1` Quick shift and kernel methods for mode seeking, Vedaldi, A. and Soatto, S. European Conference on Computer Vision, 2008 random\_walker -------------- `skimage.segmentation.random_walker(data, labels, beta=130, mode='cg_j', tol=0.001, copy=True, multichannel=False, return_full_prob=False, spacing=None, *, prob_tol=0.001)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/segmentation/random_walker_segmentation.py#L266-L514) Random walker algorithm for segmentation from markers. Random walker algorithm is implemented for gray-level or multichannel images. Parameters `dataarray_like` Image to be segmented in phases. Gray-level `data` can be two- or three-dimensional; multichannel data can be three- or four- dimensional (multichannel=True) with the highest dimension denoting channels. Data spacing is assumed isotropic unless the `spacing` keyword argument is used. `labelsarray of ints, of same shape as data without channels dimension` Array of seed markers labeled with different positive integers for different phases. Zero-labeled pixels are unlabeled pixels. Negative labels correspond to inactive pixels that are not taken into account (they are removed from the graph). If labels are not consecutive integers, the labels array will be transformed so that labels are consecutive. In the multichannel case, `labels` should have the same shape as a single channel of `data`, i.e. without the final dimension denoting channels. `betafloat, optional` Penalization coefficient for the random walker motion (the greater `beta`, the more difficult the diffusion). `modestring, available options {β€˜cg’, β€˜cg_j’, β€˜cg_mg’, β€˜bf’}` Mode for solving the linear system in the random walker algorithm. * β€˜bf’ (brute force): an LU factorization of the Laplacian is computed. This is fast for small images (<1024x1024), but very slow and memory-intensive for large images (e.g., 3-D volumes). * β€˜cg’ (conjugate gradient): the linear system is solved iteratively using the Conjugate Gradient method from scipy.sparse.linalg. This is less memory-consuming than the brute force method for large images, but it is quite slow. * β€˜cg\_j’ (conjugate gradient with Jacobi preconditionner): the Jacobi preconditionner is applyed during the Conjugate gradient method iterations. This may accelerate the convergence of the β€˜cg’ method. * β€˜cg\_mg’ (conjugate gradient with multigrid preconditioner): a preconditioner is computed using a multigrid solver, then the solution is computed with the Conjugate Gradient method. This mode requires that the pyamg module is installed. `tolfloat, optional` Tolerance to achieve when solving the linear system using the conjugate gradient based modes (β€˜cg’, β€˜cg\_j’ and β€˜cg\_mg’). `copybool, optional` If copy is False, the `labels` array will be overwritten with the result of the segmentation. Use copy=False if you want to save on memory. `multichannelbool, optional` If True, input data is parsed as multichannel data (see β€˜data’ above for proper input format in this case). `return_full_probbool, optional` If True, the probability that a pixel belongs to each of the labels will be returned, instead of only the most likely label. `spacingiterable of floats, optional` Spacing between voxels in each spatial dimension. If `None`, then the spacing between pixels/voxels in each dimension is assumed 1. `prob_tolfloat, optional` Tolerance on the resulting probability to be in the interval [0, 1]. If the tolerance is not satisfied, a warning is displayed. Returns `outputndarray` * If `return_full_prob` is False, array of ints of same shape and data type as `labels`, in which each pixel has been labeled according to the marker that reached the pixel first by anisotropic diffusion. * If `return_full_prob` is True, array of floats of shape `(nlabels, labels.shape)`. `output[label_nb, i, j]` is the probability that label `label_nb` reaches the pixel `(i, j)` first. See also [`skimage.morphology.watershed`](skimage.morphology#skimage.morphology.watershed "skimage.morphology.watershed") watershed segmentation A segmentation algorithm based on mathematical morphology and β€œflooding” of regions from markers. #### Notes Multichannel inputs are scaled with all channel data combined. Ensure all channels are separately normalized prior to running this algorithm. The `spacing` argument is specifically for anisotropic datasets, where data points are spaced differently in one or more spatial dimensions. Anisotropic data is commonly encountered in medical imaging. The algorithm was first proposed in [[1]](#raf7f6bdcab09-1). The algorithm solves the diffusion equation at infinite times for sources placed on markers of each phase in turn. A pixel is labeled with the phase that has the greatest probability to diffuse first to the pixel. The diffusion equation is solved by minimizing x.T L x for each phase, where L is the Laplacian of the weighted graph of the image, and x is the probability that a marker of the given phase arrives first at a pixel by diffusion (x=1 on markers of the phase, x=0 on the other markers, and the other coefficients are looked for). Each pixel is attributed the label for which it has a maximal value of x. The Laplacian L of the image is defined as: * L\_ii = d\_i, the number of neighbors of pixel i (the degree of i) * L\_ij = -w\_ij if i and j are adjacent pixels The weight w\_ij is a decreasing function of the norm of the local gradient. This ensures that diffusion is easier between pixels of similar values. When the Laplacian is decomposed into blocks of marked and unmarked pixels: ``` L = M B.T B A ``` with first indices corresponding to marked pixels, and then to unmarked pixels, minimizing x.T L x for one phase amount to solving: ``` A x = - B x_m ``` where x\_m = 1 on markers of the given phase, and 0 on other markers. This linear system is solved in the algorithm using a direct method for small images, and an iterative method for larger images. #### References `1` Leo Grady, Random walks for image segmentation, IEEE Trans Pattern Anal Mach Intell. 2006 Nov;28(11):1768-83. [DOI:10.1109/TPAMI.2006.233](https://doi.org/10.1109/TPAMI.2006.233). #### Examples ``` >>> np.random.seed(0) >>> a = np.zeros((10, 10)) + 0.2 * np.random.rand(10, 10) >>> a[5:8, 5:8] += 1 >>> b = np.zeros_like(a, dtype=np.int32) >>> b[3, 3] = 1 # Marker for first phase >>> b[6, 6] = 2 # Marker for second phase >>> random_walker(a, b) array([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 2, 2, 2, 1, 1], [1, 1, 1, 1, 1, 2, 2, 2, 1, 1], [1, 1, 1, 1, 1, 2, 2, 2, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1], [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]], dtype=int32) ``` relabel\_sequential ------------------- `skimage.segmentation.relabel_sequential(label_field, offset=1)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/segmentation/_join.py#L46-L154) Relabel arbitrary labels to {`offset`, … `offset` + number\_of\_labels}. This function also returns the forward map (mapping the original labels to the reduced labels) and the inverse map (mapping the reduced labels back to the original ones). Parameters `label_fieldnumpy array of int, arbitrary shape` An array of labels, which must be non-negative integers. `offsetint, optional` The return labels will start at `offset`, which should be strictly positive. Returns `relabelednumpy array of int, same shape as label_field` The input label field with labels mapped to {offset, …, number\_of\_labels + offset - 1}. The data type will be the same as `label_field`, except when offset + number\_of\_labels causes overflow of the current data type. `forward_mapArrayMap` The map from the original label space to the returned label space. Can be used to re-apply the same mapping. See examples for usage. The output data type will be the same as `relabeled`. `inverse_mapArrayMap` The map from the new label space to the original space. This can be used to reconstruct the original label field from the relabeled one. The output data type will be the same as `label_field`. #### Notes The label 0 is assumed to denote the background and is never remapped. The forward map can be extremely big for some inputs, since its length is given by the maximum of the label field. However, in most situations, `label_field.max()` is much smaller than `label_field.size`, and in these cases the forward map is guaranteed to be smaller than either the input or output images. #### Examples ``` >>> from skimage.segmentation import relabel_sequential >>> label_field = np.array([1, 1, 5, 5, 8, 99, 42]) >>> relab, fw, inv = relabel_sequential(label_field) >>> relab array([1, 1, 2, 2, 3, 5, 4]) >>> print(fw) ArrayMap: 1 β†’ 1 5 β†’ 2 8 β†’ 3 42 β†’ 4 99 β†’ 5 >>> np.array(fw) array([0, 1, 0, 0, 0, 2, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5]) >>> np.array(inv) array([ 0, 1, 5, 8, 42, 99]) >>> (fw[label_field] == relab).all() True >>> (inv[relab] == label_field).all() True >>> relab, fw, inv = relabel_sequential(label_field, offset=5) >>> relab array([5, 5, 6, 6, 7, 9, 8]) ``` slic ---- `skimage.segmentation.slic(image, n_segments=100, compactness=10.0, max_iter=10, sigma=0, spacing=None, multichannel=True, convert2lab=None, enforce_connectivity=True, min_size_factor=0.5, max_size_factor=3, slic_zero=False, start_label=None, mask=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/segmentation/slic_superpixels.py#L107-L333) Segments image using k-means clustering in Color-(x,y,z) space. Parameters `image2D, 3D or 4D ndarray` Input image, which can be 2D or 3D, and grayscale or multichannel (see `multichannel` parameter). Input image must either be NaN-free or the NaN’s must be masked out `n_segmentsint, optional` The (approximate) number of labels in the segmented output image. `compactnessfloat, optional` Balances color proximity and space proximity. Higher values give more weight to space proximity, making superpixel shapes more square/cubic. In SLICO mode, this is the initial compactness. This parameter depends strongly on image contrast and on the shapes of objects in the image. We recommend exploring possible values on a log scale, e.g., 0.01, 0.1, 1, 10, 100, before refining around a chosen value. `max_iterint, optional` Maximum number of iterations of k-means. `sigmafloat or (3,) array-like of floats, optional` Width of Gaussian smoothing kernel for pre-processing for each dimension of the image. The same sigma is applied to each dimension in case of a scalar value. Zero means no smoothing. Note, that `sigma` is automatically scaled if it is scalar and a manual voxel spacing is provided (see Notes section). `spacing(3,) array-like of floats, optional` The voxel spacing along each image dimension. By default, [`slic`](#skimage.segmentation.slic "skimage.segmentation.slic") assumes uniform spacing (same voxel resolution along z, y and x). This parameter controls the weights of the distances along z, y, and x during k-means clustering. `multichannelbool, optional` Whether the last axis of the image is to be interpreted as multiple channels or another spatial dimension. `convert2labbool, optional` Whether the input should be converted to Lab colorspace prior to segmentation. The input image *must* be RGB. Highly recommended. This option defaults to `True` when `multichannel=True` *and* `image.shape[-1] == 3`. `enforce_connectivitybool, optional` Whether the generated segments are connected or not `min_size_factorfloat, optional` Proportion of the minimum segment size to be removed with respect to the supposed segment size ``depth*width*height/n_segments`` `max_size_factorfloat, optional` Proportion of the maximum connected segment size. A value of 3 works in most of the cases. `slic_zerobool, optional` Run SLIC-zero, the zero-parameter mode of SLIC. [[2]](#rbeb231216055-2) **start\_label: int, optional** The labels’ index start. Should be 0 or 1. New in version 0.17: `start_label` was introduced in 0.17 `mask2D ndarray, optional` If provided, superpixels are computed only where mask is True, and seed points are homogeneously distributed over the mask using a K-means clustering strategy. New in version 0.17: `mask` was introduced in 0.17 Returns `labels2D or 3D array` Integer mask indicating segment labels. Raises ValueError If `convert2lab` is set to `True` but the last array dimension is not of length 3. ValueError If `start_label` is not 0 or 1. #### Notes * If `sigma > 0`, the image is smoothed using a Gaussian kernel prior to segmentation. * If `sigma` is scalar and `spacing` is provided, the kernel width is divided along each dimension by the spacing. For example, if `sigma=1` and `spacing=[5, 1, 1]`, the effective `sigma` is `[0.2, 1, 1]`. This ensures sensible smoothing for anisotropic images. * The image is rescaled to be in [0, 1] prior to processing. * Images of shape (M, N, 3) are interpreted as 2D RGB images by default. To interpret them as 3D with the last dimension having length 3, use `multichannel=False`. * `start_label` is introduced to handle the issue [[4]](#rbeb231216055-4). The labels indexing starting at 0 will be deprecated in future versions. If `mask` is not `None` labels indexing starts at 1 and masked area is set to 0. #### References `1` Radhakrishna Achanta, Appu Shaji, Kevin Smith, Aurelien Lucchi, Pascal Fua, and Sabine SΓΌsstrunk, SLIC Superpixels Compared to State-of-the-art Superpixel Methods, TPAMI, May 2012. [DOI:10.1109/TPAMI.2012.120](https://doi.org/10.1109/TPAMI.2012.120) `2` <https://www.epfl.ch/labs/ivrl/research/slic-superpixels/#SLICO> `3` Irving, Benjamin. β€œmaskSLIC: regional superpixel generation with application to local pathology characterisation in medical images.”, 2016, [arXiv:1606.09518](https://arxiv.org/abs/1606.09518) `4` <https://github.com/scikit-image/scikit-image/issues/3722> #### Examples ``` >>> from skimage.segmentation import slic >>> from skimage.data import astronaut >>> img = astronaut() >>> segments = slic(img, n_segments=100, compactness=10) ``` Increasing the compactness parameter yields more square regions: ``` >>> segments = slic(img, n_segments=100, compactness=20) ``` watershed --------- `skimage.segmentation.watershed(image, markers=None, connectivity=1, offset=None, mask=None, compactness=0, watershed_line=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/segmentation/_watershed.py#L94-L227) Find watershed basins in `image` flooded from given `markers`. Parameters `imagendarray (2-D, 3-D, …) of integers` Data array where the lowest value points are labeled first. `markersint, or ndarray of int, same shape as image, optional` The desired number of markers, or an array marking the basins with the values to be assigned in the label matrix. Zero means not a marker. If `None` (no markers given), the local minima of the image are used as markers. `connectivityndarray, optional` An array with the same number of dimensions as `image` whose non-zero elements indicate neighbors for connection. Following the scipy convention, default is a one-connected array of the dimension of the image. `offsetarray_like of shape image.ndim, optional` offset of the connectivity (one offset per dimension) `maskndarray of bools or 0s and 1s, optional` Array of same shape as `image`. Only points at which mask == True will be labeled. `compactnessfloat, optional` Use compact watershed [[3]](#rc8002e235889-3) with given compactness parameter. Higher values result in more regularly-shaped watershed basins. `watershed_linebool, optional` If watershed\_line is True, a one-pixel wide line separates the regions obtained by the watershed algorithm. The line has the label 0. Returns `outndarray` A labeled matrix of the same type and shape as markers See also [`skimage.segmentation.random_walker`](#skimage.segmentation.random_walker "skimage.segmentation.random_walker") random walker segmentation A segmentation algorithm based on anisotropic diffusion, usually slower than the watershed but with good results on noisy data and boundaries with holes. #### Notes This function implements a watershed algorithm [[1]](#rc8002e235889-1) [[2]](#rc8002e235889-2) that apportions pixels into marked basins. The algorithm uses a priority queue to hold the pixels with the metric for the priority queue being pixel value, then the time of entry into the queue - this settles ties in favor of the closest marker. Some ideas taken from Soille, β€œAutomated Basin Delineation from Digital Elevation Models Using Mathematical Morphology”, Signal Processing 20 (1990) 171-182 The most important insight in the paper is that entry time onto the queue solves two problems: a pixel should be assigned to the neighbor with the largest gradient or, if there is no gradient, pixels on a plateau should be split between markers on opposite sides. This implementation converts all arguments to specific, lowest common denominator types, then passes these to a C algorithm. Markers can be determined manually, or automatically using for example the local minima of the gradient of the image, or the local maxima of the distance function to the background for separating overlapping objects (see example). #### References `1` <https://en.wikipedia.org/wiki/Watershed_%28image_processing%29> `2` <http://cmm.ensmp.fr/~beucher/wtshed.html> `3` Peer Neubert & Peter Protzel (2014). Compact Watershed and Preemptive SLIC: On Improving Trade-offs of Superpixel Segmentation Algorithms. ICPR 2014, pp 996-1001. [DOI:10.1109/ICPR.2014.181](https://doi.org/10.1109/ICPR.2014.181) <https://www.tu-chemnitz.de/etit/proaut/publications/cws_pSLIC_ICPR.pdf> #### Examples The watershed algorithm is useful to separate overlapping objects. We first generate an initial image with two overlapping circles: ``` >>> x, y = np.indices((80, 80)) >>> x1, y1, x2, y2 = 28, 28, 44, 52 >>> r1, r2 = 16, 20 >>> mask_circle1 = (x - x1)**2 + (y - y1)**2 < r1**2 >>> mask_circle2 = (x - x2)**2 + (y - y2)**2 < r2**2 >>> image = np.logical_or(mask_circle1, mask_circle2) ``` Next, we want to separate the two circles. We generate markers at the maxima of the distance to the background: ``` >>> from scipy import ndimage as ndi >>> distance = ndi.distance_transform_edt(image) >>> from skimage.feature import peak_local_max >>> local_maxi = peak_local_max(distance, labels=image, ... footprint=np.ones((3, 3)), ... indices=False) >>> markers = ndi.label(local_maxi)[0] ``` Finally, we run the watershed on the image and markers: ``` >>> labels = watershed(-distance, markers, mask=image) ``` The algorithm works also for 3-D images, and can be used for example to separate overlapping spheres. ### Examples using `skimage.segmentation.watershed` [Watershed segmentation](https://scikit-image.org/docs/0.18.x/auto_examples/segmentation/plot_watershed.html#sphx-glr-auto-examples-segmentation-plot-watershed-py) [Markers for watershed transform](https://scikit-image.org/docs/0.18.x/auto_examples/segmentation/plot_marked_watershed.html#sphx-glr-auto-examples-segmentation-plot-marked-watershed-py) [Segment human cells (in mitosis)](https://scikit-image.org/docs/0.18.x/auto_examples/applications/plot_human_mitosis.html#sphx-glr-auto-examples-applications-plot-human-mitosis-py)
programming_docs
scikit_image Module: registration Module: registration ==================== | | | | --- | --- | | [`skimage.registration.optical_flow_ilk`](#skimage.registration.optical_flow_ilk "skimage.registration.optical_flow_ilk")(…[, …]) | Coarse to fine optical flow estimator. | | [`skimage.registration.optical_flow_tvl1`](#skimage.registration.optical_flow_tvl1 "skimage.registration.optical_flow_tvl1")(…) | Coarse to fine optical flow estimator. | | [`skimage.registration.phase_cross_correlation`](#skimage.registration.phase_cross_correlation "skimage.registration.phase_cross_correlation")(…) | Efficient subpixel image translation registration by cross-correlation. | optical\_flow\_ilk ------------------ `skimage.registration.optical_flow_ilk(reference_image, moving_image, *, radius=7, num_warp=10, gaussian=False, prefilter=False, dtype=<class 'numpy.float32'>)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/registration/_optical_flow.py#L304-L374) Coarse to fine optical flow estimator. The iterative Lucas-Kanade (iLK) solver is applied at each level of the image pyramid. iLK [[1]](#r8ab46b4fab1c-1) is a fast and robust alternative to TVL1 algorithm although less accurate for rendering flat surfaces and object boundaries (see [[2]](#r8ab46b4fab1c-2)). Parameters `reference_imagendarray, shape (M, N[, P[, …]])` The first gray scale image of the sequence. `moving_imagendarray, shape (M, N[, P[, …]])` The second gray scale image of the sequence. `radiusint, optional` Radius of the window considered around each pixel. `num_warpint, optional` Number of times moving\_image is warped. `gaussianbool, optional` If True, a Gaussian kernel is used for the local integration. Otherwise, a uniform kernel is used. `prefilterbool, optional` Whether to prefilter the estimated optical flow before each image warp. When True, a median filter with window size 3 along each axis is applied. This helps to remove potential outliers. `dtypedtype, optional` Output data type: must be floating point. Single precision provides good results and saves memory usage and computation time compared to double precision. Returns `flowndarray, shape ((reference_image.ndim, M, N[, P[, …]])` The estimated optical flow components for each axis. #### Notes * The implemented algorithm is described in **Table2** of [[1]](#r8ab46b4fab1c-1). * Color images are not supported. #### References `1(1,2)` Le Besnerais, G., & Champagnat, F. (2005, September). Dense optical flow by iterative local window registration. In IEEE International Conference on Image Processing 2005 (Vol. 1, pp. I-137). IEEE. [DOI:10.1109/ICIP.2005.1529706](https://doi.org/10.1109/ICIP.2005.1529706) `2` Plyer, A., Le Besnerais, G., & Champagnat, F. (2016). Massively parallel Lucas Kanade optical flow for real-time video processing applications. Journal of Real-Time Image Processing, 11(4), 713-730. [DOI:10.1007/s11554-014-0423-0](https://doi.org/10.1007/s11554-014-0423-0) #### Examples ``` >>> from skimage.color import rgb2gray >>> from skimage.data import stereo_motorcycle >>> from skimage.registration import optical_flow_ilk >>> reference_image, moving_image, disp = stereo_motorcycle() >>> # --- Convert the images to gray level: color is not supported. >>> reference_image = rgb2gray(reference_image) >>> moving_image = rgb2gray(moving_image) >>> flow = optical_flow_ilk(moving_image, reference_image) ``` ### Examples using `skimage.registration.optical_flow_ilk` [Registration using optical flow](https://scikit-image.org/docs/0.18.x/auto_examples/registration/plot_opticalflow.html#sphx-glr-auto-examples-registration-plot-opticalflow-py) optical\_flow\_tvl1 ------------------- `skimage.registration.optical_flow_tvl1(reference_image, moving_image, *, attachment=15, tightness=0.3, num_warp=5, num_iter=10, tol=0.0001, prefilter=False, dtype=<class 'numpy.float32'>)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/registration/_optical_flow.py#L141-L222) Coarse to fine optical flow estimator. The TV-L1 solver is applied at each level of the image pyramid. TV-L1 is a popular algorithm for optical flow estimation introduced by Zack et al. [[1]](#rda1bf5cbeff5-1), improved in [[2]](#rda1bf5cbeff5-2) and detailed in [[3]](#rda1bf5cbeff5-3). Parameters `reference_imagendarray, shape (M, N[, P[, …]])` The first gray scale image of the sequence. `moving_imagendarray, shape (M, N[, P[, …]])` The second gray scale image of the sequence. `attachmentfloat, optional` Attachment parameter (\(\lambda\) in [[1]](#rda1bf5cbeff5-1)). The smaller this parameter is, the smoother the returned result will be. `tightnessfloat, optional` Tightness parameter (\(\tau\) in [[1]](#rda1bf5cbeff5-1)). It should have a small value in order to maintain attachement and regularization parts in correspondence. `num_warpint, optional` Number of times image1 is warped. `num_iterint, optional` Number of fixed point iteration. `tolfloat, optional` Tolerance used as stopping criterion based on the LΒ² distance between two consecutive values of (u, v). `prefilterbool, optional` Whether to prefilter the estimated optical flow before each image warp. When True, a median filter with window size 3 along each axis is applied. This helps to remove potential outliers. `dtypedtype, optional` Output data type: must be floating point. Single precision provides good results and saves memory usage and computation time compared to double precision. Returns `flowndarray, shape ((image0.ndim, M, N[, P[, …]])` The estimated optical flow components for each axis. #### Notes Color images are not supported. #### References `1(1,2,3)` Zach, C., Pock, T., & Bischof, H. (2007, September). A duality based approach for realtime TV-L 1 optical flow. In Joint pattern recognition symposium (pp. 214-223). Springer, Berlin, Heidelberg. [DOI:10.1007/978-3-540-74936-3\_22](https://doi.org/10.1007/978-3-540-74936-3_22) `2` Wedel, A., Pock, T., Zach, C., Bischof, H., & Cremers, D. (2009). An improved algorithm for TV-L 1 optical flow. In Statistical and geometrical approaches to visual motion analysis (pp. 23-45). Springer, Berlin, Heidelberg. [DOI:10.1007/978-3-642-03061-1\_2](https://doi.org/10.1007/978-3-642-03061-1_2) `3` PΓ©rez, J. S., Meinhardt-Llopis, E., & Facciolo, G. (2013). TV-L1 optical flow estimation. Image Processing On Line, 2013, 137-150. [DOI:10.5201/ipol.2013.26](https://doi.org/10.5201/ipol.2013.26) #### Examples ``` >>> from skimage.color import rgb2gray >>> from skimage.data import stereo_motorcycle >>> from skimage.registration import optical_flow_tvl1 >>> image0, image1, disp = stereo_motorcycle() >>> # --- Convert the images to gray level: color is not supported. >>> image0 = rgb2gray(image0) >>> image1 = rgb2gray(image1) >>> flow = optical_flow_tvl1(image1, image0) ``` ### Examples using `skimage.registration.optical_flow_tvl1` [Registration using optical flow](https://scikit-image.org/docs/0.18.x/auto_examples/registration/plot_opticalflow.html#sphx-glr-auto-examples-registration-plot-opticalflow-py) phase\_cross\_correlation ------------------------- `skimage.registration.phase_cross_correlation(reference_image, moving_image, *, upsample_factor=1, space='real', return_error=True, reference_mask=None, moving_mask=None, overlap_ratio=0.3)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/registration/_phase_cross_correlation.py#L109-L276) Efficient subpixel image translation registration by cross-correlation. This code gives the same precision as the FFT upsampled cross-correlation in a fraction of the computation time and with reduced memory requirements. It obtains an initial estimate of the cross-correlation peak by an FFT and then refines the shift estimation by upsampling the DFT only in a small neighborhood of that estimate by means of a matrix-multiply DFT. Parameters `reference_imagearray` Reference image. `moving_imagearray` Image to register. Must be same dimensionality as `reference_image`. `upsample_factorint, optional` Upsampling factor. Images will be registered to within `1 / upsample_factor` of a pixel. For example `upsample_factor == 20` means the images will be registered within 1/20th of a pixel. Default is 1 (no upsampling). Not used if any of `reference_mask` or `moving_mask` is not None. `spacestring, one of β€œreal” or β€œfourier”, optional` Defines how the algorithm interprets input data. β€œreal” means data will be FFT’d to compute the correlation, while β€œfourier” data will bypass FFT of input data. Case insensitive. Not used if any of `reference_mask` or `moving_mask` is not None. `return_errorbool, optional` Returns error and phase difference if on, otherwise only shifts are returned. Has noeffect if any of `reference_mask` or `moving_mask` is not None. In this case only shifts is returned. `reference_maskndarray` Boolean mask for `reference_image`. The mask should evaluate to `True` (or 1) on valid pixels. `reference_mask` should have the same shape as `reference_image`. `moving_maskndarray or None, optional` Boolean mask for `moving_image`. The mask should evaluate to `True` (or 1) on valid pixels. `moving_mask` should have the same shape as `moving_image`. If `None`, `reference_mask` will be used. `overlap_ratiofloat, optional` Minimum allowed overlap ratio between images. The correlation for translations corresponding with an overlap ratio lower than this threshold will be ignored. A lower `overlap_ratio` leads to smaller maximum translation, while a higher `overlap_ratio` leads to greater robustness against spurious matches due to small overlap between masked images. Used only if one of `reference_mask` or `moving_mask` is None. Returns `shiftsndarray` Shift vector (in pixels) required to register `moving_image` with `reference_image`. Axis ordering is consistent with numpy (e.g. Z, Y, X) `errorfloat` Translation invariant normalized RMS error between `reference_image` and `moving_image`. `phasedifffloat` Global phase difference between the two images (should be zero if images are non-negative). #### References `1` Manuel Guizar-Sicairos, Samuel T. Thurman, and James R. Fienup, β€œEfficient subpixel image registration algorithms,” Optics Letters 33, 156-158 (2008). [DOI:10.1364/OL.33.000156](https://doi.org/10.1364/OL.33.000156) `2` James R. Fienup, β€œInvariant error metrics for image reconstruction” Optics Letters 36, 8352-8357 (1997). [DOI:10.1364/AO.36.008352](https://doi.org/10.1364/AO.36.008352) `3` Dirk Padfield. Masked Object Registration in the Fourier Domain. IEEE Transactions on Image Processing, vol. 21(5), pp. 2706-2718 (2012). [DOI:10.1109/TIP.2011.2181402](https://doi.org/10.1109/TIP.2011.2181402) `4` D. Padfield. β€œMasked FFT registration”. In Proc. Computer Vision and Pattern Recognition, pp. 2918-2925 (2010). [DOI:10.1109/CVPR.2010.5540032](https://doi.org/10.1109/CVPR.2010.5540032) ### Examples using `skimage.registration.phase_cross_correlation` [Masked Normalized Cross-Correlation](https://scikit-image.org/docs/0.18.x/auto_examples/registration/plot_masked_register_translation.html#sphx-glr-auto-examples-registration-plot-masked-register-translation-py) scikit_image Module: viewer.plugins Module: viewer.plugins ====================== | | | | --- | --- | | [`skimage.viewer.plugins.CannyPlugin`](#skimage.viewer.plugins.CannyPlugin "skimage.viewer.plugins.CannyPlugin")(\*args, …) | Canny filter plugin to show edges of an image. | | [`skimage.viewer.plugins.ColorHistogram`](#skimage.viewer.plugins.ColorHistogram "skimage.viewer.plugins.ColorHistogram")([max\_pct]) | | | [`skimage.viewer.plugins.Crop`](#skimage.viewer.plugins.Crop "skimage.viewer.plugins.Crop")([maxdist]) | | | [`skimage.viewer.plugins.LabelPainter`](#skimage.viewer.plugins.LabelPainter "skimage.viewer.plugins.LabelPainter")([max\_radius]) | | | [`skimage.viewer.plugins.LineProfile`](#skimage.viewer.plugins.LineProfile "skimage.viewer.plugins.LineProfile")([…]) | Plugin to compute interpolated intensity under a scan line on an image. | | [`skimage.viewer.plugins.Measure`](#skimage.viewer.plugins.Measure "skimage.viewer.plugins.Measure")([maxdist]) | | | [`skimage.viewer.plugins.OverlayPlugin`](#skimage.viewer.plugins.OverlayPlugin "skimage.viewer.plugins.OverlayPlugin")(\*\*kwargs) | Plugin for ImageViewer that displays an overlay on top of main image. | | [`skimage.viewer.plugins.PlotPlugin`](#skimage.viewer.plugins.PlotPlugin "skimage.viewer.plugins.PlotPlugin")([…]) | Plugin for ImageViewer that contains a plot canvas. | | [`skimage.viewer.plugins.Plugin`](#skimage.viewer.plugins.Plugin "skimage.viewer.plugins.Plugin")([…]) | Base class for plugins that interact with an ImageViewer. | | `skimage.viewer.plugins.base` | Base class for Plugins that interact with ImageViewer. | | `skimage.viewer.plugins.canny` | | | `skimage.viewer.plugins.color_histogram` | | | `skimage.viewer.plugins.crop` | | | `skimage.viewer.plugins.labelplugin` | | | `skimage.viewer.plugins.lineprofile` | | | `skimage.viewer.plugins.measure` | | | `skimage.viewer.plugins.overlayplugin` | | | `skimage.viewer.plugins.plotplugin` | | CannyPlugin ----------- `class skimage.viewer.plugins.CannyPlugin(*args, **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/canny.py#L9-L30) Bases: `skimage.viewer.plugins.overlayplugin.OverlayPlugin` Canny filter plugin to show edges of an image. `__init__(*args, **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/canny.py#L14-L15) Initialize self. See help(type(self)) for accurate signature. `attach(image_viewer)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/canny.py#L17-L30) Attach the plugin to an ImageViewer. Note that the ImageViewer will automatically call this method when the plugin is added to the ImageViewer. For example: ``` viewer += Plugin(...) ``` Also note that [`attach`](#skimage.viewer.plugins.CannyPlugin.attach "skimage.viewer.plugins.CannyPlugin.attach") automatically calls the filter function so that the image matches the filtered value specified by attached widgets. `name = 'Canny Filter'` ColorHistogram -------------- `class skimage.viewer.plugins.ColorHistogram(max_pct=0.99, **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/color_histogram.py#L8-L83) Bases: `skimage.viewer.plugins.plotplugin.PlotPlugin` `__init__(max_pct=0.99, **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/color_histogram.py#L11-L15) Initialize self. See help(type(self)) for accurate signature. `ab_selected(extents)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/color_histogram.py#L51-L61) `attach(image_viewer)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/color_histogram.py#L17-L22) Attach the plugin to an ImageViewer. Note that the ImageViewer will automatically call this method when the plugin is added to the ImageViewer. For example: ``` viewer += Plugin(...) ``` Also note that [`attach`](#skimage.viewer.plugins.ColorHistogram.attach "skimage.viewer.plugins.ColorHistogram.attach") automatically calls the filter function so that the image matches the filtered value specified by attached widgets. `help()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/color_histogram.py#L46-L49) `name = 'Color Histogram'` `output()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/color_histogram.py#L63-L83) Return the image mask and the histogram data. Returns `maskarray of bool, same shape as image` The selected pixels. `datadict` The data describing the histogram and the selected region. The dictionary contains: * β€˜bins’ : array of float The bin boundaries for both `a` and `b` channels. * β€˜hist’ : 2D array of float The normalized histogram. * β€˜edges’ : tuple of array of float The bin edges along each dimension * β€˜extents’ : tuple of float The left and right and top and bottom of the selected region. Crop ---- `class skimage.viewer.plugins.Crop(maxdist=10, **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/crop.py#L9-L45) Bases: `skimage.viewer.plugins.base.Plugin` `__init__(maxdist=10, **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/crop.py#L12-L16) Initialize self. See help(type(self)) for accurate signature. `attach(image_viewer)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/crop.py#L18-L27) Attach the plugin to an ImageViewer. Note that the ImageViewer will automatically call this method when the plugin is added to the ImageViewer. For example: ``` viewer += Plugin(...) ``` Also note that [`attach`](#skimage.viewer.plugins.Crop.attach "skimage.viewer.plugins.Crop.attach") automatically calls the filter function so that the image matches the filtered value specified by attached widgets. `crop(extents)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/crop.py#L34-L40) `help()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/crop.py#L29-L32) `name = 'Crop'` `reset()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/crop.py#L42-L45) LabelPainter ------------ `class skimage.viewer.plugins.LabelPainter(max_radius=20, **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/labelplugin.py#L14-L67) Bases: `skimage.viewer.plugins.base.Plugin` `__init__(max_radius=20, **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/labelplugin.py#L17-L29) Initialize self. See help(type(self)) for accurate signature. `attach(image_viewer)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/labelplugin.py#L36-L44) Attach the plugin to an ImageViewer. Note that the ImageViewer will automatically call this method when the plugin is added to the ImageViewer. For example: ``` viewer += Plugin(...) ``` Also note that [`attach`](#skimage.viewer.plugins.LabelPainter.attach "skimage.viewer.plugins.LabelPainter.attach") automatically calls the filter function so that the image matches the filtered value specified by attached widgets. `help()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/labelplugin.py#L31-L34) `property label` `name = 'LabelPainter'` `on_enter(overlay)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/labelplugin.py#L50-L51) `property radius` LineProfile ----------- `class skimage.viewer.plugins.LineProfile(maxdist=10, epsilon='deprecated', limits='image', **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/lineprofile.py#L13-L167) Bases: `skimage.viewer.plugins.plotplugin.PlotPlugin` Plugin to compute interpolated intensity under a scan line on an image. See PlotPlugin and Plugin classes for additional details. Parameters `maxdistfloat` Maximum pixel distance allowed when selecting end point of scan line. `limitstuple or {None, β€˜image’, β€˜dtype’}` (minimum, maximum) intensity limits for plotted profile. The following special values are defined: None : rescale based on min/max intensity along selected scan line. β€˜image’ : fixed scale based on min/max intensity in image. β€˜dtype’ : fixed scale based on min/max intensity of image dtype. `__init__(maxdist=10, epsilon='deprecated', limits='image', **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/lineprofile.py#L32-L37) Initialize self. See help(type(self)) for accurate signature. `attach(image_viewer)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/lineprofile.py#L39-L75) Attach the plugin to an ImageViewer. Note that the ImageViewer will automatically call this method when the plugin is added to the ImageViewer. For example: ``` viewer += Plugin(...) ``` Also note that [`attach`](#skimage.viewer.plugins.LineProfile.attach "skimage.viewer.plugins.LineProfile.attach") automatically calls the filter function so that the image matches the filtered value specified by attached widgets. `get_profiles()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/lineprofile.py#L83-L95) Return intensity profile of the selected line. Returns end\_points: (2, 2) array The positions ((x1, y1), (x2, y2)) of the line ends. profile: list of 1d arrays Profile of intensity values. Length 1 (grayscale) or 3 (rgb). `help()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/lineprofile.py#L77-L81) `line_changed(end_points)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/lineprofile.py#L103-L110) `name = 'Line Profile'` `output()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/lineprofile.py#L140-L167) Return the drawn line and the resulting scan. Returns `line_image(M, N) uint8 array, same shape as image` An array of 0s with the scanned line set to 255. If the linewidth of the line tool is greater than 1, sets the values within the profiled polygon to 128. `scan(P,) or (P, 3) array of int or float` The line scan values across the image. `reset_axes(scan_data)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/lineprofile.py#L128-L138) Measure ------- `class skimage.viewer.plugins.Measure(maxdist=10, **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/measure.py#L14-L49) Bases: `skimage.viewer.plugins.base.Plugin` `__init__(maxdist=10, **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/measure.py#L17-L27) Initialize self. See help(type(self)) for accurate signature. `attach(image_viewer)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/measure.py#L29-L37) Attach the plugin to an ImageViewer. Note that the ImageViewer will automatically call this method when the plugin is added to the ImageViewer. For example: ``` viewer += Plugin(...) ``` Also note that [`attach`](#skimage.viewer.plugins.Measure.attach "skimage.viewer.plugins.Measure.attach") automatically calls the filter function so that the image matches the filtered value specified by attached widgets. `help()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/measure.py#L39-L42) `line_changed(end_points)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/measure.py#L44-L49) `name = 'Measure'` OverlayPlugin ------------- `class skimage.viewer.plugins.OverlayPlugin(**kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/overlayplugin.py#L12-L114) Bases: `skimage.viewer.plugins.base.Plugin` Plugin for ImageViewer that displays an overlay on top of main image. The base Plugin class displays the filtered image directly on the viewer. OverlayPlugin will instead overlay an image with a transparent colormap. See base Plugin class for additional details. Attributes `overlayarray` Overlay displayed on top of image. This overlay defaults to a color map with alpha values varying linearly from 0 to 1. `colorint` Color of overlay. `__init__(**kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/overlayplugin.py#L33-L38) Initialize self. See help(type(self)) for accurate signature. `attach(image_viewer)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/overlayplugin.py#L40-L43) Attach the plugin to an ImageViewer. Note that the ImageViewer will automatically call this method when the plugin is added to the ImageViewer. For example: ``` viewer += Plugin(...) ``` Also note that [`attach`](#skimage.viewer.plugins.OverlayPlugin.attach "skimage.viewer.plugins.OverlayPlugin.attach") automatically calls the filter function so that the image matches the filtered value specified by attached widgets. `closeEvent(event)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/overlayplugin.py#L100-L103) On close disconnect all artists and events from ImageViewer. Note that artists must be appended to `self.artists`. `property color` `colors = {'cyan': (0, 1, 1), 'green': (0, 1, 0), 'red': (1, 0, 0), 'yellow': (1, 1, 0)}` `display_filtered_image(image)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/overlayplugin.py#L96-L98) Display filtered image as an overlay on top of image in viewer. `property filtered_image` Return filtered image. This β€œfiltered image” is used when saving from the plugin. `output()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/overlayplugin.py#L105-L114) Return the overlaid image. Returns `overlayarray, same shape as image` The overlay currently displayed. `dataNone` `property overlay` PlotPlugin ---------- `class skimage.viewer.plugins.PlotPlugin(image_filter=None, height=150, width=400, **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/plotplugin.py#L12-L74) Bases: `skimage.viewer.plugins.base.Plugin` Plugin for ImageViewer that contains a plot canvas. Base class for plugins that contain a Matplotlib plot canvas, which can, for example, display an image histogram. See base Plugin class for additional details. `__init__(image_filter=None, height=150, width=400, **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/plotplugin.py#L21-L29) Initialize self. See help(type(self)) for accurate signature. `add_plot()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/plotplugin.py#L43-L56) `add_tool(tool)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/plotplugin.py#L62-L66) `attach(image_viewer)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/plotplugin.py#L31-L37) Attach the plugin to an ImageViewer. Note that the ImageViewer will automatically call this method when the plugin is added to the ImageViewer. For example: ``` viewer += Plugin(...) ``` Also note that [`attach`](#skimage.viewer.plugins.PlotPlugin.attach "skimage.viewer.plugins.PlotPlugin.attach") automatically calls the filter function so that the image matches the filtered value specified by attached widgets. `redraw()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/plotplugin.py#L39-L41) Redraw plot. `remove_tool(tool)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/plotplugin.py#L68-L74) Plugin ------ `class skimage.viewer.plugins.Plugin(image_filter=None, height=0, width=400, useblit=True, dock='bottom')` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/base.py#L11-L261) Bases: [`object`](https://docs.python.org/3.9/library/functions.html#object "(in Python v3.9)") Base class for plugins that interact with an ImageViewer. A plugin connects an image filter (or another function) to an image viewer. Note that a Plugin is initialized *without* an image viewer and attached in a later step. See example below for details. Parameters `image_viewerImageViewer` Window containing image used in measurement/manipulation. `image_filterfunction` Function that gets called to update image in image viewer. This value can be `None` if, for example, you have a plugin that extracts information from an image and doesn’t manipulate it. Alternatively, this function can be defined as a method in a Plugin subclass. `height, widthint` Size of plugin window in pixels. Note that Qt will automatically resize a window to fit components. So if you’re adding rows of components, you can leave `height = 0` and just let Qt determine the final height. `useblitbool` If True, use blitting to speed up animation. Only available on some Matplotlib backends. If None, set to True when using Agg backend. This only has an effect if you draw on top of an image viewer. #### Examples ``` >>> from skimage.viewer import ImageViewer >>> from skimage.viewer.widgets import Slider >>> from skimage import data >>> >>> plugin = Plugin(image_filter=lambda img, ... threshold: img > threshold) >>> plugin += Slider('threshold', 0, 255) >>> >>> image = data.coins() >>> viewer = ImageViewer(image) >>> viewer += plugin >>> thresholded = viewer.show()[0][0] ``` The plugin will automatically delegate parameters to `image_filter` based on its parameter type, i.e., `ptype` (widgets for required arguments must be added in the order they appear in the function). The image attached to the viewer is **automatically passed as the first argument** to the filter function. #TODO: Add flag so image is not passed to filter function by default. `ptype = β€˜kwarg’` is the default for most widgets so it’s unnecessary here. Attributes `image_viewerImageViewer` Window containing image used in measurement. `namestr` Name of plugin. This is displayed as the window title. `artistlist` List of Matplotlib artists and canvastools. Any artists created by the plugin should be added to this list so that it gets cleaned up on close. `__init__(image_filter=None, height=0, width=400, useblit=True, dock='bottom')` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/base.py#L80-L105) Initialize self. See help(type(self)) for accurate signature. `add_widget(widget)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/base.py#L129-L150) Add widget to plugin. Alternatively, Plugin’s `__add__` method is overloaded to add widgets: ``` plugin += Widget(...) ``` Widgets can adjust required or optional arguments of filter function or parameters for the plugin. This is specified by the Widget’s `ptype`. `attach(image_viewer)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/base.py#L107-L127) Attach the plugin to an ImageViewer. Note that the ImageViewer will automatically call this method when the plugin is added to the ImageViewer. For example: ``` viewer += Plugin(...) ``` Also note that [`attach`](#skimage.viewer.plugins.Plugin.attach "skimage.viewer.plugins.Plugin.attach") automatically calls the filter function so that the image matches the filtered value specified by attached widgets. `clean_up()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/base.py#L232-L237) `closeEvent(event)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/base.py#L224-L230) On close disconnect all artists and events from ImageViewer. Note that artists must be appended to `self.artists`. `display_filtered_image(image)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/base.py#L196-L203) Display the filtered image on image viewer. If you don’t want to simply replace the displayed image with the filtered image (e.g., you want to display a transparent overlay), you can override this method. `filter_image(*widget_arg)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/base.py#L156-L172) Call `image_filter` with widget args and kwargs Note: [`display_filtered_image`](#skimage.viewer.plugins.Plugin.display_filtered_image "skimage.viewer.plugins.Plugin.display_filtered_image") is automatically called. `property filtered_image` Return filtered image. `image_changed = None` `image_viewer = 'Plugin is not attached to ImageViewer'` `name = 'Plugin'` `output()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/base.py#L244-L261) Return the plugin’s representation and data. Returns `imagearray, same shape as self.image_viewer.image, or None` The filtered image. `dataNone` Any data associated with the plugin. #### Notes Derived classes should override this method to return a tuple containing an *overlay* of the same shape of the image, and a *data* object. Either of these is optional: return `None` if you don’t want to return a value. `remove_image_artists()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/base.py#L239-L242) Remove artists that are connected to the image viewer. `show(main_window=True)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/base.py#L213-L222) Show plugin. `update_plugin(name, value)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/viewer/plugins/base.py#L205-L211) Update keyword parameters of the plugin itself. These parameters will typically be implemented as class properties so that they update the image or some other component.
programming_docs
scikit_image Module: color Module: color ============= | | | | --- | --- | | [`skimage.color.combine_stains`](#skimage.color.combine_stains "skimage.color.combine_stains")(stains, conv\_matrix) | Stain to RGB color space conversion. | | [`skimage.color.convert_colorspace`](#skimage.color.convert_colorspace "skimage.color.convert_colorspace")(arr, …) | Convert an image array to a new color space. | | [`skimage.color.deltaE_cie76`](#skimage.color.deltaE_cie76 "skimage.color.deltaE_cie76")(lab1, lab2) | Euclidean distance between two points in Lab color space | | [`skimage.color.deltaE_ciede2000`](#skimage.color.deltaE_ciede2000 "skimage.color.deltaE_ciede2000")(lab1, lab2[, …]) | Color difference as given by the CIEDE 2000 standard. | | [`skimage.color.deltaE_ciede94`](#skimage.color.deltaE_ciede94 "skimage.color.deltaE_ciede94")(lab1, lab2[, …]) | Color difference according to CIEDE 94 standard | | [`skimage.color.deltaE_cmc`](#skimage.color.deltaE_cmc "skimage.color.deltaE_cmc")(lab1, lab2[, kL, kC]) | Color difference from the CMC l:c standard. | | [`skimage.color.gray2rgb`](#skimage.color.gray2rgb "skimage.color.gray2rgb")(image[, alpha]) | Create an RGB representation of a gray-level image. | | [`skimage.color.gray2rgba`](#skimage.color.gray2rgba "skimage.color.gray2rgba")(image[, alpha]) | Create a RGBA representation of a gray-level image. | | [`skimage.color.grey2rgb`](#skimage.color.grey2rgb "skimage.color.grey2rgb")(image[, alpha]) | Create an RGB representation of a gray-level image. | | [`skimage.color.hed2rgb`](#skimage.color.hed2rgb "skimage.color.hed2rgb")(hed) | Haematoxylin-Eosin-DAB (HED) to RGB color space conversion. | | [`skimage.color.hsv2rgb`](#skimage.color.hsv2rgb "skimage.color.hsv2rgb")(hsv) | HSV to RGB color space conversion. | | [`skimage.color.lab2lch`](#skimage.color.lab2lch "skimage.color.lab2lch")(lab) | CIE-LAB to CIE-LCH color space conversion. | | [`skimage.color.lab2rgb`](#skimage.color.lab2rgb "skimage.color.lab2rgb")(lab[, illuminant, …]) | Lab to RGB color space conversion. | | [`skimage.color.lab2xyz`](#skimage.color.lab2xyz "skimage.color.lab2xyz")(lab[, illuminant, …]) | CIE-LAB to XYZcolor space conversion. | | [`skimage.color.label2rgb`](#skimage.color.label2rgb "skimage.color.label2rgb")(label[, image, …]) | Return an RGB image where color-coded labels are painted over the image. | | [`skimage.color.lch2lab`](#skimage.color.lch2lab "skimage.color.lch2lab")(lch) | CIE-LCH to CIE-LAB color space conversion. | | [`skimage.color.rgb2gray`](#skimage.color.rgb2gray "skimage.color.rgb2gray")(rgb) | Compute luminance of an RGB image. | | [`skimage.color.rgb2grey`](#skimage.color.rgb2grey "skimage.color.rgb2grey")(rgb) | Compute luminance of an RGB image. | | [`skimage.color.rgb2hed`](#skimage.color.rgb2hed "skimage.color.rgb2hed")(rgb) | RGB to Haematoxylin-Eosin-DAB (HED) color space conversion. | | [`skimage.color.rgb2hsv`](#skimage.color.rgb2hsv "skimage.color.rgb2hsv")(rgb) | RGB to HSV color space conversion. | | [`skimage.color.rgb2lab`](#skimage.color.rgb2lab "skimage.color.rgb2lab")(rgb[, illuminant, …]) | Conversion from the sRGB color space (IEC 61966-2-1:1999) to the CIE Lab colorspace under the given illuminant and observer. | | [`skimage.color.rgb2rgbcie`](#skimage.color.rgb2rgbcie "skimage.color.rgb2rgbcie")(rgb) | RGB to RGB CIE color space conversion. | | [`skimage.color.rgb2xyz`](#skimage.color.rgb2xyz "skimage.color.rgb2xyz")(rgb) | RGB to XYZ color space conversion. | | [`skimage.color.rgb2ycbcr`](#skimage.color.rgb2ycbcr "skimage.color.rgb2ycbcr")(rgb) | RGB to YCbCr color space conversion. | | [`skimage.color.rgb2ydbdr`](#skimage.color.rgb2ydbdr "skimage.color.rgb2ydbdr")(rgb) | RGB to YDbDr color space conversion. | | [`skimage.color.rgb2yiq`](#skimage.color.rgb2yiq "skimage.color.rgb2yiq")(rgb) | RGB to YIQ color space conversion. | | [`skimage.color.rgb2ypbpr`](#skimage.color.rgb2ypbpr "skimage.color.rgb2ypbpr")(rgb) | RGB to YPbPr color space conversion. | | [`skimage.color.rgb2yuv`](#skimage.color.rgb2yuv "skimage.color.rgb2yuv")(rgb) | RGB to YUV color space conversion. | | [`skimage.color.rgba2rgb`](#skimage.color.rgba2rgb "skimage.color.rgba2rgb")(rgba[, background]) | RGBA to RGB conversion using alpha blending [[1]](#rd9bc87eaa392-1). | | [`skimage.color.rgbcie2rgb`](#skimage.color.rgbcie2rgb "skimage.color.rgbcie2rgb")(rgbcie) | RGB CIE to RGB color space conversion. | | [`skimage.color.separate_stains`](#skimage.color.separate_stains "skimage.color.separate_stains")(rgb, conv\_matrix) | RGB to stain color space conversion. | | [`skimage.color.xyz2lab`](#skimage.color.xyz2lab "skimage.color.xyz2lab")(xyz[, illuminant, …]) | XYZ to CIE-LAB color space conversion. | | [`skimage.color.xyz2rgb`](#skimage.color.xyz2rgb "skimage.color.xyz2rgb")(xyz) | XYZ to RGB color space conversion. | | [`skimage.color.ycbcr2rgb`](#skimage.color.ycbcr2rgb "skimage.color.ycbcr2rgb")(ycbcr) | YCbCr to RGB color space conversion. | | [`skimage.color.ydbdr2rgb`](#skimage.color.ydbdr2rgb "skimage.color.ydbdr2rgb")(ydbdr) | YDbDr to RGB color space conversion. | | [`skimage.color.yiq2rgb`](#skimage.color.yiq2rgb "skimage.color.yiq2rgb")(yiq) | YIQ to RGB color space conversion. | | [`skimage.color.ypbpr2rgb`](#skimage.color.ypbpr2rgb "skimage.color.ypbpr2rgb")(ypbpr) | YPbPr to RGB color space conversion. | | [`skimage.color.yuv2rgb`](#skimage.color.yuv2rgb "skimage.color.yuv2rgb")(yuv) | YUV to RGB color space conversion. | combine\_stains --------------- `skimage.color.combine_stains(stains, conv_matrix)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L1457-L1518) Stain to RGB color space conversion. Parameters `stains(…, 3) array_like` The image in stain color space. Final dimension denotes channels. **conv\_matrix: ndarray** The stain separation matrix as described by G. Landini [[1]](#r33a9a7d2e90f-1). Returns `out(…, 3) ndarray` The image in RGB format. Same dimensions as input. Raises ValueError If `stains` is not at least 2-D with shape (…, 3). #### Notes Stain combination matrices available in the `color` module and their respective colorspace: * `rgb_from_hed`: Hematoxylin + Eosin + DAB * `rgb_from_hdx`: Hematoxylin + DAB * `rgb_from_fgx`: Feulgen + Light Green * `rgb_from_bex`: Giemsa stain : Methyl Blue + Eosin * `rgb_from_rbd`: FastRed + FastBlue + DAB * `rgb_from_gdx`: Methyl Green + DAB * `rgb_from_hax`: Hematoxylin + AEC * `rgb_from_bro`: Blue matrix Anilline Blue + Red matrix Azocarmine + Orange matrix Orange-G * `rgb_from_bpx`: Methyl Blue + Ponceau Fuchsin * `rgb_from_ahx`: Alcian Blue + Hematoxylin * `rgb_from_hpx`: Hematoxylin + PAS #### References `1` <https://web.archive.org/web/20160624145052/http://www.mecourse.com/landinig/software/cdeconv/cdeconv.html> `2` A. C. Ruifrok and D. A. Johnston, β€œQuantification of histochemical staining by color deconvolution,” Anal. Quant. Cytol. Histol., vol. 23, no. 4, pp. 291–299, Aug. 2001. #### Examples ``` >>> from skimage import data >>> from skimage.color import (separate_stains, combine_stains, ... hdx_from_rgb, rgb_from_hdx) >>> ihc = data.immunohistochemistry() >>> ihc_hdx = separate_stains(ihc, hdx_from_rgb) >>> ihc_rgb = combine_stains(ihc_hdx, rgb_from_hdx) ``` convert\_colorspace ------------------- `skimage.color.convert_colorspace(arr, fromspace, tospace)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L60-L115) Convert an image array to a new color space. Valid color spaces are: β€˜RGB’, β€˜HSV’, β€˜RGB CIE’, β€˜XYZ’, β€˜YUV’, β€˜YIQ’, β€˜YPbPr’, β€˜YCbCr’, β€˜YDbDr’ Parameters `arr(…, 3) array_like` The image to convert. Final dimension denotes channels. `fromspacestr` The color space to convert from. Can be specified in lower case. `tospacestr` The color space to convert to. Can be specified in lower case. Returns `out(…, 3) ndarray` The converted image. Same dimensions as input. Raises ValueError If fromspace is not a valid color space ValueError If tospace is not a valid color space #### Notes Conversion is performed through the β€œcentral” RGB color space, i.e. conversion from XYZ to HSV is implemented as `XYZ -> RGB -> HSV` instead of directly. #### Examples ``` >>> from skimage import data >>> img = data.astronaut() >>> img_hsv = convert_colorspace(img, 'RGB', 'HSV') ``` deltaE\_cie76 ------------- `skimage.color.deltaE_cie76(lab1, lab2)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/delta_e.py#L26-L51) Euclidean distance between two points in Lab color space Parameters `lab1array_like` reference color (Lab colorspace) `lab2array_like` comparison color (Lab colorspace) Returns `dEarray_like` distance between colors `lab1` and `lab2` #### References `1` <https://en.wikipedia.org/wiki/Color_difference> `2` A. R. Robertson, β€œThe CIE 1976 color-difference formulae,” Color Res. Appl. 2, 7-11 (1977). deltaE\_ciede2000 ----------------- `skimage.color.deltaE_ciede2000(lab1, lab2, kL=1, kC=1, kH=1)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/delta_e.py#L122-L244) Color difference as given by the CIEDE 2000 standard. CIEDE 2000 is a major revision of CIDE94. The perceptual calibration is largely based on experience with automotive paint on smooth surfaces. Parameters `lab1array_like` reference color (Lab colorspace) `lab2array_like` comparison color (Lab colorspace) `kLfloat (range), optional` lightness scale factor, 1 for β€œacceptably close”; 2 for β€œimperceptible” see deltaE\_cmc `kCfloat (range), optional` chroma scale factor, usually 1 `kHfloat (range), optional` hue scale factor, usually 1 Returns `deltaEarray_like` The distance between `lab1` and `lab2` #### Notes CIEDE 2000 assumes parametric weighting factors for the lightness, chroma, and hue (`kL`, `kC`, `kH` respectively). These default to 1. #### References `1` <https://en.wikipedia.org/wiki/Color_difference> `2` <http://www.ece.rochester.edu/~gsharma/ciede2000/ciede2000noteCRNA.pdf> [DOI:10.1364/AO.33.008069](https://doi.org/10.1364/AO.33.008069) `3` M. Melgosa, J. Quesada, and E. Hita, β€œUniformity of some recent color metrics tested with an accurate color-difference tolerance dataset,” Appl. Opt. 33, 8069-8077 (1994). deltaE\_ciede94 --------------- `skimage.color.deltaE_ciede94(lab1, lab2, kH=1, kC=1, kL=1, k1=0.045, k2=0.015)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/delta_e.py#L54-L119) Color difference according to CIEDE 94 standard Accommodates perceptual non-uniformities through the use of application specific scale factors (`kH`, `kC`, `kL`, `k1`, and `k2`). Parameters `lab1array_like` reference color (Lab colorspace) `lab2array_like` comparison color (Lab colorspace) `kHfloat, optional` Hue scale `kCfloat, optional` Chroma scale `kLfloat, optional` Lightness scale `k1float, optional` first scale parameter `k2float, optional` second scale parameter Returns `dEarray_like` color difference between `lab1` and `lab2` #### Notes deltaE\_ciede94 is not symmetric with respect to lab1 and lab2. CIEDE94 defines the scales for the lightness, hue, and chroma in terms of the first color. Consequently, the first color should be regarded as the β€œreference” color. `kL`, `k1`, `k2` depend on the application and default to the values suggested for graphic arts | Parameter | Graphic Arts | Textiles | | --- | --- | --- | | `kL` | 1.000 | 2.000 | | `k1` | 0.045 | 0.048 | | `k2` | 0.015 | 0.014 | #### References `1` <https://en.wikipedia.org/wiki/Color_difference> `2` <http://www.brucelindbloom.com/index.html?Eqn_DeltaE_CIE94.html> deltaE\_cmc ----------- `skimage.color.deltaE_cmc(lab1, lab2, kL=1, kC=1)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/delta_e.py#L247-L308) Color difference from the CMC l:c standard. This color difference was developed by the Colour Measurement Committee (CMC) of the Society of Dyers and Colourists (United Kingdom). It is intended for use in the textile industry. The scale factors `kL`, `kC` set the weight given to differences in lightness and chroma relative to differences in hue. The usual values are `kL=2`, `kC=1` for β€œacceptability” and `kL=1`, `kC=1` for β€œimperceptibility”. Colors with `dE > 1` are β€œdifferent” for the given scale factors. Parameters `lab1array_like` reference color (Lab colorspace) `lab2array_like` comparison color (Lab colorspace) Returns `dEarray_like` distance between colors `lab1` and `lab2` #### Notes deltaE\_cmc the defines the scales for the lightness, hue, and chroma in terms of the first color. Consequently `deltaE_cmc(lab1, lab2) != deltaE_cmc(lab2, lab1)` #### References `1` <https://en.wikipedia.org/wiki/Color_difference> `2` <http://www.brucelindbloom.com/index.html?Eqn_DeltaE_CIE94.html> `3` F. J. J. Clarke, R. McDonald, and B. Rigg, β€œModification to the JPC79 colour-difference formula,” J. Soc. Dyers Colour. 100, 128-132 (1984). gray2rgb -------- `skimage.color.gray2rgb(image, alpha=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L834-L896) Create an RGB representation of a gray-level image. Parameters `imagearray_like` Input image. `alphabool, optional` Ensure that the output image has an alpha layer. If None, alpha layers are passed through but not created. Returns `rgb(…, 3) ndarray` RGB image. A new dimension of length 3 is added to input image. #### Notes If the input is a 1-dimensional image of shape `(M, )`, the output will be shape `(M, 3)`. ### Examples using `skimage.color.gray2rgb` [Tinting gray-scale images](https://scikit-image.org/docs/0.18.x/auto_examples/color_exposure/plot_tinting_grayscale_images.html#sphx-glr-auto-examples-color-exposure-plot-tinting-grayscale-images-py) gray2rgba --------- `skimage.color.gray2rgba(image, alpha=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L797-L831) Create a RGBA representation of a gray-level image. Parameters `imagearray_like` Input image. `alphaarray_like, optional` Alpha channel of the output image. It may be a scalar or an array that can be broadcast to `image`. If not specified it is set to the maximum limit corresponding to the `image` dtype. Returns `rgbandarray` RGBA image. A new dimension of length 4 is added to input image shape. grey2rgb -------- `skimage.color.grey2rgb(image, alpha=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L834-L896) Create an RGB representation of a gray-level image. Parameters `imagearray_like` Input image. `alphabool, optional` Ensure that the output image has an alpha layer. If None, alpha layers are passed through but not created. Returns `rgb(…, 3) ndarray` RGB image. A new dimension of length 3 is added to input image. #### Notes If the input is a 1-dimensional image of shape `(M, )`, the output will be shape `(M, 3)`. hed2rgb ------- `skimage.color.hed2rgb(hed)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L1355-L1388) Haematoxylin-Eosin-DAB (HED) to RGB color space conversion. Parameters `hed(…, 3) array_like` The image in the HED color space. Final dimension denotes channels. Returns `out(…, 3) ndarray` The image in RGB. Same dimensions as input. Raises ValueError If `hed` is not at least 2-D with shape (…, 3). #### References `1` A. C. Ruifrok and D. A. Johnston, β€œQuantification of histochemical staining by color deconvolution.,” Analytical and quantitative cytology and histology / the International Academy of Cytology [and] American Society of Cytology, vol. 23, no. 4, pp. 291-9, Aug. 2001. #### Examples ``` >>> from skimage import data >>> from skimage.color import rgb2hed, hed2rgb >>> ihc = data.immunohistochemistry() >>> ihc_hed = rgb2hed(ihc) >>> ihc_rgb = hed2rgb(ihc_hed) ``` hsv2rgb ------- `skimage.color.hsv2rgb(hsv)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L272-L324) HSV to RGB color space conversion. Parameters `hsv(…, 3) array_like` The image in HSV format. Final dimension denotes channels. Returns `out(…, 3) ndarray` The image in RGB format. Same dimensions as input. Raises ValueError If `hsv` is not at least 2-D with shape (…, 3). #### Notes Conversion between RGB and HSV color spaces results in some loss of precision, due to integer arithmetic and rounding [[1]](#r933d6ba7a3ec-1). #### References `1` <https://en.wikipedia.org/wiki/HSL_and_HSV> #### Examples ``` >>> from skimage import data >>> img = data.astronaut() >>> img_hsv = rgb2hsv(img) >>> img_rgb = hsv2rgb(img_hsv) ``` ### Examples using `skimage.color.hsv2rgb` [Tinting gray-scale images](https://scikit-image.org/docs/0.18.x/auto_examples/color_exposure/plot_tinting_grayscale_images.html#sphx-glr-auto-examples-color-exposure-plot-tinting-grayscale-images-py) [Flood Fill](https://scikit-image.org/docs/0.18.x/auto_examples/segmentation/plot_floodfill.html#sphx-glr-auto-examples-segmentation-plot-floodfill-py) lab2lch ------- `skimage.color.lab2lch(lab)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L1521-L1559) CIE-LAB to CIE-LCH color space conversion. LCH is the cylindrical representation of the LAB (Cartesian) colorspace Parameters `lab(…, 3) array_like` The N-D image in CIE-LAB format. The last (`N+1`-th) dimension must have at least 3 elements, corresponding to the `L`, `a`, and `b` color channels. Subsequent elements are copied. Returns `out(…, 3) ndarray` The image in LCH format, in a N-D array with same shape as input `lab`. Raises ValueError If `lch` does not have at least 3 color channels (i.e. l, a, b). #### Notes The Hue is expressed as an angle between `(0, 2*pi)` #### Examples ``` >>> from skimage import data >>> from skimage.color import rgb2lab, lab2lch >>> img = data.astronaut() >>> img_lab = rgb2lab(img) >>> img_lch = lab2lch(img_lab) ``` lab2rgb ------- `skimage.color.lab2rgb(lab, illuminant='D65', observer='2')` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L1076-L1109) Lab to RGB color space conversion. Parameters `lab(…, 3) array_like` The image in Lab format. Final dimension denotes channels. `illuminant{β€œA”, β€œD50”, β€œD55”, β€œD65”, β€œD75”, β€œE”}, optional` The name of the illuminant (the function is NOT case sensitive). `observer{β€œ2”, β€œ10”}, optional` The aperture angle of the observer. Returns `out(…, 3) ndarray` The image in RGB format. Same dimensions as input. Raises ValueError If `lab` is not at least 2-D with shape (…, 3). #### Notes This function uses lab2xyz and xyz2rgb. By default Observer= 2A, Illuminant= D65. CIE XYZ tristimulus values x\_ref=95.047, y\_ref=100., z\_ref=108.883. See function `get_xyz_coords` for a list of supported illuminants. #### References `1` <https://en.wikipedia.org/wiki/Standard_illuminant> lab2xyz ------- `skimage.color.lab2xyz(lab, illuminant='D65', observer='2')` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L972-L1032) CIE-LAB to XYZcolor space conversion. Parameters `lab(…, 3) array_like` The image in Lab format. Final dimension denotes channels. `illuminant{β€œA”, β€œD50”, β€œD55”, β€œD65”, β€œD75”, β€œE”}, optional` The name of the illuminant (the function is NOT case sensitive). `observer{β€œ2”, β€œ10”}, optional` The aperture angle of the observer. Returns `out(…, 3) ndarray` The image in XYZ format. Same dimensions as input. Raises ValueError If `lab` is not at least 2-D with shape (…, 3). ValueError If either the illuminant or the observer angle are not supported or unknown. UserWarning If any of the pixels are invalid (Z < 0). #### Notes By default Observer= 2A, Illuminant= D65. CIE XYZ tristimulus values x\_ref = 95.047, y\_ref = 100., z\_ref = 108.883. See function β€˜get\_xyz\_coords’ for a list of supported illuminants. #### References `1` <http://www.easyrgb.com/index.php?X=MATH&H=07> `2` <https://en.wikipedia.org/wiki/Lab_color_space> label2rgb --------- `skimage.color.label2rgb(label, image=None, colors=None, alpha=0.3, bg_label=-1, bg_color=(0, 0, 0), image_alpha=1, kind='overlay')` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorlabel.py#L74-L118) Return an RGB image where color-coded labels are painted over the image. Parameters `labelarray, shape (M, N)` Integer array of labels with the same shape as `image`. `imagearray, shape (M, N, 3), optional` Image used as underlay for labels. If the input is an RGB image, it’s converted to grayscale before coloring. `colorslist, optional` List of colors. If the number of labels exceeds the number of colors, then the colors are cycled. `alphafloat [0, 1], optional` Opacity of colorized labels. Ignored if image is `None`. `bg_labelint, optional` Label that’s treated as the background. If `bg_label` is specified, `bg_color` is `None`, and `kind` is `overlay`, background is not painted by any colors. `bg_colorstr or array, optional` Background color. Must be a name in `color_dict` or RGB float values between [0, 1]. `image_alphafloat [0, 1], optional` Opacity of the image. `kindstring, one of {β€˜overlay’, β€˜avg’}` The kind of color image desired. β€˜overlay’ cycles over defined colors and overlays the colored labels over the original image. β€˜avg’ replaces each labeled segment with its average color, for a stained-class or pastel painting appearance. Returns `resultarray of float, shape (M, N, 3)` The result of blending a cycling colormap (`colors`) for each distinct value in `label` with the image, at a certain alpha value. ### Examples using `skimage.color.label2rgb` [Segment human cells (in mitosis)](https://scikit-image.org/docs/0.18.x/auto_examples/applications/plot_human_mitosis.html#sphx-glr-auto-examples-applications-plot-human-mitosis-py) lch2lab ------- `skimage.color.lch2lab(lch)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L1572-L1607) CIE-LCH to CIE-LAB color space conversion. LCH is the cylindrical representation of the LAB (Cartesian) colorspace Parameters `lch(…, 3) array_like` The N-D image in CIE-LCH format. The last (`N+1`-th) dimension must have at least 3 elements, corresponding to the `L`, `a`, and `b` color channels. Subsequent elements are copied. Returns `out(…, 3) ndarray` The image in LAB format, with same shape as input `lch`. Raises ValueError If `lch` does not have at least 3 color channels (i.e. l, c, h). #### Examples ``` >>> from skimage import data >>> from skimage.color import rgb2lab, lch2lab >>> img = data.astronaut() >>> img_lab = rgb2lab(img) >>> img_lch = lab2lch(img_lab) >>> img_lab2 = lch2lab(img_lch) ``` rgb2gray -------- `skimage.color.rgb2gray(rgb)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L729-L787) Compute luminance of an RGB image. Parameters `rgb(…, 3) array_like` The image in RGB format. Final dimension denotes channels. Returns `outndarray` The luminance image - an array which is the same size as the input array, but with the channel dimension removed. Raises ValueError If `rgb` is not at least 2-D with shape (…, 3). #### Notes The weights used in this conversion are calibrated for contemporary CRT phosphors: ``` Y = 0.2125 R + 0.7154 G + 0.0721 B ``` If there is an alpha channel present, it is ignored. #### References `1` <http://poynton.ca/PDFs/ColorFAQ.pdf> #### Examples ``` >>> from skimage.color import rgb2gray >>> from skimage import data >>> img = data.astronaut() >>> img_gray = rgb2gray(img) ``` ### Examples using `skimage.color.rgb2gray` [Registration using optical flow](https://scikit-image.org/docs/0.18.x/auto_examples/registration/plot_opticalflow.html#sphx-glr-auto-examples-registration-plot-opticalflow-py) [Phase Unwrapping](https://scikit-image.org/docs/0.18.x/auto_examples/filters/plot_phase_unwrap.html#sphx-glr-auto-examples-filters-plot-phase-unwrap-py) rgb2grey -------- `skimage.color.rgb2grey(rgb)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L729-L787) Compute luminance of an RGB image. Parameters `rgb(…, 3) array_like` The image in RGB format. Final dimension denotes channels. Returns `outndarray` The luminance image - an array which is the same size as the input array, but with the channel dimension removed. Raises ValueError If `rgb` is not at least 2-D with shape (…, 3). #### Notes The weights used in this conversion are calibrated for contemporary CRT phosphors: ``` Y = 0.2125 R + 0.7154 G + 0.0721 B ``` If there is an alpha channel present, it is ignored. #### References `1` <http://poynton.ca/PDFs/ColorFAQ.pdf> #### Examples ``` >>> from skimage.color import rgb2gray >>> from skimage import data >>> img = data.astronaut() >>> img_gray = rgb2gray(img) ``` rgb2hed ------- `skimage.color.rgb2hed(rgb)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L1320-L1352) RGB to Haematoxylin-Eosin-DAB (HED) color space conversion. Parameters `rgb(…, 3) array_like` The image in RGB format. Final dimension denotes channels. Returns `out(…, 3) ndarray` The image in HED format. Same dimensions as input. Raises ValueError If `rgb` is not at least 2-D with shape (…, 3). #### References `1` A. C. Ruifrok and D. A. Johnston, β€œQuantification of histochemical staining by color deconvolution.,” Analytical and quantitative cytology and histology / the International Academy of Cytology [and] American Society of Cytology, vol. 23, no. 4, pp. 291-9, Aug. 2001. #### Examples ``` >>> from skimage import data >>> from skimage.color import rgb2hed >>> ihc = data.immunohistochemistry() >>> ihc_hed = rgb2hed(ihc) ``` rgb2hsv ------- `skimage.color.rgb2hsv(rgb)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L190-L269) RGB to HSV color space conversion. Parameters `rgb(…, 3) array_like` The image in RGB format. Final dimension denotes channels. Returns `out(…, 3) ndarray` The image in HSV format. Same dimensions as input. Raises ValueError If `rgb` is not at least 2-D with shape (…, 3). #### Notes Conversion between RGB and HSV color spaces results in some loss of precision, due to integer arithmetic and rounding [[1]](#r80b4a664a365-1). #### References `1` <https://en.wikipedia.org/wiki/HSL_and_HSV> #### Examples ``` >>> from skimage import color >>> from skimage import data >>> img = data.astronaut() >>> img_hsv = color.rgb2hsv(img) ``` ### Examples using `skimage.color.rgb2hsv` [Tinting gray-scale images](https://scikit-image.org/docs/0.18.x/auto_examples/color_exposure/plot_tinting_grayscale_images.html#sphx-glr-auto-examples-color-exposure-plot-tinting-grayscale-images-py) [Flood Fill](https://scikit-image.org/docs/0.18.x/auto_examples/segmentation/plot_floodfill.html#sphx-glr-auto-examples-segmentation-plot-floodfill-py) rgb2lab ------- `skimage.color.rgb2lab(rgb, illuminant='D65', observer='2')` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L1035-L1073) Conversion from the sRGB color space (IEC 61966-2-1:1999) to the CIE Lab colorspace under the given illuminant and observer. Parameters `rgb(…, 3) array_like` The image in RGB format. Final dimension denotes channels. `illuminant{β€œA”, β€œD50”, β€œD55”, β€œD65”, β€œD75”, β€œE”}, optional` The name of the illuminant (the function is NOT case sensitive). `observer{β€œ2”, β€œ10”}, optional` The aperture angle of the observer. Returns `out(…, 3) ndarray` The image in Lab format. Same dimensions as input. Raises ValueError If `rgb` is not at least 2-D with shape (…, 3). #### Notes RGB is a device-dependent color space so, if you use this function, be sure that the image you are analyzing has been mapped to the sRGB color space. This function uses rgb2xyz and xyz2lab. By default Observer= 2A, Illuminant= D65. CIE XYZ tristimulus values x\_ref=95.047, y\_ref=100., z\_ref=108.883. See function `get_xyz_coords` for a list of supported illuminants. #### References `1` <https://en.wikipedia.org/wiki/Standard_illuminant> rgb2rgbcie ---------- `skimage.color.rgb2rgbcie(rgb)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L664-L693) RGB to RGB CIE color space conversion. Parameters `rgb(…, 3) array_like` The image in RGB format. Final dimension denotes channels. Returns `out(…, 3) ndarray` The image in RGB CIE format. Same dimensions as input. Raises ValueError If `rgb` is not at least 2-D with shape (…, 3). #### References `1` <https://en.wikipedia.org/wiki/CIE_1931_color_space> #### Examples ``` >>> from skimage import data >>> from skimage.color import rgb2rgbcie >>> img = data.astronaut() >>> img_rgbcie = rgb2rgbcie(img) ``` rgb2xyz ------- `skimage.color.rgb2xyz(rgb)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L622-L661) RGB to XYZ color space conversion. Parameters `rgb(…, 3) array_like` The image in RGB format. Final dimension denotes channels. Returns `out(…, 3) ndarray` The image in XYZ format. Same dimensions as input. Raises ValueError If `rgb` is not at least 2-D with shape (…, 3). #### Notes The CIE XYZ color space is derived from the CIE RGB color space. Note however that this function converts from sRGB. #### References `1` <https://en.wikipedia.org/wiki/CIE_1931_color_space> #### Examples ``` >>> from skimage import data >>> img = data.astronaut() >>> img_xyz = rgb2xyz(img) ``` rgb2ycbcr --------- `skimage.color.rgb2ycbcr(rgb)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L1699-L1730) RGB to YCbCr color space conversion. Parameters `rgb(…, 3) array_like` The image in RGB format. Final dimension denotes channels. Returns `out(…, 3) ndarray` The image in YCbCr format. Same dimensions as input. Raises ValueError If `rgb` is not at least 2-D with shape (…, 3). #### Notes Y is between 16 and 235. This is the color space commonly used by video codecs; it is sometimes incorrectly called β€œYUV”. #### References `1` <https://en.wikipedia.org/wiki/YCbCr> rgb2ydbdr --------- `skimage.color.rgb2ydbdr(rgb)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L1733-L1761) RGB to YDbDr color space conversion. Parameters `rgb(…, 3) array_like` The image in RGB format. Final dimension denotes channels. Returns `out(…, 3) ndarray` The image in YDbDr format. Same dimensions as input. Raises ValueError If `rgb` is not at least 2-D with shape (…, 3). #### Notes This is the color space commonly used by video codecs. It is also the reversible color transform in JPEG2000. #### References `1` <https://en.wikipedia.org/wiki/YDbDr> rgb2yiq ------- `skimage.color.rgb2yiq(rgb)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L1653-L1671) RGB to YIQ color space conversion. Parameters `rgb(…, 3) array_like` The image in RGB format. Final dimension denotes channels. Returns `out(…, 3) ndarray` The image in YIQ format. Same dimensions as input. Raises ValueError If `rgb` is not at least 2-D with shape (…, 3). rgb2ypbpr --------- `skimage.color.rgb2ypbpr(rgb)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L1674-L1696) RGB to YPbPr color space conversion. Parameters `rgb(…, 3) array_like` The image in RGB format. Final dimension denotes channels. Returns `out(…, 3) ndarray` The image in YPbPr format. Same dimensions as input. Raises ValueError If `rgb` is not at least 2-D with shape (…, 3). #### References `1` <https://en.wikipedia.org/wiki/YPbPr> rgb2yuv ------- `skimage.color.rgb2yuv(rgb)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L1623-L1650) RGB to YUV color space conversion. Parameters `rgb(…, 3) array_like` The image in RGB format. Final dimension denotes channels. Returns `out(…, 3) ndarray` The image in YUV format. Same dimensions as input. Raises ValueError If `rgb` is not at least 2-D with shape (…, 3). #### Notes Y is between 0 and 1. Use YCbCr instead of YUV for the color space commonly used by video codecs, where Y ranges from 16 to 235. #### References `1` <https://en.wikipedia.org/wiki/YUV> rgba2rgb -------- `skimage.color.rgba2rgb(rgba, background=(1, 1, 1))` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L131-L187) RGBA to RGB conversion using alpha blending [[1]](#rd9bc87eaa392-1). Parameters `rgba(…, 4) array_like` The image in RGBA format. Final dimension denotes channels. `backgroundarray_like` The color of the background to blend the image with (3 floats between 0 to 1 - the RGB value of the background). Returns `out(…, 3) ndarray` The image in RGB format. Same dimensions as input. Raises ValueError If `rgba` is not at least 2-D with shape (…, 4). #### References `1(1,2)` <https://en.wikipedia.org/wiki/Alpha_compositing#Alpha_blending> #### Examples ``` >>> from skimage import color >>> from skimage import data >>> img_rgba = data.logo() >>> img_rgb = color.rgba2rgb(img_rgba) ``` rgbcie2rgb ---------- `skimage.color.rgbcie2rgb(rgbcie)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L696-L726) RGB CIE to RGB color space conversion. Parameters `rgbcie(…, 3) array_like` The image in RGB CIE format. Final dimension denotes channels. Returns `out(…, 3) ndarray` The image in RGB format. Same dimensions as input. Raises ValueError If `rgbcie` is not at least 2-D with shape (…, 3). #### References `1` <https://en.wikipedia.org/wiki/CIE_1931_color_space> #### Examples ``` >>> from skimage import data >>> from skimage.color import rgb2rgbcie, rgbcie2rgb >>> img = data.astronaut() >>> img_rgbcie = rgb2rgbcie(img) >>> img_rgb = rgbcie2rgb(img_rgbcie) ``` separate\_stains ---------------- `skimage.color.separate_stains(rgb, conv_matrix)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L1391-L1454) RGB to stain color space conversion. Parameters `rgb(…, 3) array_like` The image in RGB format. Final dimension denotes channels. **conv\_matrix: ndarray** The stain separation matrix as described by G. Landini [[1]](#re5603a4e7517-1). Returns `out(…, 3) ndarray` The image in stain color space. Same dimensions as input. Raises ValueError If `rgb` is not at least 2-D with shape (…, 3). #### Notes Stain separation matrices available in the `color` module and their respective colorspace: * `hed_from_rgb`: Hematoxylin + Eosin + DAB * `hdx_from_rgb`: Hematoxylin + DAB * `fgx_from_rgb`: Feulgen + Light Green * `bex_from_rgb`: Giemsa stain : Methyl Blue + Eosin * `rbd_from_rgb`: FastRed + FastBlue + DAB * `gdx_from_rgb`: Methyl Green + DAB * `hax_from_rgb`: Hematoxylin + AEC * `bro_from_rgb`: Blue matrix Anilline Blue + Red matrix Azocarmine + Orange matrix Orange-G * `bpx_from_rgb`: Methyl Blue + Ponceau Fuchsin * `ahx_from_rgb`: Alcian Blue + Hematoxylin * `hpx_from_rgb`: Hematoxylin + PAS This implementation borrows some ideas from DIPlib [[2]](#re5603a4e7517-2), e.g. the compensation using a small value to avoid log artifacts when calculating the Beer-Lambert law. #### References `1` <https://web.archive.org/web/20160624145052/http://www.mecourse.com/landinig/software/cdeconv/cdeconv.html> `2` <https://github.com/DIPlib/diplib/> `3` A. C. Ruifrok and D. A. Johnston, β€œQuantification of histochemical staining by color deconvolution,” Anal. Quant. Cytol. Histol., vol. 23, no. 4, pp. 291–299, Aug. 2001. #### Examples ``` >>> from skimage import data >>> from skimage.color import separate_stains, hdx_from_rgb >>> ihc = data.immunohistochemistry() >>> ihc_hdx = separate_stains(ihc, hdx_from_rgb) ``` xyz2lab ------- `skimage.color.xyz2lab(xyz, illuminant='D65', observer='2')` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L906-L969) XYZ to CIE-LAB color space conversion. Parameters `xyz(…, 3) array_like` The image in XYZ format. Final dimension denotes channels. `illuminant{β€œA”, β€œD50”, β€œD55”, β€œD65”, β€œD75”, β€œE”}, optional` The name of the illuminant (the function is NOT case sensitive). `observer{β€œ2”, β€œ10”}, optional` The aperture angle of the observer. Returns `out(…, 3) ndarray` The image in CIE-LAB format. Same dimensions as input. Raises ValueError If `xyz` is not at least 2-D with shape (…, 3). ValueError If either the illuminant or the observer angle is unsupported or unknown. #### Notes By default Observer= 2A, Illuminant= D65. CIE XYZ tristimulus values x\_ref=95.047, y\_ref=100., z\_ref=108.883. See function `get_xyz_coords` for a list of supported illuminants. #### References `1` <http://www.easyrgb.com/index.php?X=MATH&H=07> `2` <https://en.wikipedia.org/wiki/Lab_color_space> #### Examples ``` >>> from skimage import data >>> from skimage.color import rgb2xyz, xyz2lab >>> img = data.astronaut() >>> img_xyz = rgb2xyz(img) >>> img_lab = xyz2lab(img_xyz) ``` xyz2rgb ------- `skimage.color.xyz2rgb(xyz)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L577-L619) XYZ to RGB color space conversion. Parameters `xyz(…, 3) array_like` The image in XYZ format. Final dimension denotes channels. Returns `out(…, 3) ndarray` The image in RGB format. Same dimensions as input. Raises ValueError If `xyz` is not at least 2-D with shape (…, 3). #### Notes The CIE XYZ color space is derived from the CIE RGB color space. Note however that this function converts to sRGB. #### References `1` <https://en.wikipedia.org/wiki/CIE_1931_color_space> #### Examples ``` >>> from skimage import data >>> from skimage.color import rgb2xyz, xyz2rgb >>> img = data.astronaut() >>> img_xyz = rgb2xyz(img) >>> img_rgb = xyz2rgb(img_xyz) ``` ycbcr2rgb --------- `skimage.color.ycbcr2rgb(ycbcr)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L1835-L1866) YCbCr to RGB color space conversion. Parameters `ycbcr(…, 3) array_like` The image in YCbCr format. Final dimension denotes channels. Returns `out(…, 3) ndarray` The image in RGB format. Same dimensions as input. Raises ValueError If `ycbcr` is not at least 2-D with shape (…, 3). #### Notes Y is between 16 and 235. This is the color space commonly used by video codecs; it is sometimes incorrectly called β€œYUV”. #### References `1` <https://en.wikipedia.org/wiki/YCbCr> ydbdr2rgb --------- `skimage.color.ydbdr2rgb(ydbdr)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L1869-L1896) YDbDr to RGB color space conversion. Parameters `ydbdr(…, 3) array_like` The image in YDbDr format. Final dimension denotes channels. Returns `out(…, 3) ndarray` The image in RGB format. Same dimensions as input. Raises ValueError If `ydbdr` is not at least 2-D with shape (…, 3). #### Notes This is the color space commonly used by video codecs, also called the reversible color transform in JPEG2000. #### References `1` <https://en.wikipedia.org/wiki/YDbDr> yiq2rgb ------- `skimage.color.yiq2rgb(yiq)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L1789-L1807) YIQ to RGB color space conversion. Parameters `yiq(…, 3) array_like` The image in YIQ format. Final dimension denotes channels. Returns `out(…, 3) ndarray` The image in RGB format. Same dimensions as input. Raises ValueError If `yiq` is not at least 2-D with shape (…, 3). ypbpr2rgb --------- `skimage.color.ypbpr2rgb(ypbpr)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L1810-L1832) YPbPr to RGB color space conversion. Parameters `ypbpr(…, 3) array_like` The image in YPbPr format. Final dimension denotes channels. Returns `out(…, 3) ndarray` The image in RGB format. Same dimensions as input. Raises ValueError If `ypbpr` is not at least 2-D with shape (…, 3). #### References `1` <https://en.wikipedia.org/wiki/YPbPr> yuv2rgb ------- `skimage.color.yuv2rgb(yuv)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/color/colorconv.py#L1764-L1786) YUV to RGB color space conversion. Parameters `yuv(…, 3) array_like` The image in YUV format. Final dimension denotes channels. Returns `out(…, 3) ndarray` The image in RGB format. Same dimensions as input. Raises ValueError If `yuv` is not at least 2-D with shape (…, 3). #### References `1` <https://en.wikipedia.org/wiki/YUV>
programming_docs
scikit_image Module: feature Module: feature =============== | | | | --- | --- | | [`skimage.feature.blob_dog`](#skimage.feature.blob_dog "skimage.feature.blob_dog")(image[, min\_sigma, …]) | Finds blobs in the given grayscale image. | | [`skimage.feature.blob_doh`](#skimage.feature.blob_doh "skimage.feature.blob_doh")(image[, min\_sigma, …]) | Finds blobs in the given grayscale image. | | [`skimage.feature.blob_log`](#skimage.feature.blob_log "skimage.feature.blob_log")(image[, min\_sigma, …]) | Finds blobs in the given grayscale image. | | [`skimage.feature.canny`](#skimage.feature.canny "skimage.feature.canny")(image[, sigma, …]) | Edge filter an image using the Canny algorithm. | | [`skimage.feature.corner_fast`](#skimage.feature.corner_fast "skimage.feature.corner_fast")(image[, n, …]) | Extract FAST corners for a given image. | | [`skimage.feature.corner_foerstner`](#skimage.feature.corner_foerstner "skimage.feature.corner_foerstner")(image[, sigma]) | Compute Foerstner corner measure response image. | | [`skimage.feature.corner_harris`](#skimage.feature.corner_harris "skimage.feature.corner_harris")(image[, …]) | Compute Harris corner measure response image. | | [`skimage.feature.corner_kitchen_rosenfeld`](#skimage.feature.corner_kitchen_rosenfeld "skimage.feature.corner_kitchen_rosenfeld")(image) | Compute Kitchen and Rosenfeld corner measure response image. | | [`skimage.feature.corner_moravec`](#skimage.feature.corner_moravec "skimage.feature.corner_moravec")(image[, …]) | Compute Moravec corner measure response image. | | [`skimage.feature.corner_orientations`](#skimage.feature.corner_orientations "skimage.feature.corner_orientations")(image, …) | Compute the orientation of corners. | | [`skimage.feature.corner_peaks`](#skimage.feature.corner_peaks "skimage.feature.corner_peaks")(image[, …]) | Find peaks in corner measure response image. | | [`skimage.feature.corner_shi_tomasi`](#skimage.feature.corner_shi_tomasi "skimage.feature.corner_shi_tomasi")(image[, sigma]) | Compute Shi-Tomasi (Kanade-Tomasi) corner measure response image. | | [`skimage.feature.corner_subpix`](#skimage.feature.corner_subpix "skimage.feature.corner_subpix")(image, corners) | Determine subpixel position of corners. | | [`skimage.feature.daisy`](#skimage.feature.daisy "skimage.feature.daisy")(image[, step, radius, …]) | Extract DAISY feature descriptors densely for the given image. | | [`skimage.feature.draw_haar_like_feature`](#skimage.feature.draw_haar_like_feature "skimage.feature.draw_haar_like_feature")(…) | Visualization of Haar-like features. | | [`skimage.feature.draw_multiblock_lbp`](#skimage.feature.draw_multiblock_lbp "skimage.feature.draw_multiblock_lbp")(image, …) | Multi-block local binary pattern visualization. | | [`skimage.feature.greycomatrix`](#skimage.feature.greycomatrix "skimage.feature.greycomatrix")(image, …[, …]) | Calculate the grey-level co-occurrence matrix. | | [`skimage.feature.greycoprops`](#skimage.feature.greycoprops "skimage.feature.greycoprops")(P[, prop]) | Calculate texture properties of a GLCM. | | [`skimage.feature.haar_like_feature`](#skimage.feature.haar_like_feature "skimage.feature.haar_like_feature")(int\_image, …) | Compute the Haar-like features for a region of interest (ROI) of an integral image. | | [`skimage.feature.haar_like_feature_coord`](#skimage.feature.haar_like_feature_coord "skimage.feature.haar_like_feature_coord")(…) | Compute the coordinates of Haar-like features. | | [`skimage.feature.hessian_matrix`](#skimage.feature.hessian_matrix "skimage.feature.hessian_matrix")(image[, …]) | Compute Hessian matrix. | | [`skimage.feature.hessian_matrix_det`](#skimage.feature.hessian_matrix_det "skimage.feature.hessian_matrix_det")(image[, …]) | Compute the approximate Hessian Determinant over an image. | | [`skimage.feature.hessian_matrix_eigvals`](#skimage.feature.hessian_matrix_eigvals "skimage.feature.hessian_matrix_eigvals")(H\_elems) | Compute eigenvalues of Hessian matrix. | | [`skimage.feature.hog`](#skimage.feature.hog "skimage.feature.hog")(image[, orientations, …]) | Extract Histogram of Oriented Gradients (HOG) for a given image. | | [`skimage.feature.local_binary_pattern`](#skimage.feature.local_binary_pattern "skimage.feature.local_binary_pattern")(image, P, R) | Gray scale and rotation invariant LBP (Local Binary Patterns). | | [`skimage.feature.masked_register_translation`](#skimage.feature.masked_register_translation "skimage.feature.masked_register_translation")(…) | **Deprecated function**. | | [`skimage.feature.match_descriptors`](#skimage.feature.match_descriptors "skimage.feature.match_descriptors")(…[, …]) | Brute-force matching of descriptors. | | [`skimage.feature.match_template`](#skimage.feature.match_template "skimage.feature.match_template")(image, template) | Match a template to a 2-D or 3-D image using normalized correlation. | | [`skimage.feature.multiblock_lbp`](#skimage.feature.multiblock_lbp "skimage.feature.multiblock_lbp")(int\_image, r, …) | Multi-block local binary pattern (MB-LBP). | | [`skimage.feature.multiscale_basic_features`](#skimage.feature.multiscale_basic_features "skimage.feature.multiscale_basic_features")(image) | Local features for a single- or multi-channel nd image. | | [`skimage.feature.peak_local_max`](#skimage.feature.peak_local_max "skimage.feature.peak_local_max")(image[, …]) | Find peaks in an image as coordinate list or boolean mask. | | [`skimage.feature.plot_matches`](#skimage.feature.plot_matches "skimage.feature.plot_matches")(ax, image1, …) | Plot matched features. | | [`skimage.feature.register_translation`](#skimage.feature.register_translation "skimage.feature.register_translation")(…[, …]) | **Deprecated function**. | | [`skimage.feature.shape_index`](#skimage.feature.shape_index "skimage.feature.shape_index")(image[, sigma, …]) | Compute the shape index. | | [`skimage.feature.structure_tensor`](#skimage.feature.structure_tensor "skimage.feature.structure_tensor")(image[, …]) | Compute structure tensor using sum of squared differences. | | [`skimage.feature.structure_tensor_eigenvalues`](#skimage.feature.structure_tensor_eigenvalues "skimage.feature.structure_tensor_eigenvalues")(A\_elems) | Compute eigenvalues of structure tensor. | | [`skimage.feature.structure_tensor_eigvals`](#skimage.feature.structure_tensor_eigvals "skimage.feature.structure_tensor_eigvals")(…) | Compute eigenvalues of structure tensor. | | [`skimage.feature.BRIEF`](#skimage.feature.BRIEF "skimage.feature.BRIEF")([descriptor\_size, …]) | BRIEF binary descriptor extractor. | | [`skimage.feature.CENSURE`](#skimage.feature.CENSURE "skimage.feature.CENSURE")([min\_scale, …]) | CENSURE keypoint detector. | | [`skimage.feature.Cascade`](#skimage.feature.Cascade "skimage.feature.Cascade") | Class for cascade of classifiers that is used for object detection. | | [`skimage.feature.ORB`](#skimage.feature.ORB "skimage.feature.ORB")([downscale, n\_scales, …]) | Oriented FAST and rotated BRIEF feature detector and binary descriptor extractor. | blob\_dog --------- `skimage.feature.blob_dog(image, min_sigma=1, max_sigma=50, sigma_ratio=1.6, threshold=2.0, overlap=0.5, *, exclude_border=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/blob.py#L217-L375) Finds blobs in the given grayscale image. Blobs are found using the Difference of Gaussian (DoG) method [[1]](#rf5218630e229-1). For each blob found, the method returns its coordinates and the standard deviation of the Gaussian kernel that detected the blob. Parameters `image2D or 3D ndarray` Input grayscale image, blobs are assumed to be light on dark background (white on black). `min_sigmascalar or sequence of scalars, optional` The minimum standard deviation for Gaussian kernel. Keep this low to detect smaller blobs. The standard deviations of the Gaussian filter are given for each axis as a sequence, or as a single number, in which case it is equal for all axes. `max_sigmascalar or sequence of scalars, optional` The maximum standard deviation for Gaussian kernel. Keep this high to detect larger blobs. The standard deviations of the Gaussian filter are given for each axis as a sequence, or as a single number, in which case it is equal for all axes. `sigma_ratiofloat, optional` The ratio between the standard deviation of Gaussian Kernels used for computing the Difference of Gaussians `thresholdfloat, optional.` The absolute lower bound for scale space maxima. Local maxima smaller than thresh are ignored. Reduce this to detect blobs with less intensities. `overlapfloat, optional` A value between 0 and 1. If the area of two blobs overlaps by a fraction greater than `threshold`, the smaller blob is eliminated. `exclude_bordertuple of ints, int, or False, optional` If tuple of ints, the length of the tuple must match the input array’s dimensionality. Each element of the tuple will exclude peaks from within `exclude_border`-pixels of the border of the image along that dimension. If nonzero int, `exclude_border` excludes peaks from within `exclude_border`-pixels of the border of the image. If zero or False, peaks are identified regardless of their distance from the border. Returns `A(n, image.ndim + sigma) ndarray` A 2d array with each row representing 2 coordinate values for a 2D image, and 3 coordinate values for a 3D image, plus the sigma(s) used. When a single sigma is passed, outputs are: `(r, c, sigma)` or `(p, r, c, sigma)` where `(r, c)` or `(p, r, c)` are coordinates of the blob and `sigma` is the standard deviation of the Gaussian kernel which detected the blob. When an anisotropic gaussian is used (sigmas per dimension), the detected sigma is returned for each dimension. See also [`skimage.filters.difference_of_gaussians`](skimage.filters#skimage.filters.difference_of_gaussians "skimage.filters.difference_of_gaussians") #### Notes The radius of each blob is approximately \(\sqrt{2}\sigma\) for a 2-D image and \(\sqrt{3}\sigma\) for a 3-D image. #### References `1` <https://en.wikipedia.org/wiki/Blob_detection#The_difference_of_Gaussians_approach> #### Examples ``` >>> from skimage import data, feature >>> feature.blob_dog(data.coins(), threshold=.5, max_sigma=40) array([[120. , 272. , 16.777216], [193. , 213. , 16.777216], [263. , 245. , 16.777216], [185. , 347. , 16.777216], [128. , 154. , 10.48576 ], [198. , 155. , 10.48576 ], [124. , 337. , 10.48576 ], [ 45. , 336. , 16.777216], [195. , 102. , 16.777216], [125. , 45. , 16.777216], [261. , 173. , 16.777216], [194. , 277. , 16.777216], [127. , 102. , 10.48576 ], [125. , 208. , 10.48576 ], [267. , 115. , 10.48576 ], [263. , 302. , 16.777216], [196. , 43. , 10.48576 ], [260. , 46. , 16.777216], [267. , 359. , 16.777216], [ 54. , 276. , 10.48576 ], [ 58. , 100. , 10.48576 ], [ 52. , 155. , 16.777216], [ 52. , 216. , 16.777216], [ 54. , 42. , 16.777216]]) ``` blob\_doh --------- `skimage.feature.blob_doh(image, min_sigma=1, max_sigma=30, num_sigma=10, threshold=0.01, overlap=0.5, log_scale=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/blob.py#L538-L646) Finds blobs in the given grayscale image. Blobs are found using the Determinant of Hessian method [[1]](#ra19a7aed16ca-1). For each blob found, the method returns its coordinates and the standard deviation of the Gaussian Kernel used for the Hessian matrix whose determinant detected the blob. Determinant of Hessians is approximated using [[2]](#ra19a7aed16ca-2). Parameters `image2D ndarray` Input grayscale image.Blobs can either be light on dark or vice versa. `min_sigmafloat, optional` The minimum standard deviation for Gaussian Kernel used to compute Hessian matrix. Keep this low to detect smaller blobs. `max_sigmafloat, optional` The maximum standard deviation for Gaussian Kernel used to compute Hessian matrix. Keep this high to detect larger blobs. `num_sigmaint, optional` The number of intermediate values of standard deviations to consider between `min_sigma` and `max_sigma`. `thresholdfloat, optional.` The absolute lower bound for scale space maxima. Local maxima smaller than thresh are ignored. Reduce this to detect less prominent blobs. `overlapfloat, optional` A value between 0 and 1. If the area of two blobs overlaps by a fraction greater than `threshold`, the smaller blob is eliminated. `log_scalebool, optional` If set intermediate values of standard deviations are interpolated using a logarithmic scale to the base `10`. If not, linear interpolation is used. Returns `A(n, 3) ndarray` A 2d array with each row representing 3 values, `(y,x,sigma)` where `(y,x)` are coordinates of the blob and `sigma` is the standard deviation of the Gaussian kernel of the Hessian Matrix whose determinant detected the blob. #### Notes The radius of each blob is approximately `sigma`. Computation of Determinant of Hessians is independent of the standard deviation. Therefore detecting larger blobs won’t take more time. In methods line [`blob_dog()`](#skimage.feature.blob_dog "skimage.feature.blob_dog") and [`blob_log()`](#skimage.feature.blob_log "skimage.feature.blob_log") the computation of Gaussians for larger `sigma` takes more time. The downside is that this method can’t be used for detecting blobs of radius less than `3px` due to the box filters used in the approximation of Hessian Determinant. #### References `1` <https://en.wikipedia.org/wiki/Blob_detection#The_determinant_of_the_Hessian> `2` Herbert Bay, Andreas Ess, Tinne Tuytelaars, Luc Van Gool, β€œSURF: Speeded Up Robust Features” <ftp://ftp.vision.ee.ethz.ch/publications/articles/eth_biwi_00517.pdf> #### Examples ``` >>> from skimage import data, feature >>> img = data.coins() >>> feature.blob_doh(img) array([[197. , 153. , 20.33333333], [124. , 336. , 20.33333333], [126. , 153. , 20.33333333], [195. , 100. , 23.55555556], [192. , 212. , 23.55555556], [121. , 271. , 30. ], [126. , 101. , 20.33333333], [193. , 275. , 23.55555556], [123. , 205. , 20.33333333], [270. , 363. , 30. ], [265. , 113. , 23.55555556], [262. , 243. , 23.55555556], [185. , 348. , 30. ], [156. , 302. , 30. ], [123. , 44. , 23.55555556], [260. , 173. , 30. ], [197. , 44. , 20.33333333]]) ``` blob\_log --------- `skimage.feature.blob_log(image, min_sigma=1, max_sigma=50, num_sigma=10, threshold=0.2, overlap=0.5, log_scale=False, *, exclude_border=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/blob.py#L378-L535) Finds blobs in the given grayscale image. Blobs are found using the Laplacian of Gaussian (LoG) method [[1]](#r520e53dd5fa2-1). For each blob found, the method returns its coordinates and the standard deviation of the Gaussian kernel that detected the blob. Parameters `image2D or 3D ndarray` Input grayscale image, blobs are assumed to be light on dark background (white on black). `min_sigmascalar or sequence of scalars, optional` the minimum standard deviation for Gaussian kernel. Keep this low to detect smaller blobs. The standard deviations of the Gaussian filter are given for each axis as a sequence, or as a single number, in which case it is equal for all axes. `max_sigmascalar or sequence of scalars, optional` The maximum standard deviation for Gaussian kernel. Keep this high to detect larger blobs. The standard deviations of the Gaussian filter are given for each axis as a sequence, or as a single number, in which case it is equal for all axes. `num_sigmaint, optional` The number of intermediate values of standard deviations to consider between `min_sigma` and `max_sigma`. `thresholdfloat, optional.` The absolute lower bound for scale space maxima. Local maxima smaller than thresh are ignored. Reduce this to detect blobs with less intensities. `overlapfloat, optional` A value between 0 and 1. If the area of two blobs overlaps by a fraction greater than `threshold`, the smaller blob is eliminated. `log_scalebool, optional` If set intermediate values of standard deviations are interpolated using a logarithmic scale to the base `10`. If not, linear interpolation is used. `exclude_bordertuple of ints, int, or False, optional` If tuple of ints, the length of the tuple must match the input array’s dimensionality. Each element of the tuple will exclude peaks from within `exclude_border`-pixels of the border of the image along that dimension. If nonzero int, `exclude_border` excludes peaks from within `exclude_border`-pixels of the border of the image. If zero or False, peaks are identified regardless of their distance from the border. Returns `A(n, image.ndim + sigma) ndarray` A 2d array with each row representing 2 coordinate values for a 2D image, and 3 coordinate values for a 3D image, plus the sigma(s) used. When a single sigma is passed, outputs are: `(r, c, sigma)` or `(p, r, c, sigma)` where `(r, c)` or `(p, r, c)` are coordinates of the blob and `sigma` is the standard deviation of the Gaussian kernel which detected the blob. When an anisotropic gaussian is used (sigmas per dimension), the detected sigma is returned for each dimension. #### Notes The radius of each blob is approximately \(\sqrt{2}\sigma\) for a 2-D image and \(\sqrt{3}\sigma\) for a 3-D image. #### References `1` <https://en.wikipedia.org/wiki/Blob_detection#The_Laplacian_of_Gaussian> #### Examples ``` >>> from skimage import data, feature, exposure >>> img = data.coins() >>> img = exposure.equalize_hist(img) # improves detection >>> feature.blob_log(img, threshold = .3) array([[124. , 336. , 11.88888889], [198. , 155. , 11.88888889], [194. , 213. , 17.33333333], [121. , 272. , 17.33333333], [263. , 244. , 17.33333333], [194. , 276. , 17.33333333], [266. , 115. , 11.88888889], [128. , 154. , 11.88888889], [260. , 174. , 17.33333333], [198. , 103. , 11.88888889], [126. , 208. , 11.88888889], [127. , 102. , 11.88888889], [263. , 302. , 17.33333333], [197. , 44. , 11.88888889], [185. , 344. , 17.33333333], [126. , 46. , 11.88888889], [113. , 323. , 1. ]]) ``` canny ----- `skimage.feature.canny(image, sigma=1.0, low_threshold=None, high_threshold=None, mask=None, use_quantiles=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/_canny.py#L53-L297) Edge filter an image using the Canny algorithm. Parameters `image2D array` Grayscale input image to detect edges on; can be of any dtype. `sigmafloat, optional` Standard deviation of the Gaussian filter. `low_thresholdfloat, optional` Lower bound for hysteresis thresholding (linking edges). If None, low\_threshold is set to 10% of dtype’s max. `high_thresholdfloat, optional` Upper bound for hysteresis thresholding (linking edges). If None, high\_threshold is set to 20% of dtype’s max. `maskarray, dtype=bool, optional` Mask to limit the application of Canny to a certain area. `use_quantilesbool, optional` If True then treat low\_threshold and high\_threshold as quantiles of the edge magnitude image, rather than absolute edge magnitude values. If True then the thresholds must be in the range [0, 1]. Returns `output2D array (image)` The binary edge map. See also `skimage.sobel` #### Notes The steps of the algorithm are as follows: * Smooth the image using a Gaussian with `sigma` width. * Apply the horizontal and vertical Sobel operators to get the gradients within the image. The edge strength is the norm of the gradient. * Thin potential edges to 1-pixel wide curves. First, find the normal to the edge at each point. This is done by looking at the signs and the relative magnitude of the X-Sobel and Y-Sobel to sort the points into 4 categories: horizontal, vertical, diagonal and antidiagonal. Then look in the normal and reverse directions to see if the values in either of those directions are greater than the point in question. Use interpolation to get a mix of points instead of picking the one that’s the closest to the normal. * Perform a hysteresis thresholding: first label all points above the high threshold as edges. Then recursively label any point above the low threshold that is 8-connected to a labeled point as an edge. #### References `1` Canny, J., A Computational Approach To Edge Detection, IEEE Trans. Pattern Analysis and Machine Intelligence, 8:679-714, 1986 [DOI:10.1109/TPAMI.1986.4767851](https://doi.org/10.1109/TPAMI.1986.4767851) `2` William Green’s Canny tutorial <https://en.wikipedia.org/wiki/Canny_edge_detector> #### Examples ``` >>> from skimage import feature >>> # Generate noisy image of a square >>> im = np.zeros((256, 256)) >>> im[64:-64, 64:-64] = 1 >>> im += 0.2 * np.random.rand(*im.shape) >>> # First trial with the Canny filter, with the default smoothing >>> edges1 = feature.canny(im) >>> # Increase the smoothing for better results >>> edges2 = feature.canny(im, sigma=3) ``` corner\_fast ------------ `skimage.feature.corner_fast(image, n=12, threshold=0.15)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/corner.py#L762-L824) Extract FAST corners for a given image. Parameters `image2D ndarray` Input image. `nint, optional` Minimum number of consecutive pixels out of 16 pixels on the circle that should all be either brighter or darker w.r.t testpixel. A point c on the circle is darker w.r.t test pixel p if `Ic < Ip - threshold` and brighter if `Ic > Ip + threshold`. Also stands for the n in `FAST-n` corner detector. `thresholdfloat, optional` Threshold used in deciding whether the pixels on the circle are brighter, darker or similar w.r.t. the test pixel. Decrease the threshold when more corners are desired and vice-versa. Returns `responsendarray` FAST corner response image. #### References `1` Rosten, E., & Drummond, T. (2006, May). Machine learning for high-speed corner detection. In European conference on computer vision (pp. 430-443). Springer, Berlin, Heidelberg. [DOI:10.1007/11744023\_34](https://doi.org/10.1007/11744023_34) <http://www.edwardrosten.com/work/rosten_2006_machine.pdf> `2` Wikipedia, β€œFeatures from accelerated segment test”, <https://en.wikipedia.org/wiki/Features_from_accelerated_segment_test> #### Examples ``` >>> from skimage.feature import corner_fast, corner_peaks >>> square = np.zeros((12, 12)) >>> square[3:9, 3:9] = 1 >>> square.astype(int) array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0], [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0], [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0], [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0], [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0], [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]) >>> corner_peaks(corner_fast(square, 9), min_distance=1) array([[3, 3], [3, 8], [8, 3], [8, 8]]) ``` corner\_foerstner ----------------- `skimage.feature.corner_foerstner(image, sigma=1)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/corner.py#L678-L759) Compute Foerstner corner measure response image. This corner detector uses information from the auto-correlation matrix A: ``` A = [(imx**2) (imx*imy)] = [Axx Axy] [(imx*imy) (imy**2)] [Axy Ayy] ``` Where imx and imy are first derivatives, averaged with a gaussian filter. The corner measure is then defined as: ``` w = det(A) / trace(A) (size of error ellipse) q = 4 * det(A) / trace(A)**2 (roundness of error ellipse) ``` Parameters `imagendarray` Input image. `sigmafloat, optional` Standard deviation used for the Gaussian kernel, which is used as weighting function for the auto-correlation matrix. Returns `wndarray` Error ellipse sizes. `qndarray` Roundness of error ellipse. #### References `1` FΓΆrstner, W., & GΓΌlch, E. (1987, June). A fast operator for detection and precise location of distinct points, corners and centres of circular features. In Proc. ISPRS intercommission conference on fast processing of photogrammetric data (pp. 281-305). <https://cseweb.ucsd.edu/classes/sp02/cse252/foerstner/foerstner.pdf> `2` <https://en.wikipedia.org/wiki/Corner_detection> #### Examples ``` >>> from skimage.feature import corner_foerstner, corner_peaks >>> square = np.zeros([10, 10]) >>> square[2:8, 2:8] = 1 >>> square.astype(int) array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]) >>> w, q = corner_foerstner(square) >>> accuracy_thresh = 0.5 >>> roundness_thresh = 0.3 >>> foerstner = (q > roundness_thresh) * (w > accuracy_thresh) * w >>> corner_peaks(foerstner, min_distance=1) array([[2, 2], [2, 7], [7, 2], [7, 7]]) ``` corner\_harris -------------- `skimage.feature.corner_harris(image, method='k', k=0.05, eps=1e-06, sigma=1)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/corner.py#L536-L613) Compute Harris corner measure response image. This corner detector uses information from the auto-correlation matrix A: ``` A = [(imx**2) (imx*imy)] = [Axx Axy] [(imx*imy) (imy**2)] [Axy Ayy] ``` Where imx and imy are first derivatives, averaged with a gaussian filter. The corner measure is then defined as: ``` det(A) - k * trace(A)**2 ``` or: ``` 2 * det(A) / (trace(A) + eps) ``` Parameters `imagendarray` Input image. `method{β€˜k’, β€˜eps’}, optional` Method to compute the response image from the auto-correlation matrix. `kfloat, optional` Sensitivity factor to separate corners from edges, typically in range `[0, 0.2]`. Small values of k result in detection of sharp corners. `epsfloat, optional` Normalisation factor (Noble’s corner measure). `sigmafloat, optional` Standard deviation used for the Gaussian kernel, which is used as weighting function for the auto-correlation matrix. Returns `responsendarray` Harris response image. #### References `1` <https://en.wikipedia.org/wiki/Corner_detection> #### Examples ``` >>> from skimage.feature import corner_harris, corner_peaks >>> square = np.zeros([10, 10]) >>> square[2:8, 2:8] = 1 >>> square.astype(int) array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]) >>> corner_peaks(corner_harris(square), min_distance=1) array([[2, 2], [2, 7], [7, 2], [7, 7]]) ``` corner\_kitchen\_rosenfeld -------------------------- `skimage.feature.corner_kitchen_rosenfeld(image, mode='constant', cval=0)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/corner.py#L488-L533) Compute Kitchen and Rosenfeld corner measure response image. The corner measure is calculated as follows: ``` (imxx * imy**2 + imyy * imx**2 - 2 * imxy * imx * imy) / (imx**2 + imy**2) ``` Where imx and imy are the first and imxx, imxy, imyy the second derivatives. Parameters `imagendarray` Input image. `mode{β€˜constant’, β€˜reflect’, β€˜wrap’, β€˜nearest’, β€˜mirror’}, optional` How to handle values outside the image borders. `cvalfloat, optional` Used in conjunction with mode β€˜constant’, the value outside the image boundaries. Returns `responsendarray` Kitchen and Rosenfeld response image. #### References `1` Kitchen, L., & Rosenfeld, A. (1982). Gray-level corner detection. Pattern recognition letters, 1(2), 95-102. [DOI:10.1016/0167-8655(82)90020-4](https://doi.org/10.1016/0167-8655(82)90020-4) corner\_moravec --------------- `skimage.feature.corner_moravec(image, window_size=1)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/corner.py#L1108-L1152) Compute Moravec corner measure response image. This is one of the simplest corner detectors and is comparatively fast but has several limitations (e.g. not rotation invariant). Parameters `imagendarray` Input image. `window_sizeint, optional` Window size. Returns `responsendarray` Moravec response image. #### References `1` <https://en.wikipedia.org/wiki/Corner_detection> #### Examples ``` >>> from skimage.feature import corner_moravec >>> square = np.zeros([7, 7]) >>> square[3, 3] = 1 >>> square.astype(int) array([[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]]) >>> corner_moravec(square).astype(int) array([[0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 1, 2, 1, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0]]) ``` corner\_orientations -------------------- `skimage.feature.corner_orientations(image, corners, mask)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/corner.py#L1155-L1219) Compute the orientation of corners. The orientation of corners is computed using the first order central moment i.e. the center of mass approach. The corner orientation is the angle of the vector from the corner coordinate to the intensity centroid in the local neighborhood around the corner calculated using first order central moment. Parameters `image2D array` Input grayscale image. `corners(N, 2) array` Corner coordinates as `(row, col)`. `mask2D array` Mask defining the local neighborhood of the corner used for the calculation of the central moment. Returns `orientations(N, 1) array` Orientations of corners in the range [-pi, pi]. #### References `1` Ethan Rublee, Vincent Rabaud, Kurt Konolige and Gary Bradski β€œORB : An efficient alternative to SIFT and SURF” <http://www.vision.cs.chubu.ac.jp/CV-R/pdf/Rublee_iccv2011.pdf> `2` Paul L. Rosin, β€œMeasuring Corner Properties” <http://users.cs.cf.ac.uk/Paul.Rosin/corner2.pdf> #### Examples ``` >>> from skimage.morphology import octagon >>> from skimage.feature import (corner_fast, corner_peaks, ... corner_orientations) >>> square = np.zeros((12, 12)) >>> square[3:9, 3:9] = 1 >>> square.astype(int) array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0], [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0], [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0], [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0], [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0], [0, 0, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]) >>> corners = corner_peaks(corner_fast(square, 9), min_distance=1) >>> corners array([[3, 3], [3, 8], [8, 3], [8, 8]]) >>> orientations = corner_orientations(square, corners, octagon(3, 2)) >>> np.rad2deg(orientations) array([ 45., 135., -45., -135.]) ``` corner\_peaks ------------- `skimage.feature.corner_peaks(image, min_distance=1, threshold_abs=None, threshold_rel=None, exclude_border=True, indices=True, num_peaks=inf, footprint=None, labels=None, *, num_peaks_per_label=inf, p_norm=inf)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/corner.py#L1005-L1105) Find peaks in corner measure response image. This differs from [`skimage.feature.peak_local_max`](#skimage.feature.peak_local_max "skimage.feature.peak_local_max") in that it suppresses multiple connected peaks with the same accumulator value. Parameters `imagendarray` Input image. `min_distanceint, optional` The minimal allowed distance separating peaks. `**` See [`skimage.feature.peak_local_max()`](#skimage.feature.peak_local_max "skimage.feature.peak_local_max"). `p_normfloat` Which Minkowski p-norm to use. Should be in the range [1, inf]. A finite large p may cause a ValueError if overflow can occur. `inf` corresponds to the Chebyshev distance and 2 to the Euclidean distance. Returns `outputndarray or ndarray of bools` * If `indices = True` : (row, column, …) coordinates of peaks. * If `indices = False` : Boolean array shaped like `image`, with peaks represented by True values. See also [`skimage.feature.peak_local_max`](#skimage.feature.peak_local_max "skimage.feature.peak_local_max") #### Notes Changed in version 0.18: The default value of `threshold_rel` has changed to None, which corresponds to letting [`skimage.feature.peak_local_max`](#skimage.feature.peak_local_max "skimage.feature.peak_local_max") decide on the default. This is equivalent to `threshold_rel=0`. The `num_peaks` limit is applied before suppression of connected peaks. To limit the number of peaks after suppression, set `num_peaks=np.inf` and post-process the output of this function. #### Examples ``` >>> from skimage.feature import peak_local_max >>> response = np.zeros((5, 5)) >>> response[2:4, 2:4] = 1 >>> response array([[0., 0., 0., 0., 0.], [0., 0., 0., 0., 0.], [0., 0., 1., 1., 0.], [0., 0., 1., 1., 0.], [0., 0., 0., 0., 0.]]) >>> peak_local_max(response) array([[2, 2], [2, 3], [3, 2], [3, 3]]) >>> corner_peaks(response) array([[2, 2]]) ``` corner\_shi\_tomasi ------------------- `skimage.feature.corner_shi_tomasi(image, sigma=1)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/corner.py#L616-L675) Compute Shi-Tomasi (Kanade-Tomasi) corner measure response image. This corner detector uses information from the auto-correlation matrix A: ``` A = [(imx**2) (imx*imy)] = [Axx Axy] [(imx*imy) (imy**2)] [Axy Ayy] ``` Where imx and imy are first derivatives, averaged with a gaussian filter. The corner measure is then defined as the smaller eigenvalue of A: ``` ((Axx + Ayy) - sqrt((Axx - Ayy)**2 + 4 * Axy**2)) / 2 ``` Parameters `imagendarray` Input image. `sigmafloat, optional` Standard deviation used for the Gaussian kernel, which is used as weighting function for the auto-correlation matrix. Returns `responsendarray` Shi-Tomasi response image. #### References `1` <https://en.wikipedia.org/wiki/Corner_detection> #### Examples ``` >>> from skimage.feature import corner_shi_tomasi, corner_peaks >>> square = np.zeros([10, 10]) >>> square[2:8, 2:8] = 1 >>> square.astype(int) array([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]]) >>> corner_peaks(corner_shi_tomasi(square), min_distance=1) array([[2, 2], [2, 7], [7, 2], [7, 7]]) ``` corner\_subpix -------------- `skimage.feature.corner_subpix(image, corners, window_size=11, alpha=0.99)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/corner.py#L827-L1002) Determine subpixel position of corners. A statistical test decides whether the corner is defined as the intersection of two edges or a single peak. Depending on the classification result, the subpixel corner location is determined based on the local covariance of the grey-values. If the significance level for either statistical test is not sufficient, the corner cannot be classified, and the output subpixel position is set to NaN. Parameters `imagendarray` Input image. `corners(N, 2) ndarray` Corner coordinates `(row, col)`. `window_sizeint, optional` Search window size for subpixel estimation. `alphafloat, optional` Significance level for corner classification. Returns `positions(N, 2) ndarray` Subpixel corner positions. NaN for β€œnot classified” corners. #### References `1` FΓΆrstner, W., & GΓΌlch, E. (1987, June). A fast operator for detection and precise location of distinct points, corners and centres of circular features. In Proc. ISPRS intercommission conference on fast processing of photogrammetric data (pp. 281-305). <https://cseweb.ucsd.edu/classes/sp02/cse252/foerstner/foerstner.pdf> `2` <https://en.wikipedia.org/wiki/Corner_detection> #### Examples ``` >>> from skimage.feature import corner_harris, corner_peaks, corner_subpix >>> img = np.zeros((10, 10)) >>> img[:5, :5] = 1 >>> img[5:, 5:] = 1 >>> img.astype(int) array([[1, 1, 1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 1, 1, 1, 1, 1]]) >>> coords = corner_peaks(corner_harris(img), min_distance=2) >>> coords_subpix = corner_subpix(img, coords, window_size=7) >>> coords_subpix array([[4.5, 4.5]]) ``` daisy ----- `skimage.feature.daisy(image, step=4, radius=15, rings=3, histograms=8, orientations=8, normalization='l1', sigmas=None, ring_radii=None, visualize=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/_daisy.py#L9-L222) Extract DAISY feature descriptors densely for the given image. DAISY is a feature descriptor similar to SIFT formulated in a way that allows for fast dense extraction. Typically, this is practical for bag-of-features image representations. The implementation follows Tola et al. [[1]](#r3f18658b3c6d-1) but deviate on the following points: * Histogram bin contribution are smoothed with a circular Gaussian window over the tonal range (the angular range). * The sigma values of the spatial Gaussian smoothing in this code do not match the sigma values in the original code by Tola et al. [[2]](#r3f18658b3c6d-2). In their code, spatial smoothing is applied to both the input image and the center histogram. However, this smoothing is not documented in [[1]](#r3f18658b3c6d-1) and, therefore, it is omitted. Parameters `image(M, N) array` Input image (grayscale). `stepint, optional` Distance between descriptor sampling points. `radiusint, optional` Radius (in pixels) of the outermost ring. `ringsint, optional` Number of rings. `histogramsint, optional` Number of histograms sampled per ring. `orientationsint, optional` Number of orientations (bins) per histogram. `normalization[ β€˜l1’ | β€˜l2’ | β€˜daisy’ | β€˜off’ ], optional` How to normalize the descriptors * β€˜l1’: L1-normalization of each descriptor. * β€˜l2’: L2-normalization of each descriptor. * β€˜daisy’: L2-normalization of individual histograms. * β€˜off’: Disable normalization. `sigmas1D array of float, optional` Standard deviation of spatial Gaussian smoothing for the center histogram and for each ring of histograms. The array of sigmas should be sorted from the center and out. I.e. the first sigma value defines the spatial smoothing of the center histogram and the last sigma value defines the spatial smoothing of the outermost ring. Specifying sigmas overrides the following parameter. `rings = len(sigmas) - 1` `ring_radii1D array of int, optional` Radius (in pixels) for each ring. Specifying ring\_radii overrides the following two parameters. `rings = len(ring_radii)` `radius = ring_radii[-1]` If both sigmas and ring\_radii are given, they must satisfy the following predicate since no radius is needed for the center histogram. `len(ring_radii) == len(sigmas) + 1` `visualizebool, optional` Generate a visualization of the DAISY descriptors Returns `descsarray` Grid of DAISY descriptors for the given image as an array dimensionality (P, Q, R) where `P = ceil((M - radius*2) / step)` `Q = ceil((N - radius*2) / step)` `R = (rings * histograms + 1) * orientations` `descs_img(M, N, 3) array (only if visualize==True)` Visualization of the DAISY descriptors. #### References `1(1,2)` Tola et al. β€œDaisy: An efficient dense descriptor applied to wide- baseline stereo.” Pattern Analysis and Machine Intelligence, IEEE Transactions on 32.5 (2010): 815-830. `2` <http://cvlab.epfl.ch/software/daisy> draw\_haar\_like\_feature ------------------------- `skimage.feature.draw_haar_like_feature(image, r, c, width, height, feature_coord, color_positive_block=(1.0, 0.0, 0.0), color_negative_block=(0.0, 1.0, 0.0), alpha=0.5, max_n_features=None, random_state=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/haar.py#L222-L321) Visualization of Haar-like features. Parameters `image(M, N) ndarray` The region of an integral image for which the features need to be computed. `rint` Row-coordinate of top left corner of the detection window. `cint` Column-coordinate of top left corner of the detection window. `widthint` Width of the detection window. `heightint` Height of the detection window. `feature_coordndarray of list of tuples or None, optional` The array of coordinates to be extracted. This is useful when you want to recompute only a subset of features. In this case `feature_type` needs to be an array containing the type of each feature, as returned by [`haar_like_feature_coord()`](#skimage.feature.haar_like_feature_coord "skimage.feature.haar_like_feature_coord"). By default, all coordinates are computed. `color_positive_rectangletuple of 3 floats` Floats specifying the color for the positive block. Corresponding values define (R, G, B) values. Default value is red (1, 0, 0). `color_negative_blocktuple of 3 floats` Floats specifying the color for the negative block Corresponding values define (R, G, B) values. Default value is blue (0, 1, 0). `alphafloat` Value in the range [0, 1] that specifies opacity of visualization. 1 - fully transparent, 0 - opaque. `max_n_featuresint, default=None` The maximum number of features to be returned. By default, all features are returned. `random_stateint, RandomState instance or None, optional` If int, random\_state is the seed used by the random number generator; If RandomState instance, random\_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. The random state is used when generating a set of features smaller than the total number of available features. Returns `features(M, N), ndarray` An image in which the different features will be added. #### Examples ``` >>> import numpy as np >>> from skimage.feature import haar_like_feature_coord >>> from skimage.feature import draw_haar_like_feature >>> feature_coord, _ = haar_like_feature_coord(2, 2, 'type-4') >>> image = draw_haar_like_feature(np.zeros((2, 2)), ... 0, 0, 2, 2, ... feature_coord, ... max_n_features=1) >>> image array([[[0. , 0.5, 0. ], [0.5, 0. , 0. ]], [[0.5, 0. , 0. ], [0. , 0.5, 0. ]]]) ``` draw\_multiblock\_lbp --------------------- `skimage.feature.draw_multiblock_lbp(image, r, c, width, height, lbp_code=0, color_greater_block=(1, 1, 1), color_less_block=(0, 0.69, 0.96), alpha=0.5)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/texture.py#L386-L493) Multi-block local binary pattern visualization. Blocks with higher sums are colored with alpha-blended white rectangles, whereas blocks with lower sums are colored alpha-blended cyan. Colors and the `alpha` parameter can be changed. Parameters `imagendarray of float or uint` Image on which to visualize the pattern. `rint` Row-coordinate of top left corner of a rectangle containing feature. `cint` Column-coordinate of top left corner of a rectangle containing feature. `widthint` Width of one of 9 equal rectangles that will be used to compute a feature. `heightint` Height of one of 9 equal rectangles that will be used to compute a feature. `lbp_codeint` The descriptor of feature to visualize. If not provided, the descriptor with 0 value will be used. `color_greater_blocktuple of 3 floats` Floats specifying the color for the block that has greater intensity value. They should be in the range [0, 1]. Corresponding values define (R, G, B) values. Default value is white (1, 1, 1). `color_greater_blocktuple of 3 floats` Floats specifying the color for the block that has greater intensity value. They should be in the range [0, 1]. Corresponding values define (R, G, B) values. Default value is cyan (0, 0.69, 0.96). `alphafloat` Value in the range [0, 1] that specifies opacity of visualization. 1 - fully transparent, 0 - opaque. Returns `outputndarray of float` Image with MB-LBP visualization. #### References `1` Face Detection Based on Multi-Block LBP Representation. Lun Zhang, Rufeng Chu, Shiming Xiang, Shengcai Liao, Stan Z. Li <http://www.cbsr.ia.ac.cn/users/scliao/papers/Zhang-ICB07-MBLBP.pdf> greycomatrix ------------ `skimage.feature.greycomatrix(image, distances, angles, levels=None, symmetric=False, normed=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/texture.py#L15-L155) Calculate the grey-level co-occurrence matrix. A grey level co-occurrence matrix is a histogram of co-occurring greyscale values at a given offset over an image. Parameters `imagearray_like` Integer typed input image. Only positive valued images are supported. If type is other than uint8, the argument `levels` needs to be set. `distancesarray_like` List of pixel pair distance offsets. `anglesarray_like` List of pixel pair angles in radians. `levelsint, optional` The input image should contain integers in [0, `levels`-1], where levels indicate the number of grey-levels counted (typically 256 for an 8-bit image). This argument is required for 16-bit images or higher and is typically the maximum of the image. As the output matrix is at least `levels` x `levels`, it might be preferable to use binning of the input image rather than large values for `levels`. `symmetricbool, optional` If True, the output matrix `P[:, :, d, theta]` is symmetric. This is accomplished by ignoring the order of value pairs, so both (i, j) and (j, i) are accumulated when (i, j) is encountered for a given offset. The default is False. `normedbool, optional` If True, normalize each matrix `P[:, :, d, theta]` by dividing by the total number of accumulated co-occurrences for the given offset. The elements of the resulting matrix sum to 1. The default is False. Returns `P4-D ndarray` The grey-level co-occurrence histogram. The value `P[i,j,d,theta]` is the number of times that grey-level `j` occurs at a distance `d` and at an angle `theta` from grey-level `i`. If `normed` is `False`, the output is of type uint32, otherwise it is float64. The dimensions are: levels x levels x number of distances x number of angles. #### References `1` The GLCM Tutorial Home Page, <http://www.fp.ucalgary.ca/mhallbey/tutorial.htm> `2` Haralick, RM.; Shanmugam, K., β€œTextural features for image classification” IEEE Transactions on systems, man, and cybernetics 6 (1973): 610-621. [DOI:10.1109/TSMC.1973.4309314](https://doi.org/10.1109/TSMC.1973.4309314) `3` Pattern Recognition Engineering, Morton Nadler & Eric P. Smith `4` Wikipedia, <https://en.wikipedia.org/wiki/Co-occurrence_matrix> #### Examples Compute 2 GLCMs: One for a 1-pixel offset to the right, and one for a 1-pixel offset upwards. ``` >>> image = np.array([[0, 0, 1, 1], ... [0, 0, 1, 1], ... [0, 2, 2, 2], ... [2, 2, 3, 3]], dtype=np.uint8) >>> result = greycomatrix(image, [1], [0, np.pi/4, np.pi/2, 3*np.pi/4], ... levels=4) >>> result[:, :, 0, 0] array([[2, 2, 1, 0], [0, 2, 0, 0], [0, 0, 3, 1], [0, 0, 0, 1]], dtype=uint32) >>> result[:, :, 0, 1] array([[1, 1, 3, 0], [0, 1, 1, 0], [0, 0, 0, 2], [0, 0, 0, 0]], dtype=uint32) >>> result[:, :, 0, 2] array([[3, 0, 2, 0], [0, 2, 2, 0], [0, 0, 1, 2], [0, 0, 0, 0]], dtype=uint32) >>> result[:, :, 0, 3] array([[2, 0, 0, 0], [1, 1, 2, 0], [0, 0, 2, 1], [0, 0, 0, 0]], dtype=uint32) ``` ### Examples using `skimage.feature.greycomatrix` [GLCM Texture Features](https://scikit-image.org/docs/0.18.x/auto_examples/features_detection/plot_glcm.html#sphx-glr-auto-examples-features-detection-plot-glcm-py) greycoprops ----------- `skimage.feature.greycoprops(P, prop='contrast')` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/texture.py#L158-L278) Calculate texture properties of a GLCM. Compute a feature of a grey level co-occurrence matrix to serve as a compact summary of the matrix. The properties are computed as follows: * β€˜contrast’: \(\sum\_{i,j=0}^{levels-1} P\_{i,j}(i-j)^2\) * β€˜dissimilarity’: \(\sum\_{i,j=0}^{levels-1}P\_{i,j}|i-j|\) * β€˜homogeneity’: \(\sum\_{i,j=0}^{levels-1}\frac{P\_{i,j}}{1+(i-j)^2}\) * β€˜ASM’: \(\sum\_{i,j=0}^{levels-1} P\_{i,j}^2\) * β€˜energy’: \(\sqrt{ASM}\) * β€˜correlation’: \[\sum\_{i,j=0}^{levels-1} P\_{i,j}\left[\frac{(i-\mu\_i) \ (j-\mu\_j)}{\sqrt{(\sigma\_i^2)(\sigma\_j^2)}}\right]\] Each GLCM is normalized to have a sum of 1 before the computation of texture properties. Parameters `Pndarray` Input array. `P` is the grey-level co-occurrence histogram for which to compute the specified property. The value `P[i,j,d,theta]` is the number of times that grey-level j occurs at a distance d and at an angle theta from grey-level i. `prop{β€˜contrast’, β€˜dissimilarity’, β€˜homogeneity’, β€˜energy’, β€˜correlation’, β€˜ASM’}, optional` The property of the GLCM to compute. The default is β€˜contrast’. Returns `results2-D ndarray` 2-dimensional array. `results[d, a]` is the property β€˜prop’ for the d’th distance and the a’th angle. #### References `1` The GLCM Tutorial Home Page, <http://www.fp.ucalgary.ca/mhallbey/tutorial.htm> #### Examples Compute the contrast for GLCMs with distances [1, 2] and angles [0 degrees, 90 degrees] ``` >>> image = np.array([[0, 0, 1, 1], ... [0, 0, 1, 1], ... [0, 2, 2, 2], ... [2, 2, 3, 3]], dtype=np.uint8) >>> g = greycomatrix(image, [1, 2], [0, np.pi/2], levels=4, ... normed=True, symmetric=True) >>> contrast = greycoprops(g, 'contrast') >>> contrast array([[0.58333333, 1. ], [1.25 , 2.75 ]]) ``` ### Examples using `skimage.feature.greycoprops` [GLCM Texture Features](https://scikit-image.org/docs/0.18.x/auto_examples/features_detection/plot_glcm.html#sphx-glr-auto-examples-features-detection-plot-glcm-py) haar\_like\_feature ------------------- `skimage.feature.haar_like_feature(int_image, r, c, width, height, feature_type=None, feature_coord=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/haar.py#L87-L219) Compute the Haar-like features for a region of interest (ROI) of an integral image. Haar-like features have been successfully used for image classification and object detection [[1]](#rbcb83f52fce4-1). It has been used for real-time face detection algorithm proposed in [[2]](#rbcb83f52fce4-2). Parameters `int_image(M, N) ndarray` Integral image for which the features need to be computed. `rint` Row-coordinate of top left corner of the detection window. `cint` Column-coordinate of top left corner of the detection window. `widthint` Width of the detection window. `heightint` Height of the detection window. `feature_typestr or list of str or None, optional` The type of feature to consider: * β€˜type-2-x’: 2 rectangles varying along the x axis; * β€˜type-2-y’: 2 rectangles varying along the y axis; * β€˜type-3-x’: 3 rectangles varying along the x axis; * β€˜type-3-y’: 3 rectangles varying along the y axis; * β€˜type-4’: 4 rectangles varying along x and y axis. By default all features are extracted. If using with `feature_coord`, it should correspond to the feature type of each associated coordinate feature. `feature_coordndarray of list of tuples or None, optional` The array of coordinates to be extracted. This is useful when you want to recompute only a subset of features. In this case `feature_type` needs to be an array containing the type of each feature, as returned by [`haar_like_feature_coord()`](#skimage.feature.haar_like_feature_coord "skimage.feature.haar_like_feature_coord"). By default, all coordinates are computed. Returns `haar_features(n_features,) ndarray of int or float` Resulting Haar-like features. Each value is equal to the subtraction of sums of the positive and negative rectangles. The data type depends of the data type of `int_image`: `int` when the data type of `int_image` is `uint` or `int` and `float` when the data type of `int_image` is `float`. #### Notes When extracting those features in parallel, be aware that the choice of the backend (i.e. multiprocessing vs threading) will have an impact on the performance. The rule of thumb is as follows: use multiprocessing when extracting features for all possible ROI in an image; use threading when extracting the feature at specific location for a limited number of ROIs. Refer to the example [Face classification using Haar-like feature descriptor](https://scikit-image.org/docs/0.18.x/auto_examples/applications/plot_haar_extraction_selection_classification.html#sphx-glr-auto-examples-applications-plot-haar-extraction-selection-classification-py) for more insights. #### References `1` <https://en.wikipedia.org/wiki/Haar-like_feature> `2` Oren, M., Papageorgiou, C., Sinha, P., Osuna, E., & Poggio, T. (1997, June). Pedestrian detection using wavelet templates. In Computer Vision and Pattern Recognition, 1997. Proceedings., 1997 IEEE Computer Society Conference on (pp. 193-199). IEEE. <http://tinyurl.com/y6ulxfta> [DOI:10.1109/CVPR.1997.609319](https://doi.org/10.1109/CVPR.1997.609319) `3` Viola, Paul, and Michael J. Jones. β€œRobust real-time face detection.” International journal of computer vision 57.2 (2004): 137-154. <https://www.merl.com/publications/docs/TR2004-043.pdf> [DOI:10.1109/CVPR.2001.990517](https://doi.org/10.1109/CVPR.2001.990517) #### Examples ``` >>> import numpy as np >>> from skimage.transform import integral_image >>> from skimage.feature import haar_like_feature >>> img = np.ones((5, 5), dtype=np.uint8) >>> img_ii = integral_image(img) >>> feature = haar_like_feature(img_ii, 0, 0, 5, 5, 'type-3-x') >>> feature array([-1, -2, -3, -4, -1, -2, -3, -4, -1, -2, -3, -4, -1, -2, -3, -4, -1, -2, -3, -4, -1, -2, -3, -4, -1, -2, -3, -1, -2, -3, -1, -2, -3, -1, -2, -1, -2, -1, -2, -1, -1, -1]) ``` You can compute the feature for some pre-computed coordinates. ``` >>> from skimage.feature import haar_like_feature_coord >>> feature_coord, feature_type = zip( ... *[haar_like_feature_coord(5, 5, feat_t) ... for feat_t in ('type-2-x', 'type-3-x')]) >>> # only select one feature over two >>> feature_coord = np.concatenate([x[::2] for x in feature_coord]) >>> feature_type = np.concatenate([x[::2] for x in feature_type]) >>> feature = haar_like_feature(img_ii, 0, 0, 5, 5, ... feature_type=feature_type, ... feature_coord=feature_coord) >>> feature array([ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -3, -1, -3, -1, -3, -1, -3, -1, -3, -1, -3, -1, -3, -2, -1, -3, -2, -2, -2, -1]) ``` haar\_like\_feature\_coord -------------------------- `skimage.feature.haar_like_feature_coord(width, height, feature_type=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/haar.py#L36-L84) Compute the coordinates of Haar-like features. Parameters `widthint` Width of the detection window. `heightint` Height of the detection window. `feature_typestr or list of str or None, optional` The type of feature to consider: * β€˜type-2-x’: 2 rectangles varying along the x axis; * β€˜type-2-y’: 2 rectangles varying along the y axis; * β€˜type-3-x’: 3 rectangles varying along the x axis; * β€˜type-3-y’: 3 rectangles varying along the y axis; * β€˜type-4’: 4 rectangles varying along x and y axis. By default all features are extracted. Returns `feature_coord(n_features, n_rectangles, 2, 2), ndarray of list of tuple coord` Coordinates of the rectangles for each feature. `feature_type(n_features,), ndarray of str` The corresponding type for each feature. #### Examples ``` >>> import numpy as np >>> from skimage.transform import integral_image >>> from skimage.feature import haar_like_feature_coord >>> feat_coord, feat_type = haar_like_feature_coord(2, 2, 'type-4') >>> feat_coord array([ list([[(0, 0), (0, 0)], [(0, 1), (0, 1)], [(1, 1), (1, 1)], [(1, 0), (1, 0)]])], dtype=object) >>> feat_type array(['type-4'], dtype=object) ``` hessian\_matrix --------------- `skimage.feature.hessian_matrix(image, sigma=1, mode='constant', cval=0, order='rc')` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/corner.py#L133-L199) Compute Hessian matrix. The Hessian matrix is defined as: ``` H = [Hrr Hrc] [Hrc Hcc] ``` which is computed by convolving the image with the second derivatives of the Gaussian kernel in the respective r- and c-directions. Parameters `imagendarray` Input image. `sigmafloat` Standard deviation used for the Gaussian kernel, which is used as weighting function for the auto-correlation matrix. `mode{β€˜constant’, β€˜reflect’, β€˜wrap’, β€˜nearest’, β€˜mirror’}, optional` How to handle values outside the image borders. `cvalfloat, optional` Used in conjunction with mode β€˜constant’, the value outside the image boundaries. `order{β€˜rc’, β€˜xy’}, optional` This parameter allows for the use of reverse or forward order of the image axes in gradient computation. β€˜rc’ indicates the use of the first axis initially (Hrr, Hrc, Hcc), whilst β€˜xy’ indicates the usage of the last axis initially (Hxx, Hxy, Hyy) Returns `Hrrndarray` Element of the Hessian matrix for each pixel in the input image. `Hrcndarray` Element of the Hessian matrix for each pixel in the input image. `Hccndarray` Element of the Hessian matrix for each pixel in the input image. #### Examples ``` >>> from skimage.feature import hessian_matrix >>> square = np.zeros((5, 5)) >>> square[2, 2] = 4 >>> Hrr, Hrc, Hcc = hessian_matrix(square, sigma=0.1, order='rc') >>> Hrc array([[ 0., 0., 0., 0., 0.], [ 0., 1., 0., -1., 0.], [ 0., 0., 0., 0., 0.], [ 0., -1., 0., 1., 0.], [ 0., 0., 0., 0., 0.]]) ``` hessian\_matrix\_det -------------------- `skimage.feature.hessian_matrix_det(image, sigma=1, approximate=True)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/corner.py#L202-L244) Compute the approximate Hessian Determinant over an image. The 2D approximate method uses box filters over integral images to compute the approximate Hessian Determinant, as described in [[1]](#r48e33a732c34-1). Parameters `imagearray` The image over which to compute Hessian Determinant. `sigmafloat, optional` Standard deviation used for the Gaussian kernel, used for the Hessian matrix. `approximatebool, optional` If `True` and the image is 2D, use a much faster approximate computation. This argument has no effect on 3D and higher images. Returns `outarray` The array of the Determinant of Hessians. #### Notes For 2D images when `approximate=True`, the running time of this method only depends on size of the image. It is independent of `sigma` as one would expect. The downside is that the result for `sigma` less than `3` is not accurate, i.e., not similar to the result obtained if someone computed the Hessian and took its determinant. #### References `1` Herbert Bay, Andreas Ess, Tinne Tuytelaars, Luc Van Gool, β€œSURF: Speeded Up Robust Features” <ftp://ftp.vision.ee.ethz.ch/publications/articles/eth_biwi_00517.pdf> hessian\_matrix\_eigvals ------------------------ `skimage.feature.hessian_matrix_eigvals(H_elems)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/corner.py#L384-L413) Compute eigenvalues of Hessian matrix. Parameters `H_elemslist of ndarray` The upper-diagonal elements of the Hessian matrix, as returned by [`hessian_matrix`](#skimage.feature.hessian_matrix "skimage.feature.hessian_matrix"). Returns `eigsndarray` The eigenvalues of the Hessian matrix, in decreasing order. The eigenvalues are the leading dimension. That is, `eigs[i, j, k]` contains the ith-largest eigenvalue at position (j, k). #### Examples ``` >>> from skimage.feature import hessian_matrix, hessian_matrix_eigvals >>> square = np.zeros((5, 5)) >>> square[2, 2] = 4 >>> H_elems = hessian_matrix(square, sigma=0.1, order='rc') >>> hessian_matrix_eigvals(H_elems)[0] array([[ 0., 0., 2., 0., 0.], [ 0., 1., 0., 1., 0.], [ 2., 0., -2., 0., 2.], [ 0., 1., 0., 1., 0.], [ 0., 0., 2., 0., 0.]]) ``` hog --- `skimage.feature.hog(image, orientations=9, pixels_per_cell=(8, 8), cells_per_block=(3, 3), block_norm='L2-Hys', visualize=False, transform_sqrt=False, feature_vector=True, multichannel=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/_hog.py#L46-L295) Extract Histogram of Oriented Gradients (HOG) for a given image. Compute a Histogram of Oriented Gradients (HOG) by 1. (optional) global image normalization 2. computing the gradient image in `row` and `col` 3. computing gradient histograms 4. normalizing across blocks 5. flattening into a feature vector Parameters `image(M, N[, C]) ndarray` Input image. `orientationsint, optional` Number of orientation bins. `pixels_per_cell2-tuple (int, int), optional` Size (in pixels) of a cell. `cells_per_block2-tuple (int, int), optional` Number of cells in each block. `block_normstr {β€˜L1’, β€˜L1-sqrt’, β€˜L2’, β€˜L2-Hys’}, optional` Block normalization method: `L1` Normalization using L1-norm. `L1-sqrt` Normalization using L1-norm, followed by square root. `L2` Normalization using L2-norm. `L2-Hys` Normalization using L2-norm, followed by limiting the maximum values to 0.2 (`Hys` stands for `hysteresis`) and renormalization using L2-norm. (default) For details, see [[3]](#ra159ccd8c91f-3), [[4]](#ra159ccd8c91f-4). `visualizebool, optional` Also return an image of the HOG. For each cell and orientation bin, the image contains a line segment that is centered at the cell center, is perpendicular to the midpoint of the range of angles spanned by the orientation bin, and has intensity proportional to the corresponding histogram value. `transform_sqrtbool, optional` Apply power law compression to normalize the image before processing. DO NOT use this if the image contains negative values. Also see `notes` section below. `feature_vectorbool, optional` Return the data as a feature vector by calling .ravel() on the result just before returning. `multichannelboolean, optional` If True, the last `image` dimension is considered as a color channel, otherwise as spatial. Returns `out(n_blocks_row, n_blocks_col, n_cells_row, n_cells_col, n_orient) ndarray` HOG descriptor for the image. If `feature_vector` is True, a 1D (flattened) array is returned. `hog_image(M, N) ndarray, optional` A visualisation of the HOG image. Only provided if `visualize` is True. #### Notes The presented code implements the HOG extraction method from [[2]](#ra159ccd8c91f-2) with the following changes: (I) blocks of (3, 3) cells are used ((2, 2) in the paper); (II) no smoothing within cells (Gaussian spatial window with sigma=8pix in the paper); (III) L1 block normalization is used (L2-Hys in the paper). Power law compression, also known as Gamma correction, is used to reduce the effects of shadowing and illumination variations. The compression makes the dark regions lighter. When the kwarg `transform_sqrt` is set to `True`, the function computes the square root of each color channel and then applies the hog algorithm to the image. #### References `1` <https://en.wikipedia.org/wiki/Histogram_of_oriented_gradients> `2` Dalal, N and Triggs, B, Histograms of Oriented Gradients for Human Detection, IEEE Computer Society Conference on Computer Vision and Pattern Recognition 2005 San Diego, CA, USA, <https://lear.inrialpes.fr/people/triggs/pubs/Dalal-cvpr05.pdf>, [DOI:10.1109/CVPR.2005.177](https://doi.org/10.1109/CVPR.2005.177) `3` Lowe, D.G., Distinctive image features from scale-invatiant keypoints, International Journal of Computer Vision (2004) 60: 91, <http://www.cs.ubc.ca/~lowe/papers/ijcv04.pdf>, [DOI:10.1023/B:VISI.0000029664.99615.94](https://doi.org/10.1023/B:VISI.0000029664.99615.94) `4` Dalal, N, Finding People in Images and Videos, Human-Computer Interaction [cs.HC], Institut National Polytechnique de Grenoble - INPG, 2006, <https://tel.archives-ouvertes.fr/tel-00390303/file/NavneetDalalThesis.pdf> local\_binary\_pattern ---------------------- `skimage.feature.local_binary_pattern(image, P, R, method='default')` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/texture.py#L281-L337) Gray scale and rotation invariant LBP (Local Binary Patterns). LBP is an invariant descriptor that can be used for texture classification. Parameters `image(N, M) array` Graylevel image. `Pint` Number of circularly symmetric neighbour set points (quantization of the angular space). `Rfloat` Radius of circle (spatial resolution of the operator). `method{β€˜default’, β€˜ror’, β€˜uniform’, β€˜var’}` Method to determine the pattern. * β€˜default’: original local binary pattern which is gray scale but not rotation invariant. * β€˜ror’: extension of default implementation which is gray scale and rotation invariant. * β€˜uniform’: improved rotation invariance with uniform patterns and finer quantization of the angular space which is gray scale and rotation invariant. * β€˜nri\_uniform’: non rotation-invariant uniform patterns variant which is only gray scale invariant [[2]](#r648eb9e75080-2). * β€˜var’: rotation invariant variance measures of the contrast of local image texture which is rotation but not gray scale invariant. Returns `output(N, M) array` LBP image. #### References `1` Multiresolution Gray-Scale and Rotation Invariant Texture Classification with Local Binary Patterns. Timo Ojala, Matti Pietikainen, Topi Maenpaa. <http://www.ee.oulu.fi/research/mvmp/mvg/files/pdf/pdf_94.pdf>, 2002. `2` Face recognition with local binary patterns. Timo Ahonen, Abdenour Hadid, Matti Pietikainen, <http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.214.6851>, 2004. masked\_register\_translation ----------------------------- `skimage.feature.masked_register_translation(src_image, target_image, src_mask, target_mask=None, overlap_ratio=0.3)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/__init__.py#L33-L41) **Deprecated function**. Use `skimage.registration.phase_cross_correlation` instead. match\_descriptors ------------------ `skimage.feature.match_descriptors(descriptors1, descriptors2, metric=None, p=2, max_distance=inf, cross_check=True, max_ratio=1.0)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/match.py#L5-L97) Brute-force matching of descriptors. For each descriptor in the first set this matcher finds the closest descriptor in the second set (and vice-versa in the case of enabled cross-checking). Parameters `descriptors1(M, P) array` Descriptors of size P about M keypoints in the first image. `descriptors2(N, P) array` Descriptors of size P about N keypoints in the second image. `metric{β€˜euclidean’, β€˜cityblock’, β€˜minkowski’, β€˜hamming’, …} , optional` The metric to compute the distance between two descriptors. See [`scipy.spatial.distance.cdist`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.spatial.distance.cdist.html#scipy.spatial.distance.cdist "(in SciPy v1.5.4)") for all possible types. The hamming distance should be used for binary descriptors. By default the L2-norm is used for all descriptors of dtype float or double and the Hamming distance is used for binary descriptors automatically. `pint, optional` The p-norm to apply for `metric='minkowski'`. `max_distancefloat, optional` Maximum allowed distance between descriptors of two keypoints in separate images to be regarded as a match. `cross_checkbool, optional` If True, the matched keypoints are returned after cross checking i.e. a matched pair (keypoint1, keypoint2) is returned if keypoint2 is the best match for keypoint1 in second image and keypoint1 is the best match for keypoint2 in first image. `max_ratiofloat, optional` Maximum ratio of distances between first and second closest descriptor in the second set of descriptors. This threshold is useful to filter ambiguous matches between the two descriptor sets. The choice of this value depends on the statistics of the chosen descriptor, e.g., for SIFT descriptors a value of 0.8 is usually chosen, see D.G. Lowe, β€œDistinctive Image Features from Scale-Invariant Keypoints”, International Journal of Computer Vision, 2004. Returns `matches(Q, 2) array` Indices of corresponding matches in first and second set of descriptors, where `matches[:, 0]` denote the indices in the first and `matches[:, 1]` the indices in the second set of descriptors. match\_template --------------- `skimage.feature.match_template(image, template, pad_input=False, mode='constant', constant_values=0)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/template.py#L31-L179) Match a template to a 2-D or 3-D image using normalized correlation. The output is an array with values between -1.0 and 1.0. The value at a given position corresponds to the correlation coefficient between the image and the template. For `pad_input=True` matches correspond to the center and otherwise to the top-left corner of the template. To find the best match you must search for peaks in the response (output) image. Parameters `image(M, N[, D]) array` 2-D or 3-D input image. `template(m, n[, d]) array` Template to locate. It must be `(m <= M, n <= N[, d <= D])`. `pad_inputbool` If True, pad `image` so that output is the same size as the image, and output values correspond to the template center. Otherwise, the output is an array with shape `(M - m + 1, N - n + 1)` for an `(M, N)` image and an `(m, n)` template, and matches correspond to origin (top-left corner) of the template. `modesee numpy.pad, optional` Padding mode. `constant_valuessee numpy.pad, optional` Constant values used in conjunction with `mode='constant'`. Returns `outputarray` Response image with correlation coefficients. #### Notes Details on the cross-correlation are presented in [[1]](#r7bfca17c0278-1). This implementation uses FFT convolutions of the image and the template. Reference [[2]](#r7bfca17c0278-2) presents similar derivations but the approximation presented in this reference is not used in our implementation. #### References `1` J. P. Lewis, β€œFast Normalized Cross-Correlation”, Industrial Light and Magic. `2` Briechle and Hanebeck, β€œTemplate Matching using Fast Normalized Cross Correlation”, Proceedings of the SPIE (2001). [DOI:10.1117/12.421129](https://doi.org/10.1117/12.421129) #### Examples ``` >>> template = np.zeros((3, 3)) >>> template[1, 1] = 1 >>> template array([[0., 0., 0.], [0., 1., 0.], [0., 0., 0.]]) >>> image = np.zeros((6, 6)) >>> image[1, 1] = 1 >>> image[4, 4] = -1 >>> image array([[ 0., 0., 0., 0., 0., 0.], [ 0., 1., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., 0., 0.], [ 0., 0., 0., 0., -1., 0.], [ 0., 0., 0., 0., 0., 0.]]) >>> result = match_template(image, template) >>> np.round(result, 3) array([[ 1. , -0.125, 0. , 0. ], [-0.125, -0.125, 0. , 0. ], [ 0. , 0. , 0.125, 0.125], [ 0. , 0. , 0.125, -1. ]]) >>> result = match_template(image, template, pad_input=True) >>> np.round(result, 3) array([[-0.125, -0.125, -0.125, 0. , 0. , 0. ], [-0.125, 1. , -0.125, 0. , 0. , 0. ], [-0.125, -0.125, -0.125, 0. , 0. , 0. ], [ 0. , 0. , 0. , 0.125, 0.125, 0.125], [ 0. , 0. , 0. , 0.125, -1. , 0.125], [ 0. , 0. , 0. , 0.125, 0.125, 0.125]]) ``` multiblock\_lbp --------------- `skimage.feature.multiblock_lbp(int_image, r, c, width, height)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/texture.py#L340-L383) Multi-block local binary pattern (MB-LBP). The features are calculated similarly to local binary patterns (LBPs), (See [`local_binary_pattern()`](#skimage.feature.local_binary_pattern "skimage.feature.local_binary_pattern")) except that summed blocks are used instead of individual pixel values. MB-LBP is an extension of LBP that can be computed on multiple scales in constant time using the integral image. Nine equally-sized rectangles are used to compute a feature. For each rectangle, the sum of the pixel intensities is computed. Comparisons of these sums to that of the central rectangle determine the feature, similarly to LBP. Parameters `int_image(N, M) array` Integral image. `rint` Row-coordinate of top left corner of a rectangle containing feature. `cint` Column-coordinate of top left corner of a rectangle containing feature. `widthint` Width of one of the 9 equal rectangles that will be used to compute a feature. `heightint` Height of one of the 9 equal rectangles that will be used to compute a feature. Returns `outputint` 8-bit MB-LBP feature descriptor. #### References `1` Face Detection Based on Multi-Block LBP Representation. Lun Zhang, Rufeng Chu, Shiming Xiang, Shengcai Liao, Stan Z. Li <http://www.cbsr.ia.ac.cn/users/scliao/papers/Zhang-ICB07-MBLBP.pdf> multiscale\_basic\_features --------------------------- `skimage.feature.multiscale_basic_features(image, multichannel=False, intensity=True, edges=True, texture=True, sigma_min=0.5, sigma_max=16, num_sigma=None, num_workers=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/_basic_features.py#L99-L172) Local features for a single- or multi-channel nd image. Intensity, gradient intensity and local structure are computed at different scales thanks to Gaussian blurring. Parameters `imagendarray` Input image, which can be grayscale or multichannel. `multichannelbool, default False` True if the last dimension corresponds to color channels. `intensitybool, default True` If True, pixel intensities averaged over the different scales are added to the feature set. `edgesbool, default True` If True, intensities of local gradients averaged over the different scales are added to the feature set. `texturebool, default True` If True, eigenvalues of the Hessian matrix after Gaussian blurring at different scales are added to the feature set. `sigma_minfloat, optional` Smallest value of the Gaussian kernel used to average local neighbourhoods before extracting features. `sigma_maxfloat, optional` Largest value of the Gaussian kernel used to average local neighbourhoods before extracting features. `num_sigmaint, optional` Number of values of the Gaussian kernel between sigma\_min and sigma\_max. If None, sigma\_min multiplied by powers of 2 are used. `num_workersint or None, optional` The number of parallel threads to use. If set to `None`, the full set of available cores are used. Returns `featuresnp.ndarray` Array of shape `image.shape + (n_features,)` ### Examples using `skimage.feature.multiscale_basic_features` [Trainable segmentation using local features and random forests](https://scikit-image.org/docs/0.18.x/auto_examples/segmentation/plot_trainable_segmentation.html#sphx-glr-auto-examples-segmentation-plot-trainable-segmentation-py) peak\_local\_max ---------------- `skimage.feature.peak_local_max(image, min_distance=1, threshold_abs=None, threshold_rel=None, exclude_border=True, indices=True, num_peaks=inf, footprint=None, labels=None, num_peaks_per_label=inf, p_norm=inf)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/peak.py#L113-L319) Find peaks in an image as coordinate list or boolean mask. Peaks are the local maxima in a region of `2 * min_distance + 1` (i.e. peaks are separated by at least `min_distance`). If both `threshold_abs` and `threshold_rel` are provided, the maximum of the two is chosen as the minimum intensity threshold of peaks. Changed in version 0.18: Prior to version 0.18, peaks of the same height within a radius of `min_distance` were all returned, but this could cause unexpected behaviour. From 0.18 onwards, an arbitrary peak within the region is returned. See issue gh-2592. Parameters `imagendarray` Input image. `min_distanceint, optional` The minimal allowed distance separating peaks. To find the maximum number of peaks, use `min_distance=1`. `threshold_absfloat, optional` Minimum intensity of peaks. By default, the absolute threshold is the minimum intensity of the image. `threshold_relfloat, optional` Minimum intensity of peaks, calculated as `max(image) * threshold_rel`. `exclude_borderint, tuple of ints, or bool, optional` If positive integer, `exclude_border` excludes peaks from within `exclude_border`-pixels of the border of the image. If tuple of non-negative ints, the length of the tuple must match the input array’s dimensionality. Each element of the tuple will exclude peaks from within `exclude_border`-pixels of the border of the image along that dimension. If True, takes the `min_distance` parameter as value. If zero or False, peaks are identified regardless of their distance from the border. `indicesbool, optional` If True, the output will be an array representing peak coordinates. The coordinates are sorted according to peaks values (Larger first). If False, the output will be a boolean array shaped as `image.shape` with peaks present at True elements. `indices` is deprecated and will be removed in version 0.20. Default behavior will be to always return peak coordinates. You can obtain a mask as shown in the example below. `num_peaksint, optional` Maximum number of peaks. When the number of peaks exceeds `num_peaks`, return `num_peaks` peaks based on highest peak intensity. `footprintndarray of bools, optional` If provided, `footprint == 1` represents the local region within which to search for peaks at every point in `image`. `labelsndarray of ints, optional` If provided, each unique region `labels == value` represents a unique region to search for peaks. Zero is reserved for background. `num_peaks_per_labelint, optional` Maximum number of peaks for each label. `p_normfloat` Which Minkowski p-norm to use. Should be in the range [1, inf]. A finite large p may cause a ValueError if overflow can occur. `inf` corresponds to the Chebyshev distance and 2 to the Euclidean distance. Returns `outputndarray or ndarray of bools` * If `indices = True` : (row, column, …) coordinates of peaks. * If `indices = False` : Boolean array shaped like `image`, with peaks represented by True values. See also [`skimage.feature.corner_peaks`](#skimage.feature.corner_peaks "skimage.feature.corner_peaks") #### Notes The peak local maximum function returns the coordinates of local peaks (maxima) in an image. Internally, a maximum filter is used for finding local maxima. This operation dilates the original image. After comparison of the dilated and original image, this function returns the coordinates or a mask of the peaks where the dilated image equals the original image. #### Examples ``` >>> img1 = np.zeros((7, 7)) >>> img1[3, 4] = 1 >>> img1[3, 2] = 1.5 >>> img1 array([[0. , 0. , 0. , 0. , 0. , 0. , 0. ], [0. , 0. , 0. , 0. , 0. , 0. , 0. ], [0. , 0. , 0. , 0. , 0. , 0. , 0. ], [0. , 0. , 1.5, 0. , 1. , 0. , 0. ], [0. , 0. , 0. , 0. , 0. , 0. , 0. ], [0. , 0. , 0. , 0. , 0. , 0. , 0. ], [0. , 0. , 0. , 0. , 0. , 0. , 0. ]]) ``` ``` >>> peak_local_max(img1, min_distance=1) array([[3, 2], [3, 4]]) ``` ``` >>> peak_local_max(img1, min_distance=2) array([[3, 2]]) ``` ``` >>> img2 = np.zeros((20, 20, 20)) >>> img2[10, 10, 10] = 1 >>> img2[15, 15, 15] = 1 >>> peak_idx = peak_local_max(img2, exclude_border=0) >>> peak_idx array([[10, 10, 10], [15, 15, 15]]) ``` ``` >>> peak_mask = np.zeros_like(img2, dtype=bool) >>> peak_mask[tuple(peak_idx.T)] = True >>> np.argwhere(peak_mask) array([[10, 10, 10], [15, 15, 15]]) ``` ### Examples using `skimage.feature.peak_local_max` [Finding local maxima](https://scikit-image.org/docs/0.18.x/auto_examples/segmentation/plot_peak_local_max.html#sphx-glr-auto-examples-segmentation-plot-peak-local-max-py) [Watershed segmentation](https://scikit-image.org/docs/0.18.x/auto_examples/segmentation/plot_watershed.html#sphx-glr-auto-examples-segmentation-plot-watershed-py) [Segment human cells (in mitosis)](https://scikit-image.org/docs/0.18.x/auto_examples/applications/plot_human_mitosis.html#sphx-glr-auto-examples-applications-plot-human-mitosis-py) plot\_matches ------------- `skimage.feature.plot_matches(ax, image1, image2, keypoints1, keypoints2, matches, keypoints_color='k', matches_color=None, only_matches=False, alignment='horizontal')` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/util.py#L43-L137) Plot matched features. Parameters `axmatplotlib.axes.Axes` Matches and image are drawn in this ax. `image1(N, M [, 3]) array` First grayscale or color image. `image2(N, M [, 3]) array` Second grayscale or color image. `keypoints1(K1, 2) array` First keypoint coordinates as `(row, col)`. `keypoints2(K2, 2) array` Second keypoint coordinates as `(row, col)`. `matches(Q, 2) array` Indices of corresponding matches in first and second set of descriptors, where `matches[:, 0]` denote the indices in the first and `matches[:, 1]` the indices in the second set of descriptors. `keypoints_colormatplotlib color, optional` Color for keypoint locations. `matches_colormatplotlib color, optional` Color for lines which connect keypoint matches. By default the color is chosen randomly. `only_matchesbool, optional` Whether to only plot matches and not plot the keypoint locations. `alignment{β€˜horizontal’, β€˜vertical’}, optional` Whether to show images side by side, `'horizontal'`, or one above the other, `'vertical'`. register\_translation --------------------- `skimage.feature.register_translation(src_image, target_image, upsample_factor=1, space='real', return_error=True)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/__init__.py#L44-L51) **Deprecated function**. Use `skimage.registration.phase_cross_correlation` instead. shape\_index ------------ `skimage.feature.shape_index(image, sigma=1, mode='constant', cval=0)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/corner.py#L416-L485) Compute the shape index. The shape index, as defined by Koenderink & van Doorn [[1]](#rc8faae48965f-1), is a single valued measure of local curvature, assuming the image as a 3D plane with intensities representing heights. It is derived from the eigen values of the Hessian, and its value ranges from -1 to 1 (and is undefined (=NaN) in *flat* regions), with following ranges representing following shapes: Ranges of the shape index and corresponding shapes.| Interval (s in …) | Shape | | --- | --- | | [ -1, -7/8) | Spherical cup | | [-7/8, -5/8) | Through | | [-5/8, -3/8) | Rut | | [-3/8, -1/8) | Saddle rut | | [-1/8, +1/8) | Saddle | | [+1/8, +3/8) | Saddle ridge | | [+3/8, +5/8) | Ridge | | [+5/8, +7/8) | Dome | | [+7/8, +1] | Spherical cap | Parameters `imagendarray` Input image. `sigmafloat, optional` Standard deviation used for the Gaussian kernel, which is used for smoothing the input data before Hessian eigen value calculation. `mode{β€˜constant’, β€˜reflect’, β€˜wrap’, β€˜nearest’, β€˜mirror’}, optional` How to handle values outside the image borders `cvalfloat, optional` Used in conjunction with mode β€˜constant’, the value outside the image boundaries. Returns `sndarray` Shape index #### References `1` Koenderink, J. J. & van Doorn, A. J., β€œSurface shape and curvature scales”, Image and Vision Computing, 1992, 10, 557-564. [DOI:10.1016/0262-8856(92)90076-F](https://doi.org/10.1016/0262-8856(92)90076-F) #### Examples ``` >>> from skimage.feature import shape_index >>> square = np.zeros((5, 5)) >>> square[2, 2] = 4 >>> s = shape_index(square, sigma=0.1) >>> s array([[ nan, nan, -0.5, nan, nan], [ nan, -0. , nan, -0. , nan], [-0.5, nan, -1. , nan, -0.5], [ nan, -0. , nan, -0. , nan], [ nan, nan, -0.5, nan, nan]]) ``` structure\_tensor ----------------- `skimage.feature.structure_tensor(image, sigma=1, mode='constant', cval=0, order=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/corner.py#L45-L130) Compute structure tensor using sum of squared differences. The (2-dimensional) structure tensor A is defined as: ``` A = [Arr Arc] [Arc Acc] ``` which is approximated by the weighted sum of squared differences in a local window around each pixel in the image. This formula can be extended to a larger number of dimensions (see [[1]](#r0bb93eb224ab-1)). Parameters `imagendarray` Input image. `sigmafloat, optional` Standard deviation used for the Gaussian kernel, which is used as a weighting function for the local summation of squared differences. `mode{β€˜constant’, β€˜reflect’, β€˜wrap’, β€˜nearest’, β€˜mirror’}, optional` How to handle values outside the image borders. `cvalfloat, optional` Used in conjunction with mode β€˜constant’, the value outside the image boundaries. `order{β€˜rc’, β€˜xy’}, optional` NOTE: Only applies in 2D. Higher dimensions must always use β€˜rc’ order. This parameter allows for the use of reverse or forward order of the image axes in gradient computation. β€˜rc’ indicates the use of the first axis initially (Arr, Arc, Acc), whilst β€˜xy’ indicates the usage of the last axis initially (Axx, Axy, Ayy). Returns `A_elemslist of ndarray` Upper-diagonal elements of the structure tensor for each pixel in the input image. See also [`structure_tensor_eigenvalues`](#skimage.feature.structure_tensor_eigenvalues "skimage.feature.structure_tensor_eigenvalues") #### References `1` <https://en.wikipedia.org/wiki/Structure_tensor> #### Examples ``` >>> from skimage.feature import structure_tensor >>> square = np.zeros((5, 5)) >>> square[2, 2] = 1 >>> Arr, Arc, Acc = structure_tensor(square, sigma=0.1, order='rc') >>> Acc array([[0., 0., 0., 0., 0.], [0., 1., 0., 1., 0.], [0., 4., 0., 4., 0.], [0., 1., 0., 1., 0.], [0., 0., 0., 0., 0.]]) ``` structure\_tensor\_eigenvalues ------------------------------ `skimage.feature.structure_tensor_eigenvalues(A_elems)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/corner.py#L306-L340) Compute eigenvalues of structure tensor. Parameters `A_elemslist of ndarray` The upper-diagonal elements of the structure tensor, as returned by [`structure_tensor`](#skimage.feature.structure_tensor "skimage.feature.structure_tensor"). Returns ndarray The eigenvalues of the structure tensor, in decreasing order. The eigenvalues are the leading dimension. That is, the coordinate [i, j, k] corresponds to the ith-largest eigenvalue at position (j, k). See also [`structure_tensor`](#skimage.feature.structure_tensor "skimage.feature.structure_tensor") #### Examples ``` >>> from skimage.feature import structure_tensor >>> from skimage.feature import structure_tensor_eigenvalues >>> square = np.zeros((5, 5)) >>> square[2, 2] = 1 >>> A_elems = structure_tensor(square, sigma=0.1, order='rc') >>> structure_tensor_eigenvalues(A_elems)[0] array([[0., 0., 0., 0., 0.], [0., 2., 4., 2., 0.], [0., 4., 0., 4., 0.], [0., 2., 4., 2., 0.], [0., 0., 0., 0., 0.]]) ``` structure\_tensor\_eigvals -------------------------- `skimage.feature.structure_tensor_eigvals(Axx, Axy, Ayy)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/corner.py#L343-L381) Compute eigenvalues of structure tensor. Parameters `Axxndarray` Element of the structure tensor for each pixel in the input image. `Axyndarray` Element of the structure tensor for each pixel in the input image. `Ayyndarray` Element of the structure tensor for each pixel in the input image. Returns `l1ndarray` Larger eigen value for each input matrix. `l2ndarray` Smaller eigen value for each input matrix. #### Examples ``` >>> from skimage.feature import structure_tensor, structure_tensor_eigvals >>> square = np.zeros((5, 5)) >>> square[2, 2] = 1 >>> Arr, Arc, Acc = structure_tensor(square, sigma=0.1, order='rc') >>> structure_tensor_eigvals(Acc, Arc, Arr)[0] array([[0., 0., 0., 0., 0.], [0., 2., 4., 2., 0.], [0., 4., 0., 4., 0.], [0., 2., 4., 2., 0.], [0., 0., 0., 0., 0.]]) ``` BRIEF ----- `class skimage.feature.BRIEF(descriptor_size=256, patch_size=49, mode='normal', sigma=1, sample_seed=1)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/brief.py#L11-L184) Bases: `skimage.feature.util.DescriptorExtractor` BRIEF binary descriptor extractor. BRIEF (Binary Robust Independent Elementary Features) is an efficient feature point descriptor. It is highly discriminative even when using relatively few bits and is computed using simple intensity difference tests. For each keypoint, intensity comparisons are carried out for a specifically distributed number N of pixel-pairs resulting in a binary descriptor of length N. For binary descriptors the Hamming distance can be used for feature matching, which leads to lower computational cost in comparison to the L2 norm. Parameters `descriptor_sizeint, optional` Size of BRIEF descriptor for each keypoint. Sizes 128, 256 and 512 recommended by the authors. Default is 256. `patch_sizeint, optional` Length of the two dimensional square patch sampling region around the keypoints. Default is 49. `mode{β€˜normal’, β€˜uniform’}, optional` Probability distribution for sampling location of decision pixel-pairs around keypoints. `sample_seedint, optional` Seed for the random sampling of the decision pixel-pairs. From a square window with length `patch_size`, pixel pairs are sampled using the `mode` parameter to build the descriptors using intensity comparison. The value of `sample_seed` must be the same for the images to be matched while building the descriptors. `sigmafloat, optional` Standard deviation of the Gaussian low-pass filter applied to the image to alleviate noise sensitivity, which is strongly recommended to obtain discriminative and good descriptors. #### Examples ``` >>> from skimage.feature import (corner_harris, corner_peaks, BRIEF, ... match_descriptors) >>> import numpy as np >>> square1 = np.zeros((8, 8), dtype=np.int32) >>> square1[2:6, 2:6] = 1 >>> square1 array([[0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0]], dtype=int32) >>> square2 = np.zeros((9, 9), dtype=np.int32) >>> square2[2:7, 2:7] = 1 >>> square2 array([[0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 1, 1, 1, 1, 1, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=int32) >>> keypoints1 = corner_peaks(corner_harris(square1), min_distance=1) >>> keypoints2 = corner_peaks(corner_harris(square2), min_distance=1) >>> extractor = BRIEF(patch_size=5) >>> extractor.extract(square1, keypoints1) >>> descriptors1 = extractor.descriptors >>> extractor.extract(square2, keypoints2) >>> descriptors2 = extractor.descriptors >>> matches = match_descriptors(descriptors1, descriptors2) >>> matches array([[0, 0], [1, 1], [2, 2], [3, 3]]) >>> keypoints1[matches[:, 0]] array([[2, 2], [2, 5], [5, 2], [5, 5]]) >>> keypoints2[matches[:, 1]] array([[2, 2], [2, 6], [6, 2], [6, 6]]) ``` Attributes `descriptors(Q, descriptor_size) array of dtype bool` 2D ndarray of binary descriptors of size `descriptor_size` for Q keypoints after filtering out border keypoints with value at an index `(i, j)` either being `True` or `False` representing the outcome of the intensity comparison for i-th keypoint on j-th decision pixel-pair. It is `Q == np.sum(mask)`. `mask(N, ) array of dtype bool` Mask indicating whether a keypoint has been filtered out (`False`) or is described in the `descriptors` array (`True`). `__init__(descriptor_size=256, patch_size=49, mode='normal', sigma=1, sample_seed=1)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/brief.py#L114-L128) Initialize self. See help(type(self)) for accurate signature. `extract(image, keypoints)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/brief.py#L130-L184) Extract BRIEF binary descriptors for given keypoints in image. Parameters `image2D array` Input image. `keypoints(N, 2) array` Keypoint coordinates as `(row, col)`. CENSURE ------- `class skimage.feature.CENSURE(min_scale=1, max_scale=7, mode='DoB', non_max_threshold=0.15, line_threshold=10)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/censure.py#L111-L296) Bases: `skimage.feature.util.FeatureDetector` CENSURE keypoint detector. `min_scaleint, optional` Minimum scale to extract keypoints from. `max_scaleint, optional` Maximum scale to extract keypoints from. The keypoints will be extracted from all the scales except the first and the last i.e. from the scales in the range [min\_scale + 1, max\_scale - 1]. The filter sizes for different scales is such that the two adjacent scales comprise of an octave. `mode{β€˜DoB’, β€˜Octagon’, β€˜STAR’}, optional` Type of bi-level filter used to get the scales of the input image. Possible values are β€˜DoB’, β€˜Octagon’ and β€˜STAR’. The three modes represent the shape of the bi-level filters i.e. box(square), octagon and star respectively. For instance, a bi-level octagon filter consists of a smaller inner octagon and a larger outer octagon with the filter weights being uniformly negative in both the inner octagon while uniformly positive in the difference region. Use STAR and Octagon for better features and DoB for better performance. `non_max_thresholdfloat, optional` Threshold value used to suppress maximas and minimas with a weak magnitude response obtained after Non-Maximal Suppression. `line_thresholdfloat, optional` Threshold for rejecting interest points which have ratio of principal curvatures greater than this value. #### References `1` Motilal Agrawal, Kurt Konolige and Morten Rufus Blas β€œCENSURE: Center Surround Extremas for Realtime Feature Detection and Matching”, <https://link.springer.com/chapter/10.1007/978-3-540-88693-8_8> [DOI:10.1007/978-3-540-88693-8\_8](https://doi.org/10.1007/978-3-540-88693-8_8) `2` Adam Schmidt, Marek Kraft, Michal Fularz and Zuzanna Domagala β€œComparative Assessment of Point Feature Detectors and Descriptors in the Context of Robot Navigation” <http://yadda.icm.edu.pl/yadda/element/bwmeta1.element.baztech-268aaf28-0faf-4872-a4df-7e2e61cb364c/c/Schmidt_comparative.pdf> [DOI:10.1.1.465.1117](https://doi.org/10.1.1.465.1117) #### Examples ``` >>> from skimage.data import astronaut >>> from skimage.color import rgb2gray >>> from skimage.feature import CENSURE >>> img = rgb2gray(astronaut()[100:300, 100:300]) >>> censure = CENSURE() >>> censure.detect(img) >>> censure.keypoints array([[ 4, 148], [ 12, 73], [ 21, 176], [ 91, 22], [ 93, 56], [ 94, 22], [ 95, 54], [100, 51], [103, 51], [106, 67], [108, 15], [117, 20], [122, 60], [125, 37], [129, 37], [133, 76], [145, 44], [146, 94], [150, 114], [153, 33], [154, 156], [155, 151], [184, 63]]) >>> censure.scales array([2, 6, 6, 2, 4, 3, 2, 3, 2, 6, 3, 2, 2, 3, 2, 2, 2, 3, 2, 2, 4, 2, 2]) ``` Attributes `keypoints(N, 2) array` Keypoint coordinates as `(row, col)`. `scales(N, ) array` Corresponding scales. `__init__(min_scale=1, max_scale=7, mode='DoB', non_max_threshold=0.15, line_threshold=10)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/censure.py#L198-L216) Initialize self. See help(type(self)) for accurate signature. `detect(image)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/censure.py#L218-L296) Detect CENSURE keypoints along with the corresponding scale. Parameters `image2D ndarray` Input image. Cascade ------- `class skimage.feature.Cascade` Bases: [`object`](https://docs.python.org/3.9/library/functions.html#object "(in Python v3.9)") Class for cascade of classifiers that is used for object detection. The main idea behind cascade of classifiers is to create classifiers of medium accuracy and ensemble them into one strong classifier instead of just creating a strong one. The second advantage of cascade classifier is that easy examples can be classified only by evaluating some of the classifiers in the cascade, making the process much faster than the process of evaluating a one strong classifier. Attributes `epscnp.float32_t` Accuracy parameter. Increasing it, makes the classifier detect less false positives but at the same time the false negative score increases. `stages_numberPy_ssize_t` Amount of stages in a cascade. Each cascade consists of stumps i.e. trained features. `stumps_numberPy_ssize_t` The overall amount of stumps in all the stages of cascade. `features_numberPy_ssize_t` The overall amount of different features used by cascade. Two stumps can use the same features but has different trained values. `window_widthPy_ssize_t` The width of a detection window that is used. Objects smaller than this window can’t be detected. `window_heightPy_ssize_t` The height of a detection window. `stagesStage*` A link to the c array that stores stages information using Stage struct. `featuresMBLBP*` Link to the c array that stores MBLBP features using MBLBP struct. `LUTscnp.uint32_t*` The ling to the array with look-up tables that are used by trained MBLBP features (MBLBPStumps) to evaluate a particular region. `__init__()` Initialize cascade classifier. Parameters `xml_filefile’s path or file’s object` A file in a OpenCv format from which all the cascade classifier’s parameters are loaded. `epscnp.float32_t` Accuracy parameter. Increasing it, makes the classifier detect less false positives but at the same time the false negative score increases. `detect_multi_scale()` Search for the object on multiple scales of input image. The function takes the input image, the scale factor by which the searching window is multiplied on each step, minimum window size and maximum window size that specify the interval for the search windows that are applied to the input image to detect objects. Parameters `img2-D or 3-D ndarray` Ndarray that represents the input image. `scale_factorcnp.float32_t` The scale by which searching window is multiplied on each step. `step_ratiocnp.float32_t` The ratio by which the search step in multiplied on each scale of the image. 1 represents the exaustive search and usually is slow. By setting this parameter to higher values the results will be worse but the computation will be much faster. Usually, values in the interval [1, 1.5] give good results. `min_sizetyple (int, int)` Minimum size of the search window. `max_sizetyple (int, int)` Maximum size of the search window. `min_neighbour_numberint` Minimum amount of intersecting detections in order for detection to be approved by the function. `intersection_score_thresholdcnp.float32_t` The minimum value of value of ratio (intersection area) / (small rectangle ratio) in order to merge two detections into one. Returns `outputlist of dicts` Dict have form {β€˜r’: int, β€˜c’: int, β€˜width’: int, β€˜height’: int}, where β€˜r’ represents row position of top left corner of detected window, β€˜c’ - col position, β€˜width’ - width of detected window, β€˜height’ - height of detected window. `eps` `features_number` `stages_number` `stumps_number` `window_height` `window_width` ORB --- `class skimage.feature.ORB(downscale=1.2, n_scales=8, n_keypoints=500, fast_n=9, fast_threshold=0.08, harris_k=0.04)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/orb.py#L22-L348) Bases: `skimage.feature.util.FeatureDetector`, `skimage.feature.util.DescriptorExtractor` Oriented FAST and rotated BRIEF feature detector and binary descriptor extractor. Parameters `n_keypointsint, optional` Number of keypoints to be returned. The function will return the best `n_keypoints` according to the Harris corner response if more than `n_keypoints` are detected. If not, then all the detected keypoints are returned. `fast_nint, optional` The `n` parameter in [`skimage.feature.corner_fast`](#skimage.feature.corner_fast "skimage.feature.corner_fast"). Minimum number of consecutive pixels out of 16 pixels on the circle that should all be either brighter or darker w.r.t test-pixel. A point c on the circle is darker w.r.t test pixel p if `Ic < Ip - threshold` and brighter if `Ic > Ip + threshold`. Also stands for the n in `FAST-n` corner detector. `fast_thresholdfloat, optional` The `threshold` parameter in `feature.corner_fast`. Threshold used to decide whether the pixels on the circle are brighter, darker or similar w.r.t. the test pixel. Decrease the threshold when more corners are desired and vice-versa. `harris_kfloat, optional` The `k` parameter in [`skimage.feature.corner_harris`](#skimage.feature.corner_harris "skimage.feature.corner_harris"). Sensitivity factor to separate corners from edges, typically in range `[0, 0.2]`. Small values of `k` result in detection of sharp corners. `downscalefloat, optional` Downscale factor for the image pyramid. Default value 1.2 is chosen so that there are more dense scales which enable robust scale invariance for a subsequent feature description. `n_scalesint, optional` Maximum number of scales from the bottom of the image pyramid to extract the features from. #### References `1` Ethan Rublee, Vincent Rabaud, Kurt Konolige and Gary Bradski β€œORB: An efficient alternative to SIFT and SURF” <http://www.vision.cs.chubu.ac.jp/CV-R/pdf/Rublee_iccv2011.pdf> #### Examples ``` >>> from skimage.feature import ORB, match_descriptors >>> img1 = np.zeros((100, 100)) >>> img2 = np.zeros_like(img1) >>> np.random.seed(1) >>> square = np.random.rand(20, 20) >>> img1[40:60, 40:60] = square >>> img2[53:73, 53:73] = square >>> detector_extractor1 = ORB(n_keypoints=5) >>> detector_extractor2 = ORB(n_keypoints=5) >>> detector_extractor1.detect_and_extract(img1) >>> detector_extractor2.detect_and_extract(img2) >>> matches = match_descriptors(detector_extractor1.descriptors, ... detector_extractor2.descriptors) >>> matches array([[0, 0], [1, 1], [2, 2], [3, 3], [4, 4]]) >>> detector_extractor1.keypoints[matches[:, 0]] array([[42., 40.], [47., 58.], [44., 40.], [59., 42.], [45., 44.]]) >>> detector_extractor2.keypoints[matches[:, 1]] array([[55., 53.], [60., 71.], [57., 53.], [72., 55.], [58., 57.]]) ``` Attributes `keypoints(N, 2) array` Keypoint coordinates as `(row, col)`. `scales(N, ) array` Corresponding scales. `orientations(N, ) array` Corresponding orientations in radians. `responses(N, ) array` Corresponding Harris corner responses. `descriptors(Q, descriptor_size) array of dtype bool` 2D array of binary descriptors of size `descriptor_size` for Q keypoints after filtering out border keypoints with value at an index `(i, j)` either being `True` or `False` representing the outcome of the intensity comparison for i-th keypoint on j-th decision pixel-pair. It is `Q == np.sum(mask)`. `__init__(downscale=1.2, n_scales=8, n_keypoints=500, fast_n=9, fast_threshold=0.08, harris_k=0.04)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/orb.py#L117-L131) Initialize self. See help(type(self)) for accurate signature. `detect(image)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/orb.py#L163-L211) Detect oriented FAST keypoints along with the corresponding scale. Parameters `image2D array` Input image. `detect_and_extract(image)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/orb.py#L278-L348) Detect oriented FAST keypoints and extract rBRIEF descriptors. Note that this is faster than first calling [`detect`](#skimage.feature.ORB.detect "skimage.feature.ORB.detect") and then [`extract`](#skimage.feature.ORB.extract "skimage.feature.ORB.extract"). Parameters `image2D array` Input image. `extract(image, keypoints, scales, orientations)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/feature/orb.py#L225-L276) Extract rBRIEF binary descriptors for given keypoints in image. Note that the keypoints must be extracted using the same `downscale` and `n_scales` parameters. Additionally, if you want to extract both keypoints and descriptors you should use the faster [`detect_and_extract`](#skimage.feature.ORB.detect_and_extract "skimage.feature.ORB.detect_and_extract"). Parameters `image2D array` Input image. `keypoints(N, 2) array` Keypoint coordinates as `(row, col)`. `scales(N, ) array` Corresponding scales. `orientations(N, ) array` Corresponding orientations in radians.
programming_docs
scikit_image Module: metrics Module: metrics =============== | | | | --- | --- | | [`skimage.metrics.adapted_rand_error`](#skimage.metrics.adapted_rand_error "skimage.metrics.adapted_rand_error")([…]) | Compute Adapted Rand error as defined by the SNEMI3D contest. | | [`skimage.metrics.contingency_table`](#skimage.metrics.contingency_table "skimage.metrics.contingency_table")(im\_true, …) | Return the contingency table for all regions in matched segmentations. | | [`skimage.metrics.hausdorff_distance`](#skimage.metrics.hausdorff_distance "skimage.metrics.hausdorff_distance")(image0, …) | Calculate the Hausdorff distance between nonzero elements of given images. | | [`skimage.metrics.mean_squared_error`](#skimage.metrics.mean_squared_error "skimage.metrics.mean_squared_error")(image0, …) | Compute the mean-squared error between two images. | | [`skimage.metrics.normalized_root_mse`](#skimage.metrics.normalized_root_mse "skimage.metrics.normalized_root_mse")(…[, …]) | Compute the normalized root mean-squared error (NRMSE) between two images. | | [`skimage.metrics.peak_signal_noise_ratio`](#skimage.metrics.peak_signal_noise_ratio "skimage.metrics.peak_signal_noise_ratio")(…) | Compute the peak signal to noise ratio (PSNR) for an image. | | [`skimage.metrics.structural_similarity`](#skimage.metrics.structural_similarity "skimage.metrics.structural_similarity")(im1, …) | Compute the mean structural similarity index between two images. | | [`skimage.metrics.variation_of_information`](#skimage.metrics.variation_of_information "skimage.metrics.variation_of_information")([…]) | Return symmetric conditional entropies associated with the VI. | adapted\_rand\_error -------------------- `skimage.metrics.adapted_rand_error(image_true=None, image_test=None, *, table=None, ignore_labels=(0, ))` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/metrics/_adapted_rand_error.py#L7-L76) Compute Adapted Rand error as defined by the SNEMI3D contest. [[1]](#rc4bf0a102856-1) Parameters `image_truendarray of int` Ground-truth label image, same shape as im\_test. `image_testndarray of int` Test image. `tablescipy.sparse array in crs format, optional` A contingency table built with skimage.evaluate.contingency\_table. If None, it will be computed on the fly. `ignore_labelssequence of int, optional` Labels to ignore. Any part of the true image labeled with any of these values will not be counted in the score. Returns `arefloat` The adapted Rand error; equal to \(1 - \frac{2pr}{p + r}\), where `p` and `r` are the precision and recall described below. `precfloat` The adapted Rand precision: this is the number of pairs of pixels that have the same label in the test label image *and* in the true image, divided by the number in the test image. `recfloat` The adapted Rand recall: this is the number of pairs of pixels that have the same label in the test label image *and* in the true image, divided by the number in the true image. #### Notes Pixels with label 0 in the true segmentation are ignored in the score. #### References `1` Arganda-Carreras I, Turaga SC, Berger DR, et al. (2015) Crowdsourcing the creation of image segmentation algorithms for connectomics. Front. Neuroanat. 9:142. [DOI:10.3389/fnana.2015.00142](https://doi.org/10.3389/fnana.2015.00142) contingency\_table ------------------ `skimage.metrics.contingency_table(im_true, im_test, *, ignore_labels=None, normalize=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/metrics/_contingency_table.py#L7-L39) Return the contingency table for all regions in matched segmentations. Parameters `im_truendarray of int` Ground-truth label image, same shape as im\_test. `im_testndarray of int` Test image. `ignore_labelssequence of int, optional` Labels to ignore. Any part of the true image labeled with any of these values will not be counted in the score. `normalizebool` Determines if the contingency table is normalized by pixel count. Returns `contscipy.sparse.csr_matrix` A contingency table. `cont[i, j]` will equal the number of voxels labeled `i` in `im_true` and `j` in `im_test`. hausdorff\_distance ------------------- `skimage.metrics.hausdorff_distance(image0, image1)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/metrics/set_metrics.py#L4-L51) Calculate the Hausdorff distance between nonzero elements of given images. The Hausdorff distance [[1]](#rda3116704e68-1) is the maximum distance between any point on `image0` and its nearest point on `image1`, and vice-versa. Parameters `image0, image1ndarray` Arrays where `True` represents a point that is included in a set of points. Both arrays must have the same shape. Returns `distancefloat` The Hausdorff distance between coordinates of nonzero pixels in `image0` and `image1`, using the Euclidian distance. #### References `1` <http://en.wikipedia.org/wiki/Hausdorff_distance> #### Examples ``` >>> points_a = (3, 0) >>> points_b = (6, 0) >>> shape = (7, 1) >>> image_a = np.zeros(shape, dtype=bool) >>> image_b = np.zeros(shape, dtype=bool) >>> image_a[points_a] = True >>> image_b[points_b] = True >>> hausdorff_distance(image_a, image_b) 3.0 ``` ### Examples using `skimage.metrics.hausdorff_distance` [Hausdorff Distance](https://scikit-image.org/docs/0.18.x/auto_examples/segmentation/plot_hausdorff_distance.html#sphx-glr-auto-examples-segmentation-plot-hausdorff-distance-py) mean\_squared\_error -------------------- `skimage.metrics.mean_squared_error(image0, image1)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/metrics/simple_metrics.py#L21-L44) Compute the mean-squared error between two images. Parameters `image0, image1ndarray` Images. Any dimensionality, must have same shape. Returns `msefloat` The mean-squared error (MSE) metric. #### Notes Changed in version 0.16: This function was renamed from `skimage.measure.compare_mse` to `skimage.metrics.mean_squared_error`. normalized\_root\_mse --------------------- `skimage.metrics.normalized_root_mse(image_true, image_test, *, normalization='euclidean')` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/metrics/simple_metrics.py#L47-L105) Compute the normalized root mean-squared error (NRMSE) between two images. Parameters `image_truendarray` Ground-truth image, same shape as im\_test. `image_testndarray` Test image. `normalization{β€˜euclidean’, β€˜min-max’, β€˜mean’}, optional` Controls the normalization method to use in the denominator of the NRMSE. There is no standard method of normalization across the literature [[1]](#re6457782c209-1). The methods available here are as follows: * β€˜euclidean’ : normalize by the averaged Euclidean norm of `im_true`: ``` NRMSE = RMSE * sqrt(N) / || im_true || ``` where || . || denotes the Frobenius norm and `N = im_true.size`. This result is equivalent to: ``` NRMSE = || im_true - im_test || / || im_true ||. ``` * β€˜min-max’ : normalize by the intensity range of `im_true`. * β€˜mean’ : normalize by the mean of `im_true` Returns `nrmsefloat` The NRMSE metric. #### Notes Changed in version 0.16: This function was renamed from `skimage.measure.compare_nrmse` to `skimage.metrics.normalized_root_mse`. #### References `1` <https://en.wikipedia.org/wiki/Root-mean-square_deviation> peak\_signal\_noise\_ratio -------------------------- `skimage.metrics.peak_signal_noise_ratio(image_true, image_test, *, data_range=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/metrics/simple_metrics.py#L108-L160) Compute the peak signal to noise ratio (PSNR) for an image. Parameters `image_truendarray` Ground-truth image, same shape as im\_test. `image_testndarray` Test image. `data_rangeint, optional` The data range of the input image (distance between minimum and maximum possible values). By default, this is estimated from the image data-type. Returns `psnrfloat` The PSNR metric. #### Notes Changed in version 0.16: This function was renamed from `skimage.measure.compare_psnr` to `skimage.metrics.peak_signal_noise_ratio`. #### References `1` <https://en.wikipedia.org/wiki/Peak_signal-to-noise_ratio> structural\_similarity ---------------------- `skimage.metrics.structural_similarity(im1, im2, *, win_size=None, gradient=False, data_range=None, multichannel=False, gaussian_weights=False, full=False, **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/metrics/_structural_similarity.py#L12-L232) Compute the mean structural similarity index between two images. Parameters `im1, im2ndarray` Images. Any dimensionality with same shape. `win_sizeint or None, optional` The side-length of the sliding window used in comparison. Must be an odd value. If `gaussian_weights` is True, this is ignored and the window size will depend on `sigma`. `gradientbool, optional` If True, also return the gradient with respect to im2. `data_rangefloat, optional` The data range of the input image (distance between minimum and maximum possible values). By default, this is estimated from the image data-type. `multichannelbool, optional` If True, treat the last dimension of the array as channels. Similarity calculations are done independently for each channel then averaged. `gaussian_weightsbool, optional` If True, each patch has its mean and variance spatially weighted by a normalized Gaussian kernel of width sigma=1.5. `fullbool, optional` If True, also return the full structural similarity image. Returns `mssimfloat` The mean structural similarity index over the image. `gradndarray` The gradient of the structural similarity between im1 and im2 [[2]](#re0d1cfbcf329-2). This is only returned if `gradient` is set to True. `Sndarray` The full SSIM image. This is only returned if `full` is set to True. Other Parameters `use_sample_covariancebool` If True, normalize covariances by N-1 rather than, N where N is the number of pixels within the sliding window. `K1float` Algorithm parameter, K1 (small constant, see [[1]](#re0d1cfbcf329-1)). `K2float` Algorithm parameter, K2 (small constant, see [[1]](#re0d1cfbcf329-1)). `sigmafloat` Standard deviation for the Gaussian when `gaussian_weights` is True. #### Notes To match the implementation of Wang et. al. [[1]](#re0d1cfbcf329-1), set `gaussian_weights` to True, `sigma` to 1.5, and `use_sample_covariance` to False. Changed in version 0.16: This function was renamed from `skimage.measure.compare_ssim` to `skimage.metrics.structural_similarity`. #### References `1(1,2,3)` Wang, Z., Bovik, A. C., Sheikh, H. R., & Simoncelli, E. P. (2004). Image quality assessment: From error visibility to structural similarity. IEEE Transactions on Image Processing, 13, 600-612. <https://ece.uwaterloo.ca/~z70wang/publications/ssim.pdf>, [DOI:10.1109/TIP.2003.819861](https://doi.org/10.1109/TIP.2003.819861) `2` Avanaki, A. N. (2009). Exact global histogram specification optimized for structural similarity. Optical Review, 16, 613-621. [arXiv:0901.0065](https://arxiv.org/abs/0901.0065) [DOI:10.1007/s10043-009-0119-z](https://doi.org/10.1007/s10043-009-0119-z) variation\_of\_information -------------------------- `skimage.metrics.variation_of_information(image0=None, image1=None, *, table=None, ignore_labels=())` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/metrics/_variation_of_information.py#L9-L46) Return symmetric conditional entropies associated with the VI. [[1]](#rb3845a1c7d1d-1) The variation of information is defined as VI(X,Y) = H(X|Y) + H(Y|X). If X is the ground-truth segmentation, then H(X|Y) can be interpreted as the amount of under-segmentation and H(X|Y) as the amount of over-segmentation. In other words, a perfect over-segmentation will have H(X|Y)=0 and a perfect under-segmentation will have H(Y|X)=0. Parameters `image0, image1ndarray of int` Label images / segmentations, must have same shape. `tablescipy.sparse array in csr format, optional` A contingency table built with skimage.evaluate.contingency\_table. If None, it will be computed with skimage.evaluate.contingency\_table. If given, the entropies will be computed from this table and any images will be ignored. `ignore_labelssequence of int, optional` Labels to ignore. Any part of the true image labeled with any of these values will not be counted in the score. Returns `vindarray of float, shape (2,)` The conditional entropies of image1|image0 and image0|image1. #### References `1` Marina MeilΔƒ (2007), Comparing clusteringsβ€”an information based distance, Journal of Multivariate Analysis, Volume 98, Issue 5, Pages 873-895, ISSN 0047-259X, [DOI:10.1016/j.jmva.2006.11.013](https://doi.org/10.1016/j.jmva.2006.11.013). scikit_image Module: future.graph Module: future.graph ==================== | | | | --- | --- | | [`skimage.future.graph.cut_normalized`](#skimage.future.graph.cut_normalized "skimage.future.graph.cut_normalized")(labels, rag) | Perform Normalized Graph cut on the Region Adjacency Graph. | | [`skimage.future.graph.cut_threshold`](#skimage.future.graph.cut_threshold "skimage.future.graph.cut_threshold")(labels, …) | Combine regions separated by weight less than threshold. | | [`skimage.future.graph.merge_hierarchical`](#skimage.future.graph.merge_hierarchical "skimage.future.graph.merge_hierarchical")(…) | Perform hierarchical merging of a RAG. | | [`skimage.future.graph.ncut`](#skimage.future.graph.ncut "skimage.future.graph.ncut")(labels, rag[, …]) | Perform Normalized Graph cut on the Region Adjacency Graph. | | [`skimage.future.graph.rag_boundary`](#skimage.future.graph.rag_boundary "skimage.future.graph.rag_boundary")(labels, …) | Comouter RAG based on region boundaries | | [`skimage.future.graph.rag_mean_color`](#skimage.future.graph.rag_mean_color "skimage.future.graph.rag_mean_color")(image, …) | Compute the Region Adjacency Graph using mean colors. | | [`skimage.future.graph.show_rag`](#skimage.future.graph.show_rag "skimage.future.graph.show_rag")(labels, rag, image) | Show a Region Adjacency Graph on an image. | | [`skimage.future.graph.RAG`](#skimage.future.graph.RAG "skimage.future.graph.RAG")([label\_image, …]) | The Region Adjacency Graph (RAG) of an image, subclasses [networx.Graph](http://networkx.github.io/documentation/latest/reference/classes/graph.html) | cut\_normalized --------------- `skimage.future.graph.cut_normalized(labels, rag, thresh=0.001, num_cuts=10, in_place=True, max_edge=1.0, *, random_state=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/future/graph/graph_cut.py#L73-L145) Perform Normalized Graph cut on the Region Adjacency Graph. Given an image’s labels and its similarity RAG, recursively perform a 2-way normalized cut on it. All nodes belonging to a subgraph that cannot be cut further are assigned a unique label in the output. Parameters `labelsndarray` The array of labels. `ragRAG` The region adjacency graph. `threshfloat` The threshold. A subgraph won’t be further subdivided if the value of the N-cut exceeds `thresh`. `num_cutsint` The number or N-cuts to perform before determining the optimal one. `in_placebool` If set, modifies `rag` in place. For each node `n` the function will set a new attribute `rag.nodes[n]['ncut label']`. `max_edgefloat, optional` The maximum possible value of an edge in the RAG. This corresponds to an edge between identical regions. This is used to put self edges in the RAG. `random_stateint, RandomState instance or None, optional` If int, random\_state is the seed used by the random number generator; If RandomState instance, random\_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. The random state is used for the starting point of [`scipy.sparse.linalg.eigsh`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.linalg.eigsh.html#scipy.sparse.linalg.eigsh "(in SciPy v1.5.4)"). Returns `outndarray` The new labeled array. #### References `1` Shi, J.; Malik, J., β€œNormalized cuts and image segmentation”, Pattern Analysis and Machine Intelligence, IEEE Transactions on, vol. 22, no. 8, pp. 888-905, August 2000. #### Examples ``` >>> from skimage import data, segmentation >>> from skimage.future import graph >>> img = data.astronaut() >>> labels = segmentation.slic(img) >>> rag = graph.rag_mean_color(img, labels, mode='similarity') >>> new_labels = graph.cut_normalized(labels, rag) ``` cut\_threshold -------------- `skimage.future.graph.cut_threshold(labels, rag, thresh, in_place=True)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/future/graph/graph_cut.py#L9-L70) Combine regions separated by weight less than threshold. Given an image’s labels and its RAG, output new labels by combining regions whose nodes are separated by a weight less than the given threshold. Parameters `labelsndarray` The array of labels. `ragRAG` The region adjacency graph. `threshfloat` The threshold. Regions connected by edges with smaller weights are combined. `in_placebool` If set, modifies `rag` in place. The function will remove the edges with weights less that `thresh`. If set to `False` the function makes a copy of `rag` before proceeding. Returns `outndarray` The new labelled array. #### References `1` Alain Tremeau and Philippe Colantoni β€œRegions Adjacency Graph Applied To Color Image Segmentation” [DOI:10.1109/83.841950](https://doi.org/10.1109/83.841950) #### Examples ``` >>> from skimage import data, segmentation >>> from skimage.future import graph >>> img = data.astronaut() >>> labels = segmentation.slic(img) >>> rag = graph.rag_mean_color(img, labels) >>> new_labels = graph.cut_threshold(labels, rag, 10) ``` merge\_hierarchical ------------------- `skimage.future.graph.merge_hierarchical(labels, rag, thresh, rag_copy, in_place_merge, merge_func, weight_func)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/future/graph/graph_merge.py#L59-L137) Perform hierarchical merging of a RAG. Greedily merges the most similar pair of nodes until no edges lower than `thresh` remain. Parameters `labelsndarray` The array of labels. `ragRAG` The Region Adjacency Graph. `threshfloat` Regions connected by an edge with weight smaller than `thresh` are merged. `rag_copybool` If set, the RAG copied before modifying. `in_place_mergebool` If set, the nodes are merged in place. Otherwise, a new node is created for each merge.. `merge_funccallable` This function is called before merging two nodes. For the RAG `graph` while merging `src` and `dst`, it is called as follows `merge_func(graph, src, dst)`. `weight_funccallable` The function to compute the new weights of the nodes adjacent to the merged node. This is directly supplied as the argument `weight_func` to `merge_nodes`. Returns `outndarray` The new labeled array. ncut ---- `skimage.future.graph.ncut(labels, rag, thresh=0.001, num_cuts=10, in_place=True, max_edge=1.0, *, random_state=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/future/graph/graph_cut.py#L73-L145) Perform Normalized Graph cut on the Region Adjacency Graph. Given an image’s labels and its similarity RAG, recursively perform a 2-way normalized cut on it. All nodes belonging to a subgraph that cannot be cut further are assigned a unique label in the output. Parameters `labelsndarray` The array of labels. `ragRAG` The region adjacency graph. `threshfloat` The threshold. A subgraph won’t be further subdivided if the value of the N-cut exceeds `thresh`. `num_cutsint` The number or N-cuts to perform before determining the optimal one. `in_placebool` If set, modifies `rag` in place. For each node `n` the function will set a new attribute `rag.nodes[n]['ncut label']`. `max_edgefloat, optional` The maximum possible value of an edge in the RAG. This corresponds to an edge between identical regions. This is used to put self edges in the RAG. `random_stateint, RandomState instance or None, optional` If int, random\_state is the seed used by the random number generator; If RandomState instance, random\_state is the random number generator; If None, the random number generator is the RandomState instance used by `np.random`. The random state is used for the starting point of [`scipy.sparse.linalg.eigsh`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.sparse.linalg.eigsh.html#scipy.sparse.linalg.eigsh "(in SciPy v1.5.4)"). Returns `outndarray` The new labeled array. #### References `1` Shi, J.; Malik, J., β€œNormalized cuts and image segmentation”, Pattern Analysis and Machine Intelligence, IEEE Transactions on, vol. 22, no. 8, pp. 888-905, August 2000. #### Examples ``` >>> from skimage import data, segmentation >>> from skimage.future import graph >>> img = data.astronaut() >>> labels = segmentation.slic(img) >>> rag = graph.rag_mean_color(img, labels, mode='similarity') >>> new_labels = graph.cut_normalized(labels, rag) ``` rag\_boundary ------------- `skimage.future.graph.rag_boundary(labels, edge_map, connectivity=2)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/future/graph/rag.py#L385-L446) Comouter RAG based on region boundaries Given an image’s initial segmentation and its edge map this method constructs the corresponding Region Adjacency Graph (RAG). Each node in the RAG represents a set of pixels within the image with the same label in `labels`. The weight between two adjacent regions is the average value in `edge_map` along their boundary. `labelsndarray` The labelled image. `edge_mapndarray` This should have the same shape as that of `labels`. For all pixels along the boundary between 2 adjacent regions, the average value of the corresponding pixels in `edge_map` is the edge weight between them. `connectivityint, optional` Pixels with a squared distance less than `connectivity` from each other are considered adjacent. It can range from 1 to `labels.ndim`. Its behavior is the same as `connectivity` parameter in `scipy.ndimage.filters.generate_binary_structure`. #### Examples ``` >>> from skimage import data, segmentation, filters, color >>> from skimage.future import graph >>> img = data.chelsea() >>> labels = segmentation.slic(img) >>> edge_map = filters.sobel(color.rgb2gray(img)) >>> rag = graph.rag_boundary(labels, edge_map) ``` rag\_mean\_color ---------------- `skimage.future.graph.rag_mean_color(image, labels, connectivity=2, mode='distance', sigma=255.0)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/future/graph/rag.py#L295-L382) Compute the Region Adjacency Graph using mean colors. Given an image and its initial segmentation, this method constructs the corresponding Region Adjacency Graph (RAG). Each node in the RAG represents a set of pixels within `image` with the same label in `labels`. The weight between two adjacent regions represents how similar or dissimilar two regions are depending on the `mode` parameter. Parameters `imagendarray, shape(M, N, […, P,] 3)` Input image. `labelsndarray, shape(M, N, […, P])` The labelled image. This should have one dimension less than `image`. If `image` has dimensions `(M, N, 3)` `labels` should have dimensions `(M, N)`. `connectivityint, optional` Pixels with a squared distance less than `connectivity` from each other are considered adjacent. It can range from 1 to `labels.ndim`. Its behavior is the same as `connectivity` parameter in `scipy.ndimage.generate_binary_structure`. `mode{β€˜distance’, β€˜similarity’}, optional` The strategy to assign edge weights. β€˜distance’ : The weight between two adjacent regions is the \(|c\_1 - c\_2|\), where \(c\_1\) and \(c\_2\) are the mean colors of the two regions. It represents the Euclidean distance in their average color. β€˜similarity’ : The weight between two adjacent is \(e^{-d^2/sigma}\) where \(d=|c\_1 - c\_2|\), where \(c\_1\) and \(c\_2\) are the mean colors of the two regions. It represents how similar two regions are. `sigmafloat, optional` Used for computation when `mode` is β€œsimilarity”. It governs how close to each other two colors should be, for their corresponding edge weight to be significant. A very large value of `sigma` could make any two colors behave as though they were similar. Returns `outRAG` The region adjacency graph. #### References `1` Alain Tremeau and Philippe Colantoni β€œRegions Adjacency Graph Applied To Color Image Segmentation” [DOI:10.1109/83.841950](https://doi.org/10.1109/83.841950) #### Examples ``` >>> from skimage import data, segmentation >>> from skimage.future import graph >>> img = data.astronaut() >>> labels = segmentation.slic(img) >>> rag = graph.rag_mean_color(img, labels) ``` show\_rag --------- `skimage.future.graph.show_rag(labels, rag, image, border_color='black', edge_width=1.5, edge_cmap='magma', img_cmap='bone', in_place=True, ax=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/future/graph/rag.py#L449-L558) Show a Region Adjacency Graph on an image. Given a labelled image and its corresponding RAG, show the nodes and edges of the RAG on the image with the specified colors. Edges are displayed between the centroid of the 2 adjacent regions in the image. Parameters `labelsndarray, shape (M, N)` The labelled image. `ragRAG` The Region Adjacency Graph. `imagendarray, shape (M, N[, 3])` Input image. If `colormap` is `None`, the image should be in RGB format. `border_colorcolor spec, optional` Color with which the borders between regions are drawn. `edge_widthfloat, optional` The thickness with which the RAG edges are drawn. `edge_cmapmatplotlib.colors.Colormap, optional` Any matplotlib colormap with which the edges are drawn. `img_cmapmatplotlib.colors.Colormap, optional` Any matplotlib colormap with which the image is draw. If set to `None` the image is drawn as it is. `in_placebool, optional` If set, the RAG is modified in place. For each node `n` the function will set a new attribute `rag.nodes[n]['centroid']`. `axmatplotlib.axes.Axes, optional` The axes to draw on. If not specified, new axes are created and drawn on. Returns `lcmatplotlib.collections.LineCollection` A colection of lines that represent the edges of the graph. It can be passed to the [`matplotlib.figure.Figure.colorbar()`](https://matplotlib.org/api/_as_gen/matplotlib.figure.Figure.html#matplotlib.figure.Figure.colorbar "(in Matplotlib v3.3.3)") function. #### Examples ``` >>> from skimage import data, segmentation >>> from skimage.future import graph >>> import matplotlib.pyplot as plt >>> >>> img = data.coffee() >>> labels = segmentation.slic(img) >>> g = graph.rag_mean_color(img, labels) >>> lc = graph.show_rag(labels, g, img) >>> cbar = plt.colorbar(lc) ``` RAG --- `class skimage.future.graph.RAG(label_image=None, connectivity=1, data=None, **attr)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/future/graph/rag.py#L107-L292) Bases: `networkx.classes.graph.Graph` The Region Adjacency Graph (RAG) of an image, subclasses [networx.Graph](http://networkx.github.io/documentation/latest/reference/classes/graph.html) Parameters `label_imagearray of int` An initial segmentation, with each region labeled as a different integer. Every unique value in `label_image` will correspond to a node in the graph. `connectivityint in {1, …, label_image.ndim}, optional` The connectivity between pixels in `label_image`. For a 2D image, a connectivity of 1 corresponds to immediate neighbors up, down, left, and right, while a connectivity of 2 also includes diagonal neighbors. See [`scipy.ndimage.generate_binary_structure`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.generate_binary_structure.html#scipy.ndimage.generate_binary_structure "(in SciPy v1.5.4)"). `datanetworkx Graph specification, optional` Initial or additional edges to pass to the NetworkX Graph constructor. See `networkx.Graph`. Valid edge specifications include edge list (list of tuples), NumPy arrays, and SciPy sparse matrices. `**attrkeyword arguments, optional` Additional attributes to add to the graph. `__init__(label_image=None, connectivity=1, data=None, **attr)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/future/graph/rag.py#L133-L158) Initialize a graph with edges, name, or graph attributes. Parameters `incoming_graph_datainput graph (optional, default: None)` Data to initialize graph. If None (default) an empty graph is created. The data can be an edge list, or any NetworkX graph object. If the corresponding optional Python packages are installed the data can also be a NumPy matrix or 2d ndarray, a SciPy sparse matrix, or a PyGraphviz graph. `attrkeyword arguments, optional (default= no attributes)` Attributes to add to graph as key=value pairs. See also `convert` #### Examples ``` >>> G = nx.Graph() # or DiGraph, MultiGraph, MultiDiGraph, etc >>> G = nx.Graph(name="my graph") >>> e = [(1, 2), (2, 3), (3, 4)] # list of edges >>> G = nx.Graph(e) ``` Arbitrary graph attribute pairs (key=value) may be assigned ``` >>> G = nx.Graph(e, day="Friday") >>> G.graph {'day': 'Friday'} ``` `add_edge(u, v, attr_dict=None, **attr)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/future/graph/rag.py#L233-L242) Add an edge between `u` and `v` while updating max node id. See also `networkx.Graph.add_edge()`. `add_node(n, attr_dict=None, **attr)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/future/graph/rag.py#L222-L231) Add node `n` while updating the maximum node id. See also `networkx.Graph.add_node()`. `copy()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/future/graph/rag.py#L244-L250) Copy the graph with its max node id. See also `networkx.Graph.copy()`. `fresh_copy()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/future/graph/rag.py#L252-L272) Return a fresh copy graph with the same data structure. A fresh copy has no nodes, edges or graph attributes. It is the same data structure as the current graph. This method is typically used to create an empty version of the graph. This is required when subclassing Graph with networkx v2 and does not cause problems for v1. Here is more detail from the network migrating from 1.x to 2.x document: ``` With the new GraphViews (SubGraph, ReversedGraph, etc) you can't assume that ``G.__class__()`` will create a new instance of the same graph type as ``G``. In fact, the call signature for ``__class__`` differs depending on whether ``G`` is a view or a base class. For v2.x you should use ``G.fresh_copy()`` to create a null graph of the correct type---ready to fill with nodes and edges. ``` `merge_nodes(src, dst, weight_func=<function min_weight>, in_place=True, extra_arguments=[], extra_keywords={})` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/future/graph/rag.py#L160-L220) Merge node `src` and `dst`. The new combined node is adjacent to all the neighbors of `src` and `dst`. `weight_func` is called to decide the weight of edges incident on the new node. Parameters `src, dstint` Nodes to be merged. `weight_funccallable, optional` Function to decide the attributes of edges incident on the new node. For each neighbor `n` for `src and `dst`, `weight_func` will be called as follows: `weight_func(src, dst, n, *extra_arguments, **extra_keywords)`. `src`, `dst` and `n` are IDs of vertices in the RAG object which is in turn a subclass of `networkx.Graph`. It is expected to return a dict of attributes of the resulting edge. `in_placebool, optional` If set to `True`, the merged node has the id `dst`, else merged node has a new id which is returned. `extra_argumentssequence, optional` The sequence of extra positional arguments passed to `weight_func`. `extra_keywordsdictionary, optional` The dict of keyword arguments passed to the `weight_func`. Returns `idint` The id of the new node. #### Notes If `in_place` is `False` the resulting node has a new id, rather than `dst`. `next_id()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/future/graph/rag.py#L274-L284) Returns the `id` for the new node to be inserted. The current implementation returns one more than the maximum `id`. Returns `idint` The `id` of the new node to be inserted.
programming_docs
scikit_image Module: exposure Module: exposure ================ | | | | --- | --- | | [`skimage.exposure.adjust_gamma`](#skimage.exposure.adjust_gamma "skimage.exposure.adjust_gamma")(image[, …]) | Performs Gamma Correction on the input image. | | [`skimage.exposure.adjust_log`](#skimage.exposure.adjust_log "skimage.exposure.adjust_log")(image[, gain, inv]) | Performs Logarithmic correction on the input image. | | [`skimage.exposure.adjust_sigmoid`](#skimage.exposure.adjust_sigmoid "skimage.exposure.adjust_sigmoid")(image[, …]) | Performs Sigmoid Correction on the input image. | | [`skimage.exposure.cumulative_distribution`](#skimage.exposure.cumulative_distribution "skimage.exposure.cumulative_distribution")(image) | Return cumulative distribution function (cdf) for the given image. | | [`skimage.exposure.equalize_adapthist`](#skimage.exposure.equalize_adapthist "skimage.exposure.equalize_adapthist")(image[, …]) | Contrast Limited Adaptive Histogram Equalization (CLAHE). | | [`skimage.exposure.equalize_hist`](#skimage.exposure.equalize_hist "skimage.exposure.equalize_hist")(image[, …]) | Return image after histogram equalization. | | [`skimage.exposure.histogram`](#skimage.exposure.histogram "skimage.exposure.histogram")(image[, nbins, …]) | Return histogram of image. | | [`skimage.exposure.is_low_contrast`](#skimage.exposure.is_low_contrast "skimage.exposure.is_low_contrast")(image[, …]) | Determine if an image is low contrast. | | [`skimage.exposure.match_histograms`](#skimage.exposure.match_histograms "skimage.exposure.match_histograms")(image, …) | Adjust an image so that its cumulative histogram matches that of another. | | [`skimage.exposure.rescale_intensity`](#skimage.exposure.rescale_intensity "skimage.exposure.rescale_intensity")(image[, …]) | Return image after stretching or shrinking its intensity levels. | adjust\_gamma ------------- `skimage.exposure.adjust_gamma(image, gamma=1, gain=1)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/exposure/exposure.py#L447-L508) Performs Gamma Correction on the input image. Also known as Power Law Transform. This function transforms the input image pixelwise according to the equation `O = I**gamma` after scaling each pixel to the range 0 to 1. Parameters `imagendarray` Input image. `gammafloat, optional` Non negative real number. Default value is 1. `gainfloat, optional` The constant multiplier. Default value is 1. Returns `outndarray` Gamma corrected output image. See also [`adjust_log`](#skimage.exposure.adjust_log "skimage.exposure.adjust_log") #### Notes For gamma greater than 1, the histogram will shift towards left and the output image will be darker than the input image. For gamma less than 1, the histogram will shift towards right and the output image will be brighter than the input image. #### References `1` <https://en.wikipedia.org/wiki/Gamma_correction> #### Examples ``` >>> from skimage import data, exposure, img_as_float >>> image = img_as_float(data.moon()) >>> gamma_corrected = exposure.adjust_gamma(image, 2) >>> # Output is darker for gamma > 1 >>> image.mean() > gamma_corrected.mean() True ``` ### Examples using `skimage.exposure.adjust_gamma` [Explore 3D images (of cells)](https://scikit-image.org/docs/0.18.x/auto_examples/applications/plot_3d_image_processing.html#sphx-glr-auto-examples-applications-plot-3d-image-processing-py) adjust\_log ----------- `skimage.exposure.adjust_log(image, gain=1, inv=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/exposure/exposure.py#L511-L551) Performs Logarithmic correction on the input image. This function transforms the input image pixelwise according to the equation `O = gain*log(1 + I)` after scaling each pixel to the range 0 to 1. For inverse logarithmic correction, the equation is `O = gain*(2**I - 1)`. Parameters `imagendarray` Input image. `gainfloat, optional` The constant multiplier. Default value is 1. `invfloat, optional` If True, it performs inverse logarithmic correction, else correction will be logarithmic. Defaults to False. Returns `outndarray` Logarithm corrected output image. See also [`adjust_gamma`](#skimage.exposure.adjust_gamma "skimage.exposure.adjust_gamma") #### References `1` <http://www.ece.ucsb.edu/Faculty/Manjunath/courses/ece178W03/EnhancePart1.pdf> adjust\_sigmoid --------------- `skimage.exposure.adjust_sigmoid(image, cutoff=0.5, gain=10, inv=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/exposure/exposure.py#L554-L600) Performs Sigmoid Correction on the input image. Also known as Contrast Adjustment. This function transforms the input image pixelwise according to the equation `O = 1/(1 + exp*(gain*(cutoff - I)))` after scaling each pixel to the range 0 to 1. Parameters `imagendarray` Input image. `cutofffloat, optional` Cutoff of the sigmoid function that shifts the characteristic curve in horizontal direction. Default value is 0.5. `gainfloat, optional` The constant multiplier in exponential’s power of sigmoid function. Default value is 10. `invbool, optional` If True, returns the negative sigmoid correction. Defaults to False. Returns `outndarray` Sigmoid corrected output image. See also [`adjust_gamma`](#skimage.exposure.adjust_gamma "skimage.exposure.adjust_gamma") #### References `1` Gustav J. Braun, β€œImage Lightness Rescaling Using Sigmoidal Contrast Enhancement Functions”, <http://www.cis.rit.edu/fairchild/PDFs/PAP07.pdf> cumulative\_distribution ------------------------ `skimage.exposure.cumulative_distribution(image, nbins=256)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/exposure/exposure.py#L147-L184) Return cumulative distribution function (cdf) for the given image. Parameters `imagearray` Image array. `nbinsint, optional` Number of bins for image histogram. Returns `img_cdfarray` Values of cumulative distribution function. `bin_centersarray` Centers of bins. See also [`histogram`](#skimage.exposure.histogram "skimage.exposure.histogram") #### References `1` <https://en.wikipedia.org/wiki/Cumulative_distribution_function> #### Examples ``` >>> from skimage import data, exposure, img_as_float >>> image = img_as_float(data.camera()) >>> hi = exposure.histogram(image) >>> cdf = exposure.cumulative_distribution(image) >>> np.alltrue(cdf[0] == np.cumsum(hi[0])/float(image.size)) True ``` ### Examples using `skimage.exposure.cumulative_distribution` [Local Histogram Equalization](https://scikit-image.org/docs/0.18.x/auto_examples/color_exposure/plot_local_equalize.html#sphx-glr-auto-examples-color-exposure-plot-local-equalize-py) [Explore 3D images (of cells)](https://scikit-image.org/docs/0.18.x/auto_examples/applications/plot_3d_image_processing.html#sphx-glr-auto-examples-applications-plot-3d-image-processing-py) equalize\_adapthist ------------------- `skimage.exposure.equalize_adapthist(image, kernel_size=None, clip_limit=0.01, nbins=256)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/exposure/_adapthist.py#L26-L95) Contrast Limited Adaptive Histogram Equalization (CLAHE). An algorithm for local contrast enhancement, that uses histograms computed over different tile regions of the image. Local details can therefore be enhanced even in regions that are darker or lighter than most of the image. Parameters `image(N1, …,NN[, C]) ndarray` Input image. **kernel\_size: int or array\_like, optional** Defines the shape of contextual regions used in the algorithm. If iterable is passed, it must have the same number of elements as `image.ndim` (without color channel). If integer, it is broadcasted to each `image` dimension. By default, `kernel_size` is 1/8 of `image` height by 1/8 of its width. `clip_limitfloat, optional` Clipping limit, normalized between 0 and 1 (higher values give more contrast). `nbinsint, optional` Number of gray bins for histogram (β€œdata range”). Returns `out(N1, …,NN[, C]) ndarray` Equalized image with float64 dtype. See also `equalize_hist,` [`rescale_intensity`](#skimage.exposure.rescale_intensity "skimage.exposure.rescale_intensity") #### Notes * For color images, the following steps are performed: + The image is converted to HSV color space + The CLAHE algorithm is run on the V (Value) channel + The image is converted back to RGB space and returned * For RGBA images, the original alpha channel is removed. Changed in version 0.17: The values returned by this function are slightly shifted upwards because of an internal change in rounding behavior. #### References `1` <http://tog.acm.org/resources/GraphicsGems/> `2` <https://en.wikipedia.org/wiki/CLAHE#CLAHE> ### Examples using `skimage.exposure.equalize_adapthist` [3D adaptive histogram equalization](https://scikit-image.org/docs/0.18.x/auto_examples/color_exposure/plot_adapt_hist_eq_3d.html#sphx-glr-auto-examples-color-exposure-plot-adapt-hist-eq-3d-py) equalize\_hist -------------- `skimage.exposure.equalize_hist(image, nbins=256, mask=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/exposure/exposure.py#L187-L223) Return image after histogram equalization. Parameters `imagearray` Image array. `nbinsint, optional` Number of bins for image histogram. Note: this argument is ignored for integer images, for which each integer is its own bin. **mask: ndarray of bools or 0s and 1s, optional** Array of same shape as `image`. Only points at which mask == True are used for the equalization, which is applied to the whole image. Returns `outfloat array` Image array after histogram equalization. #### Notes This function is adapted from [[1]](#rda90ab4dd09a-1) with the author’s permission. #### References `1` <http://www.janeriksolem.net/histogram-equalization-with-python-and.html> `2` <https://en.wikipedia.org/wiki/Histogram_equalization> ### Examples using `skimage.exposure.equalize_hist` [Local Histogram Equalization](https://scikit-image.org/docs/0.18.x/auto_examples/color_exposure/plot_local_equalize.html#sphx-glr-auto-examples-color-exposure-plot-local-equalize-py) [3D adaptive histogram equalization](https://scikit-image.org/docs/0.18.x/auto_examples/color_exposure/plot_adapt_hist_eq_3d.html#sphx-glr-auto-examples-color-exposure-plot-adapt-hist-eq-3d-py) [Explore 3D images (of cells)](https://scikit-image.org/docs/0.18.x/auto_examples/applications/plot_3d_image_processing.html#sphx-glr-auto-examples-applications-plot-3d-image-processing-py) [Rank filters](https://scikit-image.org/docs/0.18.x/auto_examples/applications/plot_rank_filters.html#sphx-glr-auto-examples-applications-plot-rank-filters-py) histogram --------- `skimage.exposure.histogram(image, nbins=256, source_range='image', normalize=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/exposure/exposure.py#L77-L144) Return histogram of image. Unlike [`numpy.histogram`](https://numpy.org/doc/stable/reference/generated/numpy.histogram.html#numpy.histogram "(in NumPy v1.19)"), this function returns the centers of bins and does not rebin integer arrays. For integer arrays, each integer value has its own bin, which improves speed and intensity-resolution. The histogram is computed on the flattened image: for color images, the function should be used separately on each channel to obtain a histogram for each color channel. Parameters `imagearray` Input image. `nbinsint, optional` Number of bins used to calculate histogram. This value is ignored for integer arrays. `source_rangestring, optional` β€˜image’ (default) determines the range from the input image. β€˜dtype’ determines the range from the expected range of the images of that data type. `normalizebool, optional` If True, normalize the histogram by the sum of its values. Returns `histarray` The values of the histogram. `bin_centersarray` The values at the center of the bins. See also [`cumulative_distribution`](#skimage.exposure.cumulative_distribution "skimage.exposure.cumulative_distribution") #### Examples ``` >>> from skimage import data, exposure, img_as_float >>> image = img_as_float(data.camera()) >>> np.histogram(image, bins=2) (array([ 93585, 168559]), array([0. , 0.5, 1. ])) >>> exposure.histogram(image, nbins=2) (array([ 93585, 168559]), array([0.25, 0.75])) ``` ### Examples using `skimage.exposure.histogram` [Rank filters](https://scikit-image.org/docs/0.18.x/auto_examples/applications/plot_rank_filters.html#sphx-glr-auto-examples-applications-plot-rank-filters-py) is\_low\_contrast ----------------- `skimage.exposure.is_low_contrast(image, fraction_threshold=0.05, lower_percentile=1, upper_percentile=99, method='linear')` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/exposure/exposure.py#L603-L654) Determine if an image is low contrast. Parameters `imagearray-like` The image under test. `fraction_thresholdfloat, optional` The low contrast fraction threshold. An image is considered low- contrast when its range of brightness spans less than this fraction of its data type’s full range. [[1]](#re0c68370bb9d-1) `lower_percentilefloat, optional` Disregard values below this percentile when computing image contrast. `upper_percentilefloat, optional` Disregard values above this percentile when computing image contrast. `methodstr, optional` The contrast determination method. Right now the only available option is β€œlinear”. Returns `outbool` True when the image is determined to be low contrast. #### References `1` <https://scikit-image.org/docs/dev/user_guide/data_types.html> #### Examples ``` >>> image = np.linspace(0, 0.04, 100) >>> is_low_contrast(image) True >>> image[-1] = 1 >>> is_low_contrast(image) True >>> is_low_contrast(image, upper_percentile=100) False ``` match\_histograms ----------------- `skimage.exposure.match_histograms(image, reference, *, multichannel=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/exposure/histogram_matching.py#L22-L70) Adjust an image so that its cumulative histogram matches that of another. The adjustment is applied separately for each channel. Parameters `imagendarray` Input image. Can be gray-scale or in color. `referencendarray` Image to match histogram of. Must have the same number of channels as image. `multichannelbool, optional` Apply the matching separately for each channel. Returns `matchedndarray` Transformed input image. Raises ValueError Thrown when the number of channels in the input image and the reference differ. #### References `1` <http://paulbourke.net/miscellaneous/equalisation/> rescale\_intensity ------------------ `skimage.exposure.rescale_intensity(image, in_range='image', out_range='dtype')` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/exposure/exposure.py#L313-L428) Return image after stretching or shrinking its intensity levels. The desired intensity range of the input and output, `in_range` and `out_range` respectively, are used to stretch or shrink the intensity range of the input image. See examples below. Parameters `imagearray` Image array. `in_range, out_rangestr or 2-tuple, optional` Min and max intensity values of input and output image. The possible values for this parameter are enumerated below. β€˜image’ Use image min/max as the intensity range. β€˜dtype’ Use min/max of the image’s dtype as the intensity range. dtype-name Use intensity range based on desired `dtype`. Must be valid key in `DTYPE_RANGE`. 2-tuple Use `range_values` as explicit min/max intensities. Returns `outarray` Image array after rescaling its intensity. This image is the same dtype as the input image. See also [`equalize_hist`](#skimage.exposure.equalize_hist "skimage.exposure.equalize_hist") #### Notes Changed in version 0.17: The dtype of the output array has changed to match the output dtype, or float if the output range is specified by a pair of floats. #### Examples By default, the min/max intensities of the input image are stretched to the limits allowed by the image’s dtype, since `in_range` defaults to β€˜image’ and `out_range` defaults to β€˜dtype’: ``` >>> image = np.array([51, 102, 153], dtype=np.uint8) >>> rescale_intensity(image) array([ 0, 127, 255], dtype=uint8) ``` It’s easy to accidentally convert an image dtype from uint8 to float: ``` >>> 1.0 * image array([ 51., 102., 153.]) ``` Use [`rescale_intensity`](#skimage.exposure.rescale_intensity "skimage.exposure.rescale_intensity") to rescale to the proper range for float dtypes: ``` >>> image_float = 1.0 * image >>> rescale_intensity(image_float) array([0. , 0.5, 1. ]) ``` To maintain the low contrast of the original, use the `in_range` parameter: ``` >>> rescale_intensity(image_float, in_range=(0, 255)) array([0.2, 0.4, 0.6]) ``` If the min/max value of `in_range` is more/less than the min/max image intensity, then the intensity levels are clipped: ``` >>> rescale_intensity(image_float, in_range=(0, 102)) array([0.5, 1. , 1. ]) ``` If you have an image with signed integers but want to rescale the image to just the positive range, use the `out_range` parameter. In that case, the output dtype will be float: ``` >>> image = np.array([-10, 0, 10], dtype=np.int8) >>> rescale_intensity(image, out_range=(0, 127)) array([ 0. , 63.5, 127. ]) ``` To get the desired range with a specific dtype, use `.astype()`: ``` >>> rescale_intensity(image, out_range=(0, 127)).astype(np.int8) array([ 0, 63, 127], dtype=int8) ``` If the input image is constant, the output will be clipped directly to the output range: >>> image = np.array([130, 130, 130], dtype=np.int32) >>> rescale\_intensity(image, out\_range=(0, 127)).astype(np.int32) array([127, 127, 127], dtype=int32) ### Examples using `skimage.exposure.rescale_intensity` [Phase Unwrapping](https://scikit-image.org/docs/0.18.x/auto_examples/filters/plot_phase_unwrap.html#sphx-glr-auto-examples-filters-plot-phase-unwrap-py) [Explore 3D images (of cells)](https://scikit-image.org/docs/0.18.x/auto_examples/applications/plot_3d_image_processing.html#sphx-glr-auto-examples-applications-plot-3d-image-processing-py) [Rank filters](https://scikit-image.org/docs/0.18.x/auto_examples/applications/plot_rank_filters.html#sphx-glr-auto-examples-applications-plot-rank-filters-py) scikit_image Module: future Module: future ============== Functionality with an experimental API. Although you can count on the functions in this package being around in the future, the API may change with any version update **and will not follow the skimage two-version deprecation path**. Therefore, use the functions herein with care, and do not use them in production code that will depend on updated skimage versions. | | | | --- | --- | | [`skimage.future.fit_segmenter`](#skimage.future.fit_segmenter "skimage.future.fit_segmenter")(labels, …) | Segmentation using labeled parts of the image and a classifier. | | [`skimage.future.manual_lasso_segmentation`](#skimage.future.manual_lasso_segmentation "skimage.future.manual_lasso_segmentation")(image) | Return a label image based on freeform selections made with the mouse. | | [`skimage.future.manual_polygon_segmentation`](#skimage.future.manual_polygon_segmentation "skimage.future.manual_polygon_segmentation")(image) | Return a label image based on polygon selections made with the mouse. | | [`skimage.future.predict_segmenter`](#skimage.future.predict_segmenter "skimage.future.predict_segmenter")(features, clf) | Segmentation of images using a pretrained classifier. | | [`skimage.future.TrainableSegmenter`](#skimage.future.TrainableSegmenter "skimage.future.TrainableSegmenter")([clf, …]) | Estimator for classifying pixels. | | [`skimage.future.graph`](skimage.future.graph#module-skimage.future.graph "skimage.future.graph") | | fit\_segmenter -------------- `skimage.future.fit_segmenter(labels, features, clf)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/future/trainable_segmentation.py#L89-L118) Segmentation using labeled parts of the image and a classifier. Parameters `labelsndarray of ints` Image of labels. Labels >= 1 correspond to the training set and label 0 to unlabeled pixels to be segmented. `featuresndarray` Array of features, with the first dimension corresponding to the number of features, and the other dimensions correspond to `labels.shape`. `clfclassifier object` classifier object, exposing a `fit` and a `predict` method as in scikit-learn’s API, for example an instance of `RandomForestClassifier` or `LogisticRegression` classifier. Returns `clfclassifier object` classifier trained on `labels` Raises `NotFittedError if self.clf has not been fitted yet (use self.fit).` ### Examples using `skimage.future.fit_segmenter` [Trainable segmentation using local features and random forests](https://scikit-image.org/docs/0.18.x/auto_examples/segmentation/plot_trainable_segmentation.html#sphx-glr-auto-examples-segmentation-plot-trainable-segmentation-py) manual\_lasso\_segmentation --------------------------- `skimage.future.manual_lasso_segmentation(image, alpha=0.4, return_all=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/future/manual_segmentation.py#L147-L227) Return a label image based on freeform selections made with the mouse. Parameters `image(M, N[, 3]) array` Grayscale or RGB image. `alphafloat, optional` Transparency value for polygons drawn over the image. `return_allbool, optional` If True, an array containing each separate polygon drawn is returned. (The polygons may overlap.) If False (default), latter polygons β€œoverwrite” earlier ones where they overlap. Returns `labelsarray of int, shape ([Q, ]M, N)` The segmented regions. If mode is `β€˜separate’`, the leading dimension of the array corresponds to the number of regions that the user drew. #### Notes Press and hold the left mouse button to draw around each object. #### Examples ``` >>> from skimage import data, future, io >>> camera = data.camera() >>> mask = future.manual_lasso_segmentation(camera) >>> io.imshow(mask) >>> io.show() ``` manual\_polygon\_segmentation ----------------------------- `skimage.future.manual_polygon_segmentation(image, alpha=0.4, return_all=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/future/manual_segmentation.py#L31-L144) Return a label image based on polygon selections made with the mouse. Parameters `image(M, N[, 3]) array` Grayscale or RGB image. `alphafloat, optional` Transparency value for polygons drawn over the image. `return_allbool, optional` If True, an array containing each separate polygon drawn is returned. (The polygons may overlap.) If False (default), latter polygons β€œoverwrite” earlier ones where they overlap. Returns `labelsarray of int, shape ([Q, ]M, N)` The segmented regions. If mode is `β€˜separate’`, the leading dimension of the array corresponds to the number of regions that the user drew. #### Notes Use left click to select the vertices of the polygon and right click to confirm the selection once all vertices are selected. #### Examples ``` >>> from skimage import data, future, io >>> camera = data.camera() >>> mask = future.manual_polygon_segmentation(camera) >>> io.imshow(mask) >>> io.show() ``` predict\_segmenter ------------------ `skimage.future.predict_segmenter(features, clf)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/future/trainable_segmentation.py#L121-L160) Segmentation of images using a pretrained classifier. Parameters `featuresndarray` Array of features, with the last dimension corresponding to the number of features, and the other dimensions are compatible with the shape of the image to segment, or a flattened image. `clfclassifier object` trained classifier object, exposing a `predict` method as in scikit-learn’s API, for example an instance of `RandomForestClassifier` or `LogisticRegression` classifier. The classifier must be already trained, for example with `skimage.segmentation.fit_segmenter()`. Returns `outputndarray` Labeled array, built from the prediction of the classifier. ### Examples using `skimage.future.predict_segmenter` [Trainable segmentation using local features and random forests](https://scikit-image.org/docs/0.18.x/auto_examples/segmentation/plot_trainable_segmentation.html#sphx-glr-auto-examples-segmentation-plot-trainable-segmentation-py) TrainableSegmenter ------------------ `class skimage.future.TrainableSegmenter(clf=None, features_func=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/future/trainable_segmentation.py#L14-L86) Bases: [`object`](https://docs.python.org/3.9/library/functions.html#object "(in Python v3.9)") Estimator for classifying pixels. Parameters `clfclassifier object, optional` classifier object, exposing a `fit` and a `predict` method as in scikit-learn’s API, for example an instance of `RandomForestClassifier` or `LogisticRegression` classifier. `features_funcfunction, optional` function computing features on all pixels of the image, to be passed to the classifier. The output should be of shape `(m_features, *labels.shape)`. If None, `skimage.segmentation.multiscale_basic_features()` is used. #### Methods | | | | --- | --- | | [`fit`](#skimage.future.TrainableSegmenter.fit "skimage.future.TrainableSegmenter.fit")(image, labels) | Train classifier using partially labeled (annotated) image. | | [`predict`](#skimage.future.TrainableSegmenter.predict "skimage.future.TrainableSegmenter.predict")(image) | Segment new image using trained internal classifier. | | | | | --- | --- | | **compute\_features** | | `__init__(clf=None, features_func=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/future/trainable_segmentation.py#L36-L47) Initialize self. See help(type(self)) for accurate signature. `compute_features(image)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/future/trainable_segmentation.py#L49-L52) `fit(image, labels)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/future/trainable_segmentation.py#L54-L68) Train classifier using partially labeled (annotated) image. Parameters `imagendarray` Input image, which can be grayscale or multichannel, and must have a number of dimensions compatible with `self.features_func`. `labelsndarray of ints` Labeled array of shape compatible with `image` (same shape for a single-channel image). Labels >= 1 correspond to the training set and label 0 to unlabeled pixels to be segmented. `predict(image)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/future/trainable_segmentation.py#L70-L86) Segment new image using trained internal classifier. Parameters `imagendarray` Input image, which can be grayscale or multichannel, and must have a number of dimensions compatible with `self.features_func`. Raises `NotFittedError if self.clf has not been fitted yet (use self.fit).`
programming_docs
scikit_image Module: util Module: util ============ | | | | --- | --- | | [`skimage.util.apply_parallel`](#skimage.util.apply_parallel "skimage.util.apply_parallel")(function, array) | Map a function in parallel across an array. | | [`skimage.util.compare_images`](#skimage.util.compare_images "skimage.util.compare_images")(image1, image2) | Return an image showing the differences between two images. | | [`skimage.util.crop`](#skimage.util.crop "skimage.util.crop")(ar, crop\_width[, copy, order]) | Crop array `ar` by `crop_width` along each dimension. | | [`skimage.util.dtype_limits`](#skimage.util.dtype_limits "skimage.util.dtype_limits")(image[, clip\_negative]) | Return intensity limits, i.e. | | [`skimage.util.img_as_bool`](#skimage.util.img_as_bool "skimage.util.img_as_bool")(image[, force\_copy]) | Convert an image to boolean format. | | [`skimage.util.img_as_float`](#skimage.util.img_as_float "skimage.util.img_as_float")(image[, force\_copy]) | Convert an image to floating point format. | | [`skimage.util.img_as_float32`](#skimage.util.img_as_float32 "skimage.util.img_as_float32")(image[, force\_copy]) | Convert an image to single-precision (32-bit) floating point format. | | [`skimage.util.img_as_float64`](#skimage.util.img_as_float64 "skimage.util.img_as_float64")(image[, force\_copy]) | Convert an image to double-precision (64-bit) floating point format. | | [`skimage.util.img_as_int`](#skimage.util.img_as_int "skimage.util.img_as_int")(image[, force\_copy]) | Convert an image to 16-bit signed integer format. | | [`skimage.util.img_as_ubyte`](#skimage.util.img_as_ubyte "skimage.util.img_as_ubyte")(image[, force\_copy]) | Convert an image to 8-bit unsigned integer format. | | [`skimage.util.img_as_uint`](#skimage.util.img_as_uint "skimage.util.img_as_uint")(image[, force\_copy]) | Convert an image to 16-bit unsigned integer format. | | [`skimage.util.invert`](#skimage.util.invert "skimage.util.invert")(image[, signed\_float]) | Invert an image. | | [`skimage.util.map_array`](#skimage.util.map_array "skimage.util.map_array")(input\_arr, …[, out]) | Map values from input array from input\_vals to output\_vals. | | [`skimage.util.montage`](#skimage.util.montage "skimage.util.montage")(arr\_in[, fill, …]) | Create a montage of several single- or multichannel images. | | [`skimage.util.pad`](#skimage.util.pad "skimage.util.pad")(array, pad\_width[, mode]) | Pad an array. | | [`skimage.util.random_noise`](#skimage.util.random_noise "skimage.util.random_noise")(image[, mode, …]) | Function to add random noise of various types to a floating-point image. | | [`skimage.util.regular_grid`](#skimage.util.regular_grid "skimage.util.regular_grid")(ar\_shape, n\_points) | Find `n_points` regularly spaced along `ar_shape`. | | [`skimage.util.regular_seeds`](#skimage.util.regular_seeds "skimage.util.regular_seeds")(ar\_shape, n\_points) | Return an image with ~`n\_points` regularly-spaced nonzero pixels. | | [`skimage.util.unique_rows`](#skimage.util.unique_rows "skimage.util.unique_rows")(ar) | Remove repeated rows from a 2D array. | | [`skimage.util.view_as_blocks`](#skimage.util.view_as_blocks "skimage.util.view_as_blocks")(arr\_in, block\_shape) | Block view of the input n-dimensional array (using re-striding). | | [`skimage.util.view_as_windows`](#skimage.util.view_as_windows "skimage.util.view_as_windows")(arr\_in, …[, step]) | Rolling window view of the input n-dimensional array. | apply\_parallel --------------- `skimage.util.apply_parallel(function, array, chunks=None, depth=0, mode=None, extra_arguments=(), extra_keywords={}, *, dtype=None, multichannel=False, compute=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/util/apply_parallel.py#L58-L177) Map a function in parallel across an array. Split an array into possibly overlapping chunks of a given depth and boundary type, call the given function in parallel on the chunks, combine the chunks and return the resulting array. Parameters `functionfunction` Function to be mapped which takes an array as an argument. `arraynumpy array or dask array` Array which the function will be applied to. `chunksint, tuple, or tuple of tuples, optional` A single integer is interpreted as the length of one side of a square chunk that should be tiled across the array. One tuple of length `array.ndim` represents the shape of a chunk, and it is tiled across the array. A list of tuples of length `ndim`, where each sub-tuple is a sequence of chunk sizes along the corresponding dimension. If None, the array is broken up into chunks based on the number of available cpus. More information about chunks is in the documentation [here](https://dask.pydata.org/en/latest/array-design.html). `depthint, optional` Integer equal to the depth of the added boundary cells. Defaults to zero. `mode{β€˜reflect’, β€˜symmetric’, β€˜periodic’, β€˜wrap’, β€˜nearest’, β€˜edge’}, optional` type of external boundary padding. `extra_argumentstuple, optional` Tuple of arguments to be passed to the function. `extra_keywordsdictionary, optional` Dictionary of keyword arguments to be passed to the function. `dtypedata-type or None, optional` The data-type of the `function` output. If None, Dask will attempt to infer this by calling the function on data of shape `(1,) * ndim`. For functions expecting RGB or multichannel data this may be problematic. In such cases, the user should manually specify this dtype argument instead. New in version 0.18: `dtype` was added in 0.18. `multichannelbool, optional` If `chunks` is None and `multichannel` is True, this function will keep only a single chunk along the channels axis. When `depth` is specified as a scalar value, that depth will be applied only to the non-channels axes (a depth of 0 will be used along the channels axis). If the user manually specified both `chunks` and a `depth` tuple, then this argument will have no effect. New in version 0.18: `multichannel` was added in 0.18. `computebool, optional` If `True`, compute eagerly returning a NumPy Array. If `False`, compute lazily returning a Dask Array. If `None` (default), compute based on array type provided (eagerly for NumPy Arrays and lazily for Dask Arrays). Returns `outndarray or dask Array` Returns the result of the applying the operation. Type is dependent on the `compute` argument. #### Notes Numpy edge modes β€˜symmetric’, β€˜wrap’, and β€˜edge’ are converted to the equivalent `dask` boundary modes β€˜reflect’, β€˜periodic’ and β€˜nearest’, respectively. Setting `compute=False` can be useful for chaining later operations. For example region selection to preview a result or storing large data to disk instead of loading in memory. compare\_images --------------- `skimage.util.compare_images(image1, image2, method='diff', *, n_tiles=(8, 8))` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/util/compare.py#L6-L60) Return an image showing the differences between two images. New in version 0.16. Parameters `image1, image22-D array` Images to process, must be of the same shape. `methodstring, optional` Method used for the comparison. Valid values are {β€˜diff’, β€˜blend’, β€˜checkerboard’}. Details are provided in the note section. `n_tilestuple, optional` Used only for the `checkerboard` method. Specifies the number of tiles (row, column) to divide the image. Returns `comparison2-D array` Image showing the differences. #### Notes `'diff'` computes the absolute difference between the two images. `'blend'` computes the mean value. `'checkerboard'` makes tiles of dimension `n_tiles` that display alternatively the first and the second image. crop ---- `skimage.util.crop(ar, crop_width, copy=False, order='K')` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/util/arraycrop.py#L11-L72) Crop array `ar` by `crop_width` along each dimension. Parameters `ararray-like of rank N` Input array. `crop_width{sequence, int}` Number of values to remove from the edges of each axis. `((before_1, after_1),` … `(before_N, after_N))` specifies unique crop widths at the start and end of each axis. `((before, after),) or (before, after)` specifies a fixed start and end crop for every axis. `(n,)` or `n` for integer `n` is a shortcut for before = after = `n` for all axes. `copybool, optional` If `True`, ensure the returned array is a contiguous copy. Normally, a crop operation will return a discontiguous view of the underlying input array. `order{β€˜C’, β€˜F’, β€˜A’, β€˜K’}, optional` If `copy==True`, control the memory layout of the copy. See `np.copy`. Returns `croppedarray` The cropped array. If `copy=False` (default), this is a sliced view of the input array. dtype\_limits ------------- `skimage.util.dtype_limits(image, clip_negative=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/util/dtype.py#L38-L57) Return intensity limits, i.e. (min, max) tuple, of the image’s dtype. Parameters `imagendarray` Input image. `clip_negativebool, optional` If True, clip the negative range (i.e. return 0 for min intensity) even if the image dtype allows negative values. Returns `imin, imaxtuple` Lower and upper intensity limits. img\_as\_bool ------------- `skimage.util.img_as_bool(image, force_copy=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/util/dtype.py#L534-L555) Convert an image to boolean format. Parameters `imagendarray` Input image. `force_copybool, optional` Force a copy of the data, irrespective of its current dtype. Returns `outndarray of bool (bool_)` Output image. #### Notes The upper half of the input dtype’s positive range is True, and the lower half is False. All negative values (if present) are False. img\_as\_float -------------- `skimage.util.img_as_float(image, force_copy=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/util/dtype.py#L432-L458) Convert an image to floating point format. This function is similar to [`img_as_float64`](#skimage.util.img_as_float64 "skimage.util.img_as_float64"), but will not convert lower-precision floating point arrays to `float64`. Parameters `imagendarray` Input image. `force_copybool, optional` Force a copy of the data, irrespective of its current dtype. Returns `outndarray of float` Output image. #### Notes The range of a floating point image is [0.0, 1.0] or [-1.0, 1.0] when converting from unsigned or signed datatypes, respectively. If the input image has a float type, intensity values are not modified and can be outside the ranges [0.0, 1.0] or [-1.0, 1.0]. img\_as\_float32 ---------------- `skimage.util.img_as_float32(image, force_copy=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/util/dtype.py#L380-L403) Convert an image to single-precision (32-bit) floating point format. Parameters `imagendarray` Input image. `force_copybool, optional` Force a copy of the data, irrespective of its current dtype. Returns `outndarray of float32` Output image. #### Notes The range of a floating point image is [0.0, 1.0] or [-1.0, 1.0] when converting from unsigned or signed datatypes, respectively. If the input image has a float type, intensity values are not modified and can be outside the ranges [0.0, 1.0] or [-1.0, 1.0]. img\_as\_float64 ---------------- `skimage.util.img_as_float64(image, force_copy=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/util/dtype.py#L406-L429) Convert an image to double-precision (64-bit) floating point format. Parameters `imagendarray` Input image. `force_copybool, optional` Force a copy of the data, irrespective of its current dtype. Returns `outndarray of float64` Output image. #### Notes The range of a floating point image is [0.0, 1.0] or [-1.0, 1.0] when converting from unsigned or signed datatypes, respectively. If the input image has a float type, intensity values are not modified and can be outside the ranges [0.0, 1.0] or [-1.0, 1.0]. img\_as\_int ------------ `skimage.util.img_as_int(image, force_copy=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/util/dtype.py#L485-L507) Convert an image to 16-bit signed integer format. Parameters `imagendarray` Input image. `force_copybool, optional` Force a copy of the data, irrespective of its current dtype. Returns `outndarray of int16` Output image. #### Notes The values are scaled between -32768 and 32767. If the input data-type is positive-only (e.g., uint8), then the output image will still only have positive values. img\_as\_ubyte -------------- `skimage.util.img_as_ubyte(image, force_copy=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/util/dtype.py#L510-L531) Convert an image to 8-bit unsigned integer format. Parameters `imagendarray` Input image. `force_copybool, optional` Force a copy of the data, irrespective of its current dtype. Returns `outndarray of ubyte (uint8)` Output image. #### Notes Negative input values will be clipped. Positive values are scaled between 0 and 255. img\_as\_uint ------------- `skimage.util.img_as_uint(image, force_copy=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/util/dtype.py#L461-L482) Convert an image to 16-bit unsigned integer format. Parameters `imagendarray` Input image. `force_copybool, optional` Force a copy of the data, irrespective of its current dtype. Returns `outndarray of uint16` Output image. #### Notes Negative input values will be clipped. Positive values are scaled between 0 and 65535. invert ------ `skimage.util.invert(image, signed_float=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/util/_invert.py#L5-L74) Invert an image. Invert the intensity range of the input image, so that the dtype maximum is now the dtype minimum, and vice-versa. This operation is slightly different depending on the input dtype: * unsigned integers: subtract the image from the dtype maximum * signed integers: subtract the image from -1 (see Notes) * floats: subtract the image from 1 (if signed\_float is False, so we assume the image is unsigned), or from 0 (if signed\_float is True). See the examples for clarification. Parameters `imagendarray` Input image. `signed_floatbool, optional` If True and the image is of type float, the range is assumed to be [-1, 1]. If False and the image is of type float, the range is assumed to be [0, 1]. Returns `invertedndarray` Inverted image. #### Notes Ideally, for signed integers we would simply multiply by -1. However, signed integer ranges are asymmetric. For example, for np.int8, the range of possible values is [-128, 127], so that -128 \* -1 equals -128! By subtracting from -1, we correctly map the maximum dtype value to the minimum. #### Examples ``` >>> img = np.array([[100, 0, 200], ... [ 0, 50, 0], ... [ 30, 0, 255]], np.uint8) >>> invert(img) array([[155, 255, 55], [255, 205, 255], [225, 255, 0]], dtype=uint8) >>> img2 = np.array([[ -2, 0, -128], ... [127, 0, 5]], np.int8) >>> invert(img2) array([[ 1, -1, 127], [-128, -1, -6]], dtype=int8) >>> img3 = np.array([[ 0., 1., 0.5, 0.75]]) >>> invert(img3) array([[1. , 0. , 0.5 , 0.25]]) >>> img4 = np.array([[ 0., 1., -1., -0.25]]) >>> invert(img4, signed_float=True) array([[-0. , -1. , 1. , 0.25]]) ``` ### Examples using `skimage.util.invert` [Use rolling-ball algorithm for estimating background intensity](https://scikit-image.org/docs/0.18.x/auto_examples/segmentation/plot_rolling_ball.html#sphx-glr-auto-examples-segmentation-plot-rolling-ball-py) map\_array ---------- `skimage.util.map_array(input_arr, input_vals, output_vals, out=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/util/_map_array.py#L5-L58) Map values from input array from input\_vals to output\_vals. Parameters `input_arrarray of int, shape (M[, N][, P][, …])` The input label image. `input_valsarray of int, shape (N,)` The values to map from. `output_valsarray, shape (N,)` The values to map to. **out: array, same shape as `input\_arr`** The output array. Will be created if not provided. It should have the same dtype as `output_vals`. Returns `outarray, same shape as input_arr` The array of mapped values. montage ------- `skimage.util.montage(arr_in, fill='mean', rescale_intensity=False, grid_shape=None, padding_width=0, multichannel=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/util/_montage.py#L7-L142) Create a montage of several single- or multichannel images. Create a rectangular montage from an input array representing an ensemble of equally shaped single- (gray) or multichannel (color) images. For example, `montage(arr_in)` called with the following `arr_in` | | | | | --- | --- | --- | | 1 | 2 | 3 | will return | | | | --- | --- | | 1 | 2 | | 3 | * | where the β€˜\*’ patch will be determined by the `fill` parameter. Parameters `arr_in(K, M, N[, C]) ndarray` An array representing an ensemble of `K` images of equal shape. `fillfloat or array-like of floats or β€˜mean’, optional` Value to fill the padding areas and/or the extra tiles in the output array. Has to be `float` for single channel collections. For multichannel collections has to be an array-like of shape of number of channels. If `mean`, uses the mean value over all images. `rescale_intensitybool, optional` Whether to rescale the intensity of each image to [0, 1]. `grid_shapetuple, optional` The desired grid shape for the montage `(ntiles_row, ntiles_column)`. The default aspect ratio is square. `padding_widthint, optional` The size of the spacing between the tiles and between the tiles and the borders. If non-zero, makes the boundaries of individual images easier to perceive. `multichannelboolean, optional` If True, the last `arr_in` dimension is threated as a color channel, otherwise as spatial. Returns `arr_out(K*(M+p)+p, K*(N+p)+p[, C]) ndarray` Output array with input images glued together (including padding `p`). #### Examples ``` >>> import numpy as np >>> from skimage.util import montage >>> arr_in = np.arange(3 * 2 * 2).reshape(3, 2, 2) >>> arr_in array([[[ 0, 1], [ 2, 3]], [[ 4, 5], [ 6, 7]], [[ 8, 9], [10, 11]]]) >>> arr_out = montage(arr_in) >>> arr_out.shape (4, 4) >>> arr_out array([[ 0, 1, 4, 5], [ 2, 3, 6, 7], [ 8, 9, 5, 5], [10, 11, 5, 5]]) >>> arr_in.mean() 5.5 >>> arr_out_nonsquare = montage(arr_in, grid_shape=(1, 3)) >>> arr_out_nonsquare array([[ 0, 1, 4, 5, 8, 9], [ 2, 3, 6, 7, 10, 11]]) >>> arr_out_nonsquare.shape (2, 6) ``` pad --- `skimage.util.pad(array, pad_width, mode='constant', **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/../numpy/lib/arraypad.py#L529-L876) Pad an array. Parameters `arrayarray_like of rank N` The array to pad. `pad_width{sequence, array_like, int}` Number of values padded to the edges of each axis. ((before\_1, after\_1), … (before\_N, after\_N)) unique pad widths for each axis. ((before, after),) yields same before and after pad for each axis. (pad,) or int is a shortcut for before = after = pad width for all axes. `modestr or function, optional` One of the following string values or a user supplied function. β€˜constant’ (default) Pads with a constant value. β€˜edge’ Pads with the edge values of array. β€˜linear\_ramp’ Pads with the linear ramp between end\_value and the array edge value. β€˜maximum’ Pads with the maximum value of all or part of the vector along each axis. β€˜mean’ Pads with the mean value of all or part of the vector along each axis. β€˜median’ Pads with the median value of all or part of the vector along each axis. β€˜minimum’ Pads with the minimum value of all or part of the vector along each axis. β€˜reflect’ Pads with the reflection of the vector mirrored on the first and last values of the vector along each axis. β€˜symmetric’ Pads with the reflection of the vector mirrored along the edge of the array. β€˜wrap’ Pads with the wrap of the vector along the axis. The first values are used to pad the end and the end values are used to pad the beginning. β€˜empty’ Pads with undefined values. New in version 1.17. <function> Padding function, see Notes. `stat_lengthsequence or int, optional` Used in β€˜maximum’, β€˜mean’, β€˜median’, and β€˜minimum’. Number of values at edge of each axis used to calculate the statistic value. ((before\_1, after\_1), … (before\_N, after\_N)) unique statistic lengths for each axis. ((before, after),) yields same before and after statistic lengths for each axis. (stat\_length,) or int is a shortcut for before = after = statistic length for all axes. Default is `None`, to use the entire axis. `constant_valuessequence or scalar, optional` Used in β€˜constant’. The values to set the padded values for each axis. `((before_1, after_1), ... (before_N, after_N))` unique pad constants for each axis. `((before, after),)` yields same before and after constants for each axis. `(constant,)` or `constant` is a shortcut for `before = after = constant` for all axes. Default is 0. `end_valuessequence or scalar, optional` Used in β€˜linear\_ramp’. The values used for the ending value of the linear\_ramp and that will form the edge of the padded array. `((before_1, after_1), ... (before_N, after_N))` unique end values for each axis. `((before, after),)` yields same before and after end values for each axis. `(constant,)` or `constant` is a shortcut for `before = after = constant` for all axes. Default is 0. `reflect_type{β€˜even’, β€˜odd’}, optional` Used in β€˜reflect’, and β€˜symmetric’. The β€˜even’ style is the default with an unaltered reflection around the edge value. For the β€˜odd’ style, the extended part of the array is created by subtracting the reflected values from two times the edge value. Returns `padndarray` Padded array of rank equal to [`array`](https://docs.python.org/3.9/library/array.html#module-array "(in Python v3.9)") with shape increased according to `pad_width`. #### Notes New in version 1.7.0. For an array with rank greater than 1, some of the padding of later axes is calculated from padding of previous axes. This is easiest to think about with a rank 2 array where the corners of the padded array are calculated by using padded values from the first axis. The padding function, if used, should modify a rank 1 array in-place. It has the following signature: ``` padding_func(vector, iaxis_pad_width, iaxis, kwargs) ``` where `vectorndarray` A rank 1 array already padded with zeros. Padded values are vector[:iaxis\_pad\_width[0]] and vector[-iaxis\_pad\_width[1]:]. `iaxis_pad_widthtuple` A 2-tuple of ints, iaxis\_pad\_width[0] represents the number of values padded at the beginning of vector where iaxis\_pad\_width[1] represents the number of values padded at the end of vector. `iaxisint` The axis currently being calculated. `kwargsdict` Any keyword arguments the function requires. #### Examples ``` >>> a = [1, 2, 3, 4, 5] >>> np.pad(a, (2, 3), 'constant', constant_values=(4, 6)) array([4, 4, 1, ..., 6, 6, 6]) ``` ``` >>> np.pad(a, (2, 3), 'edge') array([1, 1, 1, ..., 5, 5, 5]) ``` ``` >>> np.pad(a, (2, 3), 'linear_ramp', end_values=(5, -4)) array([ 5, 3, 1, 2, 3, 4, 5, 2, -1, -4]) ``` ``` >>> np.pad(a, (2,), 'maximum') array([5, 5, 1, 2, 3, 4, 5, 5, 5]) ``` ``` >>> np.pad(a, (2,), 'mean') array([3, 3, 1, 2, 3, 4, 5, 3, 3]) ``` ``` >>> np.pad(a, (2,), 'median') array([3, 3, 1, 2, 3, 4, 5, 3, 3]) ``` ``` >>> a = [[1, 2], [3, 4]] >>> np.pad(a, ((3, 2), (2, 3)), 'minimum') array([[1, 1, 1, 2, 1, 1, 1], [1, 1, 1, 2, 1, 1, 1], [1, 1, 1, 2, 1, 1, 1], [1, 1, 1, 2, 1, 1, 1], [3, 3, 3, 4, 3, 3, 3], [1, 1, 1, 2, 1, 1, 1], [1, 1, 1, 2, 1, 1, 1]]) ``` ``` >>> a = [1, 2, 3, 4, 5] >>> np.pad(a, (2, 3), 'reflect') array([3, 2, 1, 2, 3, 4, 5, 4, 3, 2]) ``` ``` >>> np.pad(a, (2, 3), 'reflect', reflect_type='odd') array([-1, 0, 1, 2, 3, 4, 5, 6, 7, 8]) ``` ``` >>> np.pad(a, (2, 3), 'symmetric') array([2, 1, 1, 2, 3, 4, 5, 5, 4, 3]) ``` ``` >>> np.pad(a, (2, 3), 'symmetric', reflect_type='odd') array([0, 1, 1, 2, 3, 4, 5, 5, 6, 7]) ``` ``` >>> np.pad(a, (2, 3), 'wrap') array([4, 5, 1, 2, 3, 4, 5, 1, 2, 3]) ``` ``` >>> def pad_with(vector, pad_width, iaxis, kwargs): ... pad_value = kwargs.get('padder', 10) ... vector[:pad_width[0]] = pad_value ... vector[-pad_width[1]:] = pad_value >>> a = np.arange(6) >>> a = a.reshape((2, 3)) >>> np.pad(a, 2, pad_with) array([[10, 10, 10, 10, 10, 10, 10], [10, 10, 10, 10, 10, 10, 10], [10, 10, 0, 1, 2, 10, 10], [10, 10, 3, 4, 5, 10, 10], [10, 10, 10, 10, 10, 10, 10], [10, 10, 10, 10, 10, 10, 10]]) >>> np.pad(a, 2, pad_with, padder=100) array([[100, 100, 100, 100, 100, 100, 100], [100, 100, 100, 100, 100, 100, 100], [100, 100, 0, 1, 2, 100, 100], [100, 100, 3, 4, 5, 100, 100], [100, 100, 100, 100, 100, 100, 100], [100, 100, 100, 100, 100, 100, 100]]) ``` random\_noise ------------- `skimage.util.random_noise(image, mode='gaussian', seed=None, clip=True, **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/util/noise.py#L8-L192) Function to add random noise of various types to a floating-point image. Parameters `imagendarray` Input image data. Will be converted to float. `modestr, optional` One of the following strings, selecting the type of noise to add: * β€˜gaussian’ Gaussian-distributed additive noise. * β€˜localvar’ Gaussian-distributed additive noise, with specified local variance at each point of `image`. * β€˜poisson’ Poisson-distributed noise generated from the data. * β€˜salt’ Replaces random pixels with 1. * β€˜pepper’ Replaces random pixels with 0 (for unsigned images) or -1 (for signed images). * `β€˜s&p’ Replaces random pixels with either 1 or low_val, where` `low_val` is 0 for unsigned images or -1 for signed images. * β€˜speckle’ Multiplicative noise using out = image + n\*image, where n is Gaussian noise with specified mean & variance. `seedint, optional` If provided, this will set the random seed before generating noise, for valid pseudo-random comparisons. `clipbool, optional` If True (default), the output will be clipped after noise applied for modes `β€˜speckle’`, `β€˜poisson’`, and `β€˜gaussian’`. This is needed to maintain the proper image data range. If False, clipping is not applied, and the output may extend beyond the range [-1, 1]. `meanfloat, optional` Mean of random distribution. Used in β€˜gaussian’ and β€˜speckle’. Default : 0. `varfloat, optional` Variance of random distribution. Used in β€˜gaussian’ and β€˜speckle’. Note: variance = (standard deviation) \*\* 2. Default : 0.01 `local_varsndarray, optional` Array of positive floats, same shape as `image`, defining the local variance at every image point. Used in β€˜localvar’. `amountfloat, optional` Proportion of image pixels to replace with noise on range [0, 1]. Used in β€˜salt’, β€˜pepper’, and β€˜salt & pepper’. Default : 0.05 `salt_vs_pepperfloat, optional` Proportion of salt vs. pepper noise for β€˜s&p’ on range [0, 1]. Higher values represent more salt. Default : 0.5 (equal amounts) Returns `outndarray` Output floating-point image data on range [0, 1] or [-1, 1] if the input `image` was unsigned or signed, respectively. #### Notes Speckle, Poisson, Localvar, and Gaussian noise may generate noise outside the valid image range. The default is to clip (not alias) these values, but they may be preserved by setting `clip=False`. Note that in this case the output may contain values outside the ranges [0, 1] or [-1, 1]. Use this option with care. Because of the prevalence of exclusively positive floating-point images in intermediate calculations, it is not possible to intuit if an input is signed based on dtype alone. Instead, negative values are explicitly searched for. Only if found does this function assume signed input. Unexpected results only occur in rare, poorly exposes cases (e.g. if all values are above 50 percent gray in a signed `image`). In this event, manually scaling the input to the positive domain will solve the problem. The Poisson distribution is only defined for positive integers. To apply this noise type, the number of unique values in the image is found and the next round power of two is used to scale up the floating-point result, after which it is scaled back down to the floating-point image range. To generate Poisson noise against a signed image, the signed image is temporarily converted to an unsigned image in the floating point domain, Poisson noise is generated, then it is returned to the original range. regular\_grid ------------- `skimage.util.regular_grid(ar_shape, n_points)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/util/_regular_grid.py#L4-L83) Find `n_points` regularly spaced along `ar_shape`. The returned points (as slices) should be as close to cubically-spaced as possible. Essentially, the points are spaced by the Nth root of the input array size, where N is the number of dimensions. However, if an array dimension cannot fit a full step size, it is β€œdiscarded”, and the computation is done for only the remaining dimensions. Parameters `ar_shapearray-like of ints` The shape of the space embedding the grid. `len(ar_shape)` is the number of dimensions. `n_pointsint` The (approximate) number of points to embed in the space. Returns `slicestuple of slice objects` A slice along each dimension of `ar_shape`, such that the intersection of all the slices give the coordinates of regularly spaced points. Changed in version 0.14.1: In scikit-image 0.14.1 and 0.15, the return type was changed from a list to a tuple to ensure [compatibility with Numpy 1.15](https://github.com/numpy/numpy/blob/master/doc/release/1.15.0-notes.rst#deprecations) and higher. If your code requires the returned result to be a list, you may convert the output of this function to a list with: ``` >>> result = list(regular_grid(ar_shape=(3, 20, 40), n_points=8)) ``` #### Examples ``` >>> ar = np.zeros((20, 40)) >>> g = regular_grid(ar.shape, 8) >>> g (slice(5, None, 10), slice(5, None, 10)) >>> ar[g] = 1 >>> ar.sum() 8.0 >>> ar = np.zeros((20, 40)) >>> g = regular_grid(ar.shape, 32) >>> g (slice(2, None, 5), slice(2, None, 5)) >>> ar[g] = 1 >>> ar.sum() 32.0 >>> ar = np.zeros((3, 20, 40)) >>> g = regular_grid(ar.shape, 8) >>> g (slice(1, None, 3), slice(5, None, 10), slice(5, None, 10)) >>> ar[g] = 1 >>> ar.sum() 8.0 ``` regular\_seeds -------------- `skimage.util.regular_seeds(ar_shape, n_points, dtype=<class 'int'>)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/util/_regular_grid.py#L86-L116) Return an image with ~`n\_points` regularly-spaced nonzero pixels. Parameters `ar_shapetuple of int` The shape of the desired output image. `n_pointsint` The desired number of nonzero points. `dtypenumpy data type, optional` The desired data type of the output. Returns `seed_imgarray of int or bool` The desired image. #### Examples ``` >>> regular_seeds((5, 5), 4) array([[0, 0, 0, 0, 0], [0, 1, 0, 2, 0], [0, 0, 0, 0, 0], [0, 3, 0, 4, 0], [0, 0, 0, 0, 0]]) ``` unique\_rows ------------ `skimage.util.unique_rows(ar)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/util/unique.py#L4-L50) Remove repeated rows from a 2D array. In particular, if given an array of coordinates of shape (Npoints, Ndim), it will remove repeated points. Parameters `ar2-D ndarray` The input array. Returns `ar_out2-D ndarray` A copy of the input array with repeated rows removed. Raises `ValueErrorif ar is not two-dimensional.` #### Notes The function will generate a copy of `ar` if it is not C-contiguous, which will negatively affect performance for large input arrays. #### Examples ``` >>> ar = np.array([[1, 0, 1], ... [0, 1, 0], ... [1, 0, 1]], np.uint8) >>> unique_rows(ar) array([[0, 1, 0], [1, 0, 1]], dtype=uint8) ``` view\_as\_blocks ---------------- `skimage.util.view_as_blocks(arr_in, block_shape)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/util/shape.py#L8-L94) Block view of the input n-dimensional array (using re-striding). Blocks are non-overlapping views of the input array. Parameters `arr_inndarray` N-d input array. `block_shapetuple` The shape of the block. Each dimension must divide evenly into the corresponding dimensions of `arr_in`. Returns `arr_outndarray` Block view of the input array. #### Examples ``` >>> import numpy as np >>> from skimage.util.shape import view_as_blocks >>> A = np.arange(4*4).reshape(4,4) >>> A array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]]) >>> B = view_as_blocks(A, block_shape=(2, 2)) >>> B[0, 0] array([[0, 1], [4, 5]]) >>> B[0, 1] array([[2, 3], [6, 7]]) >>> B[1, 0, 1, 1] 13 ``` ``` >>> A = np.arange(4*4*6).reshape(4,4,6) >>> A array([[[ 0, 1, 2, 3, 4, 5], [ 6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16, 17], [18, 19, 20, 21, 22, 23]], [[24, 25, 26, 27, 28, 29], [30, 31, 32, 33, 34, 35], [36, 37, 38, 39, 40, 41], [42, 43, 44, 45, 46, 47]], [[48, 49, 50, 51, 52, 53], [54, 55, 56, 57, 58, 59], [60, 61, 62, 63, 64, 65], [66, 67, 68, 69, 70, 71]], [[72, 73, 74, 75, 76, 77], [78, 79, 80, 81, 82, 83], [84, 85, 86, 87, 88, 89], [90, 91, 92, 93, 94, 95]]]) >>> B = view_as_blocks(A, block_shape=(1, 2, 2)) >>> B.shape (4, 2, 3, 1, 2, 2) >>> B[2:, 0, 2] array([[[[52, 53], [58, 59]]], [[[76, 77], [82, 83]]]]) ``` view\_as\_windows ----------------- `skimage.util.view_as_windows(arr_in, window_shape, step=1)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/util/shape.py#L97-L247) Rolling window view of the input n-dimensional array. Windows are overlapping views of the input array, with adjacent windows shifted by a single row or column (or an index of a higher dimension). Parameters `arr_inndarray` N-d input array. `window_shapeinteger or tuple of length arr_in.ndim` Defines the shape of the elementary n-dimensional orthotope (better know as hyperrectangle [[1]](#redb8d40dc8d4-1)) of the rolling window view. If an integer is given, the shape will be a hypercube of sidelength given by its value. `stepinteger or tuple of length arr_in.ndim` Indicates step size at which extraction shall be performed. If integer is given, then the step is uniform in all dimensions. Returns `arr_outndarray` (rolling) window view of the input array. #### Notes One should be very careful with rolling views when it comes to memory usage. Indeed, although a β€˜view’ has the same memory footprint as its base array, the actual array that emerges when this β€˜view’ is used in a computation is generally a (much) larger array than the original, especially for 2-dimensional arrays and above. For example, let us consider a 3 dimensional array of size (100, 100, 100) of `float64`. This array takes about 8\*100\*\*3 Bytes for storage which is just 8 MB. If one decides to build a rolling view on this array with a window of (3, 3, 3) the hypothetical size of the rolling view (if one was to reshape the view for example) would be 8\*(100-3+1)\*\*3\*3\*\*3 which is about 203 MB! The scaling becomes even worse as the dimension of the input array becomes larger. #### References `1` <https://en.wikipedia.org/wiki/Hyperrectangle> #### Examples ``` >>> import numpy as np >>> from skimage.util.shape import view_as_windows >>> A = np.arange(4*4).reshape(4,4) >>> A array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15]]) >>> window_shape = (2, 2) >>> B = view_as_windows(A, window_shape) >>> B[0, 0] array([[0, 1], [4, 5]]) >>> B[0, 1] array([[1, 2], [5, 6]]) ``` ``` >>> A = np.arange(10) >>> A array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>> window_shape = (3,) >>> B = view_as_windows(A, window_shape) >>> B.shape (8, 3) >>> B array([[0, 1, 2], [1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6], [5, 6, 7], [6, 7, 8], [7, 8, 9]]) ``` ``` >>> A = np.arange(5*4).reshape(5, 4) >>> A array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11], [12, 13, 14, 15], [16, 17, 18, 19]]) >>> window_shape = (4, 3) >>> B = view_as_windows(A, window_shape) >>> B.shape (2, 2, 4, 3) >>> B array([[[[ 0, 1, 2], [ 4, 5, 6], [ 8, 9, 10], [12, 13, 14]], [[ 1, 2, 3], [ 5, 6, 7], [ 9, 10, 11], [13, 14, 15]]], [[[ 4, 5, 6], [ 8, 9, 10], [12, 13, 14], [16, 17, 18]], [[ 5, 6, 7], [ 9, 10, 11], [13, 14, 15], [17, 18, 19]]]]) ```
programming_docs
scikit_image Module: io Module: io ========== Utilities to read and write images in various formats. The following plug-ins are available: | | | | --- | --- | | Plugin | Description | | qt | Fast image display using the Qt library. Deprecated since 0.18. Will be removed in 0.20. | | imread | Image reading and writing via imread | | gdal | Image reading via the GDAL Library (www.gdal.org) | | simpleitk | Image reading and writing via SimpleITK | | gtk | Fast image display using the GTK library | | pil | Image reading via the Python Imaging Library | | fits | FITS image reading via PyFITS | | matplotlib | Display or save images using Matplotlib | | tifffile | Load and save TIFF and TIFF-based images using tifffile.py | | imageio | Image reading via the ImageIO Library | | | | | --- | --- | | [`skimage.io.call_plugin`](#skimage.io.call_plugin "skimage.io.call_plugin")(kind, \*args, \*\*kwargs) | Find the appropriate plugin of β€˜kind’ and execute it. | | [`skimage.io.concatenate_images`](#skimage.io.concatenate_images "skimage.io.concatenate_images")(ic) | Concatenate all images in the image collection into an array. | | [`skimage.io.find_available_plugins`](#skimage.io.find_available_plugins "skimage.io.find_available_plugins")([loaded]) | List available plugins. | | [`skimage.io.imread`](#skimage.io.imread "skimage.io.imread")(fname[, as\_gray, plugin]) | Load an image from file. | | [`skimage.io.imread_collection`](#skimage.io.imread_collection "skimage.io.imread_collection")(load\_pattern[, …]) | Load a collection of images. | | [`skimage.io.imread_collection_wrapper`](#skimage.io.imread_collection_wrapper "skimage.io.imread_collection_wrapper")(imread) | | | [`skimage.io.imsave`](#skimage.io.imsave "skimage.io.imsave")(fname, arr[, plugin, …]) | Save an image to file. | | [`skimage.io.imshow`](#skimage.io.imshow "skimage.io.imshow")(arr[, plugin]) | Display an image. | | [`skimage.io.imshow_collection`](#skimage.io.imshow_collection "skimage.io.imshow_collection")(ic[, plugin]) | Display a collection of images. | | [`skimage.io.load_sift`](#skimage.io.load_sift "skimage.io.load_sift")(f) | Read SIFT or SURF features from externally generated file. | | [`skimage.io.load_surf`](#skimage.io.load_surf "skimage.io.load_surf")(f) | Read SIFT or SURF features from externally generated file. | | [`skimage.io.plugin_info`](#skimage.io.plugin_info "skimage.io.plugin_info")(plugin) | Return plugin meta-data. | | [`skimage.io.plugin_order`](#skimage.io.plugin_order "skimage.io.plugin_order")() | Return the currently preferred plugin order. | | [`skimage.io.pop`](#skimage.io.pop "skimage.io.pop")() | Pop an image from the shared image stack. | | [`skimage.io.push`](#skimage.io.push "skimage.io.push")(img) | Push an image onto the shared image stack. | | [`skimage.io.reset_plugins`](#skimage.io.reset_plugins "skimage.io.reset_plugins")() | | | [`skimage.io.show`](#skimage.io.show "skimage.io.show")() | Display pending images. | | [`skimage.io.use_plugin`](#skimage.io.use_plugin "skimage.io.use_plugin")(name[, kind]) | Set the default plugin for a specified operation. | | [`skimage.io.ImageCollection`](#skimage.io.ImageCollection "skimage.io.ImageCollection")(load\_pattern[, …]) | Load and manage a collection of image files. | | [`skimage.io.MultiImage`](#skimage.io.MultiImage "skimage.io.MultiImage")(filename[, …]) | A class containing all frames from multi-frame images. | | `skimage.io.collection` | Data structures to hold collections of images, with optional caching. | | `skimage.io.manage_plugins` | Handle image reading, writing and plotting plugins. | | `skimage.io.sift` | | | `skimage.io.util` | | call\_plugin ------------ `skimage.io.call_plugin(kind, *args, **kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/io/manage_plugins.py#L171-L207) Find the appropriate plugin of β€˜kind’ and execute it. Parameters `kind{β€˜imshow’, β€˜imsave’, β€˜imread’, β€˜imread_collection’}` Function to look up. `pluginstr, optional` Plugin to load. Defaults to None, in which case the first matching plugin is used. `*args, **kwargsarguments and keyword arguments` Passed to the plugin function. concatenate\_images ------------------- `skimage.io.concatenate_images(ic)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/io/collection.py#L31-L63) Concatenate all images in the image collection into an array. Parameters `ican iterable of images` The images to be concatenated. Returns `array_catndarray` An array having one more dimension than the images in `ic`. Raises ValueError If images in `ic` don’t have identical shapes. See also `ImageCollection.concatenate, MultiImage.concatenate` #### Notes `concatenate_images` receives any iterable object containing images, including ImageCollection and MultiImage, and returns a NumPy array. find\_available\_plugins ------------------------ `skimage.io.find_available_plugins(loaded=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/io/manage_plugins.py#L138-L165) List available plugins. Parameters `loadedbool` If True, show only those plugins currently loaded. By default, all plugins are shown. Returns `pdict` Dictionary with plugin names as keys and exposed functions as values. imread ------ `skimage.io.imread(fname, as_gray=False, plugin=None, **plugin_args)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/io/_io.py#L14-L63) Load an image from file. Parameters `fnamestring` Image file name, e.g. `test.jpg` or URL. `as_graybool, optional` If True, convert color images to gray-scale (64-bit floats). Images that are already in gray-scale format are not converted. `pluginstr, optional` Name of plugin to use. By default, the different plugins are tried (starting with imageio) until a suitable candidate is found. If not given and fname is a tiff file, the tifffile plugin will be used. Returns `img_arrayndarray` The different color bands/channels are stored in the third dimension, such that a gray-image is MxN, an RGB-image MxNx3 and an RGBA-image MxNx4. Other Parameters `plugin_argskeywords` Passed to the given plugin. imread\_collection ------------------ `skimage.io.imread_collection(load_pattern, conserve_memory=True, plugin=None, **plugin_args)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/io/_io.py#L66-L93) Load a collection of images. Parameters `load_patternstr or list` List of objects to load. These are usually filenames, but may vary depending on the currently active plugin. See the docstring for `ImageCollection` for the default behaviour of this parameter. `conserve_memorybool, optional` If True, never keep more than one in memory at a specific time. Otherwise, images will be cached once they are loaded. Returns `icImageCollection` Collection of images. Other Parameters `plugin_argskeywords` Passed to the given plugin. imread\_collection\_wrapper --------------------------- `skimage.io.imread_collection_wrapper(imread)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/io/collection.py#L378-L401) imsave ------ `skimage.io.imsave(fname, arr, plugin=None, check_contrast=True, **plugin_args)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/io/_io.py#L96-L136) Save an image to file. Parameters `fnamestr` Target filename. `arrndarray of shape (M,N) or (M,N,3) or (M,N,4)` Image data. `pluginstr, optional` Name of plugin to use. By default, the different plugins are tried (starting with imageio) until a suitable candidate is found. If not given and fname is a tiff file, the tifffile plugin will be used. `check_contrastbool, optional` Check for low contrast and print warning (default: True). Other Parameters `plugin_argskeywords` Passed to the given plugin. #### Notes When saving a JPEG, the compression ratio may be controlled using the `quality` keyword argument which is an integer with values in [1, 100] where 1 is worst quality and smallest file size, and 100 is best quality and largest file size (default 75). This is only available when using the PIL and imageio plugins. imshow ------ `skimage.io.imshow(arr, plugin=None, **plugin_args)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/io/_io.py#L139-L159) Display an image. Parameters `arrndarray or str` Image data or name of image file. `pluginstr` Name of plugin to use. By default, the different plugins are tried (starting with imageio) until a suitable candidate is found. Other Parameters `plugin_argskeywords` Passed to the given plugin. ### Examples using `skimage.io.imshow` [Explore 3D images (of cells)](https://scikit-image.org/docs/0.18.x/auto_examples/applications/plot_3d_image_processing.html#sphx-glr-auto-examples-applications-plot-3d-image-processing-py) imshow\_collection ------------------ `skimage.io.imshow_collection(ic, plugin=None, **plugin_args)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/io/_io.py#L162-L179) Display a collection of images. Parameters `icImageCollection` Collection to display. `pluginstr` Name of plugin to use. By default, the different plugins are tried until a suitable candidate is found. Other Parameters `plugin_argskeywords` Passed to the given plugin. load\_sift ---------- `skimage.io.load_sift(f)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/io/sift.py#L72-L73) Read SIFT or SURF features from externally generated file. This routine reads SIFT or SURF files generated by binary utilities from <http://people.cs.ubc.ca/~lowe/keypoints/> and <http://www.vision.ee.ethz.ch/~surf/>. This routine *does not* generate SIFT/SURF features from an image. These algorithms are patent encumbered. Please use [`skimage.feature.CENSURE`](skimage.feature#skimage.feature.CENSURE "skimage.feature.CENSURE") instead. Parameters `filelikestring or open file` Input file generated by the feature detectors from <http://people.cs.ubc.ca/~lowe/keypoints/> or <http://www.vision.ee.ethz.ch/~surf/> . `mode{β€˜SIFT’, β€˜SURF’}, optional` Kind of descriptor used to generate `filelike`. Returns `datarecord array with fields` * row: int row position of feature * column: int column position of feature * scale: float feature scale * orientation: float feature orientation * data: array feature values load\_surf ---------- `skimage.io.load_surf(f)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/io/sift.py#L76-L77) Read SIFT or SURF features from externally generated file. This routine reads SIFT or SURF files generated by binary utilities from <http://people.cs.ubc.ca/~lowe/keypoints/> and <http://www.vision.ee.ethz.ch/~surf/>. This routine *does not* generate SIFT/SURF features from an image. These algorithms are patent encumbered. Please use [`skimage.feature.CENSURE`](skimage.feature#skimage.feature.CENSURE "skimage.feature.CENSURE") instead. Parameters `filelikestring or open file` Input file generated by the feature detectors from <http://people.cs.ubc.ca/~lowe/keypoints/> or <http://www.vision.ee.ethz.ch/~surf/> . `mode{β€˜SIFT’, β€˜SURF’}, optional` Kind of descriptor used to generate `filelike`. Returns `datarecord array with fields` * row: int row position of feature * column: int column position of feature * scale: float feature scale * orientation: float feature orientation * data: array feature values plugin\_info ------------ `skimage.io.plugin_info(plugin)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/io/manage_plugins.py#L311-L328) Return plugin meta-data. Parameters `pluginstr` Name of plugin. Returns `mdict` Meta data as specified in plugin `.ini`. plugin\_order ------------- `skimage.io.plugin_order()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/io/manage_plugins.py#L331-L344) Return the currently preferred plugin order. Returns `pdict` Dictionary of preferred plugin order, with function name as key and plugins (in order of preference) as value. pop --- `skimage.io.pop()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/io/_image_stack.py#L26-L35) Pop an image from the shared image stack. Returns `imgndarray` Image popped from the stack. push ---- `skimage.io.push(img)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/io/_image_stack.py#L11-L23) Push an image onto the shared image stack. Parameters `imgndarray` Image to push. reset\_plugins -------------- `skimage.io.reset_plugins()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/io/manage_plugins.py#L85-L87) show ---- `skimage.io.show()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/io/_io.py#L182-L201) Display pending images. Launch the event loop of the current gui plugin, and display all pending images, queued via [`imshow`](#skimage.io.imshow "skimage.io.imshow"). This is required when using [`imshow`](#skimage.io.imshow "skimage.io.imshow") from non-interactive scripts. A call to [`show`](#skimage.io.show "skimage.io.show") will block execution of code until all windows have been closed. #### Examples ``` >>> import skimage.io as io ``` ``` >>> for i in range(4): ... ax_im = io.imshow(np.random.rand(50, 50)) >>> io.show() ``` use\_plugin ----------- `skimage.io.use_plugin(name, kind=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/io/manage_plugins.py#L210-L263) Set the default plugin for a specified operation. The plugin will be loaded if it hasn’t been already. Parameters `namestr` Name of plugin. `kind{β€˜imsave’, β€˜imread’, β€˜imshow’, β€˜imread_collection’, β€˜imshow_collection’}, optional` Set the plugin for this function. By default, the plugin is set for all functions. See also `available_plugins` List of available plugins #### Examples To use Matplotlib as the default image reader, you would write: ``` >>> from skimage import io >>> io.use_plugin('matplotlib', 'imread') ``` To see a list of available plugins run `io.available_plugins`. Note that this lists plugins that are defined, but the full list may not be usable if your system does not have the required libraries installed. ImageCollection --------------- `class skimage.io.ImageCollection(load_pattern, conserve_memory=True, load_func=None, **load_func_kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/io/collection.py#L109-L375) Bases: [`object`](https://docs.python.org/3.9/library/functions.html#object "(in Python v3.9)") Load and manage a collection of image files. Parameters `load_patternstr or list of str` Pattern string or list of strings to load. The filename path can be absolute or relative. `conserve_memorybool, optional` If True, [`ImageCollection`](#skimage.io.ImageCollection "skimage.io.ImageCollection") does not keep more than one in memory at a specific time. Otherwise, images will be cached once they are loaded. Other Parameters `load_funccallable` `imread` by default. See notes below. #### Notes Note that files are always returned in alphanumerical order. Also note that slicing returns a new ImageCollection, *not* a view into the data. ImageCollection can be modified to load images from an arbitrary source by specifying a combination of `load_pattern` and `load_func`. For an ImageCollection `ic`, `ic[5]` uses `load_func(load_pattern[5])` to load the image. Imagine, for example, an ImageCollection that loads every third frame from a video file: ``` video_file = 'no_time_for_that_tiny.gif' def vidread_step(f, step): vid = imageio.get_reader(f) seq = [v for v in vid.iter_data()] return seq[::step] ic = ImageCollection(video_file, load_func=vidread_step, step=3) ic # is an ImageCollection object of length 1 because there is 1 file x = ic[0] # calls vidread_step(video_file, step=3) x[5] # is the sixth element of a list of length 8 (24 / 3) ``` Another use of `load_func` would be to convert all images to `uint8`: ``` def imread_convert(f): return imread(f).astype(np.uint8) ic = ImageCollection('/tmp/*.png', load_func=imread_convert) ``` #### Examples ``` >>> import skimage.io as io >>> from skimage import data_dir ``` ``` >>> coll = io.ImageCollection(data_dir + '/chess*.png') >>> len(coll) 2 >>> coll[0].shape (200, 200) ``` ``` >>> ic = io.ImageCollection(['/tmp/work/*.png', '/tmp/other/*.jpg']) ``` Attributes `fileslist of str` If a pattern string is given for `load_pattern`, this attribute stores the expanded file list. Otherwise, this is equal to `load_pattern`. `__init__(load_pattern, conserve_memory=True, load_func=None, **load_func_kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/io/collection.py#L180-L214) Load and manage a collection of images. `concatenate()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/io/collection.py#L358-L375) Concatenate all images in the collection into an array. Returns `arnp.ndarray` An array having one more dimension than the images in `self`. Raises ValueError If images in the [`ImageCollection`](#skimage.io.ImageCollection "skimage.io.ImageCollection") don’t have identical shapes. See also [`concatenate_images`](#skimage.io.concatenate_images "skimage.io.concatenate_images") `property conserve_memory` `property files` `reload(n=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/io/collection.py#L346-L356) Clear the image cache. Parameters `nNone or int` Clear the cache for this image only. By default, the entire cache is erased. MultiImage ---------- `class skimage.io.MultiImage(filename, conserve_memory=True, dtype=None, **imread_kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/io/collection.py#L404-L459) Bases: `skimage.io.collection.ImageCollection` A class containing all frames from multi-frame images. Parameters `load_patternstr or list of str` Pattern glob or filenames to load. The path can be absolute or relative. `conserve_memorybool, optional` Whether to conserve memory by only caching a single frame. Default is True. Other Parameters `load_funccallable` `imread` by default. See notes below. #### Notes If `conserve_memory=True` the memory footprint can be reduced, however the performance can be affected because frames have to be read from file more often. The last accessed frame is cached, all other frames will have to be read from file. The current implementation makes use of `tifffile` for Tiff files and PIL otherwise. #### Examples ``` >>> from skimage import data_dir ``` ``` >>> img = MultiImage(data_dir + '/multipage.tif') >>> len(img) 2 >>> for frame in img: ... print(frame.shape) (15, 10) (15, 10) ``` `__init__(filename, conserve_memory=True, dtype=None, **imread_kwargs)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/io/collection.py#L448-L455) Load a multi-img. `property filename` scikit_image Module: filters Module: filters =============== | | | | --- | --- | | [`skimage.filters.apply_hysteresis_threshold`](#skimage.filters.apply_hysteresis_threshold "skimage.filters.apply_hysteresis_threshold")(…) | Apply hysteresis thresholding to `image`. | | [`skimage.filters.correlate_sparse`](#skimage.filters.correlate_sparse "skimage.filters.correlate_sparse")(image, kernel) | Compute valid cross-correlation of `padded_array` and `kernel`. | | [`skimage.filters.difference_of_gaussians`](#skimage.filters.difference_of_gaussians "skimage.filters.difference_of_gaussians")(…) | Find features between `low_sigma` and `high_sigma` in size. | | [`skimage.filters.farid`](#skimage.filters.farid "skimage.filters.farid")(image, \*[, mask]) | Find the edge magnitude using the Farid transform. | | [`skimage.filters.farid_h`](#skimage.filters.farid_h "skimage.filters.farid_h")(image, \*[, mask]) | Find the horizontal edges of an image using the Farid transform. | | [`skimage.filters.farid_v`](#skimage.filters.farid_v "skimage.filters.farid_v")(image, \*[, mask]) | Find the vertical edges of an image using the Farid transform. | | [`skimage.filters.frangi`](#skimage.filters.frangi "skimage.filters.frangi")(image[, sigmas, …]) | Filter an image with the Frangi vesselness filter. | | [`skimage.filters.gabor`](#skimage.filters.gabor "skimage.filters.gabor")(image, frequency[, …]) | Return real and imaginary responses to Gabor filter. | | [`skimage.filters.gabor_kernel`](#skimage.filters.gabor_kernel "skimage.filters.gabor_kernel")(frequency[, …]) | Return complex 2D Gabor filter kernel. | | [`skimage.filters.gaussian`](#skimage.filters.gaussian "skimage.filters.gaussian")(image[, sigma, …]) | Multi-dimensional Gaussian filter. | | [`skimage.filters.hessian`](#skimage.filters.hessian "skimage.filters.hessian")(image[, sigmas, …]) | Filter an image with the Hybrid Hessian filter. | | [`skimage.filters.inverse`](#skimage.filters.inverse "skimage.filters.inverse")(data[, …]) | Apply the filter in reverse to the given data. | | [`skimage.filters.laplace`](#skimage.filters.laplace "skimage.filters.laplace")(image[, ksize, mask]) | Find the edges of an image using the Laplace operator. | | [`skimage.filters.median`](#skimage.filters.median "skimage.filters.median")(image[, selem, out, …]) | Return local median of an image. | | [`skimage.filters.meijering`](#skimage.filters.meijering "skimage.filters.meijering")(image[, sigmas, …]) | Filter an image with the Meijering neuriteness filter. | | [`skimage.filters.prewitt`](#skimage.filters.prewitt "skimage.filters.prewitt")(image[, mask, axis, …]) | Find the edge magnitude using the Prewitt transform. | | [`skimage.filters.prewitt_h`](#skimage.filters.prewitt_h "skimage.filters.prewitt_h")(image[, mask]) | Find the horizontal edges of an image using the Prewitt transform. | | [`skimage.filters.prewitt_v`](#skimage.filters.prewitt_v "skimage.filters.prewitt_v")(image[, mask]) | Find the vertical edges of an image using the Prewitt transform. | | [`skimage.filters.rank_order`](#skimage.filters.rank_order "skimage.filters.rank_order")(image) | Return an image of the same shape where each pixel is the index of the pixel value in the ascending order of the unique values of `image`, aka the rank-order value. | | [`skimage.filters.roberts`](#skimage.filters.roberts "skimage.filters.roberts")(image[, mask]) | Find the edge magnitude using Roberts’ cross operator. | | [`skimage.filters.roberts_neg_diag`](#skimage.filters.roberts_neg_diag "skimage.filters.roberts_neg_diag")(image[, mask]) | Find the cross edges of an image using the Roberts’ Cross operator. | | [`skimage.filters.roberts_pos_diag`](#skimage.filters.roberts_pos_diag "skimage.filters.roberts_pos_diag")(image[, mask]) | Find the cross edges of an image using Roberts’ cross operator. | | [`skimage.filters.sato`](#skimage.filters.sato "skimage.filters.sato")(image[, sigmas, …]) | Filter an image with the Sato tubeness filter. | | [`skimage.filters.scharr`](#skimage.filters.scharr "skimage.filters.scharr")(image[, mask, axis, …]) | Find the edge magnitude using the Scharr transform. | | [`skimage.filters.scharr_h`](#skimage.filters.scharr_h "skimage.filters.scharr_h")(image[, mask]) | Find the horizontal edges of an image using the Scharr transform. | | [`skimage.filters.scharr_v`](#skimage.filters.scharr_v "skimage.filters.scharr_v")(image[, mask]) | Find the vertical edges of an image using the Scharr transform. | | [`skimage.filters.sobel`](#skimage.filters.sobel "skimage.filters.sobel")(image[, mask, axis, …]) | Find edges in an image using the Sobel filter. | | [`skimage.filters.sobel_h`](#skimage.filters.sobel_h "skimage.filters.sobel_h")(image[, mask]) | Find the horizontal edges of an image using the Sobel transform. | | [`skimage.filters.sobel_v`](#skimage.filters.sobel_v "skimage.filters.sobel_v")(image[, mask]) | Find the vertical edges of an image using the Sobel transform. | | [`skimage.filters.threshold_isodata`](#skimage.filters.threshold_isodata "skimage.filters.threshold_isodata")([image, …]) | Return threshold value(s) based on ISODATA method. | | [`skimage.filters.threshold_li`](#skimage.filters.threshold_li "skimage.filters.threshold_li")(image, \*[, …]) | Compute threshold value by Li’s iterative Minimum Cross Entropy method. | | [`skimage.filters.threshold_local`](#skimage.filters.threshold_local "skimage.filters.threshold_local")(image, …) | Compute a threshold mask image based on local pixel neighborhood. | | [`skimage.filters.threshold_mean`](#skimage.filters.threshold_mean "skimage.filters.threshold_mean")(image) | Return threshold value based on the mean of grayscale values. | | [`skimage.filters.threshold_minimum`](#skimage.filters.threshold_minimum "skimage.filters.threshold_minimum")([image, …]) | Return threshold value based on minimum method. | | [`skimage.filters.threshold_multiotsu`](#skimage.filters.threshold_multiotsu "skimage.filters.threshold_multiotsu")(image[, …]) | Generate `classes`-1 threshold values to divide gray levels in `image`. | | [`skimage.filters.threshold_niblack`](#skimage.filters.threshold_niblack "skimage.filters.threshold_niblack")(image[, …]) | Applies Niblack local threshold to an array. | | [`skimage.filters.threshold_otsu`](#skimage.filters.threshold_otsu "skimage.filters.threshold_otsu")([image, …]) | Return threshold value based on Otsu’s method. | | [`skimage.filters.threshold_sauvola`](#skimage.filters.threshold_sauvola "skimage.filters.threshold_sauvola")(image[, …]) | Applies Sauvola local threshold to an array. | | [`skimage.filters.threshold_triangle`](#skimage.filters.threshold_triangle "skimage.filters.threshold_triangle")(image[, …]) | Return threshold value based on the triangle algorithm. | | [`skimage.filters.threshold_yen`](#skimage.filters.threshold_yen "skimage.filters.threshold_yen")([image, …]) | Return threshold value based on Yen’s method. | | [`skimage.filters.try_all_threshold`](#skimage.filters.try_all_threshold "skimage.filters.try_all_threshold")(image[, …]) | Returns a figure comparing the outputs of different thresholding methods. | | [`skimage.filters.unsharp_mask`](#skimage.filters.unsharp_mask "skimage.filters.unsharp_mask")(image[, …]) | Unsharp masking filter. | | [`skimage.filters.wiener`](#skimage.filters.wiener "skimage.filters.wiener")(data[, …]) | Minimum Mean Square Error (Wiener) inverse filter. | | [`skimage.filters.window`](#skimage.filters.window "skimage.filters.window")(window\_type, shape[, …]) | Return an n-dimensional window of a given size and dimensionality. | | [`skimage.filters.LPIFilter2D`](#skimage.filters.LPIFilter2D "skimage.filters.LPIFilter2D")(…) | Linear Position-Invariant Filter (2-dimensional) | | [`skimage.filters.rank`](skimage.filters.rank#module-skimage.filters.rank "skimage.filters.rank") | | apply\_hysteresis\_threshold ---------------------------- `skimage.filters.apply_hysteresis_threshold(image, low, high)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/thresholding.py#L1090-L1134) Apply hysteresis thresholding to `image`. This algorithm finds regions where `image` is greater than `high` OR `image` is greater than `low` *and* that region is connected to a region greater than `high`. Parameters `imagearray, shape (M,[ N, …, P])` Grayscale input image. `lowfloat, or array of same shape as image` Lower threshold. `highfloat, or array of same shape as image` Higher threshold. Returns `thresholdedarray of bool, same shape as image` Array in which `True` indicates the locations where `image` was above the hysteresis threshold. #### References `1` J. Canny. A computational approach to edge detection. IEEE Transactions on Pattern Analysis and Machine Intelligence. 1986; vol. 8, pp.679-698. [DOI:10.1109/TPAMI.1986.4767851](https://doi.org/10.1109/TPAMI.1986.4767851) #### Examples ``` >>> image = np.array([1, 2, 3, 2, 1, 2, 1, 3, 2]) >>> apply_hysteresis_threshold(image, 1.5, 2.5).astype(int) array([0, 1, 1, 1, 0, 0, 0, 1, 1]) ``` correlate\_sparse ----------------- `skimage.filters.correlate_sparse(image, kernel, mode='reflect')` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/_sparse.py#L35-L97) Compute valid cross-correlation of `padded_array` and `kernel`. This function is *fast* when `kernel` is large with many zeros. See `scipy.ndimage.correlate` for a description of cross-correlation. Parameters `imagendarray, dtype float, shape (M, N,[ …,] P)` The input array. If mode is β€˜valid’, this array should already be padded, as a margin of the same shape as kernel will be stripped off. `kernelndarray, dtype float shape (Q, R,[ …,] S)` The kernel to be correlated. Must have the same number of dimensions as `padded_array`. For high performance, it should be sparse (few nonzero entries). `modestring, optional` See [`scipy.ndimage.correlate`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.correlate.html#scipy.ndimage.correlate "(in SciPy v1.5.4)") for valid modes. Additionally, mode β€˜valid’ is accepted, in which case no padding is applied and the result is the result for the smaller image for which the kernel is entirely inside the original data. Returns `resultarray of float, shape (M, N,[ …,] P)` The result of cross-correlating `image` with `kernel`. If mode β€˜valid’ is used, the resulting shape is (M-Q+1, N-R+1,[ …,] P-S+1). difference\_of\_gaussians ------------------------- `skimage.filters.difference_of_gaussians(image, low_sigma, high_sigma=None, *, mode='nearest', cval=0, multichannel=False, truncate=4.0)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/_gaussian.py#L160-L290) Find features between `low_sigma` and `high_sigma` in size. This function uses the Difference of Gaussians method for applying band-pass filters to multi-dimensional arrays. The input array is blurred with two Gaussian kernels of differing sigmas to produce two intermediate, filtered images. The more-blurred image is then subtracted from the less-blurred image. The final output image will therefore have had high-frequency components attenuated by the smaller-sigma Gaussian, and low frequency components will have been removed due to their presence in the more-blurred intermediate. Parameters `imagendarray` Input array to filter. `low_sigmascalar or sequence of scalars` Standard deviation(s) for the Gaussian kernel with the smaller sigmas across all axes. The standard deviations are given for each axis as a sequence, or as a single number, in which case the single number is used as the standard deviation value for all axes. `high_sigmascalar or sequence of scalars, optional (default is None)` Standard deviation(s) for the Gaussian kernel with the larger sigmas across all axes. The standard deviations are given for each axis as a sequence, or as a single number, in which case the single number is used as the standard deviation value for all axes. If None is given (default), sigmas for all axes are calculated as 1.6 \* low\_sigma. `mode{β€˜reflect’, β€˜constant’, β€˜nearest’, β€˜mirror’, β€˜wrap’}, optional` The `mode` parameter determines how the array borders are handled, where `cval` is the value when mode is equal to β€˜constant’. Default is β€˜nearest’. `cvalscalar, optional` Value to fill past edges of input if `mode` is β€˜constant’. Default is 0.0 `multichannelbool, optional (default: False)` Whether the last axis of the image is to be interpreted as multiple channels. If True, each channel is filtered separately (channels are not mixed together). `truncatefloat, optional (default is 4.0)` Truncate the filter at this many standard deviations. Returns `filtered_imagendarray` the filtered array. See also `skimage.feature.blog_dog` #### Notes This function will subtract an array filtered with a Gaussian kernel with sigmas given by `high_sigma` from an array filtered with a Gaussian kernel with sigmas provided by `low_sigma`. The values for `high_sigma` must always be greater than or equal to the corresponding values in `low_sigma`, or a `ValueError` will be raised. When `high_sigma` is none, the values for `high_sigma` will be calculated as 1.6x the corresponding values in `low_sigma`. This ratio was originally proposed by Marr and Hildreth (1980) [[1]](#r96d4c0941595-1) and is commonly used when approximating the inverted Laplacian of Gaussian, which is used in edge and blob detection. Input image is converted according to the conventions of `img_as_float`. Except for sigma values, all parameters are used for both filters. #### References `1` Marr, D. and Hildreth, E. Theory of Edge Detection. Proc. R. Soc. Lond. Series B 207, 187-217 (1980). <https://doi.org/10.1098/rspb.1980.0020> #### Examples Apply a simple Difference of Gaussians filter to a color image: ``` >>> from skimage.data import astronaut >>> from skimage.filters import difference_of_gaussians >>> filtered_image = difference_of_gaussians(astronaut(), 2, 10, ... multichannel=True) ``` Apply a Laplacian of Gaussian filter as approximated by the Difference of Gaussians filter: ``` >>> filtered_image = difference_of_gaussians(astronaut(), 2, ... multichannel=True) ``` Apply a Difference of Gaussians filter to a grayscale image using different sigma values for each axis: ``` >>> from skimage.data import camera >>> filtered_image = difference_of_gaussians(camera(), (2,5), (3,20)) ``` farid ----- `skimage.filters.farid(image, *, mask=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/edges.py#L690-L737) Find the edge magnitude using the Farid transform. Parameters `image2-D array` Image to process. `mask2-D array, optional` An optional mask to limit the application to a certain area. Note that pixels surrounding masked regions are also masked to prevent masked regions from affecting the result. Returns `output2-D array` The Farid edge map. See also `sobel, prewitt, canny` #### Notes Take the square root of the sum of the squares of the horizontal and vertical derivatives to get a magnitude that is somewhat insensitive to direction. Similar to the Scharr operator, this operator is designed with a rotation invariance constraint. #### References `1` Farid, H. and Simoncelli, E. P., β€œDifferentiation of discrete multidimensional signals”, IEEE Transactions on Image Processing 13(4): 496-508, 2004. [DOI:10.1109/TIP.2004.823819](https://doi.org/10.1109/TIP.2004.823819) `2` Wikipedia, β€œFarid and Simoncelli Derivatives.” Available at: <<https://en.wikipedia.org/wiki/Image_derivatives#Farid_and_Simoncelli_Derivatives>> #### Examples ``` >>> from skimage import data >>> camera = data.camera() >>> from skimage import filters >>> edges = filters.farid(camera) ``` farid\_h -------- `skimage.filters.farid_h(image, *, mask=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/edges.py#L740-L773) Find the horizontal edges of an image using the Farid transform. Parameters `image2-D array` Image to process. `mask2-D array, optional` An optional mask to limit the application to a certain area. Note that pixels surrounding masked regions are also masked to prevent masked regions from affecting the result. Returns `output2-D array` The Farid edge map. #### Notes The kernel was constructed using the 5-tap weights from [1]. #### References `1` Farid, H. and Simoncelli, E. P., β€œDifferentiation of discrete multidimensional signals”, IEEE Transactions on Image Processing 13(4): 496-508, 2004. [DOI:10.1109/TIP.2004.823819](https://doi.org/10.1109/TIP.2004.823819) `2` Farid, H. and Simoncelli, E. P. β€œOptimally rotation-equivariant directional derivative kernels”, In: 7th International Conference on Computer Analysis of Images and Patterns, Kiel, Germany. Sep, 1997. farid\_v -------- `skimage.filters.farid_v(image, *, mask=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/edges.py#L776-L806) Find the vertical edges of an image using the Farid transform. Parameters `image2-D array` Image to process. `mask2-D array, optional` An optional mask to limit the application to a certain area. Note that pixels surrounding masked regions are also masked to prevent masked regions from affecting the result. Returns `output2-D array` The Farid edge map. #### Notes The kernel was constructed using the 5-tap weights from [1]. #### References `1` Farid, H. and Simoncelli, E. P., β€œDifferentiation of discrete multidimensional signals”, IEEE Transactions on Image Processing 13(4): 496-508, 2004. [DOI:10.1109/TIP.2004.823819](https://doi.org/10.1109/TIP.2004.823819) frangi ------ `skimage.filters.frangi(image, sigmas=range(1, 10, 2), scale_range=None, scale_step=None, alpha=0.5, beta=0.5, gamma=15, black_ridges=True, mode='reflect', cval=0)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/ridges.py#L357-L490) Filter an image with the Frangi vesselness filter. This filter can be used to detect continuous ridges, e.g. vessels, wrinkles, rivers. It can be used to calculate the fraction of the whole image containing such objects. Defined only for 2-D and 3-D images. Calculates the eigenvectors of the Hessian to compute the similarity of an image region to vessels, according to the method described in [[1]](#r9152c279884a-1). Parameters `image(N, M[, P]) ndarray` Array with input image data. `sigmasiterable of floats, optional` Sigmas used as scales of filter, i.e., np.arange(scale\_range[0], scale\_range[1], scale\_step) `scale_range2-tuple of floats, optional` The range of sigmas used. `scale_stepfloat, optional` Step size between sigmas. `alphafloat, optional` Frangi correction constant that adjusts the filter’s sensitivity to deviation from a plate-like structure. `betafloat, optional` Frangi correction constant that adjusts the filter’s sensitivity to deviation from a blob-like structure. `gammafloat, optional` Frangi correction constant that adjusts the filter’s sensitivity to areas of high variance/texture/structure. `black_ridgesboolean, optional` When True (the default), the filter detects black ridges; when False, it detects white ridges. `mode{β€˜constant’, β€˜reflect’, β€˜wrap’, β€˜nearest’, β€˜mirror’}, optional` How to handle values outside the image borders. `cvalfloat, optional` Used in conjunction with mode β€˜constant’, the value outside the image boundaries. Returns `out(N, M[, P]) ndarray` Filtered image (maximum of pixels across all scales). See also [`meijering`](#skimage.filters.meijering "skimage.filters.meijering") [`sato`](#skimage.filters.sato "skimage.filters.sato") [`hessian`](#skimage.filters.hessian "skimage.filters.hessian") #### Notes Written by Marc Schrijver, November 2001 Re-Written by D. J. Kroon, University of Twente, May 2009, [[2]](#r9152c279884a-2) Adoption of 3D version from D. G. Ellis, Januar 20017, [[3]](#r9152c279884a-3) #### References `1` Frangi, A. F., Niessen, W. J., Vincken, K. L., & Viergever, M. A. (1998,). Multiscale vessel enhancement filtering. In International Conference on Medical Image Computing and Computer-Assisted Intervention (pp. 130-137). Springer Berlin Heidelberg. [DOI:10.1007/BFb0056195](https://doi.org/10.1007/BFb0056195) `2` Kroon, D. J.: Hessian based Frangi vesselness filter. `3` Ellis, D. G.: <https://github.com/ellisdg/frangi3d/tree/master/frangi> gabor ----- `skimage.filters.gabor(image, frequency, theta=0, bandwidth=1, sigma_x=None, sigma_y=None, n_stds=3, offset=0, mode='reflect', cval=0)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/_gabor.py#L98-L177) Return real and imaginary responses to Gabor filter. The real and imaginary parts of the Gabor filter kernel are applied to the image and the response is returned as a pair of arrays. Gabor filter is a linear filter with a Gaussian kernel which is modulated by a sinusoidal plane wave. Frequency and orientation representations of the Gabor filter are similar to those of the human visual system. Gabor filter banks are commonly used in computer vision and image processing. They are especially suitable for edge detection and texture classification. Parameters `image2-D array` Input image. `frequencyfloat` Spatial frequency of the harmonic function. Specified in pixels. `thetafloat, optional` Orientation in radians. If 0, the harmonic is in the x-direction. `bandwidthfloat, optional` The bandwidth captured by the filter. For fixed bandwidth, `sigma_x` and `sigma_y` will decrease with increasing frequency. This value is ignored if `sigma_x` and `sigma_y` are set by the user. `sigma_x, sigma_yfloat, optional` Standard deviation in x- and y-directions. These directions apply to the kernel *before* rotation. If `theta = pi/2`, then the kernel is rotated 90 degrees so that `sigma_x` controls the *vertical* direction. `n_stdsscalar, optional` The linear size of the kernel is n\_stds (3 by default) standard deviations. `offsetfloat, optional` Phase offset of harmonic function in radians. `mode{β€˜constant’, β€˜nearest’, β€˜reflect’, β€˜mirror’, β€˜wrap’}, optional` Mode used to convolve image with a kernel, passed to `ndi.convolve` `cvalscalar, optional` Value to fill past edges of input if `mode` of convolution is β€˜constant’. The parameter is passed to `ndi.convolve`. Returns `real, imagarrays` Filtered images using the real and imaginary parts of the Gabor filter kernel. Images are of the same dimensions as the input one. #### References `1` <https://en.wikipedia.org/wiki/Gabor_filter> `2` <https://web.archive.org/web/20180127125930/http://mplab.ucsd.edu/tutorials/gabor.pdf> #### Examples ``` >>> from skimage.filters import gabor >>> from skimage import data, io >>> from matplotlib import pyplot as plt ``` ``` >>> image = data.coins() >>> # detecting edges in a coin image >>> filt_real, filt_imag = gabor(image, frequency=0.6) >>> plt.figure() >>> io.imshow(filt_real) >>> io.show() ``` ``` >>> # less sensitivity to finer details with the lower frequency kernel >>> filt_real, filt_imag = gabor(image, frequency=0.1) >>> plt.figure() >>> io.imshow(filt_real) >>> io.show() ``` gabor\_kernel ------------- `skimage.filters.gabor_kernel(frequency, theta=0, bandwidth=1, sigma_x=None, sigma_y=None, n_stds=3, offset=0)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/_gabor.py#L16-L95) Return complex 2D Gabor filter kernel. Gabor kernel is a Gaussian kernel modulated by a complex harmonic function. Harmonic function consists of an imaginary sine function and a real cosine function. Spatial frequency is inversely proportional to the wavelength of the harmonic and to the standard deviation of a Gaussian kernel. The bandwidth is also inversely proportional to the standard deviation. Parameters `frequencyfloat` Spatial frequency of the harmonic function. Specified in pixels. `thetafloat, optional` Orientation in radians. If 0, the harmonic is in the x-direction. `bandwidthfloat, optional` The bandwidth captured by the filter. For fixed bandwidth, `sigma_x` and `sigma_y` will decrease with increasing frequency. This value is ignored if `sigma_x` and `sigma_y` are set by the user. `sigma_x, sigma_yfloat, optional` Standard deviation in x- and y-directions. These directions apply to the kernel *before* rotation. If `theta = pi/2`, then the kernel is rotated 90 degrees so that `sigma_x` controls the *vertical* direction. `n_stdsscalar, optional` The linear size of the kernel is n\_stds (3 by default) standard deviations `offsetfloat, optional` Phase offset of harmonic function in radians. Returns `gcomplex array` Complex filter kernel. #### References `1` <https://en.wikipedia.org/wiki/Gabor_filter> `2` <https://web.archive.org/web/20180127125930/http://mplab.ucsd.edu/tutorials/gabor.pdf> #### Examples ``` >>> from skimage.filters import gabor_kernel >>> from skimage import io >>> from matplotlib import pyplot as plt ``` ``` >>> gk = gabor_kernel(frequency=0.2) >>> plt.figure() >>> io.imshow(gk.real) >>> io.show() ``` ``` >>> # more ripples (equivalent to increasing the size of the >>> # Gaussian spread) >>> gk = gabor_kernel(frequency=0.2, bandwidth=0.1) >>> plt.figure() >>> io.imshow(gk.real) >>> io.show() ``` gaussian -------- `skimage.filters.gaussian(image, sigma=1, output=None, mode='nearest', cval=0, multichannel=None, preserve_range=False, truncate=4.0)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/_gaussian.py#L12-L126) Multi-dimensional Gaussian filter. Parameters `imagearray-like` Input image (grayscale or color) to filter. `sigmascalar or sequence of scalars, optional` Standard deviation for Gaussian kernel. The standard deviations of the Gaussian filter are given for each axis as a sequence, or as a single number, in which case it is equal for all axes. `outputarray, optional` The `output` parameter passes an array in which to store the filter output. `mode{β€˜reflect’, β€˜constant’, β€˜nearest’, β€˜mirror’, β€˜wrap’}, optional` The `mode` parameter determines how the array borders are handled, where `cval` is the value when mode is equal to β€˜constant’. Default is β€˜nearest’. `cvalscalar, optional` Value to fill past edges of input if `mode` is β€˜constant’. Default is 0.0 `multichannelbool, optional (default: None)` Whether the last axis of the image is to be interpreted as multiple channels. If True, each channel is filtered separately (channels are not mixed together). Only 3 channels are supported. If `None`, the function will attempt to guess this, and raise a warning if ambiguous, when the array has shape (M, N, 3). `preserve_rangebool, optional` Whether to keep the original range of values. Otherwise, the input image is converted according to the conventions of `img_as_float`. Also see <https://scikit-image.org/docs/dev/user_guide/data_types.html> `truncatefloat, optional` Truncate the filter at this many standard deviations. Returns `filtered_imagendarray` the filtered array #### Notes This function is a wrapper around `scipy.ndi.gaussian_filter()`. Integer arrays are converted to float. The `output` should be floating point data type since gaussian converts to float provided `image`. If `output` is not provided, another array will be allocated and returned as the result. The multi-dimensional filter is implemented as a sequence of one-dimensional convolution filters. The intermediate arrays are stored in the same data type as the output. Therefore, for output types with a limited precision, the results may be imprecise because intermediate results may be stored with insufficient precision. #### Examples ``` >>> a = np.zeros((3, 3)) >>> a[1, 1] = 1 >>> a array([[0., 0., 0.], [0., 1., 0.], [0., 0., 0.]]) >>> gaussian(a, sigma=0.4) # mild smoothing array([[0.00163116, 0.03712502, 0.00163116], [0.03712502, 0.84496158, 0.03712502], [0.00163116, 0.03712502, 0.00163116]]) >>> gaussian(a, sigma=1) # more smoothing array([[0.05855018, 0.09653293, 0.05855018], [0.09653293, 0.15915589, 0.09653293], [0.05855018, 0.09653293, 0.05855018]]) >>> # Several modes are possible for handling boundaries >>> gaussian(a, sigma=1, mode='reflect') array([[0.08767308, 0.12075024, 0.08767308], [0.12075024, 0.16630671, 0.12075024], [0.08767308, 0.12075024, 0.08767308]]) >>> # For RGB images, each is filtered separately >>> from skimage.data import astronaut >>> image = astronaut() >>> filtered_img = gaussian(image, sigma=1, multichannel=True) ``` hessian ------- `skimage.filters.hessian(image, sigmas=range(1, 10, 2), scale_range=None, scale_step=None, alpha=0.5, beta=0.5, gamma=15, black_ridges=True, mode=None, cval=0)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/ridges.py#L493-L571) Filter an image with the Hybrid Hessian filter. This filter can be used to detect continuous edges, e.g. vessels, wrinkles, rivers. It can be used to calculate the fraction of the whole image containing such objects. Defined only for 2-D and 3-D images. Almost equal to Frangi filter, but uses alternative method of smoothing. Refer to [[1]](#r29057abd4159-1) to find the differences between Frangi and Hessian filters. Parameters `image(N, M[, P]) ndarray` Array with input image data. `sigmasiterable of floats, optional` Sigmas used as scales of filter, i.e., np.arange(scale\_range[0], scale\_range[1], scale\_step) `scale_range2-tuple of floats, optional` The range of sigmas used. `scale_stepfloat, optional` Step size between sigmas. `betafloat, optional` Frangi correction constant that adjusts the filter’s sensitivity to deviation from a blob-like structure. `gammafloat, optional` Frangi correction constant that adjusts the filter’s sensitivity to areas of high variance/texture/structure. `black_ridgesboolean, optional` When True (the default), the filter detects black ridges; when False, it detects white ridges. `mode{β€˜constant’, β€˜reflect’, β€˜wrap’, β€˜nearest’, β€˜mirror’}, optional` How to handle values outside the image borders. `cvalfloat, optional` Used in conjunction with mode β€˜constant’, the value outside the image boundaries. Returns `out(N, M[, P]) ndarray` Filtered image (maximum of pixels across all scales). See also [`meijering`](#skimage.filters.meijering "skimage.filters.meijering") [`sato`](#skimage.filters.sato "skimage.filters.sato") [`frangi`](#skimage.filters.frangi "skimage.filters.frangi") #### Notes Written by Marc Schrijver (November 2001) Re-Written by D. J. Kroon University of Twente (May 2009) [[2]](#r29057abd4159-2) #### References `1` Ng, C. C., Yap, M. H., Costen, N., & Li, B. (2014,). Automatic wrinkle detection using hybrid Hessian filter. In Asian Conference on Computer Vision (pp. 609-622). Springer International Publishing. [DOI:10.1007/978-3-319-16811-1\_40](https://doi.org/10.1007/978-3-319-16811-1_40) `2` Kroon, D. J.: Hessian based Frangi vesselness filter. inverse ------- `skimage.filters.inverse(data, impulse_response=None, filter_params={}, max_gain=2, predefined_filter=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/lpi_filter.py#L167-L204) Apply the filter in reverse to the given data. Parameters `data(M,N) ndarray` Input data. `impulse_responsecallable f(r, c, **filter_params)` Impulse response of the filter. See LPIFilter2D.\_\_init\_\_. `filter_paramsdict` Additional keyword parameters to the impulse\_response function. `max_gainfloat` Limit the filter gain. Often, the filter contains zeros, which would cause the inverse filter to have infinite gain. High gain causes amplification of artefacts, so a conservative limit is recommended. Other Parameters `predefined_filterLPIFilter2D` If you need to apply the same filter multiple times over different images, construct the LPIFilter2D and specify it here. laplace ------- `skimage.filters.laplace(image, ksize=3, mask=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/edges.py#L656-L687) Find the edges of an image using the Laplace operator. Parameters `imagendarray` Image to process. `ksizeint, optional` Define the size of the discrete Laplacian operator such that it will have a size of (ksize,) \* image.ndim. `maskndarray, optional` An optional mask to limit the application to a certain area. Note that pixels surrounding masked regions are also masked to prevent masked regions from affecting the result. Returns `outputndarray` The Laplace edge map. #### Notes The Laplacian operator is generated using the function skimage.restoration.uft.laplacian(). median ------ `skimage.filters.median(image, selem=None, out=None, mode='nearest', cval=0.0, behavior='ndimage')` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/_median.py#L10-L78) Return local median of an image. Parameters `imagearray-like` Input image. `selemndarray, optional` If `behavior=='rank'`, `selem` is a 2-D array of 1’s and 0’s. If `behavior=='ndimage'`, `selem` is a N-D array of 1’s and 0’s with the same number of dimension than `image`. If None, `selem` will be a N-D array with 3 elements for each dimension (e.g., vector, square, cube, etc.) `outndarray, (same dtype as image), optional` If None, a new array is allocated. `mode{β€˜reflect’, β€˜constant’, β€˜nearest’, β€˜mirror’,β€™β€˜wrap’}, optional` The mode parameter determines how the array borders are handled, where `cval` is the value when mode is equal to β€˜constant’. Default is β€˜nearest’. New in version 0.15: `mode` is used when `behavior='ndimage'`. `cvalscalar, optional` Value to fill past edges of input if mode is β€˜constant’. Default is 0.0 New in version 0.15: `cval` was added in 0.15 is used when `behavior='ndimage'`. `behavior{β€˜ndimage’, β€˜rank’}, optional` Either to use the old behavior (i.e., < 0.15) or the new behavior. The old behavior will call the [`skimage.filters.rank.median()`](skimage.filters.rank#skimage.filters.rank.median "skimage.filters.rank.median"). The new behavior will call the [`scipy.ndimage.median_filter()`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.median_filter.html#scipy.ndimage.median_filter "(in SciPy v1.5.4)"). Default is β€˜ndimage’. New in version 0.15: `behavior` is introduced in 0.15 Changed in version 0.16: Default `behavior` has been changed from β€˜rank’ to β€˜ndimage’ Returns `out2-D array (same dtype as input image)` Output image. See also [`skimage.filters.rank.median`](skimage.filters.rank#skimage.filters.rank.median "skimage.filters.rank.median") Rank-based implementation of the median filtering offering more flexibility with additional parameters but dedicated for unsigned integer images. #### Examples ``` >>> from skimage import data >>> from skimage.morphology import disk >>> from skimage.filters import median >>> img = data.camera() >>> med = median(img, disk(5)) ``` meijering --------- `skimage.filters.meijering(image, sigmas=range(1, 10, 2), alpha=None, black_ridges=True, mode='reflect', cval=0)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/ridges.py#L167-L265) Filter an image with the Meijering neuriteness filter. This filter can be used to detect continuous ridges, e.g. neurites, wrinkles, rivers. It can be used to calculate the fraction of the whole image containing such objects. Calculates the eigenvectors of the Hessian to compute the similarity of an image region to neurites, according to the method described in [[1]](#rbd62388c4e81-1). Parameters `image(N, M[, …, P]) ndarray` Array with input image data. `sigmasiterable of floats, optional` Sigmas used as scales of filter `alphafloat, optional` Frangi correction constant that adjusts the filter’s sensitivity to deviation from a plate-like structure. `black_ridgesboolean, optional` When True (the default), the filter detects black ridges; when False, it detects white ridges. `mode{β€˜constant’, β€˜reflect’, β€˜wrap’, β€˜nearest’, β€˜mirror’}, optional` How to handle values outside the image borders. `cvalfloat, optional` Used in conjunction with mode β€˜constant’, the value outside the image boundaries. Returns `out(N, M[, …, P]) ndarray` Filtered image (maximum of pixels across all scales). See also [`sato`](#skimage.filters.sato "skimage.filters.sato") [`frangi`](#skimage.filters.frangi "skimage.filters.frangi") [`hessian`](#skimage.filters.hessian "skimage.filters.hessian") #### References `1` Meijering, E., Jacob, M., Sarria, J. C., Steiner, P., Hirling, H., Unser, M. (2004). Design and validation of a tool for neurite tracing and analysis in fluorescence microscopy images. Cytometry Part A, 58(2), 167-176. [DOI:10.1002/cyto.a.20022](https://doi.org/10.1002/cyto.a.20022) prewitt ------- `skimage.filters.prewitt(image, mask=None, *, axis=None, mode='reflect', cval=0.0)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/edges.py#L434-L489) Find the edge magnitude using the Prewitt transform. Parameters `imagearray` The input image. `maskarray of bool, optional` Clip the output image to this mask. (Values where mask=0 will be set to 0.) `axisint or sequence of int, optional` Compute the edge filter along this axis. If not provided, the edge magnitude is computed. This is defined as: ``` prw_mag = np.sqrt(sum([prewitt(image, axis=i)**2 for i in range(image.ndim)]) / image.ndim) ``` The magnitude is also computed if axis is a sequence. `modestr or sequence of str, optional` The boundary mode for the convolution. See [`scipy.ndimage.convolve`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.convolve.html#scipy.ndimage.convolve "(in SciPy v1.5.4)") for a description of the modes. This can be either a single boundary mode or one boundary mode per axis. `cvalfloat, optional` When `mode` is `'constant'`, this is the constant used in values outside the boundary of the image data. Returns `outputarray of float` The Prewitt edge map. See also `sobel,` [`scharr`](#skimage.filters.scharr "skimage.filters.scharr") #### Notes The edge magnitude depends slightly on edge directions, since the approximation of the gradient operator by the Prewitt operator is not completely rotation invariant. For a better rotation invariance, the Scharr operator should be used. The Sobel operator has a better rotation invariance than the Prewitt operator, but a worse rotation invariance than the Scharr operator. #### Examples ``` >>> from skimage import data >>> from skimage import filters >>> camera = data.camera() >>> edges = filters.prewitt(camera) ``` prewitt\_h ---------- `skimage.filters.prewitt_h(image, mask=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/edges.py#L492-L519) Find the horizontal edges of an image using the Prewitt transform. Parameters `image2-D array` Image to process. `mask2-D array, optional` An optional mask to limit the application to a certain area. Note that pixels surrounding masked regions are also masked to prevent masked regions from affecting the result. Returns `output2-D array` The Prewitt edge map. #### Notes We use the following kernel: ``` 1/3 1/3 1/3 0 0 0 -1/3 -1/3 -1/3 ``` prewitt\_v ---------- `skimage.filters.prewitt_v(image, mask=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/edges.py#L522-L549) Find the vertical edges of an image using the Prewitt transform. Parameters `image2-D array` Image to process. `mask2-D array, optional` An optional mask to limit the application to a certain area. Note that pixels surrounding masked regions are also masked to prevent masked regions from affecting the result. Returns `output2-D array` The Prewitt edge map. #### Notes We use the following kernel: ``` 1/3 0 -1/3 1/3 0 -1/3 1/3 0 -1/3 ``` rank\_order ----------- `skimage.filters.rank_order(image)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/_rank_order.py#L14-L59) Return an image of the same shape where each pixel is the index of the pixel value in the ascending order of the unique values of `image`, aka the rank-order value. Parameters `imagendarray` Returns `labelsndarray of type np.uint32, of shape image.shape` New array where each pixel has the rank-order value of the corresponding pixel in `image`. Pixel values are between 0 and n - 1, where n is the number of distinct unique values in `image`. `original_values1-D ndarray` Unique original values of `image` #### Examples ``` >>> a = np.array([[1, 4, 5], [4, 4, 1], [5, 1, 1]]) >>> a array([[1, 4, 5], [4, 4, 1], [5, 1, 1]]) >>> rank_order(a) (array([[0, 1, 2], [1, 1, 0], [2, 0, 0]], dtype=uint32), array([1, 4, 5])) >>> b = np.array([-1., 2.5, 3.1, 2.5]) >>> rank_order(b) (array([0, 1, 2, 1], dtype=uint32), array([-1. , 2.5, 3.1])) ``` roberts ------- `skimage.filters.roberts(image, mask=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/edges.py#L552-L585) Find the edge magnitude using Roberts’ cross operator. Parameters `image2-D array` Image to process. `mask2-D array, optional` An optional mask to limit the application to a certain area. Note that pixels surrounding masked regions are also masked to prevent masked regions from affecting the result. Returns `output2-D array` The Roberts’ Cross edge map. See also `sobel, scharr, prewitt, feature.canny` #### Examples ``` >>> from skimage import data >>> camera = data.camera() >>> from skimage import filters >>> edges = filters.roberts(camera) ``` roberts\_neg\_diag ------------------ `skimage.filters.roberts_neg_diag(image, mask=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/edges.py#L622-L653) Find the cross edges of an image using the Roberts’ Cross operator. The kernel is applied to the input image to produce separate measurements of the gradient component one orientation. Parameters `image2-D array` Image to process. `mask2-D array, optional` An optional mask to limit the application to a certain area. Note that pixels surrounding masked regions are also masked to prevent masked regions from affecting the result. Returns `output2-D array` The Robert’s edge map. #### Notes We use the following kernel: ``` 0 1 -1 0 ``` roberts\_pos\_diag ------------------ `skimage.filters.roberts_pos_diag(image, mask=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/edges.py#L588-L619) Find the cross edges of an image using Roberts’ cross operator. The kernel is applied to the input image to produce separate measurements of the gradient component one orientation. Parameters `image2-D array` Image to process. `mask2-D array, optional` An optional mask to limit the application to a certain area. Note that pixels surrounding masked regions are also masked to prevent masked regions from affecting the result. Returns `output2-D array` The Robert’s edge map. #### Notes We use the following kernel: ``` 1 0 0 -1 ``` sato ---- `skimage.filters.sato(image, sigmas=range(1, 10, 2), black_ridges=True, mode=None, cval=0)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/ridges.py#L268-L354) Filter an image with the Sato tubeness filter. This filter can be used to detect continuous ridges, e.g. tubes, wrinkles, rivers. It can be used to calculate the fraction of the whole image containing such objects. Defined only for 2-D and 3-D images. Calculates the eigenvectors of the Hessian to compute the similarity of an image region to tubes, according to the method described in [[1]](#r7b0e4f38c6a4-1). Parameters `image(N, M[, P]) ndarray` Array with input image data. `sigmasiterable of floats, optional` Sigmas used as scales of filter. `black_ridgesboolean, optional` When True (the default), the filter detects black ridges; when False, it detects white ridges. `mode{β€˜constant’, β€˜reflect’, β€˜wrap’, β€˜nearest’, β€˜mirror’}, optional` How to handle values outside the image borders. `cvalfloat, optional` Used in conjunction with mode β€˜constant’, the value outside the image boundaries. Returns `out(N, M[, P]) ndarray` Filtered image (maximum of pixels across all scales). See also [`meijering`](#skimage.filters.meijering "skimage.filters.meijering") [`frangi`](#skimage.filters.frangi "skimage.filters.frangi") [`hessian`](#skimage.filters.hessian "skimage.filters.hessian") #### References `1` Sato, Y., Nakajima, S., Shiraga, N., Atsumi, H., Yoshida, S., Koller, T., …, Kikinis, R. (1998). Three-dimensional multi-scale line filter for segmentation and visualization of curvilinear structures in medical images. Medical image analysis, 2(2), 143-168. [DOI:10.1016/S1361-8415(98)80009-1](https://doi.org/10.1016/S1361-8415(98)80009-1) scharr ------ `skimage.filters.scharr(image, mask=None, *, axis=None, mode='reflect', cval=0.0)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/edges.py#L304-L362) Find the edge magnitude using the Scharr transform. Parameters `imagearray` The input image. `maskarray of bool, optional` Clip the output image to this mask. (Values where mask=0 will be set to 0.) `axisint or sequence of int, optional` Compute the edge filter along this axis. If not provided, the edge magnitude is computed. This is defined as: ``` sch_mag = np.sqrt(sum([scharr(image, axis=i)**2 for i in range(image.ndim)]) / image.ndim) ``` The magnitude is also computed if axis is a sequence. `modestr or sequence of str, optional` The boundary mode for the convolution. See [`scipy.ndimage.convolve`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.convolve.html#scipy.ndimage.convolve "(in SciPy v1.5.4)") for a description of the modes. This can be either a single boundary mode or one boundary mode per axis. `cvalfloat, optional` When `mode` is `'constant'`, this is the constant used in values outside the boundary of the image data. Returns `outputarray of float` The Scharr edge map. See also `sobel, prewitt, canny` #### Notes The Scharr operator has a better rotation invariance than other edge filters such as the Sobel or the Prewitt operators. #### References `1` D. Kroon, 2009, Short Paper University Twente, Numerical Optimization of Kernel Based Image Derivatives. `2` <https://en.wikipedia.org/wiki/Sobel_operator#Alternative_operators> #### Examples ``` >>> from skimage import data >>> from skimage import filters >>> camera = data.camera() >>> edges = filters.scharr(camera) ``` scharr\_h --------- `skimage.filters.scharr_h(image, mask=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/edges.py#L365-L397) Find the horizontal edges of an image using the Scharr transform. Parameters `image2-D array` Image to process. `mask2-D array, optional` An optional mask to limit the application to a certain area. Note that pixels surrounding masked regions are also masked to prevent masked regions from affecting the result. Returns `output2-D array` The Scharr edge map. #### Notes We use the following kernel: ``` 3 10 3 0 0 0 -3 -10 -3 ``` #### References `1` D. Kroon, 2009, Short Paper University Twente, Numerical Optimization of Kernel Based Image Derivatives. scharr\_v --------- `skimage.filters.scharr_v(image, mask=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/edges.py#L400-L431) Find the vertical edges of an image using the Scharr transform. Parameters `image2-D array` Image to process `mask2-D array, optional` An optional mask to limit the application to a certain area. Note that pixels surrounding masked regions are also masked to prevent masked regions from affecting the result. Returns `output2-D array` The Scharr edge map. #### Notes We use the following kernel: ``` 3 0 -3 10 0 -10 3 0 -3 ``` #### References `1` D. Kroon, 2009, Short Paper University Twente, Numerical Optimization of Kernel Based Image Derivatives. sobel ----- `skimage.filters.sobel(image, mask=None, *, axis=None, mode='reflect', cval=0.0)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/edges.py#L188-L241) Find edges in an image using the Sobel filter. Parameters `imagearray` The input image. `maskarray of bool, optional` Clip the output image to this mask. (Values where mask=0 will be set to 0.) `axisint or sequence of int, optional` Compute the edge filter along this axis. If not provided, the edge magnitude is computed. This is defined as: ``` sobel_mag = np.sqrt(sum([sobel(image, axis=i)**2 for i in range(image.ndim)]) / image.ndim) ``` The magnitude is also computed if axis is a sequence. `modestr or sequence of str, optional` The boundary mode for the convolution. See [`scipy.ndimage.convolve`](https://docs.scipy.org/doc/scipy/reference/generated/scipy.ndimage.convolve.html#scipy.ndimage.convolve "(in SciPy v1.5.4)") for a description of the modes. This can be either a single boundary mode or one boundary mode per axis. `cvalfloat, optional` When `mode` is `'constant'`, this is the constant used in values outside the boundary of the image data. Returns `outputarray of float` The Sobel edge map. See also `scharr, prewitt, canny` #### References `1` D. Kroon, 2009, Short Paper University Twente, Numerical Optimization of Kernel Based Image Derivatives. `2` <https://en.wikipedia.org/wiki/Sobel_operator> #### Examples ``` >>> from skimage import data >>> from skimage import filters >>> camera = data.camera() >>> edges = filters.sobel(camera) ``` ### Examples using `skimage.filters.sobel` [Flood Fill](https://scikit-image.org/docs/0.18.x/auto_examples/segmentation/plot_floodfill.html#sphx-glr-auto-examples-segmentation-plot-floodfill-py) sobel\_h -------- `skimage.filters.sobel_h(image, mask=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/edges.py#L244-L271) Find the horizontal edges of an image using the Sobel transform. Parameters `image2-D array` Image to process. `mask2-D array, optional` An optional mask to limit the application to a certain area. Note that pixels surrounding masked regions are also masked to prevent masked regions from affecting the result. Returns `output2-D array` The Sobel edge map. #### Notes We use the following kernel: ``` 1 2 1 0 0 0 -1 -2 -1 ``` sobel\_v -------- `skimage.filters.sobel_v(image, mask=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/edges.py#L274-L301) Find the vertical edges of an image using the Sobel transform. Parameters `image2-D array` Image to process. `mask2-D array, optional` An optional mask to limit the application to a certain area. Note that pixels surrounding masked regions are also masked to prevent masked regions from affecting the result. Returns `output2-D array` The Sobel edge map. #### Notes We use the following kernel: ``` 1 0 -1 2 0 -2 1 0 -1 ``` threshold\_isodata ------------------ `skimage.filters.threshold_isodata(image=None, nbins=256, return_all=False, *, hist=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/thresholding.py#L414-L528) Return threshold value(s) based on ISODATA method. Histogram-based threshold, known as Ridler-Calvard method or inter-means. Threshold values returned satisfy the following equality: ``` threshold = (image[image <= threshold].mean() + image[image > threshold].mean()) / 2.0 ``` That is, returned thresholds are intensities that separate the image into two groups of pixels, where the threshold intensity is midway between the mean intensities of these groups. For integer images, the above equality holds to within one; for floating- point images, the equality holds to within the histogram bin-width. Either image or hist must be provided. In case hist is given, the actual histogram of the image is ignored. Parameters `image(N, M) ndarray, optional` Input image. `nbinsint, optional` Number of bins used to calculate histogram. This value is ignored for integer arrays. `return_allbool, optional` If False (default), return only the lowest threshold that satisfies the above equality. If True, return all valid thresholds. `histarray, or 2-tuple of arrays, optional` Histogram to determine the threshold from and a corresponding array of bin center intensities. Alternatively, only the histogram can be passed. Returns `thresholdfloat or int or array` Threshold value(s). #### References `1` Ridler, TW & Calvard, S (1978), β€œPicture thresholding using an iterative selection method” IEEE Transactions on Systems, Man and Cybernetics 8: 630-632, [DOI:10.1109/TSMC.1978.4310039](https://doi.org/10.1109/TSMC.1978.4310039) `2` Sezgin M. and Sankur B. (2004) β€œSurvey over Image Thresholding Techniques and Quantitative Performance Evaluation” Journal of Electronic Imaging, 13(1): 146-165, <http://www.busim.ee.boun.edu.tr/~sankur/SankurFolder/Threshold_survey.pdf> [DOI:10.1117/1.1631315](https://doi.org/10.1117/1.1631315) `3` ImageJ AutoThresholder code, <http://fiji.sc/wiki/index.php/Auto_Threshold> #### Examples ``` >>> from skimage.data import coins >>> image = coins() >>> thresh = threshold_isodata(image) >>> binary = image > thresh ``` threshold\_li ------------- `skimage.filters.threshold_li(image, *, tolerance=None, initial_guess=None, iter_callback=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/thresholding.py#L586-L707) Compute threshold value by Li’s iterative Minimum Cross Entropy method. Parameters `imagendarray` Input image. `tolerancefloat, optional` Finish the computation when the change in the threshold in an iteration is less than this value. By default, this is half the smallest difference between intensity values in `image`. `initial_guessfloat or Callable[[array[float]], float], optional` Li’s iterative method uses gradient descent to find the optimal threshold. If the image intensity histogram contains more than two modes (peaks), the gradient descent could get stuck in a local optimum. An initial guess for the iteration can help the algorithm find the globally-optimal threshold. A float value defines a specific start point, while a callable should take in an array of image intensities and return a float value. Example valid callables include `numpy.mean` (default), `lambda arr: numpy.quantile(arr, 0.95)`, or even [`skimage.filters.threshold_otsu()`](#skimage.filters.threshold_otsu "skimage.filters.threshold_otsu"). `iter_callbackCallable[[float], Any], optional` A function that will be called on the threshold at every iteration of the algorithm. Returns `thresholdfloat` Upper threshold value. All pixels with an intensity higher than this value are assumed to be foreground. #### References `1` Li C.H. and Lee C.K. (1993) β€œMinimum Cross Entropy Thresholding” Pattern Recognition, 26(4): 617-625 [DOI:10.1016/0031-3203(93)90115-D](https://doi.org/10.1016/0031-3203(93)90115-D) `2` Li C.H. and Tam P.K.S. (1998) β€œAn Iterative Algorithm for Minimum Cross Entropy Thresholding” Pattern Recognition Letters, 18(8): 771-776 [DOI:10.1016/S0167-8655(98)00057-9](https://doi.org/10.1016/S0167-8655(98)00057-9) `3` Sezgin M. and Sankur B. (2004) β€œSurvey over Image Thresholding Techniques and Quantitative Performance Evaluation” Journal of Electronic Imaging, 13(1): 146-165 [DOI:10.1117/1.1631315](https://doi.org/10.1117/1.1631315) `4` ImageJ AutoThresholder code, <http://fiji.sc/wiki/index.php/Auto_Threshold> #### Examples ``` >>> from skimage.data import camera >>> image = camera() >>> thresh = threshold_li(image) >>> binary = image > thresh ``` threshold\_local ---------------- `skimage.filters.threshold_local(image, block_size, method='gaussian', offset=0, mode='reflect', param=None, cval=0)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/thresholding.py#L145-L236) Compute a threshold mask image based on local pixel neighborhood. Also known as adaptive or dynamic thresholding. The threshold value is the weighted mean for the local neighborhood of a pixel subtracted by a constant. Alternatively the threshold can be determined dynamically by a given function, using the β€˜generic’ method. Parameters `image(N, M) ndarray` Input image. `block_sizeint` Odd size of pixel neighborhood which is used to calculate the threshold value (e.g. 3, 5, 7, …, 21, …). `method{β€˜generic’, β€˜gaussian’, β€˜mean’, β€˜median’}, optional` Method used to determine adaptive threshold for local neighbourhood in weighted mean image. * β€˜generic’: use custom function (see `param` parameter) * β€˜gaussian’: apply gaussian filter (see `param` parameter for custom sigma value) * β€˜mean’: apply arithmetic mean filter * β€˜median’: apply median rank filter By default the β€˜gaussian’ method is used. `offsetfloat, optional` Constant subtracted from weighted mean of neighborhood to calculate the local threshold value. Default offset is 0. `mode{β€˜reflect’, β€˜constant’, β€˜nearest’, β€˜mirror’, β€˜wrap’}, optional` The mode parameter determines how the array borders are handled, where cval is the value when mode is equal to β€˜constant’. Default is β€˜reflect’. `param{int, function}, optional` Either specify sigma for β€˜gaussian’ method or function object for β€˜generic’ method. This functions takes the flat array of local neighbourhood as a single argument and returns the calculated threshold for the centre pixel. `cvalfloat, optional` Value to fill past edges of input if mode is β€˜constant’. Returns `threshold(N, M) ndarray` Threshold image. All pixels in the input image higher than the corresponding pixel in the threshold image are considered foreground. #### References `1` <https://docs.opencv.org/modules/imgproc/doc/miscellaneous_transformations.html?highlight=threshold#adaptivethreshold> #### Examples ``` >>> from skimage.data import camera >>> image = camera()[:50, :50] >>> binary_image1 = image > threshold_local(image, 15, 'mean') >>> func = lambda arr: arr.mean() >>> binary_image2 = image > threshold_local(image, 15, 'generic', ... param=func) ``` threshold\_mean --------------- `skimage.filters.threshold_mean(image)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/thresholding.py#L802-L830) Return threshold value based on the mean of grayscale values. Parameters `image(N, M[, …, P]) ndarray` Grayscale input image. Returns `thresholdfloat` Upper threshold value. All pixels with an intensity higher than this value are assumed to be foreground. #### References `1` C. A. Glasbey, β€œAn analysis of histogram-based thresholding algorithms,” CVGIP: Graphical Models and Image Processing, vol. 55, pp. 532-537, 1993. [DOI:10.1006/cgip.1993.1040](https://doi.org/10.1006/cgip.1993.1040) #### Examples ``` >>> from skimage.data import camera >>> image = camera() >>> thresh = threshold_mean(image) >>> binary = image > thresh ``` threshold\_minimum ------------------ `skimage.filters.threshold_minimum(image=None, nbins=256, max_iter=10000, *, hist=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/thresholding.py#L710-L799) Return threshold value based on minimum method. The histogram of the input `image` is computed if not provided and smoothed until there are only two maxima. Then the minimum in between is the threshold value. Either image or hist must be provided. In case hist is given, the actual histogram of the image is ignored. Parameters `image(M, N) ndarray, optional` Input image. `nbinsint, optional` Number of bins used to calculate histogram. This value is ignored for integer arrays. `max_iterint, optional` Maximum number of iterations to smooth the histogram. `histarray, or 2-tuple of arrays, optional` Histogram to determine the threshold from and a corresponding array of bin center intensities. Alternatively, only the histogram can be passed. Returns `thresholdfloat` Upper threshold value. All pixels with an intensity higher than this value are assumed to be foreground. Raises RuntimeError If unable to find two local maxima in the histogram or if the smoothing takes more than 1e4 iterations. #### References `1` C. A. Glasbey, β€œAn analysis of histogram-based thresholding algorithms,” CVGIP: Graphical Models and Image Processing, vol. 55, pp. 532-537, 1993. `2` Prewitt, JMS & Mendelsohn, ML (1966), β€œThe analysis of cell images”, Annals of the New York Academy of Sciences 128: 1035-1053 [DOI:10.1111/j.1749-6632.1965.tb11715.x](https://doi.org/10.1111/j.1749-6632.1965.tb11715.x) #### Examples ``` >>> from skimage.data import camera >>> image = camera() >>> thresh = threshold_minimum(image) >>> binary = image > thresh ``` threshold\_multiotsu -------------------- `skimage.filters.threshold_multiotsu(image, classes=3, nbins=256)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/thresholding.py#L1137-L1228) Generate `classes`-1 threshold values to divide gray levels in `image`. The threshold values are chosen to maximize the total sum of pairwise variances between the thresholded graylevel classes. See Notes and [[1]](#r9f5f8b3d5d49-1) for more details. Parameters `image(N, M) ndarray` Grayscale input image. `classesint, optional` Number of classes to be thresholded, i.e. the number of resulting regions. `nbinsint, optional` Number of bins used to calculate the histogram. This value is ignored for integer arrays. Returns `thresharray` Array containing the threshold values for the desired classes. Raises ValueError If `image` contains less grayscale value then the desired number of classes. #### Notes This implementation relies on a Cython function whose complexity is \(O\left(\frac{Ch^{C-1}}{(C-1)!}\right)\), where \(h\) is the number of histogram bins and \(C\) is the number of classes desired. The input image must be grayscale. #### References `1` Liao, P-S., Chen, T-S. and Chung, P-C., β€œA fast algorithm for multilevel thresholding”, Journal of Information Science and Engineering 17 (5): 713-727, 2001. Available at: <<https://ftp.iis.sinica.edu.tw/JISE/2001/200109_01.pdf>> [DOI:10.6688/JISE.2001.17.5.1](https://doi.org/10.6688/JISE.2001.17.5.1) `2` Tosa, Y., β€œMulti-Otsu Threshold”, a java plugin for ImageJ. Available at: <<http://imagej.net/plugins/download/Multi_OtsuThreshold.java>> #### Examples ``` >>> from skimage.color import label2rgb >>> from skimage import data >>> image = data.camera() >>> thresholds = threshold_multiotsu(image) >>> regions = np.digitize(image, bins=thresholds) >>> regions_colorized = label2rgb(regions) ``` ### Examples using `skimage.filters.threshold_multiotsu` [Multi-Otsu Thresholding](https://scikit-image.org/docs/0.18.x/auto_examples/segmentation/plot_multiotsu.html#sphx-glr-auto-examples-segmentation-plot-multiotsu-py) [Segment human cells (in mitosis)](https://scikit-image.org/docs/0.18.x/auto_examples/applications/plot_human_mitosis.html#sphx-glr-auto-examples-applications-plot-human-mitosis-py) threshold\_niblack ------------------ `skimage.filters.threshold_niblack(image, window_size=15, k=0.2)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/thresholding.py#L967-L1027) Applies Niblack local threshold to an array. A threshold T is calculated for every pixel in the image using the following formula: ``` T = m(x,y) - k * s(x,y) ``` where m(x,y) and s(x,y) are the mean and standard deviation of pixel (x,y) neighborhood defined by a rectangular window with size w times w centered around the pixel. k is a configurable parameter that weights the effect of standard deviation. Parameters `imagendarray` Input image. `window_sizeint, or iterable of int, optional` Window size specified as a single odd integer (3, 5, 7, …), or an iterable of length `image.ndim` containing only odd integers (e.g. `(1, 5, 5)`). `kfloat, optional` Value of parameter k in threshold formula. Returns `threshold(N, M) ndarray` Threshold mask. All pixels with an intensity higher than this value are assumed to be foreground. #### Notes This algorithm is originally designed for text recognition. The Bradley threshold is a particular case of the Niblack one, being equivalent to ``` >>> from skimage import data >>> image = data.page() >>> q = 1 >>> threshold_image = threshold_niblack(image, k=0) * q ``` for some value `q`. By default, Bradley and Roth use `q=1`. #### References `1` W. Niblack, An introduction to Digital Image Processing, Prentice-Hall, 1986. `2` D. Bradley and G. Roth, β€œAdaptive thresholding using Integral Image”, Journal of Graphics Tools 12(2), pp. 13-21, 2007. [DOI:10.1080/2151237X.2007.10129236](https://doi.org/10.1080/2151237X.2007.10129236) #### Examples ``` >>> from skimage import data >>> image = data.page() >>> threshold_image = threshold_niblack(image, window_size=7, k=0.1) ``` threshold\_otsu --------------- `skimage.filters.threshold_otsu(image=None, nbins=256, *, hist=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/thresholding.py#L282-L350) Return threshold value based on Otsu’s method. Either image or hist must be provided. If hist is provided, the actual histogram of the image is ignored. Parameters `image(N, M) ndarray, optional` Grayscale input image. `nbinsint, optional` Number of bins used to calculate histogram. This value is ignored for integer arrays. `histarray, or 2-tuple of arrays, optional` Histogram from which to determine the threshold, and optionally a corresponding array of bin center intensities. An alternative use of this function is to pass it only hist. Returns `thresholdfloat` Upper threshold value. All pixels with an intensity higher than this value are assumed to be foreground. #### Notes The input image must be grayscale. #### References `1` Wikipedia, [https://en.wikipedia.org/wiki/Otsu’s\_Method](https://en.wikipedia.org/wiki/Otsu's_Method) #### Examples ``` >>> from skimage.data import camera >>> image = camera() >>> thresh = threshold_otsu(image) >>> binary = image <= thresh ``` ### Examples using `skimage.filters.threshold_otsu` [Measure region properties](https://scikit-image.org/docs/0.18.x/auto_examples/segmentation/plot_regionprops.html#sphx-glr-auto-examples-segmentation-plot-regionprops-py) [Rank filters](https://scikit-image.org/docs/0.18.x/auto_examples/applications/plot_rank_filters.html#sphx-glr-auto-examples-applications-plot-rank-filters-py) threshold\_sauvola ------------------ `skimage.filters.threshold_sauvola(image, window_size=15, k=0.2, r=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/thresholding.py#L1030-L1087) Applies Sauvola local threshold to an array. Sauvola is a modification of Niblack technique. In the original method a threshold T is calculated for every pixel in the image using the following formula: ``` T = m(x,y) * (1 + k * ((s(x,y) / R) - 1)) ``` where m(x,y) and s(x,y) are the mean and standard deviation of pixel (x,y) neighborhood defined by a rectangular window with size w times w centered around the pixel. k is a configurable parameter that weights the effect of standard deviation. R is the maximum standard deviation of a greyscale image. Parameters `imagendarray` Input image. `window_sizeint, or iterable of int, optional` Window size specified as a single odd integer (3, 5, 7, …), or an iterable of length `image.ndim` containing only odd integers (e.g. `(1, 5, 5)`). `kfloat, optional` Value of the positive parameter k. `rfloat, optional` Value of R, the dynamic range of standard deviation. If None, set to the half of the image dtype range. Returns `threshold(N, M) ndarray` Threshold mask. All pixels with an intensity higher than this value are assumed to be foreground. #### Notes This algorithm is originally designed for text recognition. #### References `1` J. Sauvola and M. Pietikainen, β€œAdaptive document image binarization,” Pattern Recognition 33(2), pp. 225-236, 2000. [DOI:10.1016/S0031-3203(99)00055-2](https://doi.org/10.1016/S0031-3203(99)00055-2) #### Examples ``` >>> from skimage import data >>> image = data.page() >>> t_sauvola = threshold_sauvola(image, window_size=15, k=0.2) >>> binary_image = image > t_sauvola ``` threshold\_triangle ------------------- `skimage.filters.threshold_triangle(image, nbins=256)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/thresholding.py#L833-L907) Return threshold value based on the triangle algorithm. Parameters `image(N, M[, …, P]) ndarray` Grayscale input image. `nbinsint, optional` Number of bins used to calculate histogram. This value is ignored for integer arrays. Returns `thresholdfloat` Upper threshold value. All pixels with an intensity higher than this value are assumed to be foreground. #### References `1` Zack, G. W., Rogers, W. E. and Latt, S. A., 1977, Automatic Measurement of Sister Chromatid Exchange Frequency, Journal of Histochemistry and Cytochemistry 25 (7), pp. 741-753 [DOI:10.1177/25.7.70454](https://doi.org/10.1177/25.7.70454) `2` ImageJ AutoThresholder code, <http://fiji.sc/wiki/index.php/Auto_Threshold> #### Examples ``` >>> from skimage.data import camera >>> image = camera() >>> thresh = threshold_triangle(image) >>> binary = image > thresh ``` threshold\_yen -------------- `skimage.filters.threshold_yen(image=None, nbins=256, *, hist=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/thresholding.py#L353-L411) Return threshold value based on Yen’s method. Either image or hist must be provided. In case hist is given, the actual histogram of the image is ignored. Parameters `image(N, M) ndarray, optional` Input image. `nbinsint, optional` Number of bins used to calculate histogram. This value is ignored for integer arrays. `histarray, or 2-tuple of arrays, optional` Histogram from which to determine the threshold, and optionally a corresponding array of bin center intensities. An alternative use of this function is to pass it only hist. Returns `thresholdfloat` Upper threshold value. All pixels with an intensity higher than this value are assumed to be foreground. #### References `1` Yen J.C., Chang F.J., and Chang S. (1995) β€œA New Criterion for Automatic Multilevel Thresholding” IEEE Trans. on Image Processing, 4(3): 370-378. [DOI:10.1109/83.366472](https://doi.org/10.1109/83.366472) `2` Sezgin M. and Sankur B. (2004) β€œSurvey over Image Thresholding Techniques and Quantitative Performance Evaluation” Journal of Electronic Imaging, 13(1): 146-165, [DOI:10.1117/1.1631315](https://doi.org/10.1117/1.1631315) <http://www.busim.ee.boun.edu.tr/~sankur/SankurFolder/Threshold_survey.pdf> `3` ImageJ AutoThresholder code, <http://fiji.sc/wiki/index.php/Auto_Threshold> #### Examples ``` >>> from skimage.data import camera >>> image = camera() >>> thresh = threshold_yen(image) >>> binary = image <= thresh ``` try\_all\_threshold ------------------- `skimage.filters.try_all_threshold(image, figsize=(8, 5), verbose=True)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/thresholding.py#L86-L142) Returns a figure comparing the outputs of different thresholding methods. Parameters `image(N, M) ndarray` Input image. `figsizetuple, optional` Figure size (in inches). `verbosebool, optional` Print function name for each method. Returns `fig, axtuple` Matplotlib figure and axes. #### Notes The following algorithms are used: * isodata * li * mean * minimum * otsu * triangle * yen #### Examples ``` >>> from skimage.data import text >>> fig, ax = try_all_threshold(text(), figsize=(10, 6), verbose=False) ``` unsharp\_mask ------------- `skimage.filters.unsharp_mask(image, radius=1.0, amount=1.0, multichannel=False, preserve_range=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/_unsharp_mask.py#L19-L135) Unsharp masking filter. The sharp details are identified as the difference between the original image and its blurred version. These details are then scaled, and added back to the original image. Parameters `image[P, …, ]M[, N][, C] ndarray` Input image. `radiusscalar or sequence of scalars, optional` If a scalar is given, then its value is used for all dimensions. If sequence is given, then there must be exactly one radius for each dimension except the last dimension for multichannel images. Note that 0 radius means no blurring, and negative values are not allowed. `amountscalar, optional` The details will be amplified with this factor. The factor could be 0 or negative. Typically, it is a small positive number, e.g. 1.0. `multichannelbool, optional` If True, the last `image` dimension is considered as a color channel, otherwise as spatial. Color channels are processed individually. `preserve_rangebool, optional` Whether to keep the original range of values. Otherwise, the input image is converted according to the conventions of `img_as_float`. Also see <https://scikit-image.org/docs/dev/user_guide/data_types.html> Returns `output[P, …, ]M[, N][, C] ndarray of float` Image with unsharp mask applied. #### Notes Unsharp masking is an image sharpening technique. It is a linear image operation, and numerically stable, unlike deconvolution which is an ill-posed problem. Because of this stability, it is often preferred over deconvolution. The main idea is as follows: sharp details are identified as the difference between the original image and its blurred version. These details are added back to the original image after a scaling step: enhanced image = original + amount \* (original - blurred) When applying this filter to several color layers independently, color bleeding may occur. More visually pleasing result can be achieved by processing only the brightness/lightness/intensity channel in a suitable color space such as HSV, HSL, YUV, or YCbCr. Unsharp masking is described in most introductory digital image processing books. This implementation is based on [[1]](#re30cac9066b6-1). #### References `1` Maria Petrou, Costas Petrou β€œImage Processing: The Fundamentals”, (2010), ed ii., page 357, ISBN 13: 9781119994398 [DOI:10.1002/9781119994398](https://doi.org/10.1002/9781119994398) `2` Wikipedia. Unsharp masking <https://en.wikipedia.org/wiki/Unsharp_masking> #### Examples ``` >>> array = np.ones(shape=(5,5), dtype=np.uint8)*100 >>> array[2,2] = 120 >>> array array([[100, 100, 100, 100, 100], [100, 100, 100, 100, 100], [100, 100, 120, 100, 100], [100, 100, 100, 100, 100], [100, 100, 100, 100, 100]], dtype=uint8) >>> np.around(unsharp_mask(array, radius=0.5, amount=2),2) array([[0.39, 0.39, 0.39, 0.39, 0.39], [0.39, 0.39, 0.38, 0.39, 0.39], [0.39, 0.38, 0.53, 0.38, 0.39], [0.39, 0.39, 0.38, 0.39, 0.39], [0.39, 0.39, 0.39, 0.39, 0.39]]) ``` ``` >>> array = np.ones(shape=(5,5), dtype=np.int8)*100 >>> array[2,2] = 127 >>> np.around(unsharp_mask(array, radius=0.5, amount=2),2) array([[0.79, 0.79, 0.79, 0.79, 0.79], [0.79, 0.78, 0.75, 0.78, 0.79], [0.79, 0.75, 1. , 0.75, 0.79], [0.79, 0.78, 0.75, 0.78, 0.79], [0.79, 0.79, 0.79, 0.79, 0.79]]) ``` ``` >>> np.around(unsharp_mask(array, radius=0.5, amount=2, preserve_range=True), 2) array([[100. , 100. , 99.99, 100. , 100. ], [100. , 99.39, 95.48, 99.39, 100. ], [ 99.99, 95.48, 147.59, 95.48, 99.99], [100. , 99.39, 95.48, 99.39, 100. ], [100. , 100. , 99.99, 100. , 100. ]]) ``` wiener ------ `skimage.filters.wiener(data, impulse_response=None, filter_params={}, K=0.25, predefined_filter=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/lpi_filter.py#L207-L246) Minimum Mean Square Error (Wiener) inverse filter. Parameters `data(M,N) ndarray` Input data. `Kfloat or (M,N) ndarray` Ratio between power spectrum of noise and undegraded image. `impulse_responsecallable f(r, c, **filter_params)` Impulse response of the filter. See LPIFilter2D.\_\_init\_\_. `filter_paramsdict` Additional keyword parameters to the impulse\_response function. Other Parameters `predefined_filterLPIFilter2D` If you need to apply the same filter multiple times over different images, construct the LPIFilter2D and specify it here. window ------ `skimage.filters.window(window_type, shape, warp_kwargs=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/_window.py#L8-L129) Return an n-dimensional window of a given size and dimensionality. Parameters `window_typestring, float, or tuple` The type of window to be created. Any window type supported by `scipy.signal.get_window` is allowed here. See notes below for a current list, or the SciPy documentation for the version of SciPy on your machine. `shapetuple of int or int` The shape of the window along each axis. If an integer is provided, a 1D window is generated. `warp_kwargsdict` Keyword arguments passed to [`skimage.transform.warp`](skimage.transform#skimage.transform.warp "skimage.transform.warp") (e.g., `warp_kwargs={'order':3}` to change interpolation method). Returns `nd_windowndarray` A window of the specified `shape`. `dtype` is `np.double`. #### Notes This function is based on `scipy.signal.get_window` and thus can access all of the window types available to that function (e.g., `"hann"`, `"boxcar"`). Note that certain window types require parameters that have to be supplied with the window name as a tuple (e.g., `("tukey", 0.8)`). If only a float is supplied, it is interpreted as the beta parameter of the Kaiser window. See <https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.windows.get_window.html> for more details. Note that this function generates a double precision array of the specified `shape` and can thus generate very large arrays that consume a large amount of available memory. The approach taken here to create nD windows is to first calculate the Euclidean distance from the center of the intended nD window to each position in the array. That distance is used to sample, with interpolation, from a 1D window returned from `scipy.signal.get_window`. The method of interpolation can be changed with the `order` keyword argument passed to [`skimage.transform.warp`](skimage.transform#skimage.transform.warp "skimage.transform.warp"). Some coordinates in the output window will be outside of the original signal; these will be filled in with zeros. Window types: - boxcar - triang - blackman - hamming - hann - bartlett - flattop - parzen - bohman - blackmanharris - nuttall - barthann - kaiser (needs beta) - gaussian (needs standard deviation) - general\_gaussian (needs power, width) - slepian (needs width) - dpss (needs normalized half-bandwidth) - chebwin (needs attenuation) - exponential (needs decay scale) - tukey (needs taper fraction) #### References `1` Two-dimensional window design, Wikipedia, <https://en.wikipedia.org/wiki/Two_dimensional_window_design> #### Examples Return a Hann window with shape (512, 512): ``` >>> from skimage.filters import window >>> w = window('hann', (512, 512)) ``` Return a Kaiser window with beta parameter of 16 and shape (256, 256, 35): ``` >>> w = window(16, (256, 256, 35)) ``` Return a Tukey window with an alpha parameter of 0.8 and shape (100, 300): ``` >>> w = window(('tukey', 0.8), (100, 300)) ``` LPIFilter2D ----------- `class skimage.filters.LPIFilter2D(impulse_response, **filter_params)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/lpi_filter.py#L42-L127) Bases: [`object`](https://docs.python.org/3.9/library/functions.html#object "(in Python v3.9)") Linear Position-Invariant Filter (2-dimensional) `__init__(impulse_response, **filter_params)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/filters/lpi_filter.py#L47-L83) Parameters `impulse_responsecallable f(r, c, **filter_params)` Function that yields the impulse response. `r` and `c` are 1-dimensional vectors that represent row and column positions, in other words coordinates are (r[0],c[0]),(r[0],c[1]) etc. `**filter_params` are passed through. In other words, `impulse_response` would be called like this: ``` >>> def impulse_response(r, c, **filter_params): ... pass >>> >>> r = [0,0,0,1,1,1,2,2,2] >>> c = [0,1,2,0,1,2,0,1,2] >>> filter_params = {'kw1': 1, 'kw2': 2, 'kw3': 3} >>> impulse_response(r, c, **filter_params) ``` #### Examples Gaussian filter: Use a 1-D gaussian in each direction without normalization coefficients. ``` >>> def filt_func(r, c, sigma = 1): ... return np.exp(-np.hypot(r, c)/sigma) >>> filter = LPIFilter2D(filt_func) ```
programming_docs
scikit_image Module: graph Module: graph ============= | | | | --- | --- | | [`skimage.graph.route_through_array`](#skimage.graph.route_through_array "skimage.graph.route_through_array")(array, …) | Simple example of how to use the MCP and MCP\_Geometric classes. | | [`skimage.graph.shortest_path`](#skimage.graph.shortest_path "skimage.graph.shortest_path")(arr[, reach, …]) | Find the shortest path through an n-d array from one side to another. | | [`skimage.graph.MCP`](#skimage.graph.MCP "skimage.graph.MCP")(costs[, offsets, …]) | A class for finding the minimum cost path through a given n-d costs array. | | [`skimage.graph.MCP_Connect`](#skimage.graph.MCP_Connect "skimage.graph.MCP_Connect")(costs[, offsets, …]) | Connect source points using the distance-weighted minimum cost function. | | [`skimage.graph.MCP_Flexible`](#skimage.graph.MCP_Flexible "skimage.graph.MCP_Flexible")(costs[, offsets, …]) | Find minimum cost paths through an N-d costs array. | | [`skimage.graph.MCP_Geometric`](#skimage.graph.MCP_Geometric "skimage.graph.MCP_Geometric")(costs[, …]) | Find distance-weighted minimum cost paths through an n-d costs array. | route\_through\_array --------------------- `skimage.graph.route_through_array(array, start, end, fully_connected=True, geometric=True)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/graph/mcp.py#L4-L89) Simple example of how to use the MCP and MCP\_Geometric classes. See the MCP and MCP\_Geometric class documentation for explanation of the path-finding algorithm. Parameters `arrayndarray` Array of costs. `startiterable` n-d index into [`array`](https://docs.python.org/3.9/library/array.html#module-array "(in Python v3.9)") defining the starting point `enditerable` n-d index into [`array`](https://docs.python.org/3.9/library/array.html#module-array "(in Python v3.9)") defining the end point `fully_connectedbool (optional)` If True, diagonal moves are permitted, if False, only axial moves. `geometricbool (optional)` If True, the MCP\_Geometric class is used to calculate costs, if False, the MCP base class is used. See the class documentation for an explanation of the differences between MCP and MCP\_Geometric. Returns `pathlist` List of n-d index tuples defining the path from `start` to `end`. `costfloat` Cost of the path. If `geometric` is False, the cost of the path is the sum of the values of [`array`](https://docs.python.org/3.9/library/array.html#module-array "(in Python v3.9)") along the path. If `geometric` is True, a finer computation is made (see the documentation of the MCP\_Geometric class). See also `MCP,` [`MCP_Geometric`](#skimage.graph.MCP_Geometric "skimage.graph.MCP_Geometric") #### Examples ``` >>> import numpy as np >>> from skimage.graph import route_through_array >>> >>> image = np.array([[1, 3], [10, 12]]) >>> image array([[ 1, 3], [10, 12]]) >>> # Forbid diagonal steps >>> route_through_array(image, [0, 0], [1, 1], fully_connected=False) ([(0, 0), (0, 1), (1, 1)], 9.5) >>> # Now allow diagonal steps: the path goes directly from start to end >>> route_through_array(image, [0, 0], [1, 1]) ([(0, 0), (1, 1)], 9.19238815542512) >>> # Cost is the sum of array values along the path (16 = 1 + 3 + 12) >>> route_through_array(image, [0, 0], [1, 1], fully_connected=False, ... geometric=False) ([(0, 0), (0, 1), (1, 1)], 16.0) >>> # Larger array where we display the path that is selected >>> image = np.arange((36)).reshape((6, 6)) >>> image array([[ 0, 1, 2, 3, 4, 5], [ 6, 7, 8, 9, 10, 11], [12, 13, 14, 15, 16, 17], [18, 19, 20, 21, 22, 23], [24, 25, 26, 27, 28, 29], [30, 31, 32, 33, 34, 35]]) >>> # Find the path with lowest cost >>> indices, weight = route_through_array(image, (0, 0), (5, 5)) >>> indices = np.stack(indices, axis=-1) >>> path = np.zeros_like(image) >>> path[indices[0], indices[1]] = 1 >>> path array([[1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 1], [0, 0, 0, 0, 0, 1]]) ``` shortest\_path -------------- `skimage.graph.shortest_path(arr, reach=1, axis=-1, output_indexlist=False)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/graph/spath.py#L5-L81) Find the shortest path through an n-d array from one side to another. Parameters `arrndarray of float64` `reachint, optional` By default (`reach = 1`), the shortest path can only move one row up or down for every step it moves forward (i.e., the path gradient is limited to 1). `reach` defines the number of elements that can be skipped along each non-axis dimension at each step. `axisint, optional` The axis along which the path must always move forward (default -1) `output_indexlistbool, optional` See return value `p` for explanation. Returns `piterable of int` For each step along `axis`, the coordinate of the shortest path. If `output_indexlist` is True, then the path is returned as a list of n-d tuples that index into `arr`. If False, then the path is returned as an array listing the coordinates of the path along the non-axis dimensions for each step along the axis dimension. That is, `p.shape == (arr.shape[axis], arr.ndim-1)` except that p is squeezed before returning so if `arr.ndim == 2`, then `p.shape == (arr.shape[axis],)` `costfloat` Cost of path. This is the absolute sum of all the differences along the path. MCP --- `class skimage.graph.MCP(costs, offsets=None, fully_connected=True, sampling=None)` Bases: [`object`](https://docs.python.org/3.9/library/functions.html#object "(in Python v3.9)") A class for finding the minimum cost path through a given n-d costs array. Given an n-d costs array, this class can be used to find the minimum-cost path through that array from any set of points to any other set of points. Basic usage is to initialize the class and call find\_costs() with a one or more starting indices (and an optional list of end indices). After that, call traceback() one or more times to find the path from any given end-position to the closest starting index. New paths through the same costs array can be found by calling find\_costs() repeatedly. The cost of a path is calculated simply as the sum of the values of the `costs` array at each point on the path. The class MCP\_Geometric, on the other hand, accounts for the fact that diagonal vs. axial moves are of different lengths, and weights the path cost accordingly. Array elements with infinite or negative costs will simply be ignored, as will paths whose cumulative cost overflows to infinite. Parameters `costsndarray` `offsetsiterable, optional` A list of offset tuples: each offset specifies a valid move from a given n-d position. If not provided, offsets corresponding to a singly- or fully-connected n-d neighborhood will be constructed with make\_offsets(), using the `fully_connected` parameter value. `fully_connectedbool, optional` If no `offsets` are provided, this determines the connectivity of the generated neighborhood. If true, the path may go along diagonals between elements of the `costs` array; otherwise only axial moves are permitted. `samplingtuple, optional` For each dimension, specifies the distance between two cells/voxels. If not given or None, the distance is assumed unit. Attributes `offsetsndarray` Equivalent to the `offsets` provided to the constructor, or if none were so provided, the offsets created for the requested n-d neighborhood. These are useful for interpreting the [`traceback`](#skimage.graph.MCP.traceback "skimage.graph.MCP.traceback") array returned by the find\_costs() method. `__init__(costs, offsets=None, fully_connected=True, sampling=None)` See class documentation. `find_costs()` Find the minimum-cost path from the given starting points. This method finds the minimum-cost path to the specified ending indices from any one of the specified starting indices. If no end positions are given, then the minimum-cost path to every position in the costs array will be found. Parameters `startsiterable` A list of n-d starting indices (where n is the dimension of the `costs` array). The minimum cost path to the closest/cheapest starting point will be found. `endsiterable, optional` A list of n-d ending indices. `find_all_endsbool, optional` If β€˜True’ (default), the minimum-cost-path to every specified end-position will be found; otherwise the algorithm will stop when a a path is found to any end-position. (If no `ends` were specified, then this parameter has no effect.) Returns `cumulative_costsndarray` Same shape as the `costs` array; this array records the minimum cost path from the nearest/cheapest starting index to each index considered. (If `ends` were specified, not all elements in the array will necessarily be considered: positions not evaluated will have a cumulative cost of inf. If `find_all_ends` is β€˜False’, only one of the specified end-positions will have a finite cumulative cost.) `tracebackndarray` Same shape as the `costs` array; this array contains the offset to any given index from its predecessor index. The offset indices index into the `offsets` attribute, which is a array of n-d offsets. In the 2-d case, if offsets[traceback[x, y]] is (-1, -1), that means that the predecessor of [x, y] in the minimum cost path to some start position is [x+1, y+1]. Note that if the offset\_index is -1, then the given index was not considered. `goal_reached()` int goal\_reached(int index, float cumcost) This method is called each iteration after popping an index from the heap, before examining the neighbours. This method can be overloaded to modify the behavior of the MCP algorithm. An example might be to stop the algorithm when a certain cumulative cost is reached, or when the front is a certain distance away from the seed point. This method should return 1 if the algorithm should not check the current point’s neighbours and 2 if the algorithm is now done. `traceback(end)` Trace a minimum cost path through the pre-calculated traceback array. This convenience function reconstructs the the minimum cost path to a given end position from one of the starting indices provided to find\_costs(), which must have been called previously. This function can be called as many times as desired after find\_costs() has been run. Parameters `enditerable` An n-d index into the `costs` array. Returns `tracebacklist of n-d tuples` A list of indices into the `costs` array, starting with one of the start positions passed to find\_costs(), and ending with the given `end` index. These indices specify the minimum-cost path from any given start index to the `end` index. (The total cost of that path can be read out from the `cumulative_costs` array returned by find\_costs().) MCP\_Connect ------------ `class skimage.graph.MCP_Connect(costs, offsets=None, fully_connected=True)` Bases: `skimage.graph._mcp.MCP` Connect source points using the distance-weighted minimum cost function. A front is grown from each seed point simultaneously, while the origin of the front is tracked as well. When two fronts meet, create\_connection() is called. This method must be overloaded to deal with the found edges in a way that is appropriate for the application. `__init__(*args, **kwargs)` Initialize self. See help(type(self)) for accurate signature. `create_connection()` create\_connection id1, id2, pos1, pos2, cost1, cost2) Overload this method to keep track of the connections that are found during MCP processing. Note that a connection with the same ids can be found multiple times (but with different positions and costs). At the time that this method is called, both points are β€œfrozen” and will not be visited again by the MCP algorithm. Parameters `id1int` The seed point id where the first neighbor originated from. `id2int` The seed point id where the second neighbor originated from. `pos1tuple` The index of of the first neighbour in the connection. `pos2tuple` The index of of the second neighbour in the connection. `cost1float` The cumulative cost at `pos1`. `cost2float` The cumulative costs at `pos2`. MCP\_Flexible ------------- `class skimage.graph.MCP_Flexible(costs, offsets=None, fully_connected=True)` Bases: `skimage.graph._mcp.MCP` Find minimum cost paths through an N-d costs array. See the documentation for MCP for full details. This class differs from MCP in that several methods can be overloaded (from pure Python) to modify the behavior of the algorithm and/or create custom algorithms based on MCP. Note that goal\_reached can also be overloaded in the MCP class. `__init__(costs, offsets=None, fully_connected=True, sampling=None)` See class documentation. `examine_neighbor(index, new_index, offset_length)` This method is called once for every pair of neighboring nodes, as soon as both nodes are frozen. This method can be overloaded to obtain information about neightboring nodes, and/or to modify the behavior of the MCP algorithm. One example is the MCP\_Connect class, which checks for meeting fronts using this hook. `travel_cost(old_cost, new_cost, offset_length)` This method calculates the travel cost for going from the current node to the next. The default implementation returns new\_cost. Overload this method to adapt the behaviour of the algorithm. `update_node(index, new_index, offset_length)` This method is called when a node is updated, right after new\_index is pushed onto the heap and the traceback map is updated. This method can be overloaded to keep track of other arrays that are used by a specific implementation of the algorithm. For instance the MCP\_Connect class uses it to update an id map. MCP\_Geometric -------------- `class skimage.graph.MCP_Geometric(costs, offsets=None, fully_connected=True)` Bases: `skimage.graph._mcp.MCP` Find distance-weighted minimum cost paths through an n-d costs array. See the documentation for MCP for full details. This class differs from MCP in that the cost of a path is not simply the sum of the costs along that path. This class instead assumes that the costs array contains at each position the β€œcost” of a unit distance of travel through that position. For example, a move (in 2-d) from (1, 1) to (1, 2) is assumed to originate in the center of the pixel (1, 1) and terminate in the center of (1, 2). The entire move is of distance 1, half through (1, 1) and half through (1, 2); thus the cost of that move is `(1/2)*costs[1,1] + (1/2)*costs[1,2]`. On the other hand, a move from (1, 1) to (2, 2) is along the diagonal and is sqrt(2) in length. Half of this move is within the pixel (1, 1) and the other half in (2, 2), so the cost of this move is calculated as `(sqrt(2)/2)*costs[1,1] + (sqrt(2)/2)*costs[2,2]`. These calculations don’t make a lot of sense with offsets of magnitude greater than 1. Use the `sampling` argument in order to deal with anisotropic data. `__init__(costs, offsets=None, fully_connected=True, sampling=None)` See class documentation. scikit_image Module: data Module: data ============ Standard test images. For more images, see * <http://sipi.usc.edu/database/database.php> | | | | --- | --- | | [`skimage.data.astronaut`](#skimage.data.astronaut "skimage.data.astronaut")() | Color image of the astronaut Eileen Collins. | | [`skimage.data.binary_blobs`](#skimage.data.binary_blobs "skimage.data.binary_blobs")([length, …]) | Generate synthetic binary image with several rounded blob-like objects. | | [`skimage.data.brain`](#skimage.data.brain "skimage.data.brain")() | Subset of data from the University of North Carolina Volume Rendering Test Data Set. | | [`skimage.data.brick`](#skimage.data.brick "skimage.data.brick")() | Brick wall. | | [`skimage.data.camera`](#skimage.data.camera "skimage.data.camera")() | Gray-level β€œcamera” image. | | [`skimage.data.cat`](#skimage.data.cat "skimage.data.cat")() | Chelsea the cat. | | [`skimage.data.cell`](#skimage.data.cell "skimage.data.cell")() | Cell floating in saline. | | [`skimage.data.cells3d`](#skimage.data.cells3d "skimage.data.cells3d")() | 3D fluorescence microscopy image of cells. | | [`skimage.data.checkerboard`](#skimage.data.checkerboard "skimage.data.checkerboard")() | Checkerboard image. | | [`skimage.data.chelsea`](#skimage.data.chelsea "skimage.data.chelsea")() | Chelsea the cat. | | [`skimage.data.clock`](#skimage.data.clock "skimage.data.clock")() | Motion blurred clock. | | [`skimage.data.coffee`](#skimage.data.coffee "skimage.data.coffee")() | Coffee cup. | | [`skimage.data.coins`](#skimage.data.coins "skimage.data.coins")() | Greek coins from Pompeii. | | [`skimage.data.colorwheel`](#skimage.data.colorwheel "skimage.data.colorwheel")() | Color Wheel. | | [`skimage.data.download_all`](#skimage.data.download_all "skimage.data.download_all")([directory]) | Download all datasets for use with scikit-image offline. | | [`skimage.data.eagle`](#skimage.data.eagle "skimage.data.eagle")() | A golden eagle. | | [`skimage.data.grass`](#skimage.data.grass "skimage.data.grass")() | Grass. | | [`skimage.data.gravel`](#skimage.data.gravel "skimage.data.gravel")() | Gravel | | [`skimage.data.horse`](#skimage.data.horse "skimage.data.horse")() | Black and white silhouette of a horse. | | [`skimage.data.hubble_deep_field`](#skimage.data.hubble_deep_field "skimage.data.hubble_deep_field")() | Hubble eXtreme Deep Field. | | [`skimage.data.human_mitosis`](#skimage.data.human_mitosis "skimage.data.human_mitosis")() | Image of human cells undergoing mitosis. | | [`skimage.data.immunohistochemistry`](#skimage.data.immunohistochemistry "skimage.data.immunohistochemistry")() | Immunohistochemical (IHC) staining with hematoxylin counterstaining. | | [`skimage.data.kidney`](#skimage.data.kidney "skimage.data.kidney")() | Mouse kidney tissue. | | [`skimage.data.lbp_frontal_face_cascade_filename`](#skimage.data.lbp_frontal_face_cascade_filename "skimage.data.lbp_frontal_face_cascade_filename")() | Return the path to the XML file containing the weak classifier cascade. | | [`skimage.data.lfw_subset`](#skimage.data.lfw_subset "skimage.data.lfw_subset")() | Subset of data from the LFW dataset. | | [`skimage.data.lily`](#skimage.data.lily "skimage.data.lily")() | Lily of the valley plant stem. | | [`skimage.data.logo`](#skimage.data.logo "skimage.data.logo")() | Scikit-image logo, a RGBA image. | | [`skimage.data.microaneurysms`](#skimage.data.microaneurysms "skimage.data.microaneurysms")() | Gray-level β€œmicroaneurysms” image. | | [`skimage.data.moon`](#skimage.data.moon "skimage.data.moon")() | Surface of the moon. | | [`skimage.data.page`](#skimage.data.page "skimage.data.page")() | Scanned page. | | [`skimage.data.retina`](#skimage.data.retina "skimage.data.retina")() | Human retina. | | [`skimage.data.rocket`](#skimage.data.rocket "skimage.data.rocket")() | Launch photo of DSCOVR on Falcon 9 by SpaceX. | | [`skimage.data.shepp_logan_phantom`](#skimage.data.shepp_logan_phantom "skimage.data.shepp_logan_phantom")() | Shepp Logan Phantom. | | [`skimage.data.skin`](#skimage.data.skin "skimage.data.skin")() | Microscopy image of dermis and epidermis (skin layers). | | [`skimage.data.stereo_motorcycle`](#skimage.data.stereo_motorcycle "skimage.data.stereo_motorcycle")() | Rectified stereo image pair with ground-truth disparities. | | [`skimage.data.text`](#skimage.data.text "skimage.data.text")() | Gray-level β€œtext” image used for corner detection. | astronaut --------- `skimage.data.astronaut()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L394-L413) Color image of the astronaut Eileen Collins. Photograph of Eileen Collins, an American astronaut. She was selected as an astronaut in 1992 and first piloted the space shuttle STS-63 in 1995. She retired in 2006 after spending a total of 38 days, 8 hours and 10 minutes in outer space. This image was downloaded from the NASA Great Images database <<https://flic.kr/p/r9qvLn>>`\_\_. No known copyright restrictions, released into the public domain. Returns `astronaut(512, 512, 3) uint8 ndarray` Astronaut image. ### Examples using `skimage.data.astronaut` [Flood Fill](https://scikit-image.org/docs/0.18.x/auto_examples/segmentation/plot_floodfill.html#sphx-glr-auto-examples-segmentation-plot-floodfill-py) binary\_blobs ------------- `skimage.data.binary_blobs(length=512, blob_size_fraction=0.1, n_dim=2, volume_fraction=0.5, seed=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/_binary_blobs.py#L4-L57) Generate synthetic binary image with several rounded blob-like objects. Parameters `lengthint, optional` Linear size of output image. `blob_size_fractionfloat, optional` Typical linear size of blob, as a fraction of `length`, should be smaller than 1. `n_dimint, optional` Number of dimensions of output image. `volume_fractionfloat, default 0.5` Fraction of image pixels covered by the blobs (where the output is 1). Should be in [0, 1]. `seedint, optional` Seed to initialize the random number generator. If `None`, a random seed from the operating system is used. Returns `blobsndarray of bools` Output binary image #### Examples ``` >>> from skimage import data >>> data.binary_blobs(length=5, blob_size_fraction=0.2, seed=1) array([[ True, False, True, True, True], [ True, True, True, False, True], [False, True, False, True, True], [ True, False, False, True, True], [ True, False, False, False, True]]) >>> blobs = data.binary_blobs(length=256, blob_size_fraction=0.1) >>> # Finer structures >>> blobs = data.binary_blobs(length=256, blob_size_fraction=0.05) >>> # Blobs cover a smaller volume fraction of the image >>> blobs = data.binary_blobs(length=256, volume_fraction=0.3) ``` brain ----- `skimage.data.brain()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L1162-L1181) Subset of data from the University of North Carolina Volume Rendering Test Data Set. The full dataset is available at [[1]](#r77fa297eebeb-1). Returns `image(10, 256, 256) uint16 ndarray` #### Notes The 3D volume consists of 10 layers from the larger volume. #### References `1` <https://graphics.stanford.edu/data/voldata/> ### Examples using `skimage.data.brain` [Local Histogram Equalization](https://scikit-image.org/docs/0.18.x/auto_examples/color_exposure/plot_local_equalize.html#sphx-glr-auto-examples-color-exposure-plot-local-equalize-py) [Rank filters](https://scikit-image.org/docs/0.18.x/auto_examples/applications/plot_rank_filters.html#sphx-glr-auto-examples-applications-plot-rank-filters-py) brick ----- `skimage.data.brick()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L416-L479) Brick wall. Returns `brick(512, 512) uint8 image` A small section of a brick wall. #### Notes The original image was downloaded from [CC0Textures](https://cc0textures.com/view.php?tex=Bricks25) and licensed under the Creative Commons CC0 License. A perspective transform was then applied to the image, prior to rotating it by 90 degrees, cropping and scaling it to obtain the final image. camera ------ `skimage.data.camera()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L351-L373) Gray-level β€œcamera” image. Can be used for segmentation and denoising examples. Returns `camera(512, 512) uint8 ndarray` Camera image. #### Notes No copyright restrictions. CC0 by the photographer (Lav Varshney). Changed in version 0.18: This image was replaced due to copyright restrictions. For more information, please see [[1]](#r2f100140753e-1). #### References `1` <https://github.com/scikit-image/scikit-image/issues/3927> ### Examples using `skimage.data.camera` [Tinting gray-scale images](https://scikit-image.org/docs/0.18.x/auto_examples/color_exposure/plot_tinting_grayscale_images.html#sphx-glr-auto-examples-color-exposure-plot-tinting-grayscale-images-py) [Masked Normalized Cross-Correlation](https://scikit-image.org/docs/0.18.x/auto_examples/registration/plot_masked_register_translation.html#sphx-glr-auto-examples-registration-plot-masked-register-translation-py) [Entropy](https://scikit-image.org/docs/0.18.x/auto_examples/filters/plot_entropy.html#sphx-glr-auto-examples-filters-plot-entropy-py) [GLCM Texture Features](https://scikit-image.org/docs/0.18.x/auto_examples/features_detection/plot_glcm.html#sphx-glr-auto-examples-features-detection-plot-glcm-py) [Multi-Otsu Thresholding](https://scikit-image.org/docs/0.18.x/auto_examples/segmentation/plot_multiotsu.html#sphx-glr-auto-examples-segmentation-plot-multiotsu-py) [Flood Fill](https://scikit-image.org/docs/0.18.x/auto_examples/segmentation/plot_floodfill.html#sphx-glr-auto-examples-segmentation-plot-floodfill-py) [Rank filters](https://scikit-image.org/docs/0.18.x/auto_examples/applications/plot_rank_filters.html#sphx-glr-auto-examples-applications-plot-rank-filters-py) cat --- `skimage.data.cat()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L902-L917) Chelsea the cat. An example with texture, prominent edges in horizontal and diagonal directions, as well as features of differing scales. Returns `chelsea(300, 451, 3) uint8 ndarray` Chelsea image. #### Notes No copyright restrictions. CC0 by the photographer (Stefan van der Walt). cell ---- `skimage.data.cell()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L677-L705) Cell floating in saline. This is a quantitative phase image retrieved from a digital hologram using the Python library `qpformat`. The image shows a cell with high phase value, above the background phase. Because of a banding pattern artifact in the background, this image is a good test of thresholding algorithms. The pixel spacing is 0.107 Β΅m. These data were part of a comparison between several refractive index retrieval techniques for spherical objects as part of [[1]](#r02365d02e4e0-1). This image is CC0, dedicated to the public domain. You may copy, modify, or distribute it without asking permission. Returns `cell(660, 550) uint8 array` Image of a cell. #### References `1` Paul MΓΌller, Mirjam SchΓΌrmann, Salvatore Girardo, Gheorghe Cojoc, and Jochen Guck. β€œAccurate evaluation of size and refractive index for spherical objects in quantitative phase imaging.” Optics Express 26(8): 10729-10743 (2018). [DOI:10.1364/OE.26.010729](https://doi.org/10.1364/OE.26.010729) cells3d ------- `skimage.data.cells3d()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L619-L645) 3D fluorescence microscopy image of cells. The returned data is a 3D multichannel array with dimensions provided in `(z, c, y, x)` order. Each voxel has a size of `(0.29 0.26 0.26)` micrometer. Channel 0 contains cell membranes, channel 1 contains nuclei. Returns cells3d: (60, 2, 256, 256) uint16 ndarray The volumetric images of cells taken with an optical microscope. #### Notes The data for this was provided by the Allen Institute for Cell Science. It has been downsampled by a factor of 4 in the row and column dimensions to reduce computational time. The microscope reports the following voxel spacing in microns: * Original voxel size is `(0.290, 0.065, 0.065)`. * Scaling factor is `(1, 4, 4)` in each dimension. * After rescaling the voxel size is `(0.29 0.26 0.26)`. ### Examples using `skimage.data.cells3d` [3D adaptive histogram equalization](https://scikit-image.org/docs/0.18.x/auto_examples/color_exposure/plot_adapt_hist_eq_3d.html#sphx-glr-auto-examples-color-exposure-plot-adapt-hist-eq-3d-py) [Use rolling-ball algorithm for estimating background intensity](https://scikit-image.org/docs/0.18.x/auto_examples/segmentation/plot_rolling_ball.html#sphx-glr-auto-examples-segmentation-plot-rolling-ball-py) [Explore 3D images (of cells)](https://scikit-image.org/docs/0.18.x/auto_examples/applications/plot_3d_image_processing.html#sphx-glr-auto-examples-applications-plot-3d-image-processing-py) checkerboard ------------ `skimage.data.checkerboard()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L604-L616) Checkerboard image. Checkerboards are often used in image calibration, since the corner-points are easy to locate. Because of the many parallel edges, they also visualise distortions particularly well. Returns `checkerboard(200, 200) uint8 ndarray` Checkerboard image. ### Examples using `skimage.data.checkerboard` [Flood Fill](https://scikit-image.org/docs/0.18.x/auto_examples/segmentation/plot_floodfill.html#sphx-glr-auto-examples-segmentation-plot-floodfill-py) chelsea ------- `skimage.data.chelsea()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L902-L917) Chelsea the cat. An example with texture, prominent edges in horizontal and diagonal directions, as well as features of differing scales. Returns `chelsea(300, 451, 3) uint8 ndarray` Chelsea image. #### Notes No copyright restrictions. CC0 by the photographer (Stefan van der Walt). ### Examples using `skimage.data.chelsea` [Phase Unwrapping](https://scikit-image.org/docs/0.18.x/auto_examples/filters/plot_phase_unwrap.html#sphx-glr-auto-examples-filters-plot-phase-unwrap-py) [Flood Fill](https://scikit-image.org/docs/0.18.x/auto_examples/segmentation/plot_floodfill.html#sphx-glr-auto-examples-segmentation-plot-floodfill-py) clock ----- `skimage.data.clock()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L865-L879) Motion blurred clock. This photograph of a wall clock was taken while moving the camera in an aproximately horizontal direction. It may be used to illustrate inverse filters and deconvolution. Released into the public domain by the photographer (Stefan van der Walt). Returns `clock(300, 400) uint8 ndarray` Clock image. coffee ------ `skimage.data.coffee()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L924-L940) Coffee cup. This photograph is courtesy of Pikolo Espresso Bar. It contains several elliptical shapes as well as varying texture (smooth porcelain to course wood grain). Returns `coffee(400, 600, 3) uint8 ndarray` Coffee image. #### Notes No copyright restrictions. CC0 by the photographer (Rachel Michetti). coins ----- `skimage.data.coins()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L708-L730) Greek coins from Pompeii. This image shows several coins outlined against a gray background. It is especially useful in, e.g. segmentation tests, where individual objects need to be identified against a background. The background shares enough grey levels with the coins that a simple segmentation is not sufficient. Returns `coins(303, 384) uint8 ndarray` Coins image. #### Notes This image was downloaded from the [Brooklyn Museum Collection](https://www.brooklynmuseum.org/opencollection/archives/image/51611). No known copyright restrictions. ### Examples using `skimage.data.coins` [Finding local maxima](https://scikit-image.org/docs/0.18.x/auto_examples/segmentation/plot_peak_local_max.html#sphx-glr-auto-examples-segmentation-plot-peak-local-max-py) [Measure region properties](https://scikit-image.org/docs/0.18.x/auto_examples/segmentation/plot_regionprops.html#sphx-glr-auto-examples-segmentation-plot-regionprops-py) [Use rolling-ball algorithm for estimating background intensity](https://scikit-image.org/docs/0.18.x/auto_examples/segmentation/plot_rolling_ball.html#sphx-glr-auto-examples-segmentation-plot-rolling-ball-py) colorwheel ---------- `skimage.data.colorwheel()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L1011-L1019) Color Wheel. Returns `colorwheel(370, 371, 3) uint8 image` A colorwheel. download\_all ------------- `skimage.data.download_all(directory=None)` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L263-L312) Download all datasets for use with scikit-image offline. Scikit-image datasets are no longer shipped with the library by default. This allows us to use higher quality datasets, while keeping the library download size small. This function requires the installation of an optional dependency, pooch, to download the full dataset. Follow installation instruction found at <https://scikit-image.org/docs/stable/install.html> Call this function to download all sample images making them available offline on your machine. Parameters **directory: path-like, optional** The directory where the dataset should be stored. Raises ModuleNotFoundError: If pooch is not install, this error will be raised. #### Notes scikit-image will only search for images stored in the default directory. Only specify the directory if you wish to download the images to your own folder for a particular reason. You can access the location of the default data directory by inspecting the variable `skimage.data.data_dir`. eagle ----- `skimage.data.eagle()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L376-L391) A golden eagle. Suitable for examples on segmentation, Hough transforms, and corner detection. Returns `eagle(2019, 1826) uint8 ndarray` Eagle image. #### Notes No copyright restrictions. CC0 by the photographer (Dayane Machado). ### Examples using `skimage.data.eagle` [Markers for watershed transform](https://scikit-image.org/docs/0.18.x/auto_examples/segmentation/plot_marked_watershed.html#sphx-glr-auto-examples-segmentation-plot-marked-watershed-py) grass ----- `skimage.data.grass()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L482-L527) Grass. Returns `grass(512, 512) uint8 image` Some grass. #### Notes The original image was downloaded from [DeviantArt](https://www.deviantart.com/linolafett/art/Grass-01-434853879) and licensed underthe Creative Commons CC0 License. The downloaded image was cropped to include a region of `(512, 512)` pixels around the top left corner, converted to grayscale, then to uint8 prior to saving the result in PNG format. gravel ------ `skimage.data.gravel()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L530-L582) Gravel Returns `gravel(512, 512) uint8 image` Grayscale gravel sample. #### Notes The original image was downloaded from [CC0Textures](https://cc0textures.com/view.php?tex=Gravel04) and licensed under the Creative Commons CC0 License. The downloaded image was then rescaled to `(1024, 1024)`, then the top left `(512, 512)` pixel region was cropped prior to converting the image to grayscale and uint8 data type. The result was saved using the PNG format. horse ----- `skimage.data.horse()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L849-L862) Black and white silhouette of a horse. This image was downloaded from `openclipart` No copyright restrictions. CC0 given by owner (Andreas Preuss (marauder)). Returns `horse(328, 400) bool ndarray` Horse image. hubble\_deep\_field ------------------- `skimage.data.hubble_deep_field()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L943-L964) Hubble eXtreme Deep Field. This photograph contains the Hubble Telescope’s farthest ever view of the universe. It can be useful as an example for multi-scale detection. Returns `hubble_deep_field(872, 1000, 3) uint8 ndarray` Hubble deep field image. #### Notes This image was downloaded from [HubbleSite](http://hubblesite.org/newscenter/archive/releases/2012/37/image/a/). The image was captured by NASA and [may be freely used in the public domain](http://www.nasa.gov/audience/formedia/features/MP_Photo_Guidelines.html). human\_mitosis -------------- `skimage.data.human_mitosis()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L648-L674) Image of human cells undergoing mitosis. Returns human\_mitosis: (512, 512) uint8 ndimage Data of human cells undergoing mitosis taken during the preperation of the manuscript in [[1]](#r2b0a1772c690-1). #### Notes Copyright David Root. Licensed under CC-0 [[2]](#r2b0a1772c690-2). #### References `1` Moffat J, Grueneberg DA, Yang X, Kim SY, Kloepfer AM, Hinkle G, Piqani B, Eisenhaure TM, Luo B, Grenier JK, Carpenter AE, Foo SY, Stewart SA, Stockwell BR, Hacohen N, Hahn WC, Lander ES, Sabatini DM, Root DE (2006) A lentiviral RNAi library for human and mouse genes applied to an arrayed viral high-content screen. Cell, 124(6):1283-98 / :DOI: `10.1016/j.cell.2006.01.040` PMID 16564017 `2` GitHub licensing discussion <https://github.com/CellProfiler/examples/issues/41> ### Examples using `skimage.data.human_mitosis` [Segment human cells (in mitosis)](https://scikit-image.org/docs/0.18.x/auto_examples/applications/plot_human_mitosis.html#sphx-glr-auto-examples-applications-plot-human-mitosis-py) immunohistochemistry -------------------- `skimage.data.immunohistochemistry()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L882-L899) Immunohistochemical (IHC) staining with hematoxylin counterstaining. This picture shows colonic glands where the IHC expression of FHL2 protein is revealed with DAB. Hematoxylin counterstaining is applied to enhance the negative parts of the tissue. This image was acquired at the Center for Microscopy And Molecular Imaging (CMMI). No known copyright restrictions. Returns `immunohistochemistry(512, 512, 3) uint8 ndarray` Immunohistochemistry image. kidney ------ `skimage.data.kidney()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L733-L755) Mouse kidney tissue. This biological tissue on a pre-prepared slide was imaged with confocal fluorescence microscopy (Nikon C1 inverted microscope). Image shape is (16, 512, 512, 3). That is 512x512 pixels in X-Y, 16 image slices in Z, and 3 color channels (emission wavelengths 450nm, 515nm, and 605nm, respectively). Real-space voxel size is 1.24 microns in X-Y, and 1.25 microns in Z. Data type is unsigned 16-bit integers. Returns `kidney(16, 512, 512, 3) uint16 ndarray` Kidney 3D multichannel image. #### Notes This image was acquired by Genevieve Buckley at Monasoh Micro Imaging in 2018. License: CC0 lbp\_frontal\_face\_cascade\_filename ------------------------------------- `skimage.data.lbp_frontal_face_cascade_filename()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L315-L327) Return the path to the XML file containing the weak classifier cascade. These classifiers were trained using LBP features. The file is part of the OpenCV repository [[1]](#rde45415ad1b5-1). #### References `1` OpenCV lbpcascade trained files <https://github.com/opencv/opencv/tree/master/data/lbpcascades> lfw\_subset ----------- `skimage.data.lfw_subset()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L1106-L1135) Subset of data from the LFW dataset. This database is a subset of the LFW database containing: * 100 faces * 100 non-faces The full dataset is available at [[2]](#r9c6d6b06eb8d-2). Returns `images(200, 25, 25) uint8 ndarray` 100 first images are faces and subsequent 100 are non-faces. #### Notes The faces were randomly selected from the LFW dataset and the non-faces were extracted from the background of the same dataset. The cropped ROIs have been resized to a 25 x 25 pixels. #### References `1` Huang, G., Mattar, M., Lee, H., & Learned-Miller, E. G. (2012). Learning to align from scratch. In Advances in Neural Information Processing Systems (pp. 764-772). `2` <http://vis-www.cs.umass.edu/lfw/> ### Examples using `skimage.data.lfw_subset` [Specific images](https://scikit-image.org/docs/0.18.x/auto_examples/data/plot_specific.html#sphx-glr-auto-examples-data-plot-specific-py) lily ---- `skimage.data.lily()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L758-L779) Lily of the valley plant stem. This plant stem on a pre-prepared slide was imaged with confocal fluorescence microscopy (Nikon C1 inverted microscope). Image shape is (922, 922, 4). That is 922x922 pixels in X-Y, with 4 color channels. Real-space voxel size is 1.24 microns in X-Y. Data type is unsigned 16-bit integers. Returns `lily(922, 922, 4) uint16 ndarray` Lily 2D multichannel image. #### Notes This image was acquired by Genevieve Buckley at Monasoh Micro Imaging in 2018. License: CC0 logo ---- `skimage.data.logo()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L782-L790) Scikit-image logo, a RGBA image. Returns `logo(500, 500, 4) uint8 ndarray` Logo image. microaneurysms -------------- `skimage.data.microaneurysms()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L793-L818) Gray-level β€œmicroaneurysms” image. Detail from an image of the retina (green channel). The image is a crop of image 07\_dr.JPG from the High-Resolution Fundus (HRF) Image Database: <https://www5.cs.fau.de/research/data/fundus-images/> Returns `microaneurysms(102, 102) uint8 ndarray` Retina image with lesions. #### Notes No copyright restrictions. CC0 given by owner (Andreas Maier). #### References `1` Budai, A., Bock, R, Maier, A., Hornegger, J., Michelson, G. (2013). Robust Vessel Segmentation in Fundus Images. International Journal of Biomedical Imaging, vol. 2013, 2013. [DOI:10.1155/2013/154860](https://doi.org/10.1155/2013/154860) moon ---- `skimage.data.moon()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L821-L832) Surface of the moon. This low-contrast image of the surface of the moon is useful for illustrating histogram equalization and contrast stretching. Returns `moon(512, 512) uint8 ndarray` Moon image. ### Examples using `skimage.data.moon` [Local Histogram Equalization](https://scikit-image.org/docs/0.18.x/auto_examples/color_exposure/plot_local_equalize.html#sphx-glr-auto-examples-color-exposure-plot-local-equalize-py) page ---- `skimage.data.page()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L835-L846) Scanned page. This image of printed text is useful for demonstrations requiring uneven background illumination. Returns `page(191, 384) uint8 ndarray` Page image. ### Examples using `skimage.data.page` [Use rolling-ball algorithm for estimating background intensity](https://scikit-image.org/docs/0.18.x/auto_examples/segmentation/plot_rolling_ball.html#sphx-glr-auto-examples-segmentation-plot-rolling-ball-py) [Rank filters](https://scikit-image.org/docs/0.18.x/auto_examples/applications/plot_rank_filters.html#sphx-glr-auto-examples-applications-plot-rank-filters-py) retina ------ `skimage.data.retina()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L967-L991) Human retina. This image of a retina is useful for demonstrations requiring circular images. Returns `retina(1411, 1411, 3) uint8 ndarray` Retina image in RGB. #### Notes This image was downloaded from `wikimedia`. This file is made available under the Creative Commons CC0 1.0 Universal Public Domain Dedication. #### References `1` HΓ€ggstrΓΆm, Mikael (2014). β€œMedical gallery of Mikael HΓ€ggstrΓΆm 2014”. WikiJournal of Medicine 1 (2). [DOI:10.15347/wjm/2014.008](https://doi.org/10.15347/wjm/2014.008). ISSN 2002-4436. Public Domain rocket ------ `skimage.data.rocket()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L1022-L1042) Launch photo of DSCOVR on Falcon 9 by SpaceX. This is the launch photo of Falcon 9 carrying DSCOVR lifted off from SpaceX’s Launch Complex 40 at Cape Canaveral Air Force Station, FL. Returns `rocket(427, 640, 3) uint8 ndarray` Rocket image. #### Notes This image was downloaded from [SpaceX Photos](https://www.flickr.com/photos/spacexphotos/16511594820/in/photostream/). The image was captured by SpaceX and [released in the public domain](http://arstechnica.com/tech-policy/2015/03/elon-musk-puts-spacex-photos-into-the-public-domain/). shepp\_logan\_phantom --------------------- `skimage.data.shepp_logan_phantom()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L994-L1008) Shepp Logan Phantom. Returns `phantom(400, 400) float64 image` Image of the Shepp-Logan phantom in grayscale. #### References `1` L. A. Shepp and B. F. Logan, β€œThe Fourier reconstruction of a head section,” in IEEE Transactions on Nuclear Science, vol. 21, no. 3, pp. 21-43, June 1974. [DOI:10.1109/TNS.1974.6499235](https://doi.org/10.1109/TNS.1974.6499235) skin ---- `skimage.data.skin()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L1138-L1159) Microscopy image of dermis and epidermis (skin layers). Hematoxylin and eosin stained slide at 10x of normal epidermis and dermis with a benign intradermal nevus. Returns `skin(960, 1280, 3) RGB image of uint8` #### Notes This image requires an Internet connection the first time it is called, and to have the `pooch` package installed, in order to fetch the image file from the scikit-image datasets repository. The source of this image is <https://en.wikipedia.org/wiki/File:Normal_Epidermis_and_Dermis_with_Intradermal_Nevus_10x.JPG> The image was released in the public domain by its author Kilbad. ### Examples using `skimage.data.skin` [Trainable segmentation using local features and random forests](https://scikit-image.org/docs/0.18.x/auto_examples/segmentation/plot_trainable_segmentation.html#sphx-glr-auto-examples-segmentation-plot-trainable-segmentation-py) stereo\_motorcycle ------------------ `skimage.data.stereo_motorcycle()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L1045-L1103) Rectified stereo image pair with ground-truth disparities. The two images are rectified such that every pixel in the left image has its corresponding pixel on the same scanline in the right image. That means that both images are warped such that they have the same orientation but a horizontal spatial offset (baseline). The ground-truth pixel offset in column direction is specified by the included disparity map. The two images are part of the Middlebury 2014 stereo benchmark. The dataset was created by Nera Nesic, Porter Westling, Xi Wang, York Kitajima, Greg Krathwohl, and Daniel Scharstein at Middlebury College. A detailed description of the acquisition process can be found in [[1]](#re12479cea6aa-1). The images included here are down-sampled versions of the default exposure images in the benchmark. The images are down-sampled by a factor of 4 using the function [`skimage.transform.downscale_local_mean`](skimage.transform#skimage.transform.downscale_local_mean "skimage.transform.downscale_local_mean"). The calibration data in the following and the included ground-truth disparity map are valid for the down-sampled images: ``` Focal length: 994.978px Principal point x: 311.193px Principal point y: 254.877px Principal point dx: 31.086px Baseline: 193.001mm ``` Returns `img_left(500, 741, 3) uint8 ndarray` Left stereo image. `img_right(500, 741, 3) uint8 ndarray` Right stereo image. `disp(500, 741, 3) float ndarray` Ground-truth disparity map, where each value describes the offset in column direction between corresponding pixels in the left and the right stereo images. E.g. the corresponding pixel of `img_left[10, 10 + disp[10, 10]]` is `img_right[10, 10]`. NaNs denote pixels in the left image that do not have ground-truth. #### Notes The original resolution images, images with different exposure and lighting, and ground-truth depth maps can be found at the Middlebury website [[2]](#re12479cea6aa-2). #### References `1` D. Scharstein, H. Hirschmueller, Y. Kitajima, G. Krathwohl, N. Nesic, X. Wang, and P. Westling. High-resolution stereo datasets with subpixel-accurate ground truth. In German Conference on Pattern Recognition (GCPR 2014), Muenster, Germany, September 2014. `2` <http://vision.middlebury.edu/stereo/data/scenes2014/> ### Examples using `skimage.data.stereo_motorcycle` [Specific images](https://scikit-image.org/docs/0.18.x/auto_examples/data/plot_specific.html#sphx-glr-auto-examples-data-plot-specific-py) [Registration using optical flow](https://scikit-image.org/docs/0.18.x/auto_examples/registration/plot_opticalflow.html#sphx-glr-auto-examples-registration-plot-opticalflow-py) text ---- `skimage.data.text()` [[source]](https://github.com/scikit-image/scikit-image/blob/v0.18.0/skimage/data/__init__.py#L585-L601) Gray-level β€œtext” image used for corner detection. Returns `text(172, 448) uint8 ndarray` Text image. #### Notes This image was downloaded from Wikipedia <<https://en.wikipedia.org/wiki/File:Corner.png>>`\_\_. No known copyright restrictions, released into the public domain.
programming_docs
nokogiri Nokogiri Nokogiri ======== * [README](https://nokogiri.org/rdoc/README_md.html) * [Nokogiri](nokogiri) * [Nokogiri::CSS](nokogiri/css) * [Nokogiri::CSS::SyntaxError](nokogiri/css/syntaxerror) * [Nokogiri::CSS::XPathVisitor](nokogiri/css/xpathvisitor) * [Nokogiri::CSS::XPathVisitor::BuiltinsConfig](nokogiri/css/xpathvisitor/builtinsconfig) * [Nokogiri::CSS::XPathVisitor::DoctypeConfig](nokogiri/css/xpathvisitor/doctypeconfig) * [Nokogiri::ClassResolver](nokogiri/classresolver) * [Nokogiri::Decorators](nokogiri/decorators) * [Nokogiri::Decorators::Slop](nokogiri/decorators/slop) * [Nokogiri::EncodingHandler](nokogiri/encodinghandler) * [Nokogiri::Gumbo](nokogiri/gumbo) * [Nokogiri::HTML](nokogiri/html4) * [Nokogiri::HTML4](nokogiri/html4) * [Nokogiri::HTML4::Builder](nokogiri/html4/builder) * [Nokogiri::HTML4::Document](nokogiri/html4/document) * [Nokogiri::HTML4::DocumentFragment](nokogiri/html4/documentfragment) * [Nokogiri::HTML4::ElementDescription](nokogiri/html4/elementdescription) * [Nokogiri::HTML4::EntityDescription](nokogiri/html4/entitydescription) * [Nokogiri::HTML4::EntityLookup](nokogiri/html4/entitylookup) * [Nokogiri::HTML4::SAX](nokogiri/html4/sax) * [Nokogiri::HTML4::SAX::Parser](nokogiri/html4/sax/parser) * [Nokogiri::HTML4::SAX::ParserContext](nokogiri/html4/sax/parsercontext) * [Nokogiri::HTML4::SAX::PushParser](nokogiri/html4/sax/pushparser) * [Nokogiri::HTML5](nokogiri/html5) * [Nokogiri::HTML5::Document](nokogiri/html5/document) * [Nokogiri::HTML5::DocumentFragment](nokogiri/html5/documentfragment) * [Nokogiri::HTML5::Node](nokogiri/html5/node) * [Nokogiri::HTML5::QuirksMode](nokogiri/html5/quirksmode) * [Nokogiri::HTML::Builder](nokogiri/html/builder) * [Nokogiri::HTML::Document](nokogiri/html/document) * [Nokogiri::HTML::DocumentFragment](nokogiri/html/documentfragment) * [Nokogiri::SyntaxError](nokogiri/syntaxerror) * [Nokogiri::XML](nokogiri/xml) * [Nokogiri::XML::Attr](nokogiri/xml/attr) * [Nokogiri::XML::AttributeDecl](nokogiri/xml/attributedecl) * [Nokogiri::XML::Builder](nokogiri/xml/builder) * [Nokogiri::XML::CDATA](nokogiri/xml/cdata) * [Nokogiri::XML::CharacterData](nokogiri/xml/characterdata) * [Nokogiri::XML::Comment](nokogiri/xml/comment) * [Nokogiri::XML::DTD](nokogiri/xml/dtd) * [Nokogiri::XML::Document](nokogiri/xml/document) * [Nokogiri::XML::DocumentFragment](nokogiri/xml/documentfragment) * [Nokogiri::XML::Element](nokogiri/xml/element) * [Nokogiri::XML::ElementContent](nokogiri/xml/elementcontent) * [Nokogiri::XML::ElementDecl](nokogiri/xml/elementdecl) * [Nokogiri::XML::EntityDecl](nokogiri/xml/entitydecl) * [Nokogiri::XML::EntityReference](nokogiri/xml/entityreference) * [Nokogiri::XML::Namespace](nokogiri/xml/namespace) * [Nokogiri::XML::Node](nokogiri/xml/node) * [Nokogiri::XML::Node::SaveOptions](nokogiri/xml/node/saveoptions) * [Nokogiri::XML::NodeSet](nokogiri/xml/nodeset) * [Nokogiri::XML::Notation](nokogiri/xml/notation) * [Nokogiri::XML::ParseOptions](nokogiri/xml/parseoptions) * [Nokogiri::XML::ProcessingInstruction](nokogiri/xml/processinginstruction) * [Nokogiri::XML::Reader](nokogiri/xml/reader) * [Nokogiri::XML::RelaxNG](nokogiri/xml/relaxng) * [Nokogiri::XML::SAX](nokogiri/xml/sax) * [Nokogiri::XML::SAX::Document](nokogiri/xml/sax/document) * [Nokogiri::XML::SAX::Parser](nokogiri/xml/sax/parser) * [Nokogiri::XML::SAX::Parser::Attribute](nokogiri/xml/sax/parser/attribute) * [Nokogiri::XML::SAX::ParserContext](nokogiri/xml/sax/parsercontext) * [Nokogiri::XML::SAX::PushParser](nokogiri/xml/sax/pushparser) * [Nokogiri::XML::Schema](nokogiri/xml/schema) * [Nokogiri::XML::Searchable](nokogiri/xml/searchable) * [Nokogiri::XML::SyntaxError](nokogiri/xml/syntaxerror) * [Nokogiri::XML::Text](nokogiri/xml/text) * [Nokogiri::XML::XPath](nokogiri/xml/xpath) * [Nokogiri::XML::XPath::SyntaxError](nokogiri/xml/xpath/syntaxerror) * [Nokogiri::XML::XPathContext](nokogiri/xml/xpathcontext) * [Nokogiri::XSLT](nokogiri/xslt) * [Nokogiri::XSLT::Stylesheet](nokogiri/xslt/stylesheet) * [Object](https://nokogiri.org/rdoc/Object.html) * [XSD](xsd) * [XSD::XMLParser](xsd/xmlparser) * [XSD::XMLParser::Nokogiri](xsd/xmlparser/nokogiri) nokogiri module Nokogiri module Nokogiri ================ [`Nokogiri`](nokogiri) parses and searches XML/HTML very quickly, and also has correctly implemented CSS3 selector support as well as XPath 1.0 support. Parsing a document returns either a [`Nokogiri::XML::Document`](nokogiri/xml/document), or a [`Nokogiri::HTML4::Document`](nokogiri/html4/document) depending on the kind of document you parse. Here is an example: ``` require 'nokogiri' require 'open-uri' # Get a Nokogiri::HTML4::Document for the page we’re interested in... doc = Nokogiri::HTML4(URI.open('http://www.google.com/search?q=tenderlove')) # Do funky things with it using Nokogiri::XML::Node methods... #### # Search for nodes by css doc.css('h3.r a.l').each do |link| puts link.content end ``` See also: * [`Nokogiri::XML::Searchable#css`](nokogiri/xml/searchable#method-i-css) for more information about [`CSS`](nokogiri/css) searching * [`Nokogiri::XML::Searchable#xpath`](nokogiri/xml/searchable#method-i-xpath) for more information about XPath searching HTML Alias for [`Nokogiri::HTML4`](nokogiri/html4) JAR\_DEPENDENCIES generated by the :vendor\_jars rake task NEKO\_VERSION VERSION The version of [`Nokogiri`](nokogiri) you are using XERCES\_VERSION HTML(input, url = nil, encoding = nil, options = XML::ParseOptions::DEFAULT\_HTML, &block) β†’ Nokogiri::HTML4::Document Show source ``` # File lib/nokogiri/html.rb, line 10 ``` Parse [`HTML`](nokogiri/html4). Convenience method for [`Nokogiri::HTML4::Document.parse`](nokogiri/html4/document#method-c-parse) HTML4(input, url = nil, encoding = nil, options = XML::ParseOptions::DEFAULT\_HTML, &block) β†’ Nokogiri::HTML4::Document Show source ``` # File lib/nokogiri/html4.rb, line 10 def HTML4(input, url = nil, encoding = nil, options = XML::ParseOptions::DEFAULT_HTML, &block) Nokogiri::HTML4::Document.parse(input, url, encoding, options, &block) end ``` Parse [`HTML`](nokogiri/html4). Convenience method for [`Nokogiri::HTML4::Document.parse`](nokogiri/html4/document#method-c-parse) HTML5(input, url = nil, encoding = nil, \*\*options, &block) Show source ``` # File lib/nokogiri/html5.rb, line 30 def self.HTML5(input, url = nil, encoding = nil, **options, &block) Nokogiri::HTML5::Document.parse(input, url, encoding, **options, &block) end ``` Since v1.12.0 ⚠ [`HTML5`](nokogiri/html5) functionality is not available when running JRuby. Parse an [`HTML5`](nokogiri/html5) document. Convenience method for {Nokogiri::HTML5::Document.parse} Slop(\*args, &block) Show source ``` # File lib/nokogiri.rb, line 83 def Slop(*args, &block) Nokogiri(*args, &block).slop! end ``` Parse a document and add the [`Slop`](nokogiri#method-c-Slop) decorator. The [`Slop`](nokogiri#method-c-Slop) decorator implements method\_missing such that methods may be used instead of [`CSS`](nokogiri/css) or XPath. For example: ``` doc = Nokogiri::Slop(<<-eohtml) <html> <body> <p>first</p> <p>second</p> </body> </html> eohtml assert_equal('second', doc.html.body.p[1].text) ``` XML(thing, url = nil, encoding = nil, options = XML::ParseOptions::DEFAULT\_XML, &block) Show source ``` # File lib/nokogiri/xml.rb, line 7 def XML(thing, url = nil, encoding = nil, options = XML::ParseOptions::DEFAULT_XML, &block) Nokogiri::XML::Document.parse(thing, url, encoding, options, &block) end ``` Parse [`XML`](nokogiri/xml). Convenience method for [`Nokogiri::XML::Document.parse`](nokogiri/xml/document#method-c-parse) XSLT(stylesheet, modules = {}) Show source ``` # File lib/nokogiri/xslt.rb, line 13 def XSLT(stylesheet, modules = {}) XSLT.parse(stylesheet, modules) end ``` Create a [`Nokogiri::XSLT::Stylesheet`](nokogiri/xslt/stylesheet) with `stylesheet`. Example: ``` xslt = Nokogiri::XSLT(File.read(ARGV[0])) ``` make(input = nil, opts = {}, &blk) Show source ``` # File lib/nokogiri.rb, line 60 def make(input = nil, opts = {}, &blk) if input Nokogiri::HTML4.fragment(input).children.first else Nokogiri(&blk) end end ``` Create a new [`Nokogiri::XML::DocumentFragment`](nokogiri/xml/documentfragment) parse(string, url = nil, encoding = nil, options = nil) { |doc| ... } Show source ``` # File lib/nokogiri.rb, line 42 def parse(string, url = nil, encoding = nil, options = nil) if string.respond_to?(:read) || /^\s*<(?:!DOCTYPE\s+)?html[\s>]/i.match?(string[0, 512]) # Expect an HTML indicator to appear within the first 512 # characters of a document. (<?xml ?> + <?xml-stylesheet ?> # shouldn't be that long) Nokogiri.HTML4(string, url, encoding, options || XML::ParseOptions::DEFAULT_HTML) else Nokogiri.XML(string, url, encoding, options || XML::ParseOptions::DEFAULT_XML) end.tap do |doc| yield doc if block_given? end end ``` Parse an [`HTML`](nokogiri/html4) or [`XML`](nokogiri/xml) document. `string` contains the document. nokogiri class XSD::XMLParser::Nokogiri class XSD::XMLParser::Nokogiri =============================== Parent: XSD::XMLParser::Parser [`Nokogiri`](nokogiri) XML parser for soap4r. [`Nokogiri`](nokogiri) may be used as the XML parser in soap4r. Simply require β€˜xsd/xmlparser/nokogiri’ in your soap4r applications, and soap4r will use [`Nokogiri`](nokogiri) as it’s XML parser. No other changes should be required to use [`Nokogiri`](nokogiri) as the XML parser. Example (using UW ITS Web Services): ``` require 'rubygems' require 'nokogiri' gem 'soap4r' require 'defaultDriver' require 'xsd/xmlparser/nokogiri' obj = AvlPortType.new obj.getLatestByRoute(obj.getAgencies.first, 8).each do |bus| p "#{bus.routeID}, #{bus.longitude}, #{bus.latitude}" end ``` new(host, opt = {}) Show source ``` # File lib/xsd/xmlparser/nokogiri.rb, line 31 def initialize(host, opt = {}) super @parser = ::Nokogiri::XML::SAX::Parser.new(self, @charset || "UTF-8") end ``` Create a new [`XSD`](../../xsd) parser with `host` and `opt` Calls superclass method cdata\_block(string) Show source ``` # File lib/xsd/xmlparser/nokogiri.rb, line 63 def cdata_block(string) characters(string) end ``` Handle cdata\_blocks containing `string` do\_parse(string\_or\_readable) Show source ``` # File lib/xsd/xmlparser/nokogiri.rb, line 38 def do_parse(string_or_readable) @parser.parse(string_or_readable) end ``` Start parsing `string_or_readable` end\_element(name) Show source ``` # File lib/xsd/xmlparser/nokogiri.rb, line 50 def end_element(name) super end ``` Handle the [`end_element`](nokogiri#method-i-end_element) event with `name` Calls superclass method end\_element\_namespace(name, prefix = nil, uri = nil) Show source ``` # File lib/xsd/xmlparser/nokogiri.rb, line 91 def end_element_namespace(name, prefix = nil, uri = nil) ### # Deal with SAX v1 interface end_element([prefix, name].compact.join(":")) end ``` Called at the end of an element `name` is the element’s name `prefix` is the namespace prefix associated with the element `uri` is the associated namespace URI error(msg) Show source ``` # File lib/xsd/xmlparser/nokogiri.rb, line 56 def error(msg) raise ParseError, msg end ``` Handle errors with message `msg` Also aliased as: [warning](nokogiri#method-i-warning) start\_element(name, attrs = []) Show source ``` # File lib/xsd/xmlparser/nokogiri.rb, line 44 def start_element(name, attrs = []) super(name, Hash[*attrs.flatten]) end ``` Handle the [`start_element`](nokogiri#method-i-start_element) event with `name` and `attrs` Calls superclass method start\_element\_namespace(name, attrs = [], prefix = nil, uri = nil, ns = []) Show source ``` # File lib/xsd/xmlparser/nokogiri.rb, line 74 def start_element_namespace(name, attrs = [], prefix = nil, uri = nil, ns = []) ### # Deal with SAX v1 interface name = [prefix, name].compact.join(":") attributes = ns.map do |ns_prefix, ns_uri| [["xmlns", ns_prefix].compact.join(":"), ns_uri] end + attrs.map do |attr| [[attr.prefix, attr.localname].compact.join(":"), attr.value] end.flatten start_element(name, attributes) end ``` Called at the beginning of an element `name` is the element name `attrs` is a list of attributes `prefix` is the namespace prefix for the element `uri` is the associated namespace URI `ns` is a hash of namespace prefix:urls associated with the element warning(msg) Alias for: [error](nokogiri#method-i-error) nokogiri module Nokogiri::HTML5 module Nokogiri::HTML5 ======================= Usage ----- ⚠ [`HTML5`](html5) functionality is not available when running JRuby. Parse an [`HTML5`](html5) document: ``` doc = Nokogiri.HTML5(string) ``` Parse an [`HTML5`](html5) fragment: ``` fragment = Nokogiri::HTML5.fragment(string) ``` Parsing options --------------- The document and fragment parsing methods support options that are different from Nokogiri’s. * `Nokogiri.HTML5(html, url = nil, encoding = nil, options = {})` * `Nokogiri::HTML5.parse(html, url = nil, encoding = nil, options = {})` * `Nokogiri::HTML5::Document.parse(html, url = nil, encoding = nil, options = {})` * `Nokogiri::HTML5.fragment(html, encoding = nil, options = {})` * `Nokogiri::HTML5::DocumentFragment.parse(html, encoding = nil, options = {})` The three currently supported options are `:max_errors`, `:max_tree_depth` and `:max_attributes`, described below. ### Error reporting [`Nokogiri`](../nokogiri) contains an experimental [`HTML5`](html5) parse error reporting facility. By default, no parse errors are reported but this can be configured by passing the `:max_errors` option to {HTML5.parse} or {HTML5.fragment}. For example, this script: ``` doc = Nokogiri::HTML5.parse('<span/>Hi there!</span foo=bar />', max_errors: 10) doc.errors.each do |err| puts(err) end ``` Emits: ``` 1:1: ERROR: Expected a doctype token <span/>Hi there!</span foo=bar /> ^ 1:1: ERROR: Start tag of nonvoid HTML element ends with '/>', use '>'. <span/>Hi there!</span foo=bar /> ^ 1:17: ERROR: End tag ends with '/>', use '>'. <span/>Hi there!</span foo=bar /> ^ 1:17: ERROR: End tag contains attributes. <span/>Hi there!</span foo=bar /> ^ ``` Using `max_errors: -1` results in an unlimited number of errors being returned. The errors returned by {HTML5::Document#errors} are instances of {Nokogiri::XML::SyntaxError}. The {[html.spec.whatwg.org/multipage/parsing.html#parse-errors](https://html.spec.whatwg.org/multipage/parsing.html#parse-errors) [`HTML`](html4) standard} defines a number of standard parse error codes. These error codes only cover the β€œtokenization” stage of parsing [`HTML`](html4). The parse errors in the β€œtree construction” stage do not have standardized error codes (yet). As a convenience to [`Nokogiri`](../nokogiri) users, the defined error codes are available via {Nokogiri::XML::SyntaxError#str1} method. ``` doc = Nokogiri::HTML5.parse('<span/>Hi there!</span foo=bar />', max_errors: 10) doc.errors.each do |err| puts("#{err.line}:#{err.column}: #{err.str1}") end # => 1:1: generic-parser # 1:1: non-void-html-element-start-tag-with-trailing-solidus # 1:17: end-tag-with-trailing-solidus # 1:17: end-tag-with-attributes ``` Note that the first error is `generic-parser` because it’s an error from the tree construction stage and doesn’t have a standardized error code. For the purposes of semantic versioning, the error messages, error locations, and error codes are not part of Nokogiri’s public API. That is, these are subject to change without Nokogiri’s major version number changing. These may be stabilized in the future. ### Maximum tree depth The maximum depth of the DOM tree parsed by the various parsing methods is configurable by the `:max_tree_depth` option. If the depth of the tree would exceed this limit, then an {::ArgumentError} is thrown. This limit (which defaults to `Nokogiri::Gumbo::DEFAULT_MAX_TREE_DEPTH = 400`) can be removed by giving the option `max_tree_depth: -1`. ``` html = '<!DOCTYPE html>' + '<div>' * 1000 doc = Nokogiri.HTML5(html) # raises ArgumentError: Document tree depth limit exceeded doc = Nokogiri.HTML5(html, max_tree_depth: -1) ``` ### Attribute limit per element The maximum number of attributes per DOM element is configurable by the `:max_attributes` option. If a given element would exceed this limit, then an {::ArgumentError} is thrown. This limit (which defaults to `Nokogiri::Gumbo::DEFAULT_MAX_ATTRIBUTES = 400`) can be removed by giving the option `max_attributes: -1`. ``` html = '<!DOCTYPE html><div ' + (1..1000).map { |x| "attr-#{x}" }.join(' ') + '>' # "<!DOCTYPE html><div attr-1 attr-2 attr-3 ... attr-1000>" doc = Nokogiri.HTML5(html) # raises ArgumentError: Attributes per element limit exceeded doc = Nokogiri.HTML5(html, max_attributes: -1) ``` [`HTML`](html4) Serialization ------------------------------ After parsing [`HTML`](html4), it may be serialized using any of the {Nokogiri::XML::Node} serialization methods. In particular, {XML::Node#serialize}, {XML::Node#to\_html}, and {XML::Node#to\_s} will serialize a given node and its children. (This is the equivalent of JavaScript’s `Element.outerHTML`.) Similarly, {XML::Node#inner\_html} will serialize the children of a given node. (This is the equivalent of JavaScript’s `Element.innerHTML`.) ``` doc = Nokogiri::HTML5("<!DOCTYPE html><span>Hello world!</span>") puts doc.serialize # => <!DOCTYPE html><html><head></head><body><span>Hello world!</span></body></html> ``` Due to quirks in how [`HTML`](html4) is parsed and serialized, it’s possible for a DOM tree to be serialized and then re-parsed, resulting in a different DOM. Mostly, this happens with DOMs produced from invalid [`HTML`](html4). Unfortunately, even valid [`HTML`](html4) may not survive serialization and re-parsing. In particular, a newline at the start of `pre`, `listing`, and `textarea` elements is ignored by the parser. ``` doc = Nokogiri::HTML5(<<-EOF) <!DOCTYPE html> <pre> Content</pre> EOF puts doc.at('/html/body/pre').serialize # => <pre>Content</pre> ``` In this case, the original [`HTML`](html4) is semantically equivalent to the serialized version. If the `pre`, `listing`, or `textarea` content starts with two newlines, the first newline will be stripped on the first parse and the second newline will be stripped on the second, leading to semantically different DOMs. Passing the parameter `preserve_newline: true` will cause two or more newlines to be preserved. (A single leading newline will still be removed.) ``` doc = Nokogiri::HTML5(<<-EOF) <!DOCTYPE html> <listing> Content</listing> EOF puts doc.at('/html/body/listing').serialize(preserve_newline: true) # => <listing> # # Content</listing> ``` Encodings --------- [`Nokogiri`](../nokogiri) always parses [`HTML5`](html5) using {[en.wikipedia.org/wiki/UTF-8](https://en.wikipedia.org/wiki/UTF-8) UTF-8}; however, the encoding of the input can be explicitly selected via the optional `encoding` parameter. This is most useful when the input comes not from a string but from an IO object. When serializing a document or node, the encoding of the output string can be specified via the `:encoding` options. Characters that cannot be encoded in the selected encoding will be encoded as {[en.wikipedia.org/wiki/List\_of\_XML\_and\_HTML\_character\_entity\_references](https://en.wikipedia.org/wiki/List_of_XML_and_HTML_character_entity_references) [`HTML`](html4) numeric entities}. ``` frag = Nokogiri::HTML5.fragment('<span>μ•„λŠ” 길도 물어가라</span>') html = frag.serialize(encoding: 'US-ASCII') puts html # => <span>&#xc544;&#xb294; &#xae38;&#xb3c4; &#xbb3c;&#xc5b4;&#xac00;&#xb77c;</span> frag = Nokogiri::HTML5.fragment(html) puts frag.serialize # => <span>μ•„λŠ” 길도 물어가라</span> ``` (There’s a {[bugs.ruby-lang.org/issues/15033](https://bugs.ruby-lang.org/issues/15033) bug} in all current versions of Ruby that can cause the entity encoding to fail. Of the mandated supported encodings for [`HTML`](html4), the only encoding I’m aware of that has this bug is `'ISO-2022-JP'`. We recommend avoiding this encoding.) Notes ----- * The {Nokogiri::HTML5.fragment} function takes a string and parses it as a [`HTML5`](html5) document. The +<html>+, +<head>+, and +<body>+ elements are removed from this document, and any children of these elements that remain are returned as a {Nokogiri::HTML5::DocumentFragment}. * The {Nokogiri::HTML5.parse} function takes a string and passes it to the `gumbo_parse_with_options` method, using the default options. The resulting [`Gumbo`](gumbo) parse tree is then walked. * Instead of uppercase element names, lowercase element names are produced. * Instead of returning `unknown` as the element name for unknown tags, the original tag name is returned verbatim. Since v1.12.0 fragment(string, encoding = nil, \*\*options) Show source ``` # File lib/nokogiri/html5.rb, line 238 def fragment(string, encoding = nil, **options) DocumentFragment.parse(string, encoding, options) end ``` Parse a fragment from `string`. Convenience method for {Nokogiri::HTML5::DocumentFragment.parse}. get(uri, options = {}) Show source ``` # File lib/nokogiri/html5.rb, line 249 def get(uri, options = {}) # TODO: deprecate warn("Nokogiri::HTML5.get is deprecated and will be removed in a future version of Nokogiri.", uplevel: 1, category: :deprecated) get_impl(uri, options) end ``` Fetch and parse a [`HTML`](html4) document from the web, following redirects, handling https, and determining the character encoding using [`HTML5`](html5) rules. `uri` may be a `String` or a `URI`. `options` contains http headers and special options. Everything which is not a special option is considered a header. Special options include: ``` * :follow_limit => number of redirects which are followed * :basic_auth => [username, password] ``` parse(string, url = nil, encoding = nil, \*\*options, &block) Show source ``` # File lib/nokogiri/html5.rb, line 232 def parse(string, url = nil, encoding = nil, **options, &block) Document.parse(string, url, encoding, **options, &block) end ``` Parse an [`HTML`](html4) 5 document. Convenience method for {Nokogiri::HTML5::Document.parse}
programming_docs
nokogiri module Nokogiri::Gumbo module Nokogiri::Gumbo ======================= DEFAULT\_MAX\_ATTRIBUTES The default maximum number of attributes per element. DEFAULT\_MAX\_ERRORS The default maximum number of errors for parsing a document or a fragment. DEFAULT\_MAX\_TREE\_DEPTH The default maximum depth of the DOM tree produced by parsing a document or fragment. nokogiri module Nokogiri::HTML4 module Nokogiri::HTML4 ======================= πŸ’‘ This module/namespace is an alias for [`Nokogiri::HTML4`](html4) as of v1.12.0. Before v1.12.0, ``` Nokogiri::HTML4 did not exist, and this was the module/namespace for all HTML-related classes. ``` Since v1.12.0 πŸ’‘ Before v1.12.0, [`Nokogiri::HTML4`](html4) did not exist, and [`Nokogiri::HTML`](html4) was the module/namespace for parsing [`HTML`](html4). NamedCharacters Instance of [`Nokogiri::HTML4::EntityLookup`](html4/entitylookup) fragment(string, encoding = nil, options = XML::ParseOptions::DEFAULT\_HTML, &block) Show source ``` # File lib/nokogiri/html4.rb, line 29 def fragment(string, encoding = nil, options = XML::ParseOptions::DEFAULT_HTML, &block) HTML4::DocumentFragment.parse(string, encoding, options, &block) end ``` Parse a fragment from `string` in to a NodeSet. parse(input, url = nil, encoding = nil, options = XML::ParseOptions::DEFAULT\_HTML, &block) Show source ``` # File lib/nokogiri/html4.rb, line 23 def parse(input, url = nil, encoding = nil, options = XML::ParseOptions::DEFAULT_HTML, &block) Document.parse(input, url, encoding, options, &block) end ``` Parse [`HTML`](html4). Convenience method for [`Nokogiri::HTML4::Document.parse`](html4/document#method-c-parse) nokogiri module Nokogiri::CSS module Nokogiri::CSS ===================== Translate a [`CSS`](css) selector into an XPath 1.0 query xpath\_for(selector) β†’ String Show source xpath\_for(selector [, prefix:] [, visitor:] [, ns:]) β†’ String ``` # File lib/nokogiri/css.rb, line 42 def xpath_for(selector, options = {}) raise TypeError, "no implicit conversion of #{selector.inspect} to String" unless selector.respond_to?(:to_str) selector = selector.to_str raise Nokogiri::CSS::SyntaxError, "empty CSS selector" if selector.empty? prefix = options.fetch(:prefix, Nokogiri::XML::XPath::GLOBAL_SEARCH_PREFIX) visitor = options.fetch(:visitor) { Nokogiri::CSS::XPathVisitor.new } ns = options.fetch(:ns, {}) Parser.new(ns).xpath_for(selector, prefix, visitor) end ``` Translate a [`CSS`](css) selector to the equivalent XPath query. Parameters * `selector` (String) The [`CSS`](css) selector to be translated into XPath * `prefix:` (String) The XPath prefix for the query, see [`Nokogiri::XML::XPath`](xml/xpath) for some options. Default is `XML::XPath::GLOBAL_SEARCH_PREFIX`. * `visitor:` ([`Nokogiri::CSS::XPathVisitor`](css/xpathvisitor)) The visitor class to use to transform the AST into XPath. Default is `Nokogiri::CSS::XPathVisitor.new`. * `ns:` (Hash<String β‡’ String>) The namespaces that are referenced in the query, if any. This is a hash where the keys are the namespace prefix and the values are the namespace URIs. Default is an empty Hash. Returns (String) The equivalent XPath query for `selector` πŸ’‘ Note that translated queries are cached for performance concerns. nokogiri module Nokogiri::ClassResolver module Nokogiri::ClassResolver =============================== Some classes in [`Nokogiri`](../nokogiri) are namespaced as a group, for example Document, DocumentFragment, and Builder. It’s sometimes necessary to look up the related class, e.g.: ``` XML::Builder β†’ XML::Document HTML4::Builder β†’ HTML4::Document HTML5::Document β†’ HTML5::DocumentFragment ``` This module is included into those key classes who need to do this. VALID\_NAMESPACES [`related_class`](classresolver#method-i-related_class) restricts matching namespaces to those matching this set. related\_class(class\_name) β†’ Class Show source ``` # File lib/nokogiri/class_resolver.rb, line 46 def related_class(class_name) klass = nil inspecting = self.class while inspecting namespace_path = inspecting.name.split("::")[0..-2] inspecting = inspecting.superclass next unless VALID_NAMESPACES.include?(namespace_path.last) related_class_name = (namespace_path << class_name).join("::") klass = begin Object.const_get(related_class_name) rescue NameError nil end break if klass end klass end ``` Find a class constant within the Some examples: ``` Nokogiri::XML::Document.new.related_class("DocumentFragment") # => Nokogiri::XML::DocumentFragment Nokogiri::HTML4::Document.new.related_class("DocumentFragment") # => Nokogiri::HTML4::DocumentFragment ``` Note this will also work for subclasses that follow the same convention, e.g.: ``` Loofah::HTML::Document.new.related_class("DocumentFragment") # => Loofah::HTML::DocumentFragment ``` And even if it’s a subclass, this will iterate through the superclasses: ``` class ThisIsATopLevelClass < Nokogiri::HTML4::Builder ; end ThisIsATopLevelClass.new.related_class("Document") # => Nokogiri::HTML4::Document ``` nokogiri class Nokogiri::EncodingHandler class Nokogiri::EncodingHandler ================================ Parent: [Object](https://nokogiri.org/rdoc/Object.html) USEFUL\_ALIASES Popular encoding aliases not known by all iconv implementations that [`Nokogiri`](../nokogiri) should support. Nokogiri::EncodingHandler.[](name) Show source ``` static VALUE rb_xml_encoding_handler_s_get(VALUE klass, VALUE key) { xmlCharEncodingHandlerPtr handler; handler = xmlFindCharEncodingHandler(StringValueCStr(key)); if (handler) { return Data_Wrap_Struct(klass, NULL, _xml_encoding_handler_dealloc, handler); } return Qnil; } ``` Get the encoding handler for `name` Nokogiri::EncodingHandler.alias(real\_name, alias\_name) Show source ``` static VALUE rb_xml_encoding_handler_s_alias(VALUE klass, VALUE from, VALUE to) { xmlAddEncodingAlias(StringValueCStr(from), StringValueCStr(to)); return to; } ``` Alias encoding handler with name `real_name` to name `alias_name` Nokogiri::EncodingHandler.clear\_aliases! Show source ``` static VALUE rb_xml_encoding_handler_s_clear_aliases(VALUE klass) { xmlCleanupEncodingAliases(); return klass; } ``` Remove all encoding aliases. Nokogiri::EncodingHandler.delete(name) Show source ``` static VALUE rb_xml_encoding_handler_s_delete(VALUE klass, VALUE name) { if (xmlDelEncodingAlias(StringValueCStr(name))) { return Qnil; } return Qtrue; } ``` Delete the encoding alias named `name` install\_default\_aliases() Show source ``` # File lib/nokogiri/encoding_handler.rb, line 15 def install_default_aliases USEFUL_ALIASES.each do |alias_name, name| EncodingHandler.alias(name, alias_name) if EncodingHandler[alias_name].nil? end end ``` name Show source ``` static VALUE rb_xml_encoding_handler_name(VALUE self) { xmlCharEncodingHandlerPtr handler; Data_Get_Struct(self, xmlCharEncodingHandler, handler); return NOKOGIRI_STR_NEW2(handler->name); } ``` Get the name of this [`EncodingHandler`](encodinghandler) nokogiri module Nokogiri::XSLT module Nokogiri::XSLT ====================== See [`Nokogiri::XSLT::Stylesheet`](xslt/stylesheet) for creating and manipulating [`Stylesheet`](xslt/stylesheet) object. parse(string, modules = {}) Show source ``` # File lib/nokogiri/xslt.rb, line 25 def parse(string, modules = {}) modules.each do |url, klass| XSLT.register(url, klass) end doc = XML::Document.parse(string, nil, nil, XML::ParseOptions::DEFAULT_XSLT) if Nokogiri.jruby? Stylesheet.parse_stylesheet_doc(doc, string) else Stylesheet.parse_stylesheet_doc(doc) end end ``` Parse the stylesheet in `string`, register any `modules` quote\_params(params) β†’ Array Show source ``` # File lib/nokogiri/xslt.rb, line 49 def quote_params(params) params.flatten.each_slice(2).with_object([]) do |kv, quoted_params| key, value = kv.map(&:to_s) value = if /'/.match?(value) "concat('#{value.gsub(/'/, %q{', "'", '})}')" else "'#{value}'" end quoted_params << key quoted_params << value end end ``` Quote parameters in `params` for stylesheet safety. See [`Nokogiri::XSLT::Stylesheet.transform`](xslt/stylesheet#method-i-transform) for example usage. Parameters * `params` (Hash, Array) [`XSLT`](xslt) parameters (key->value, or tuples of [key, value]) Returns Array of string parameters, with quotes correctly escaped for use with [`XSLT::Stylesheet.transform`](xslt/stylesheet#method-i-transform) nokogiri module Nokogiri::XML module Nokogiri::XML ===================== XML\_C14N\_1\_0 Original C14N 1.0 spec canonicalization XML\_C14N\_1\_1 C14N 1.1 spec canonicalization XML\_C14N\_EXCLUSIVE\_1\_0 Exclusive C14N 1.0 spec canonicalization Reader(string\_or\_io, url = nil, encoding = nil, options = ParseOptions::STRICT) { |options| ... } Show source ``` # File lib/nokogiri/xml.rb, line 23 def Reader(string_or_io, url = nil, encoding = nil, options = ParseOptions::STRICT) options = Nokogiri::XML::ParseOptions.new(options) if Integer === options yield options if block_given? if string_or_io.respond_to?(:read) return Reader.from_io(string_or_io, url, encoding, options.to_i) end Reader.from_memory(string_or_io, url, encoding, options.to_i) end ``` Parse an [`XML`](xml) document using the [`Nokogiri::XML::Reader`](xml/reader) API. See [`Nokogiri::XML::Reader`](xml/reader) for mor information RelaxNG(string\_or\_io, options = ParseOptions::DEFAULT\_SCHEMA) Show source ``` # File lib/nokogiri/xml/relax_ng.rb, line 9 def RelaxNG(string_or_io, options = ParseOptions::DEFAULT_SCHEMA) RelaxNG.new(string_or_io, options) end ``` Create a new [`Nokogiri::XML::RelaxNG`](xml/relaxng) document from `string_or_io`. See [`Nokogiri::XML::RelaxNG`](xml/relaxng) for an example. Schema(string\_or\_io, options = ParseOptions::DEFAULT\_SCHEMA) Show source ``` # File lib/nokogiri/xml/schema.rb, line 9 def Schema(string_or_io, options = ParseOptions::DEFAULT_SCHEMA) Schema.new(string_or_io, options) end ``` Create a new [`Nokogiri::XML::Schema`](xml/schema) object using a `string_or_io` object. fragment(string, options = ParseOptions::DEFAULT\_XML, &block) Show source ``` # File lib/nokogiri/xml.rb, line 42 def fragment(string, options = ParseOptions::DEFAULT_XML, &block) XML::DocumentFragment.parse(string, options, &block) end ``` Parse a fragment from `string` in to a [`NodeSet`](xml/nodeset). parse(thing, url = nil, encoding = nil, options = ParseOptions::DEFAULT\_XML, &block) Show source ``` # File lib/nokogiri/xml.rb, line 36 def parse(thing, url = nil, encoding = nil, options = ParseOptions::DEFAULT_XML, &block) Document.parse(thing, url, encoding, options, &block) end ``` Parse [`XML`](xml). Convenience method for [`Nokogiri::XML::Document.parse`](xml/document#method-c-parse) nokogiri module Nokogiri::HTML5::Node module Nokogiri::HTML5::Node ============================= Since v1.12.0 πŸ’‘ [`HTML5`](../html5) functionality is not available when running JRuby. fragment(tags) Show source ``` # File lib/nokogiri/html5/node.rb, line 65 def fragment(tags) return super(tags) unless document.is_a?(HTML5::Document) DocumentFragment.new(document, tags, self) end ``` Calls superclass method inner\_html(options = {}) Show source ``` # File lib/nokogiri/html5/node.rb, line 28 def inner_html(options = {}) return super(options) unless document.is_a?(HTML5::Document) result = options[:preserve_newline] && prepend_newline? ? +"\n" : +"" result << children.map { |child| child.to_html(options) }.join result end ``` Calls superclass method write\_to(io, \*options) { |config| ... } Show source ``` # File lib/nokogiri/html5/node.rb, line 36 def write_to(io, *options) return super(io, *options) unless document.is_a?(HTML5::Document) options = options.first.is_a?(Hash) ? options.shift : {} encoding = options[:encoding] || options[0] if Nokogiri.jruby? save_options = options[:save_with] || options[1] indent_times = options[:indent] || 0 else save_options = options[:save_with] || options[1] || XML::Node::SaveOptions::FORMAT indent_times = options[:indent] || 2 end indent_string = (options[:indent_text] || " ") * indent_times config = XML::Node::SaveOptions.new(save_options.to_i) yield config if block_given? config_options = config.options if config_options & (XML::Node::SaveOptions::AS_XML | XML::Node::SaveOptions::AS_XHTML) != 0 # Use Nokogiri's serializing code. native_write_to(io, encoding, indent_string, config_options) else # Serialize including the current node. html = html_standard_serialize(options[:preserve_newline] || false) encoding ||= document.encoding || Encoding::UTF_8 io << html.encode(encoding, fallback: lambda { |c| "&#x#{c.ord.to_s(16)};" }) end end ``` Calls superclass method nokogiri class Nokogiri::HTML5::Document class Nokogiri::HTML5::Document ================================ Parent: [Nokogiri::HTML4::Document](../html4/document) Since v1.12.0 πŸ’‘ [`HTML5`](../html5) functionality is not available when running JRuby. quirks\_mode[R] Get the parser’s quirks mode value. See [`HTML5::QuirksMode`](quirksmode). This method returns β€˜nil` if the parser was not invoked (e.g., `Nokogiri::HTML5::Document.new`). Since v1.14.0 url[R] Get the url name for this document, as passed into [`Document.parse`](document#method-c-parse), [`Document.read_io`](document#method-c-read_io), or [`Document.read_memory`](document#method-c-read_memory) parse(input) Show source parse(input, url=nil, encoding=nil, \*\*options) parse(input, url=nil, encoding=nil) { |options| ... } ``` # File lib/nokogiri/html5/document.rb, line 80 def parse(string_or_io, url = nil, encoding = nil, **options, &block) yield options if block string_or_io = "" unless string_or_io if string_or_io.respond_to?(:encoding) && string_or_io.encoding != Encoding::ASCII_8BIT encoding ||= string_or_io.encoding.name end if string_or_io.respond_to?(:read) && string_or_io.respond_to?(:path) url ||= string_or_io.path end unless string_or_io.respond_to?(:read) || string_or_io.respond_to?(:to_str) raise ArgumentError, "not a string or IO object" end do_parse(string_or_io, url, encoding, options) end ``` Parse [`HTML5`](../html5) input. Parameters * `input` may be a String, or any object that responds to *read* and *close* such as an IO, or StringIO. * `url` (optional) is a String indicating the canonical URI where this document is located. * `encoding` (optional) is the encoding that should be used when processing the document. * `options` (optional) is a configuration Hash (or keyword arguments) to set options during parsing. The three currently supported options are `:max_errors`, `:max_tree_depth` and `:max_attributes`, described at [`Nokogiri::HTML5`](../html5). ⚠ Note that these options are different than those made available by [`Nokogiri::XML::Document`](../xml/document) and [`Nokogiri::HTML4::Document`](../html4/document). * `block` (optional) is passed a configuration Hash on which parse options may be set. See [`Nokogiri::HTML5`](../html5) for more information and usage. Returns [`Nokogiri::HTML5::Document`](document) read\_io(io, url = nil, encoding = nil, \*\*options) Show source ``` # File lib/nokogiri/html5/document.rb, line 101 def read_io(io, url = nil, encoding = nil, **options) raise ArgumentError, "io object doesn't respond to :read" unless io.respond_to?(:read) do_parse(io, url, encoding, options) end ``` Create a new document from an IO object. πŸ’‘ Most users should prefer [`Document.parse`](document#method-c-parse) to this method. read\_memory(string, url = nil, encoding = nil, \*\*options) Show source ``` # File lib/nokogiri/html5/document.rb, line 110 def read_memory(string, url = nil, encoding = nil, **options) raise ArgumentError, "string object doesn't respond to :to_str" unless string.respond_to?(:to_str) do_parse(string, url, encoding, options) end ``` Create a new document from a String. πŸ’‘ Most users should prefer [`Document.parse`](document#method-c-parse) to this method. fragment() β†’ Nokogiri::HTML5::DocumentFragment Show source fragment(markup) β†’ Nokogiri::HTML5::DocumentFragment ``` # File lib/nokogiri/html5/document.rb, line 147 def fragment(markup = nil) DocumentFragment.new(self, markup) end ``` Parse a [`HTML5`](../html5) document fragment from `markup`, returning a [`Nokogiri::HTML5::DocumentFragment`](documentfragment). Properties * `markup` (String) The [`HTML5`](../html5) markup fragment to be parsed Returns [`Nokogiri::HTML5::DocumentFragment`](documentfragment). This object’s children will be empty if β€˜markup` is not passed, is empty, or is `nil`. xpath\_doctype() β†’ Nokogiri::CSS::XPathVisitor::DoctypeConfig Show source ``` # File lib/nokogiri/html5/document.rb, line 163 def xpath_doctype Nokogiri::CSS::XPathVisitor::DoctypeConfig::HTML5 end ``` Returns The document type which determines CSS-to-XPath translation. See [`CSS::XPathVisitor`](../css/xpathvisitor) for more information. nokogiri module Nokogiri::HTML5::QuirksMode module Nokogiri::HTML5::QuirksMode =================================== Enum for the [`HTML5`](../html5) parser quirks mode values. Values returned by [`HTML5::Document#quirks_mode`](document#attribute-i-quirks_mode) See [dom.spec.whatwg.org/#concept-document-quirks](https://dom.spec.whatwg.org/#concept-document-quirks) for more information on [`HTML5`](../html5) quirks mode. Since v1.14.0 LIMITED\_QUIRKS NO\_QUIRKS QUIRKS nokogiri class Nokogiri::HTML5::DocumentFragment class Nokogiri::HTML5::DocumentFragment ======================================== Parent: [Nokogiri::HTML4::DocumentFragment](../html4/documentfragment) Since v1.12.0 πŸ’‘ [`HTML5`](../html5) functionality is not available when running JRuby. document[RW] errors[RW] quirks\_mode[R] Get the parser’s quirks mode value. See [`HTML5::QuirksMode`](quirksmode). This method returns β€˜nil` if the parser was not invoked (e.g., `Nokogiri::HTML5::DocumentFragment.new(doc)`). Since v1.14.0 new(doc, tags = nil, ctx = nil, options = {}) Show source ``` # File lib/nokogiri/html5/document_fragment.rb, line 39 def initialize(doc, tags = nil, ctx = nil, options = {}) self.document = doc self.errors = [] return self unless tags max_attributes = options[:max_attributes] || Nokogiri::Gumbo::DEFAULT_MAX_ATTRIBUTES max_errors = options[:max_errors] || Nokogiri::Gumbo::DEFAULT_MAX_ERRORS max_depth = options[:max_tree_depth] || Nokogiri::Gumbo::DEFAULT_MAX_TREE_DEPTH tags = Nokogiri::HTML5.read_and_encode(tags, nil) Nokogiri::Gumbo.fragment(self, tags, ctx, max_attributes, max_errors, max_depth) end ``` Create a document fragment. parse(tags, encoding = nil, options = {}) Show source ``` # File lib/nokogiri/html5/document_fragment.rb, line 58 def self.parse(tags, encoding = nil, options = {}) doc = HTML5::Document.new tags = HTML5.read_and_encode(tags, encoding) doc.encoding = "UTF-8" new(doc, tags, nil, options) end ``` Parse a document fragment from `tags`, returning a Nodeset. nokogiri class Nokogiri::HTML4::Builder class Nokogiri::HTML4::Builder =============================== Parent: [Nokogiri::XML::Builder](../xml/builder) [`Nokogiri`](../../nokogiri) [`HTML`](../html4) builder is used for building [`HTML`](../html4) documents. It is very similar to the [`Nokogiri::XML::Builder`](../xml/builder). In fact, you should go read the documentation for [`Nokogiri::XML::Builder`](../xml/builder) before reading this documentation. Synopsis: --------- Create an [`HTML`](../html4) document with a body that has an onload attribute, and a span tag with a class of β€œbold” that has content of β€œHello world”. ``` builder = Nokogiri::HTML4::Builder.new do |doc| doc.html { doc.body(:onload => 'some_func();') { doc.span.bold { doc.text "Hello world" } } } end puts builder.to_html ``` The [`HTML`](../html4) builder inherits from the [`XML`](../xml) builder, so make sure to read the [`Nokogiri::XML::Builder`](../xml/builder) documentation. to\_html() Show source ``` # File lib/nokogiri/html4/builder.rb, line 32 def to_html @doc.to_html end ``` Convert the builder to [`HTML`](../html4)
programming_docs
nokogiri class Nokogiri::HTML4::EntityDescription class Nokogiri::HTML4::EntityDescription ========================================= Parent: Struct.new(:value, :name, :description); nokogiri class Nokogiri::HTML4::EntityLookup class Nokogiri::HTML4::EntityLookup ==================================== Parent: [Object](https://nokogiri.org/rdoc/Object.html) [](name) Show source ``` # File lib/nokogiri/html4/entity_lookup.rb, line 10 def [](name) (val = get(name)) && val.value end ``` Look up entity with `name` nokogiri class Nokogiri::HTML4::ElementDescription class Nokogiri::HTML4::ElementDescription ========================================== Parent: [Object](https://nokogiri.org/rdoc/Object.html) ACTION\_ATTR ALIGN\_ATTR ALT\_ATTR APPLET\_ATTRS AREA\_ATTRS ATTRS A\_ATTRS BASEFONT\_ATTRS BGCOLOR\_ATTR BLOCK BLOCKLI\_ELT BODY\_ATTRS BODY\_CONTENTS BODY\_DEPR BUTTON\_ATTRS CELLHALIGN CELLVALIGN CLEAR\_ATTRS COL\_ATTRS COL\_ELT COMPACT\_ATTR COMPACT\_ATTRS CONTENT\_ATTR COREATTRS CORE\_ATTRS CORE\_I18N\_ATTRS DIR\_ATTR DL\_CONTENTS DefaultDescriptions This is filled in down below. Desc Methods are defined protected by method\_defined? because at this point the C-library or Java library is already loaded, and we don’t want to clobber any methods that have been defined there. EDIT\_ATTRS EMBED\_ATTRS EMPTY EVENTS FIELDSET\_CONTENTS FLOW FLOW\_PARAM FONTSTYLE Attributes defined and categorized FONT\_ATTRS FORMCTRL FORM\_ATTRS FORM\_CONTENTS FRAMESET\_ATTRS FRAMESET\_CONTENTS FRAME\_ATTRS HEADING HEAD\_ATTRS HEAD\_CONTENTS HREF\_ATTRS HR\_DEPR HTML\_ATTRS HTML\_CDATA HTML\_CONTENT HTML\_FLOW HTML\_INLINE HTML\_PCDATA I18N I18N\_ATTRS IFRAME\_ATTRS IMG\_ATTRS INLINE INLINE\_P INPUT\_ATTRS LABEL\_ATTR LABEL\_ATTRS LANGUAGE\_ATTR LEGEND\_ATTRS LINK\_ATTRS LIST LI\_ELT MAP\_CONTENTS META\_ATTRS MODIFIER NAME\_ATTR NOFRAMES\_CONTENT OBJECT\_ATTRS OBJECT\_CONTENTS OBJECT\_DEPR OL\_ATTRS OPTGROUP\_ATTRS OPTION\_ATTRS OPTION\_ELT PARAM\_ATTRS PCDATA PHRASE PRE\_CONTENT PROMPT\_ATTRS QUOTE\_ATTRS ROWS\_COLS\_ATTR SCRIPT\_ATTRS SELECT\_ATTRS SELECT\_CONTENT SPECIAL SRC\_ALT\_ATTRS STYLE\_ATTRS TABLE\_ATTRS TABLE\_CONTENTS TABLE\_DEPR TALIGN\_ATTRS TARGET\_ATTR TEXTAREA\_ATTRS TH\_TD\_ATTR TH\_TD\_DEPR TR\_CONTENTS TR\_ELT TYPE\_ATTR UL\_DEPR VERSION\_ATTR WIDTH\_ATTR block?() Show source ``` # File lib/nokogiri/html4/element_description.rb, line 8 def block? !inline? end ``` Is this element a block element? default\_sub\_element() Show source ``` # File lib/nokogiri/html4/element_description_defaults.rb, line 57 def default_sub_element default_desc&.defaultsubelt end ``` deprecated?() Show source ``` # File lib/nokogiri/html4/element_description_defaults.rb, line 45 def deprecated? default_desc&.depr end ``` deprecated\_attributes() Show source ``` # File lib/nokogiri/html4/element_description_defaults.rb, line 70 def deprecated_attributes d = default_desc d ? d.attrs_depr : [] end ``` description() Show source ``` # File lib/nokogiri/html4/element_description_defaults.rb, line 51 def description default_desc&.desc end ``` implied\_end\_tag?() Show source ``` # File lib/nokogiri/html4/element_description_defaults.rb, line 33 def implied_end_tag? default_desc&.endTag end ``` implied\_start\_tag?() Show source ``` # File lib/nokogiri/html4/element_description_defaults.rb, line 27 def implied_start_tag? default_desc&.startTag end ``` inspect() Show source ``` # File lib/nokogiri/html4/element_description.rb, line 20 def inspect "#<#{self.class.name}: #{name} #{description}>" end ``` Inspection information optional\_attributes() Show source ``` # File lib/nokogiri/html4/element_description_defaults.rb, line 63 def optional_attributes d = default_desc d ? d.attrs_opt : [] end ``` required\_attributes() Show source ``` # File lib/nokogiri/html4/element_description_defaults.rb, line 77 def required_attributes d = default_desc d ? d.attrs_req : [] end ``` save\_end\_tag?() Show source ``` # File lib/nokogiri/html4/element_description_defaults.rb, line 39 def save_end_tag? default_desc&.saveEndTag end ``` to\_s() Show source ``` # File lib/nokogiri/html4/element_description.rb, line 14 def to_s "#{name}: #{description}" end ``` Convert this description to a string nokogiri class Nokogiri::HTML4::Document class Nokogiri::HTML4::Document ================================ Parent: [Nokogiri::XML::Document](../xml/document) parse(string\_or\_io, url = nil, encoding = nil, options = XML::ParseOptions::DEFAULT\_HTML) { |options| ... } Show source ``` # File lib/nokogiri/html4/document.rb, line 172 def parse(string_or_io, url = nil, encoding = nil, options = XML::ParseOptions::DEFAULT_HTML) options = Nokogiri::XML::ParseOptions.new(options) if Integer === options yield options if block_given? url ||= string_or_io.respond_to?(:path) ? string_or_io.path : nil if string_or_io.respond_to?(:encoding) unless string_or_io.encoding == Encoding::ASCII_8BIT encoding ||= string_or_io.encoding.name end end if string_or_io.respond_to?(:read) if string_or_io.is_a?(Pathname) # resolve the Pathname to the file and open it as an IO object, see #2110 string_or_io = string_or_io.expand_path.open url ||= string_or_io.path end unless encoding string_or_io = EncodingReader.new(string_or_io) begin return read_io(string_or_io, url, encoding, options.to_i) rescue EncodingReader::EncodingFound => e encoding = e.found_encoding end end return read_io(string_or_io, url, encoding, options.to_i) end # read_memory pukes on empty docs if string_or_io.nil? || string_or_io.empty? return encoding ? new.tap { |i| i.encoding = encoding } : new end encoding ||= EncodingReader.detect_encoding(string_or_io) read_memory(string_or_io, url, encoding, options.to_i) end ``` Parse [`HTML`](../html4). `string_or_io` may be a String, or any object that responds to *read* and *close* such as an IO, or StringIO. `url` is resource where this document is located. `encoding` is the encoding that should be used when processing the document. `options` is a number that sets options in the parser, such as Nokogiri::XML::ParseOptions::RECOVER. See the constants in [`Nokogiri::XML::ParseOptions`](../xml/parseoptions). fragment(tags = nil) Show source ``` # File lib/nokogiri/html4/document.rb, line 149 def fragment(tags = nil) DocumentFragment.new(self, tags, root) end ``` Create a [`Nokogiri::XML::DocumentFragment`](../xml/documentfragment) from `tags` meta\_encoding() Show source ``` # File lib/nokogiri/html4/document.rb, line 12 def meta_encoding if (meta = at_xpath("//meta[@charset]")) meta[:charset] elsif (meta = meta_content_type) meta["content"][/charset\s*=\s*([\w-]+)/i, 1] end end ``` Get the meta tag encoding for this document. If there is no meta tag, then nil is returned. meta\_encoding=(encoding) Show source ``` # File lib/nokogiri/html4/document.rb, line 36 def meta_encoding=(encoding) if (meta = meta_content_type) meta["content"] = format("text/html; charset=%s", encoding) encoding elsif (meta = at_xpath("//meta[@charset]")) meta["charset"] = encoding else meta = XML::Node.new("meta", self) if (dtd = internal_subset) && dtd.html5_dtd? meta["charset"] = encoding else meta["http-equiv"] = "Content-Type" meta["content"] = format("text/html; charset=%s", encoding) end if (head = at_xpath("//head")) head.prepend_child(meta) else set_metadata_element(meta) end encoding end end ``` Set the meta tag encoding for this document. If an meta encoding tag is already present, its content is replaced with the given text. Otherwise, this method tries to create one at an appropriate place supplying head and/or html elements as necessary, which is inside a head element if any, and before any text node or content element (typically <body>) if any. The result when trying to set an encoding that is different from the document encoding is undefined. Beware in CRuby, that libxml2 automatically inserts a meta tag into a head element. serialize(options = {}) Show source ``` # File lib/nokogiri/html4/document.rb, line 142 def serialize(options = {}) options[:save_with] ||= XML::Node::SaveOptions::DEFAULT_HTML super end ``` Serialize Node using `options`. Save options can also be set using a block. See also [`Nokogiri::XML::Node::SaveOptions`](../xml/node/saveoptions) and Node. These two statements are equivalent: ``` node.serialize(:encoding => 'UTF-8', :save_with => FORMAT | AS_XML) ``` or ``` node.serialize(:encoding => 'UTF-8') do |config| config.format.as_xml end ``` Calls superclass method title() Show source ``` # File lib/nokogiri/html4/document.rb, line 70 def title (title = at_xpath("//title")) && title.inner_text end ``` Get the title string of this document. Return nil if there is no title tag. title=(text) Show source ``` # File lib/nokogiri/html4/document.rb, line 85 def title=(text) tnode = XML::Text.new(text, self) if (title = at_xpath("//title")) title.children = tnode return text end title = XML::Node.new("title", self) << tnode if (head = at_xpath("//head")) head << title elsif (meta = (at_xpath("//meta[@charset]") || meta_content_type)) # better put after charset declaration meta.add_next_sibling(title) else set_metadata_element(title) end end ``` Set the title string of this document. If a title element is already present, its content is replaced with the given text. Otherwise, this method tries to create one at an appropriate place supplying head and/or html elements as necessary, which is inside a head element if any, right after a meta encoding/charset tag if any, and before any text node or content element (typically <body>) if any. xpath\_doctype() β†’ Nokogiri::CSS::XPathVisitor::DoctypeConfig Show source ``` # File lib/nokogiri/html4/document.rb, line 159 def xpath_doctype Nokogiri::CSS::XPathVisitor::DoctypeConfig::HTML4 end ``` Returns The document type which determines CSS-to-XPath translation. See XPathVisitor for more information. nokogiri module Nokogiri::HTML4::SAX module Nokogiri::HTML4::SAX ============================ [`Nokogiri`](../../nokogiri) lets you write a [`SAX`](sax) parser to process [`HTML`](../html4) but get [`HTML`](../html4) correction features. See [`Nokogiri::HTML4::SAX::Parser`](sax/parser) for a basic example of using a [`SAX`](sax) parser with [`HTML`](../html4). For more information on [`SAX`](sax) parsers, see [`Nokogiri::XML::SAX`](../xml/sax) nokogiri class Nokogiri::HTML4::DocumentFragment class Nokogiri::HTML4::DocumentFragment ======================================== Parent: [Nokogiri::XML::DocumentFragment](../xml/documentfragment) new(document, tags = nil, ctx = nil, options = XML::ParseOptions::DEFAULT\_HTML) { |options| ... } Show source ``` # File lib/nokogiri/html4/document_fragment.rb, line 27 def initialize(document, tags = nil, ctx = nil, options = XML::ParseOptions::DEFAULT_HTML) return self unless tags options = Nokogiri::XML::ParseOptions.new(options) if Integer === options yield options if block_given? if ctx preexisting_errors = document.errors.dup node_set = ctx.parse("<div>#{tags}</div>", options) node_set.first.children.each { |child| child.parent = self } unless node_set.empty? self.errors = document.errors - preexisting_errors else # This is a horrible hack, but I don't care path = if /^\s*?<body/i.match?(tags) "/html/body" else "/html/body/node()" end temp_doc = HTML4::Document.parse("<html><body>#{tags}", nil, document.encoding, options) temp_doc.xpath(path).each { |child| child.parent = self } self.errors = temp_doc.errors end children end ``` parse(tags, encoding = nil, options = XML::ParseOptions::DEFAULT\_HTML, &block) Show source ``` # File lib/nokogiri/html4/document_fragment.rb, line 8 def self.parse(tags, encoding = nil, options = XML::ParseOptions::DEFAULT_HTML, &block) doc = HTML4::Document.new encoding ||= if tags.respond_to?(:encoding) encoding = tags.encoding if encoding == ::Encoding::ASCII_8BIT "UTF-8" else encoding.name end else "UTF-8" end doc.encoding = encoding new(doc, tags, nil, options, &block) end ``` Create a [`Nokogiri::XML::DocumentFragment`](../xml/documentfragment) from `tags`, using `encoding` nokogiri class Nokogiri::HTML4::SAX::ParserContext class Nokogiri::HTML4::SAX::ParserContext ========================================== Parent: [Nokogiri::XML::SAX::ParserContext](../../xml/sax/parsercontext) πŸ’‘ This class is an alias for [`Nokogiri::HTML4::SAX::ParserContext`](parsercontext) as of v1.12.0. Context for [`HTML`](../../html4) [`SAX`](../sax) parsers. This class is usually not instantiated by the user. Instead, you should be looking at [`Nokogiri::HTML4::SAX::Parser`](parser) new(thing, encoding = "UTF-8") Show source ``` # File lib/nokogiri/html4/sax/parser_context.rb, line 10 def self.new(thing, encoding = "UTF-8") if [:read, :close].all? { |x| thing.respond_to?(x) } super else memory(thing, encoding) end end ``` Calls superclass method [`Nokogiri::XML::SAX::ParserContext::new`](../../xml/sax/parsercontext#method-c-new) nokogiri class Nokogiri::HTML4::SAX::Parser class Nokogiri::HTML4::SAX::Parser =================================== Parent: [Nokogiri::XML::SAX::Parser](../../xml/sax/parser) πŸ’‘ This class is an alias for [`Nokogiri::HTML4::SAX::Parser`](parser) as of v1.12.0. This class lets you perform [`SAX`](../sax) style parsing on [`HTML`](../../html4) with [`HTML`](../../html4) error correction. Here is a basic usage example: ``` class MyDoc < Nokogiri::XML::SAX::Document def start_element name, attributes = [] puts "found a #{name}" end end parser = Nokogiri::HTML4::SAX::Parser.new(MyDoc.new) parser.parse(File.read(ARGV[0], mode: 'rb')) ``` For more information on [`SAX`](../sax) parsers, see [`Nokogiri::XML::SAX`](../../xml/sax) parse\_file(filename, encoding = "UTF-8") { |ctx| ... } Show source ``` # File lib/nokogiri/html4/sax/parser.rb, line 51 def parse_file(filename, encoding = "UTF-8") raise ArgumentError unless filename raise Errno::ENOENT unless File.exist?(filename) raise Errno::EISDIR if File.directory?(filename) ctx = ParserContext.file(filename, encoding) yield ctx if block_given? ctx.parse_with(self) end ``` Parse a file with `filename` parse\_io(io, encoding = "UTF-8") { |ctx| ... } Show source ``` # File lib/nokogiri/html4/sax/parser.rb, line 41 def parse_io(io, encoding = "UTF-8") check_encoding(encoding) @encoding = encoding ctx = ParserContext.io(io, ENCODINGS[encoding]) yield ctx if block_given? ctx.parse_with(self) end ``` Parse given `io` parse\_memory(data, encoding = "UTF-8") { |ctx| ... } Show source ``` # File lib/nokogiri/html4/sax/parser.rb, line 30 def parse_memory(data, encoding = "UTF-8") raise TypeError unless String === data return if data.empty? ctx = ParserContext.memory(data, encoding) yield ctx if block_given? ctx.parse_with(self) end ``` Parse html stored in `data` using `encoding` nokogiri class Nokogiri::HTML4::SAX::PushParser class Nokogiri::HTML4::SAX::PushParser ======================================= Parent: [Object](https://nokogiri.org/rdoc/Object.html) πŸ’‘ This class is an alias for [`Nokogiri::HTML4::SAX::PushParser`](pushparser) as of v1.12.0. document[RW] The Nokogiri::HTML4::SAX::Document on which the [`PushParser`](pushparser) will be operating new(doc = HTML4::SAX::Document.new, file\_name = nil, encoding = "UTF-8") Show source ``` # File lib/nokogiri/html4/sax/push_parser.rb, line 11 def initialize(doc = HTML4::SAX::Document.new, file_name = nil, encoding = "UTF-8") @document = doc @encoding = encoding @sax_parser = HTML4::SAX::Parser.new(doc, @encoding) ## Create our push parser context initialize_native(@sax_parser, file_name, encoding) end ``` <<(chunk, last\_chunk = false) Alias for: [write](pushparser#method-i-write) finish() Show source ``` # File lib/nokogiri/html4/sax/push_parser.rb, line 31 def finish write("", true) end ``` Finish the parsing. This method is only necessary for Nokogiri::HTML4::SAX::Document#end\_document to be called. write(chunk, last\_chunk = false) Show source ``` # File lib/nokogiri/html4/sax/push_parser.rb, line 23 def write(chunk, last_chunk = false) native_write(chunk, last_chunk) end ``` Write a `chunk` of [`HTML`](../../html4) to the [`PushParser`](pushparser). Any callback methods that can be called will be called immediately. Also aliased as: [<<](pushparser#method-i-3C-3C) nokogiri class Nokogiri::CSS::XPathVisitor class Nokogiri::CSS::XPathVisitor ================================== Parent: [Object](https://nokogiri.org/rdoc/Object.html) When translating [`CSS`](../css) selectors to XPath queries with [`Nokogiri::CSS.xpath_for`](../css#method-c-xpath_for), the [`XPathVisitor`](xpathvisitor) class allows for changing some of the behaviors related to builtin xpath functions and quirks of [`HTML5`](../html5). new() β†’ XPathVisitor Show source new(builtins:, doctype:) β†’ XPathVisitor ``` # File lib/nokogiri/css/xpath_visitor.rb, line 57 def initialize(builtins: BuiltinsConfig::NEVER, doctype: DoctypeConfig::XML) unless BuiltinsConfig::VALUES.include?(builtins) raise(ArgumentError, "Invalid values #{builtins.inspect} for builtins: keyword parameter") end unless DoctypeConfig::VALUES.include?(doctype) raise(ArgumentError, "Invalid values #{doctype.inspect} for doctype: keyword parameter") end @builtins = builtins @doctype = doctype end ``` Parameters * `builtins:` ([`BuiltinsConfig`](xpathvisitor/builtinsconfig)) Determine when to use Nokogiri’s built-in xpath functions for performance improvements. * `doctype:` ([`DoctypeConfig`](xpathvisitor/doctypeconfig)) Make document-type-specific accommodations for [`CSS`](../css) queries. Returns [`XPathVisitor`](xpathvisitor) config() β†’ Hash Show source ``` # File lib/nokogiri/css/xpath_visitor.rb, line 74 def config { builtins: @builtins, doctype: @doctype } end ``` Returns a Hash representing the configuration of the [`XPathVisitor`](xpathvisitor), suitable for use as part of the [`CSS`](../css) cache key. nokogiri class Nokogiri::CSS::SyntaxError class Nokogiri::CSS::SyntaxError ================================= Parent: [Nokogiri::SyntaxError](../syntaxerror) nokogiri module Nokogiri::CSS::XPathVisitor::BuiltinsConfig module Nokogiri::CSS::XPathVisitor::BuiltinsConfig =================================================== Enum to direct [`XPathVisitor`](../xpathvisitor) when to use [`Nokogiri`](../../../nokogiri) builtin XPath functions. ALWAYS Always use [`Nokogiri`](../../../nokogiri) builtin functions whenever possible. This is probably only useful for testing. NEVER Never use [`Nokogiri`](../../../nokogiri) builtin functions, always generate vanilla XPath 1.0 queries. This is the default when calling [`Nokogiri::CSS.xpath_for`](../../css#method-c-xpath_for) directly. OPTIMAL Only use [`Nokogiri`](../../../nokogiri) builtin functions when they will be faster than vanilla XPath. This is the behavior chosen when searching for [`CSS`](../../css) selectors on a [`Nokogiri`](../../../nokogiri) document, fragment, or node.
programming_docs
nokogiri module Nokogiri::CSS::XPathVisitor::DoctypeConfig module Nokogiri::CSS::XPathVisitor::DoctypeConfig ================================================== Enum to direct [`XPathVisitor`](../xpathvisitor) when to tweak the XPath query to suit the nature of the document being searched. Note that searches for [`CSS`](../../css) selectors from a [`Nokogiri`](../../../nokogiri) document, fragment, or node will choose the correct option automatically. HTML4 The document being searched is an [`HTML4`](../../html4) document. HTML5 The document being searched is an [`HTML5`](../../html5) document. XML The document being searched is an [`XML`](../../xml) document. This is the default. nokogiri module Nokogiri::Decorators::Slop module Nokogiri::Decorators::Slop ================================== The [`Slop`](slop) decorator implements method missing such that a methods may be used instead of XPath or [`CSS`](../css). See [`Nokogiri.Slop`](../../nokogiri#method-c-Slop) XPATH\_PREFIX The default XPath search context for [`Slop`](slop) method\_missing(name, \*args, &block) Show source ``` # File lib/nokogiri/decorators/slop.rb, line 14 def method_missing(name, *args, &block) if args.empty? list = xpath("#{XPATH_PREFIX}#{name.to_s.sub(/^_/, "")}") elsif args.first.is_a?(Hash) hash = args.first if hash[:css] list = css("#{name}#{hash[:css]}") elsif hash[:xpath] conds = Array(hash[:xpath]).join(" and ") list = xpath("#{XPATH_PREFIX}#{name}[#{conds}]") end else CSS::Parser.without_cache do list = xpath( *CSS.xpath_for("#{name}#{args.first}", prefix: XPATH_PREFIX), ) end end super if list.empty? list.length == 1 ? list.first : list end ``` look for node with `name`. See [`Nokogiri.Slop`](../../nokogiri#method-c-Slop) Calls superclass method respond\_to\_missing?(name, include\_private = false) Show source ``` # File lib/nokogiri/decorators/slop.rb, line 37 def respond_to_missing?(name, include_private = false) list = xpath("#{XPATH_PREFIX}#{name.to_s.sub(/^_/, "")}") !list.empty? end ``` nokogiri class Nokogiri::HTML::Builder class Nokogiri::HTML::Builder ============================== Parent: [Nokogiri::XML::Builder](../xml/builder) πŸ’‘ This class is an alias for [`Nokogiri::HTML4::Builder`](../html4/builder) as of v1.12.0. nokogiri class Nokogiri::HTML::Document class Nokogiri::HTML::Document =============================== Parent: [Nokogiri::XML::Document](../xml/document) πŸ’‘ This class is an alias for [`Nokogiri::HTML4::Document`](../html4/document) as of v1.12.0. nokogiri class Nokogiri::HTML::DocumentFragment class Nokogiri::HTML::DocumentFragment ======================================= Parent: [Nokogiri::XML::DocumentFragment](../xml/documentfragment) πŸ’‘ This class is an alias for [`Nokogiri::HTML4::DocumentFragment`](../html4/documentfragment) as of v1.12.0. nokogiri class Nokogiri::XML::Text class Nokogiri::XML::Text ========================== Parent: cNokogiriXmlCharacterData Wraps [`Text`](text) nodes. new(content, document) Show source ``` static VALUE new (int argc, VALUE *argv, VALUE klass) { xmlDocPtr doc; xmlNodePtr node; VALUE string; VALUE document; VALUE rest; VALUE rb_node; rb_scan_args(argc, argv, "2*", &string, &document, &rest); Noko_Node_Get_Struct(document, xmlDoc, doc); node = xmlNewText((xmlChar *)StringValueCStr(string)); node->doc = doc->doc; noko_xml_document_pin_node(node); rb_node = noko_xml_node_wrap(klass, node) ; rb_obj_call_init(rb_node, argc, argv); if (rb_block_given_p()) { rb_yield(rb_node); } return rb_node; } ``` Create a new [`Text`](text) element on the `document` with `content` content=(string) Show source ``` # File lib/nokogiri/xml/text.rb, line 6 def content=(string) self.native_content = string.to_s end ``` nokogiri class Nokogiri::XML::Node class Nokogiri::XML::Node ========================== Parent: [Object](https://nokogiri.org/rdoc/Object.html) Included modules: [Nokogiri::XML::PP::Node](pp/node), [Nokogiri::XML::Searchable](searchable), [Nokogiri::ClassResolver](../classresolver) [`Nokogiri::XML::Node`](node) is the primary API you’ll use to interact with your [`Document`](document). Attributes ---------- A [`Nokogiri::XML::Node`](node) may be treated similarly to a hash with regard to attributes. For example: ``` node = Nokogiri::XML::DocumentFragment.parse("<a href='#foo' id='link'>link</a>").at_css("a") node.to_html # => "<a href=\"#foo\" id=\"link\">link</a>" node['href'] # => "#foo" node.keys # => ["href", "id"] node.values # => ["#foo", "link"] node['class'] = 'green' # => "green" node.to_html # => "<a href=\"#foo\" id=\"link\" class=\"green\">link</a>" ``` See the method group entitled [Working With Node Attributes at `Node`](node#class-Nokogiri::XML::Node-label-Working+With+Node+Attributes) for the full set of methods. Navigation ---------- [`Nokogiri::XML::Node`](node) also has methods that let you move around your tree: [`#parent`](node#method-i-parent), [`#children`](node#method-i-children), [`#next`](node#method-i-next), [`#previous`](node#method-i-previous) Navigate up, down, or through siblings. See the method group entitled [Traversing Document Structure at `Node`](node#class-Nokogiri::XML::Node-label-Traversing+Document+Structure) for the full set of methods. Serialization ------------- When printing or otherwise emitting a document or a node (and its subtree), there are a few methods you might want to use: [`#content`](node#method-i-content), [`#text`](node#method-i-text), [`#inner_text`](node#method-i-inner_text), [`#to_str`](node#method-i-to_str) These methods will all \*\*emit plaintext\*\*, meaning that entities will be replaced (e.g., +&lt;+ will be replaced with +<+), meaning that any sanitizing will likely be un-done in the output. [`#to_s`](node#method-i-to_s), [`#to_xml`](node#method-i-to_xml), [`#to_html`](node#method-i-to_html), [`#inner_html`](node#method-i-inner_html) These methods will all \*\*emit properly-escaped markup\*\*, meaning that it’s suitable for consumption by browsers, parsers, etc. See the method group entitled [Serialization and Generating Output at `Node`](node#class-Nokogiri::XML::Node-label-Serialization+and+Generating+Output) for the full set of methods. Searching --------- You may search this node’s subtree using methods like [`#xpath`](node#method-i-xpath) and [`#css`](node#method-i-css). See the method group entitled [Searching via XPath or CSS Queries at `Node`](node#class-Nokogiri::XML::Node-label-Searching+via+XPath+or+CSS+Queries) for the full set of methods. ATTRIBUTE\_DECL Attribute declaration type ATTRIBUTE\_NODE Attribute node type CDATA\_SECTION\_NODE [`CDATA`](cdata) node type, see [`Nokogiri::XML::Node#cdata?`](node#method-i-cdata-3F) COMMENT\_NODE [`Comment`](comment) node type, see [`Nokogiri::XML::Node#comment?`](node#method-i-comment-3F) DOCB\_DOCUMENT\_NODE DOCB document node type DOCUMENT\_FRAG\_NODE [`Document`](document) fragment node type DOCUMENT\_NODE [`Document`](document) node type, see [`Nokogiri::XML::Node#xml?`](node#method-i-xml-3F) DOCUMENT\_TYPE\_NODE [`Document`](document) type node type DTD\_NODE [`DTD`](dtd) node type ELEMENT\_DECL [`Element`](element) declaration type ELEMENT\_NODE [`Element`](element) node type, see [`Nokogiri::XML::Node#element?`](node#method-i-element-3F) ENTITY\_DECL Entity declaration type ENTITY\_NODE Entity node type ENTITY\_REF\_NODE Entity reference node type HTML\_DOCUMENT\_NODE [`HTML`](../html4) document node type, see [`Nokogiri::XML::Node#html?`](node#method-i-html-3F) IMPLIED\_XPATH\_CONTEXTS LOOKS\_LIKE\_XPATH Included from [Nokogiri::XML::Searchable](searchable) Regular expression used by [`Searchable#search`](searchable#method-i-search) to determine if a query string is [`CSS`](../css) or [`XPath`](xpath) NAMESPACE\_DECL [`Namespace`](namespace) declaration type NOTATION\_NODE [`Notation`](notation) node type PI\_NODE PI node type TEXT\_NODE [`Text`](text) node type, see [`Nokogiri::XML::Node#text?`](node#method-i-text-3F) VALID\_NAMESPACES Included from [Nokogiri::ClassResolver](../classresolver) [`related_class`](node#method-i-related_class) restricts matching namespaces to those matching this set. XINCLUDE\_END XInclude end type XINCLUDE\_START XInclude start type new(name, document) β†’ Nokogiri::XML::Node Show source new(name, document) { |node| ... } β†’ Nokogiri::XML::Node ``` # File lib/nokogiri/xml/node.rb, line 126 def initialize(name, document) # This is intentionally empty, and sets the method signature for subclasses. end ``` Create a new node with `name` that belongs to `document`. If you intend to add a node to a document tree, it’s likely that you will prefer one of the [`Nokogiri::XML::Node`](node) methods like [`#add_child`](node#method-i-add_child), [`#add_next_sibling`](node#method-i-add_next_sibling), [`#replace`](node#method-i-replace), etc. which will both create an element (or subtree) and place it in the document tree. Another alternative, if you are concerned about performance, is Nokogiri::XML::Document#create\_element which accepts additional arguments for contents or attributes but (like this method) avoids parsing markup. Parameters * `name` (String) * `document` ([`Nokogiri::XML::Document`](document)) The document to which the the returned node will belong. Yields [`Nokogiri::XML::Node`](node) Returns [`Nokogiri::XML::Node`](node) <=>(other) Show source ``` # File lib/nokogiri/xml/node.rb, line 1256 def <=>(other) return nil unless other.is_a?(Nokogiri::XML::Node) return nil unless document == other.document compare(other) end ``` Compare two [`Node`](node) objects with respect to their [`Document`](document). Nodes from different documents cannot be compared. ==(other) Show source ``` # File lib/nokogiri/xml/node.rb, line 1246 def ==(other) return false unless other return false unless other.respond_to?(:pointer_id) pointer_id == other.pointer_id end ``` Test to see if this [`Node`](node) is equal to `other` accept(visitor) Show source ``` # File lib/nokogiri/xml/node.rb, line 1240 def accept(visitor) visitor.visit(self) end ``` Accept a visitor. This method calls β€œvisit” on `visitor` with self. ancestors(selector = nil) Show source ``` # File lib/nokogiri/xml/node.rb, line 1209 def ancestors(selector = nil) return NodeSet.new(document) unless respond_to?(:parent) return NodeSet.new(document) unless parent parents = [parent] while parents.last.respond_to?(:parent) break unless (ctx_parent = parents.last.parent) parents << ctx_parent end return NodeSet.new(document, parents) unless selector root = parents.last search_results = root.search(selector) NodeSet.new(document, parents.find_all do |parent| search_results.include?(parent) end) end ``` Get a list of ancestor [`Node`](node) for this [`Node`](node). If `selector` is given, the ancestors must match `selector` blank? β†’ Boolean Show source ``` static VALUE rb_xml_node_blank_eh(VALUE self) { xmlNodePtr node; Noko_Node_Get_Struct(self, xmlNode, node); return (1 == xmlIsBlankNode(node)) ? Qtrue : Qfalse ; } ``` Returns `true` if the node is an empty or whitespace-only text or cdata node, else `false`. **Example:** ``` Nokogiri("<root><child/></root>").root.child.blank? # => false Nokogiri("<root>\t \n</root>").root.child.blank? # => true Nokogiri("<root><![CDATA[\t \n]]></root>").root.child.blank? # => true Nokogiri("<root>not-blank</root>").root.child .tap { |n| n.content = "" }.blank # => true ``` cdata?() Show source ``` # File lib/nokogiri/xml/node.rb, line 1130 def cdata? type == CDATA_SECTION_NODE end ``` Returns true if this is a [`CDATA`](cdata) clone(p1 = v1, p2 = v2) Alias for: [dup](node#method-i-dup) comment?() Show source ``` # File lib/nokogiri/xml/node.rb, line 1125 def comment? type == COMMENT_NODE end ``` Returns true if this is a [`Comment`](comment) content() β†’ String Show source ``` static VALUE rb_xml_node_content(VALUE self) { xmlNodePtr node; xmlChar *content; Noko_Node_Get_Struct(self, xmlNode, node); content = xmlNodeGetContent(node); if (content) { VALUE rval = NOKOGIRI_STR_NEW2(content); xmlFree(content); return rval; } return Qnil; } ``` Returns Contents of all the text nodes in this node’s subtree, concatenated together into a single String. ⚠ Note that entities will *always* be expanded in the returned String. See related: [`#inner_html`](node#method-i-inner_html) **Example** of how entities are handled: Note that `&lt;` becomes `<` in the returned String. ``` doc = Nokogiri::XML.fragment("<child>a &lt; b</child>") doc.at_css("child").content # => "a < b" ``` **Example** of how a subtree is handled: Note that the `<span>` tags are omitted and only the text node contents are returned, concatenated into a single string. ``` doc = Nokogiri::XML.fragment("<child><span>first</span> <span>second</span></child>") doc.at_css("child").content # => "first second" ``` Also aliased as: [inner\_text](node#method-i-inner_text), [text](node#method-i-text), [to\_str](node#method-i-to_str) create\_external\_subset(name, external\_id, system\_id) Show source ``` static VALUE create_external_subset(VALUE self, VALUE name, VALUE external_id, VALUE system_id) { xmlNodePtr node; xmlDocPtr doc; xmlDtdPtr dtd; Noko_Node_Get_Struct(self, xmlNode, node); doc = node->doc; if (doc->extSubset) { rb_raise(rb_eRuntimeError, "Document already has an external subset"); } dtd = xmlNewDtd( doc, NIL_P(name) ? NULL : (const xmlChar *)StringValueCStr(name), NIL_P(external_id) ? NULL : (const xmlChar *)StringValueCStr(external_id), NIL_P(system_id) ? NULL : (const xmlChar *)StringValueCStr(system_id) ); if (!dtd) { return Qnil; } return noko_xml_node_wrap(Qnil, (xmlNodePtr)dtd); } ``` Create an external subset create\_internal\_subset(name, external\_id, system\_id) Show source ``` static VALUE create_internal_subset(VALUE self, VALUE name, VALUE external_id, VALUE system_id) { xmlNodePtr node; xmlDocPtr doc; xmlDtdPtr dtd; Noko_Node_Get_Struct(self, xmlNode, node); doc = node->doc; if (xmlGetIntSubset(doc)) { rb_raise(rb_eRuntimeError, "Document already has an internal subset"); } dtd = xmlCreateIntSubset( doc, NIL_P(name) ? NULL : (const xmlChar *)StringValueCStr(name), NIL_P(external_id) ? NULL : (const xmlChar *)StringValueCStr(external_id), NIL_P(system_id) ? NULL : (const xmlChar *)StringValueCStr(system_id) ); if (!dtd) { return Qnil; } return noko_xml_node_wrap(Qnil, (xmlNodePtr)dtd); } ``` Create the internal subset of a document. ``` doc.create_internal_subset("chapter", "-//OASIS//DTD DocBook XML//EN", "chapter.dtd") # => <!DOCTYPE chapter PUBLIC "-//OASIS//DTD DocBook XML//EN" "chapter.dtd"> doc.create_internal_subset("chapter", nil, "chapter.dtd") # => <!DOCTYPE chapter SYSTEM "chapter.dtd"> ``` css\_path() Show source ``` # File lib/nokogiri/xml/node.rb, line 1200 def css_path path.split(%r{/}).filter_map do |part| part.empty? ? nil : part.gsub(/\[(\d+)\]/, ':nth-of-type(\1)') end.join(" > ") end ``` Get the path to this node as a [`CSS`](../css) expression decorate!() Show source ``` # File lib/nokogiri/xml/node.rb, line 132 def decorate! document.decorate(self) end ``` Decorate this node with the decorators set up in this node’s [`Document`](document) description() Show source ``` # File lib/nokogiri/xml/node.rb, line 1167 def description return nil if document.xml? Nokogiri::HTML4::ElementDescription[name] end ``` Fetch the [`Nokogiri::HTML4::ElementDescription`](../html4/elementdescription) for this node. Returns nil on [`XML`](../xml) documents and on unknown tags. document?() Show source ``` # File lib/nokogiri/xml/node.rb, line 1145 def document? is_a?(XML::Document) end ``` Returns true if this is a [`Document`](document) dup β†’ Nokogiri::XML::Node Show source dup(depth) β†’ Nokogiri::XML::Node dup(depth, new\_parent\_doc) β†’ Nokogiri::XML::Node ``` static VALUE duplicate_node(int argc, VALUE *argv, VALUE self) { VALUE r_level, r_new_parent_doc; int level; int n_args; xmlDocPtr new_parent_doc; xmlNodePtr node, dup; Noko_Node_Get_Struct(self, xmlNode, node); n_args = rb_scan_args(argc, argv, "02", &r_level, &r_new_parent_doc); if (n_args < 1) { r_level = INT2NUM((long)1); } level = (int)NUM2INT(r_level); if (n_args < 2) { new_parent_doc = node->doc; } else { Data_Get_Struct(r_new_parent_doc, xmlDoc, new_parent_doc); } dup = xmlDocCopyNode(node, new_parent_doc, level); if (dup == NULL) { return Qnil; } noko_xml_document_pin_node(dup); return noko_xml_node_wrap(rb_obj_class(self), dup); } ``` Copy this node. Parameters * `depth` 0 is a shallow copy, 1 (the default) is a deep copy. * `new_parent_doc` The new node’s parent [`Document`](document). Defaults to the this node’s document. Returns The new Nokgiri::XML::Node Also aliased as: [clone](node#method-i-clone) elem?() Alias for: [element?](node#method-i-element-3F) element?() Show source ``` # File lib/nokogiri/xml/node.rb, line 1181 def element? type == ELEMENT_NODE end ``` Returns true if this is an [`Element`](element) node Also aliased as: [elem?](node#method-i-elem-3F) element\_children() β†’ NodeSet Show source ``` static VALUE rb_xml_node_element_children(VALUE self) { xmlNodePtr node; xmlNodePtr child; xmlNodeSetPtr set; VALUE document; VALUE node_set; Noko_Node_Get_Struct(self, xmlNode, node); child = xmlFirstElementChild(node); set = xmlXPathNodeSetCreate(child); document = DOC_RUBY_OBJECT(node->doc); if (!child) { return noko_xml_node_set_wrap(set, document); } child = xmlNextElementSibling(child); while (NULL != child) { xmlXPathNodeSetAddUnique(set, child); child = xmlNextElementSibling(child); } node_set = noko_xml_node_set_wrap(set, document); return node_set; } ``` Returns The node’s child elements as a [`NodeSet`](nodeset). Only children that are elements will be returned, which notably excludes [`Text`](text) nodes. **Example:** Note that [`#children`](node#method-i-children) returns the [`Text`](text) node β€œhello” while [`#element_children`](node#method-i-element_children) does not. ``` div = Nokogiri::HTML5("<div>hello<span>world</span>").at_css("div") div.element_children # => [#<Nokogiri::XML::Element:0x50 name="span" children=[#<Nokogiri::XML::Text:0x3c "world">]>] div.children # => [#<Nokogiri::XML::Text:0x64 "hello">, # #<Nokogiri::XML::Element:0x50 name="span" children=[#<Nokogiri::XML::Text:0x3c "world">]>] ``` Also aliased as: [elements](node#method-i-elements) elements() β†’ NodeSet Alias for: [element\_children](node#method-i-element_children) encode\_special\_chars(string) β†’ String Show source ``` static VALUE encode_special_chars(VALUE self, VALUE string) { xmlNodePtr node; xmlChar *encoded; VALUE encoded_str; Noko_Node_Get_Struct(self, xmlNode, node); encoded = xmlEncodeSpecialChars( node->doc, (const xmlChar *)StringValueCStr(string) ); encoded_str = NOKOGIRI_STR_NEW2(encoded); xmlFree(encoded); return encoded_str; } ``` Encode any special characters in `string` external\_subset() Show source ``` static VALUE external_subset(VALUE self) { xmlNodePtr node; xmlDocPtr doc; xmlDtdPtr dtd; Noko_Node_Get_Struct(self, xmlNode, node); if (!node->doc) { return Qnil; } doc = node->doc; dtd = doc->extSubset; if (!dtd) { return Qnil; } return noko_xml_node_wrap(Qnil, (xmlNodePtr)dtd); } ``` Get the external subset first\_element\_child() β†’ Node Show source ``` static VALUE rb_xml_node_first_element_child(VALUE self) { xmlNodePtr node, child; Noko_Node_Get_Struct(self, xmlNode, node); child = xmlFirstElementChild(node); if (!child) { return Qnil; } return noko_xml_node_wrap(Qnil, child); } ``` Returns The first child [`Node`](node) that is an element. **Example:** Note that the β€œhello” child, which is a [`Text`](text) node, is skipped and the `<span>` element is returned. ``` div = Nokogiri::HTML5("<div>hello<span>world</span>").at_css("div") div.first_element_child # => #(Element:0x3c { name = "span", children = [ #(Text "world")] }) ``` fragment(tags) Show source ``` # File lib/nokogiri/xml/node.rb, line 1022 def fragment(tags) document.related_class("DocumentFragment").new(document, tags, self) end ``` Create a [`DocumentFragment`](documentfragment) containing `tags` that is relative to *this* context node. fragment?() Show source ``` # File lib/nokogiri/xml/node.rb, line 1160 def fragment? type == DOCUMENT_FRAG_NODE end ``` Returns true if this is a [`DocumentFragment`](documentfragment) html?() Show source ``` # File lib/nokogiri/xml/node.rb, line 1140 def html? type == HTML_DOCUMENT_NODE end ``` Returns true if this is an [`HTML4::Document`](../html4/document) or [`HTML5::Document`](../html5/document) node inner\_html(\*args) Show source ``` # File lib/nokogiri/xml/node.rb, line 1195 def inner_html(*args) children.map { |x| x.to_html(*args) }.join end ``` Get the [`inner_html`](node#method-i-inner_html) for this node’s [`Node#children`](node#method-i-children) inner\_text() Alias for: [content](node#method-i-content) internal\_subset() Show source ``` static VALUE internal_subset(VALUE self) { xmlNodePtr node; xmlDocPtr doc; xmlDtdPtr dtd; Noko_Node_Get_Struct(self, xmlNode, node); if (!node->doc) { return Qnil; } doc = node->doc; dtd = xmlGetIntSubset(doc); if (!dtd) { return Qnil; } return noko_xml_node_wrap(Qnil, (xmlNodePtr)dtd); } ``` Get the internal subset key?(attribute) Show source ``` static VALUE key_eh(VALUE self, VALUE attribute) { xmlNodePtr node; Noko_Node_Get_Struct(self, xmlNode, node); if (xmlHasProp(node, (xmlChar *)StringValueCStr(attribute))) { return Qtrue; } return Qfalse; } ``` Returns true if `attribute` is set Also aliased as: [has\_attribute?](node#method-i-has_attribute-3F) lang Show source ``` static VALUE get_lang(VALUE self_rb) { xmlNodePtr self ; xmlChar *lang ; VALUE lang_rb ; Noko_Node_Get_Struct(self_rb, xmlNode, self); lang = xmlNodeGetLang(self); if (lang) { lang_rb = NOKOGIRI_STR_NEW2(lang); xmlFree(lang); return lang_rb ; } return Qnil ; } ``` Searches the language of a node, i.e. the values of the xml:lang attribute or the one carried by the nearest ancestor. lang= Show source ``` static VALUE set_lang(VALUE self_rb, VALUE lang_rb) { xmlNodePtr self ; xmlChar *lang ; Noko_Node_Get_Struct(self_rb, xmlNode, self); lang = (xmlChar *)StringValueCStr(lang_rb); xmlNodeSetLang(self, lang); return Qnil ; } ``` Set the language of a node, i.e. the values of the xml:lang attribute. last\_element\_child() β†’ Node Show source ``` static VALUE rb_xml_node_last_element_child(VALUE self) { xmlNodePtr node, child; Noko_Node_Get_Struct(self, xmlNode, node); child = xmlLastElementChild(node); if (!child) { return Qnil; } return noko_xml_node_wrap(Qnil, child); } ``` Returns The last child [`Node`](node) that is an element. **Example:** Note that the β€œhello” child, which is a [`Text`](text) node, is skipped and the `<span>yes</span>` element is returned. ``` div = Nokogiri::HTML5("<div><span>no</span><span>yes</span>skip</div>").at_css("div") div.last_element_child # => #(Element:0x3c { name = "span", children = [ #(Text "yes")] }) ``` line() β†’ Integer Show source ``` static VALUE rb_xml_node_line(VALUE rb_node) { xmlNodePtr c_node; Noko_Node_Get_Struct(rb_node, xmlNode, c_node); return LONG2NUM(xmlGetLineNo(c_node)); } ``` Returns The line number of this [`Node`](node). **⚠ The CRuby and JRuby implementations differ in important ways!** Semantic differences: * The CRuby method reflects the node’s line number *in the parsed string* * The JRuby method reflects the node’s line number *in the final DOM structure* after corrections have been applied Performance differences: * The CRuby method is [O(1)](https://en.wikipedia.org/wiki/Time_complexity#Constant_time) (constant time) * The JRuby method is [O(n)](https://en.wikipedia.org/wiki/Time_complexity#Linear_time) (linear time, where n is the number of nodes before/above the element in the DOM) If you’d like to help improve the JRuby implementation, please review these issues and reach out to the maintainers: * [github.com/sparklemotion/nokogiri/issues/1223](https://github.com/sparklemotion/nokogiri/issues/1223) * [github.com/sparklemotion/nokogiri/pull/2177](https://github.com/sparklemotion/nokogiri/pull/2177) * [github.com/sparklemotion/nokogiri/issues/2380](https://github.com/sparklemotion/nokogiri/issues/2380) line=(num) Show source ``` static VALUE rb_xml_node_line_set(VALUE rb_node, VALUE rb_line_number) { xmlNodePtr c_node; int line_number = NUM2INT(rb_line_number); Noko_Node_Get_Struct(rb_node, xmlNode, c_node); // libxml2 optionally uses xmlNode.psvi to store longer line numbers, but only for text nodes. // search for "psvi" in SAX2.c and tree.c to learn more. if (line_number < 65535) { c_node->line = (short) line_number; } else { c_node->line = 65535; if (c_node->type == XML_TEXT_NODE) { c_node->psvi = (void *)(ptrdiff_t) line_number; } } return rb_line_number; } ``` Sets the line for this [`Node`](node). num must be less than 65535. matches?(selector) Show source ``` # File lib/nokogiri/xml/node.rb, line 1015 def matches?(selector) ancestors.last.search(selector).include?(self) end ``` Returns true if this [`Node`](node) matches `selector` name Alias for: [node\_name](node#method-i-node_name) namespace() β†’ Namespace Show source ``` static VALUE rb_xml_node_namespace(VALUE rb_node) { xmlNodePtr c_node ; Noko_Node_Get_Struct(rb_node, xmlNode, c_node); if (c_node->ns) { return noko_xml_namespace_wrap(c_node->ns, c_node->doc); } return Qnil ; } ``` Returns The [`Namespace`](namespace) of the element or attribute node, or `nil` if there is no namespace. **Example:** ``` doc = Nokogiri::XML(<<~EOF) <root> <first/> <second xmlns="http://example.com/child"/> <foo:third xmlns:foo="http://example.com/foo"/> </root> EOF doc.at_xpath("//first").namespace # => nil doc.at_xpath("//xmlns:second", "xmlns" => "http://example.com/child").namespace # => #(Namespace:0x3c { href = "http://example.com/child" }) doc.at_xpath("//foo:third", "foo" => "http://example.com/foo").namespace # => #(Namespace:0x50 { prefix = "foo", href = "http://example.com/foo" }) ``` namespace\_definitions() β†’ Array<Nokogiri::XML::Namespace> Show source ``` static VALUE namespace_definitions(VALUE rb_node) { /* this code in the mode of xmlHasProp() */ xmlNodePtr c_node ; xmlNsPtr c_namespace; VALUE definitions = rb_ary_new(); Noko_Node_Get_Struct(rb_node, xmlNode, c_node); c_namespace = c_node->nsDef; if (!c_namespace) { return definitions; } while (c_namespace != NULL) { rb_ary_push(definitions, noko_xml_namespace_wrap(c_namespace, c_node->doc)); c_namespace = c_namespace->next; } return definitions; } ``` Returns Namespaces that are defined directly on this node, as an Array of [`Namespace`](namespace) objects. The array will be empty if no namespaces are defined on this node. **Example:** ``` doc = Nokogiri::XML(<<~EOF) <root xmlns="http://example.com/root"> <first/> <second xmlns="http://example.com/child" xmlns:unused="http://example.com/unused"/> <foo:third xmlns:foo="http://example.com/foo"/> </root> EOF doc.at_xpath("//root:first", "root" => "http://example.com/root").namespace_definitions # => [] doc.at_xpath("//xmlns:second", "xmlns" => "http://example.com/child").namespace_definitions # => [#(Namespace:0x3c { href = "http://example.com/child" }), # #(Namespace:0x50 { # prefix = "unused", # href = "http://example.com/unused" # })] doc.at_xpath("//foo:third", "foo" => "http://example.com/foo").namespace_definitions # => [#(Namespace:0x64 { prefix = "foo", href = "http://example.com/foo" })] ``` namespace\_scopes() β†’ Array<Nokogiri::XML::Namespace> Show source ``` static VALUE rb_xml_node_namespace_scopes(VALUE rb_node) { xmlNodePtr c_node ; xmlNsPtr *namespaces; VALUE scopes = rb_ary_new(); int j; Noko_Node_Get_Struct(rb_node, xmlNode, c_node); namespaces = xmlGetNsList(c_node->doc, c_node); if (!namespaces) { return scopes; } for (j = 0 ; namespaces[j] != NULL ; ++j) { rb_ary_push(scopes, noko_xml_namespace_wrap(namespaces[j], c_node->doc)); } xmlFree(namespaces); return scopes; } ``` Returns Array of all the Namespaces on this node and its ancestors. See also [`#namespaces`](node#method-i-namespaces) **Example:** ``` doc = Nokogiri::XML(<<~EOF) <root xmlns="http://example.com/root" xmlns:bar="http://example.com/bar"> <first/> <second xmlns="http://example.com/child"/> <third xmlns:foo="http://example.com/foo"/> </root> EOF doc.at_xpath("//root:first", "root" => "http://example.com/root").namespace_scopes # => [#(Namespace:0x3c { href = "http://example.com/root" }), # #(Namespace:0x50 { prefix = "bar", href = "http://example.com/bar" })] doc.at_xpath("//child:second", "child" => "http://example.com/child").namespace_scopes # => [#(Namespace:0x64 { href = "http://example.com/child" }), # #(Namespace:0x50 { prefix = "bar", href = "http://example.com/bar" })] doc.at_xpath("//root:third", "root" => "http://example.com/root").namespace_scopes # => [#(Namespace:0x78 { prefix = "foo", href = "http://example.com/foo" }), # #(Namespace:0x3c { href = "http://example.com/root" }), # #(Namespace:0x50 { prefix = "bar", href = "http://example.com/bar" })] ``` namespaced\_key?(attribute, namespace) Show source ``` static VALUE namespaced_key_eh(VALUE self, VALUE attribute, VALUE namespace) { xmlNodePtr node; Noko_Node_Get_Struct(self, xmlNode, node); if (xmlHasNsProp(node, (xmlChar *)StringValueCStr(attribute), NIL_P(namespace) ? NULL : (xmlChar *)StringValueCStr(namespace))) { return Qtrue; } return Qfalse; } ``` Returns true if `attribute` is set with `namespace` namespaces() β†’ Hash<String(Namespace#prefix) β‡’ String(Namespace#href)> Show source ``` # File lib/nokogiri/xml/node.rb, line 1116 def namespaces namespace_scopes.each_with_object({}) do |ns, hash| prefix = ns.prefix key = prefix ? "xmlns:#{prefix}" : "xmlns" hash[key] = ns.href end end ``` Fetch all the namespaces on this node and its ancestors. Note that the keys in this hash [`XML`](../xml) attributes that would be used to define this namespace, such as β€œxmlns:prefix”, not just the prefix. The default namespace for this node will be included with key β€œxmlns”. See also [`#namespace_scopes`](node#method-i-namespace_scopes) Returns Hash containing all the namespaces on this node and its ancestors. The hash keys are the namespace prefix, and the hash value for each key is the namespace URI. **Example:** ``` doc = Nokogiri::XML(<<~EOF) <root xmlns="http://example.com/root" xmlns:in_scope="http://example.com/in_scope"> <first/> <second xmlns="http://example.com/child"/> <third xmlns:foo="http://example.com/foo"/> </root> EOF doc.at_xpath("//root:first", "root" => "http://example.com/root").namespaces # => {"xmlns"=>"http://example.com/root", # "xmlns:in_scope"=>"http://example.com/in_scope"} doc.at_xpath("//child:second", "child" => "http://example.com/child").namespaces # => {"xmlns"=>"http://example.com/child", # "xmlns:in_scope"=>"http://example.com/in_scope"} doc.at_xpath("//root:third", "root" => "http://example.com/root").namespaces # => {"xmlns:foo"=>"http://example.com/foo", # "xmlns"=>"http://example.com/root", # "xmlns:in_scope"=>"http://example.com/in_scope"} ``` content= Show source ``` static VALUE set_native_content(VALUE self, VALUE content) { xmlNodePtr node, child, next ; Noko_Node_Get_Struct(self, xmlNode, node); child = node->children; while (NULL != child) { next = child->next ; xmlUnlinkNode(child) ; noko_xml_document_pin_node(child); child = next ; } xmlNodeSetContent(node, (xmlChar *)StringValueCStr(content)); return content; } ``` Set the content for this [`Node`](node) next\_element Show source ``` static VALUE next_element(VALUE self) { xmlNodePtr node, sibling; Noko_Node_Get_Struct(self, xmlNode, node); sibling = xmlNextElementSibling(node); if (!sibling) { return Qnil; } return noko_xml_node_wrap(Qnil, sibling); } ``` Returns the next [`Nokogiri::XML::Element`](element) type sibling node. next\_sibling Show source ``` static VALUE next_sibling(VALUE self) { xmlNodePtr node, sibling; Noko_Node_Get_Struct(self, xmlNode, node); sibling = node->next; if (!sibling) { return Qnil; } return noko_xml_node_wrap(Qnil, sibling) ; } ``` Returns the next sibling node Also aliased as: [next](node#method-i-next) name Show source ``` static VALUE get_name(VALUE self) { xmlNodePtr node; Noko_Node_Get_Struct(self, xmlNode, node); if (node->name) { return NOKOGIRI_STR_NEW2(node->name); } return Qnil; } ``` Returns the name for this [`Node`](node) Also aliased as: [name](node#method-i-name) node\_name=(new\_name) Show source ``` static VALUE set_name(VALUE self, VALUE new_name) { xmlNodePtr node; Noko_Node_Get_Struct(self, xmlNode, node); xmlNodeSetName(node, (xmlChar *)StringValueCStr(new_name)); return new_name; } ``` Set the name for this [`Node`](node) Also aliased as: [name=](node#method-i-name-3D) node\_type Show source ``` static VALUE node_type(VALUE self) { xmlNodePtr node; Noko_Node_Get_Struct(self, xmlNode, node); return INT2NUM(node->type); } ``` Get the type for this [`Node`](node) Also aliased as: [type](node#method-i-type) parent Show source ``` static VALUE get_parent(VALUE self) { xmlNodePtr node, parent; Noko_Node_Get_Struct(self, xmlNode, node); parent = node->parent; if (!parent) { return Qnil; } return noko_xml_node_wrap(Qnil, parent) ; } ``` Get the parent [`Node`](node) for this [`Node`](node) parse(string\_or\_io, options = nil) { |options| ... } Show source ``` # File lib/nokogiri/xml/node.rb, line 1030 def parse(string_or_io, options = nil) ## # When the current node is unparented and not an element node, use the # document as the parsing context instead. Otherwise, the in-context # parser cannot find an element or a document node. # Document Fragments are also not usable by the in-context parser. if !element? && !document? && (!parent || parent.fragment?) return document.parse(string_or_io, options) end options ||= (document.html? ? ParseOptions::DEFAULT_HTML : ParseOptions::DEFAULT_XML) options = Nokogiri::XML::ParseOptions.new(options) if Integer === options yield options if block_given? contents = if string_or_io.respond_to?(:read) string_or_io.read else string_or_io end return Nokogiri::XML::NodeSet.new(document) if contents.empty? # libxml2 does not obey the +recover+ option after encountering errors during +in_context+ # parsing, and so this horrible hack is here to try to emulate recovery behavior. # # Unfortunately, this means we're no longer parsing "in context" and so namespaces that # would have been inherited from the context node won't be handled correctly. This hack was # written in 2010, and I regret it, because it's silently degrading functionality in a way # that's not easily prevented (or even detected). # # I think preferable behavior would be to either: # # a. add an error noting that we "fell back" and pointing the user to turning off the +recover+ option # b. don't recover, but raise a sensible exception # # For context and background: https://github.com/sparklemotion/nokogiri/issues/313 # FIXME bug report: https://github.com/sparklemotion/nokogiri/issues/2092 error_count = document.errors.length node_set = in_context(contents, options.to_i) if node_set.empty? && (document.errors.length > error_count) if options.recover? fragment = document.related_class("DocumentFragment").parse(contents) node_set = fragment.children else raise document.errors[error_count] end end node_set end ``` Parse `string_or_io` as a document fragment within the context of **this** node. Returns a [`XML::NodeSet`](nodeset) containing the nodes parsed from `string_or_io`. path Show source ``` static VALUE rb_xml_node_path(VALUE rb_node) { xmlNodePtr c_node; xmlChar *c_path ; VALUE rval; Noko_Node_Get_Struct(rb_node, xmlNode, c_node); c_path = xmlGetNodePath(c_node); if (c_path == NULL) { // see https://github.com/sparklemotion/nokogiri/issues/2250 // this behavior is clearly undesirable, but is what libxml <= 2.9.10 returned, and so we // do this for now to preserve the behavior across libxml2 versions. rval = NOKOGIRI_STR_NEW2("?"); } else { rval = NOKOGIRI_STR_NEW2(c_path); xmlFree(c_path); } return rval ; } ``` Returns the path associated with this [`Node`](node) pointer\_id() β†’ Integer Show source ``` static VALUE rb_xml_node_pointer_id(VALUE self) { xmlNodePtr node; Noko_Node_Get_Struct(self, xmlNode, node); return rb_uint2inum((uintptr_t)(node)); } ``` Returns A unique id for this node based on the internal memory structures. This method is used by [`#==`](node#method-i-3D-3D) to determine node identity. previous\_element Show source ``` static VALUE previous_element(VALUE self) { xmlNodePtr node, sibling; Noko_Node_Get_Struct(self, xmlNode, node); /* * note that we don't use xmlPreviousElementSibling here because it's buggy pre-2.7.7. */ sibling = node->prev; if (!sibling) { return Qnil; } while (sibling && sibling->type != XML_ELEMENT_NODE) { sibling = sibling->prev; } return sibling ? noko_xml_node_wrap(Qnil, sibling) : Qnil ; } ``` Returns the previous [`Nokogiri::XML::Element`](element) type sibling node. previous\_sibling Show source ``` static VALUE previous_sibling(VALUE self) { xmlNodePtr node, sibling; Noko_Node_Get_Struct(self, xmlNode, node); sibling = node->prev; if (!sibling) { return Qnil; } return noko_xml_node_wrap(Qnil, sibling); } ``` Returns the previous sibling node Also aliased as: [previous](node#method-i-previous) processing\_instruction?() Show source ``` # File lib/nokogiri/xml/node.rb, line 1150 def processing_instruction? type == PI_NODE end ``` Returns true if this is a [`ProcessingInstruction`](processinginstruction) node read\_only?() Show source ``` # File lib/nokogiri/xml/node.rb, line 1175 def read_only? # According to gdome2, these are read-only node types [NOTATION_NODE, ENTITY_NODE, ENTITY_DECL].include?(type) end ``` Is this a read only node? related\_class(class\_name) β†’ Class Show source ``` # File lib/nokogiri/class_resolver.rb, line 46 def related_class(class_name) klass = nil inspecting = self.class while inspecting namespace_path = inspecting.name.split("::")[0..-2] inspecting = inspecting.superclass next unless VALID_NAMESPACES.include?(namespace_path.last) related_class_name = (namespace_path << class_name).join("::") klass = begin Object.const_get(related_class_name) rescue NameError nil end break if klass end klass end ``` Included from [Nokogiri::ClassResolver](../classresolver) Find a class constant within the Some examples: ``` Nokogiri::XML::Document.new.related_class("DocumentFragment") # => Nokogiri::XML::DocumentFragment Nokogiri::HTML4::Document.new.related_class("DocumentFragment") # => Nokogiri::HTML4::DocumentFragment ``` Note this will also work for subclasses that follow the same convention, e.g.: ``` Loofah::HTML::Document.new.related_class("DocumentFragment") # => Loofah::HTML::DocumentFragment ``` And even if it’s a subclass, this will iterate through the superclasses: ``` class ThisIsATopLevelClass < Nokogiri::HTML4::Builder ; end ThisIsATopLevelClass.new.related_class("Document") # => Nokogiri::HTML4::Document ``` text() β†’ String Alias for: [content](node#method-i-content) text?() Show source ``` # File lib/nokogiri/xml/node.rb, line 1155 def text? type == TEXT_NODE end ``` Returns true if this is a [`Text`](text) node to\_s() Show source ``` # File lib/nokogiri/xml/node.rb, line 1190 def to_s document.xml? ? to_xml : to_html end ``` Turn this node in to a string. If the document is [`HTML`](../html4), this method returns html. If the document is [`XML`](../xml), this method returns [`XML`](../xml). to\_str() β†’ String Alias for: [content](node#method-i-content) traverse() { |self| ... } Show source ``` # File lib/nokogiri/xml/node.rb, line 1233 def traverse(&block) children.each { |j| j.traverse(&block) } yield(self) end ``` Yields self and all children to `block` recursively. node\_type Alias for: [node\_type](node#method-i-node_type) unlink() β†’ self Show source ``` static VALUE unlink_node(VALUE self) { xmlNodePtr node; Noko_Node_Get_Struct(self, xmlNode, node); xmlUnlinkNode(node); noko_xml_document_pin_node(node); return self; } ``` Unlink this node from its current context. Also aliased as: [remove](node#method-i-remove) xml?() Show source ``` # File lib/nokogiri/xml/node.rb, line 1135 def xml? type == DOCUMENT_NODE end ``` Returns true if this is an [`XML::Document`](document) node coerce(data) Show source ``` # File lib/nokogiri/xml/node.rb, line 1473 def coerce(data) case data when XML::NodeSet return data when XML::DocumentFragment return data.children when String return fragment(data).children when Document, XML::Attr # unacceptable when XML::Node return data end raise ArgumentError, <<~EOERR Requires a Node, NodeSet or String argument, and cannot accept a #{data.class}. (You probably want to select a node from the Document with at() or search(), or create a new Node via Node.new().) EOERR end ``` <<(node\_or\_tags) Show source ``` # File lib/nokogiri/xml/node.rb, line 256 def <<(node_or_tags) add_child(node_or_tags) self end ``` Add `node_or_tags` as a child of this [`Node`](node). `node_or_tags` can be a [`Nokogiri::XML::Node`](node), a ::DocumentFragment, a ::NodeSet, or a String containing markup. Returns `self`, to support chaining of calls (e.g., root << child1 << child2) Also see related method `add_child`. add\_child(node\_or\_tags) Show source ``` # File lib/nokogiri/xml/node.rb, line 148 def add_child(node_or_tags) node_or_tags = coerce(node_or_tags) if node_or_tags.is_a?(XML::NodeSet) node_or_tags.each { |n| add_child_node_and_reparent_attrs(n) } else add_child_node_and_reparent_attrs(node_or_tags) end node_or_tags end ``` Add `node_or_tags` as a child of this [`Node`](node). `node_or_tags` can be a [`Nokogiri::XML::Node`](node), a ::DocumentFragment, a ::NodeSet, or a String containing markup. Returns the reparented node (if `node_or_tags` is a [`Node`](node)), or [`NodeSet`](nodeset) (if `node_or_tags` is a [`DocumentFragment`](documentfragment), [`NodeSet`](nodeset), or String). Also see related method +<<+. add\_namespace(prefix, href) β†’ Nokogiri::XML::Namespace Alias for: [add\_namespace\_definition](node#method-i-add_namespace_definition) add\_namespace\_definition(prefix, href) β†’ Nokogiri::XML::Namespace Show source ``` static VALUE rb_xml_node_add_namespace_definition(VALUE rb_node, VALUE rb_prefix, VALUE rb_href) { xmlNodePtr c_node, element; xmlNsPtr c_namespace; const xmlChar *c_prefix = (const xmlChar *)(NIL_P(rb_prefix) ? NULL : StringValueCStr(rb_prefix)); Noko_Node_Get_Struct(rb_node, xmlNode, c_node); element = c_node ; c_namespace = xmlSearchNs(c_node->doc, c_node, c_prefix); if (!c_namespace) { if (c_node->type != XML_ELEMENT_NODE) { element = c_node->parent; } c_namespace = xmlNewNs(element, (const xmlChar *)StringValueCStr(rb_href), c_prefix); } if (!c_namespace) { return Qnil ; } if (NIL_P(rb_prefix) || c_node != element) { xmlSetNs(c_node, c_namespace); } return noko_xml_namespace_wrap(c_namespace, c_node->doc); } ``` Adds a namespace definition to this node with `prefix` using `href` value, as if this node had included an attribute β€œxmlns:prefix=href”. A default namespace definition for this node can be added by passing `nil` for `prefix`. Parameters * `prefix` (String, `nil`) An [XML Name](https://www.w3.org/TR/xml-names/#ns-decl) * `href` (String) The [URI reference](https://www.w3.org/TR/xml-names/#sec-namespaces) Returns The new [`Nokogiri::XML::Namespace`](namespace) **Example:** adding a non-default namespace definition ``` doc = Nokogiri::XML("<store><inventory></inventory></store>") inventory = doc.at_css("inventory") inventory.add_namespace_definition("automobile", "http://alices-autos.com/") inventory.add_namespace_definition("bicycle", "http://bobs-bikes.com/") inventory.add_child("<automobile:tire>Michelin model XGV, size 75R</automobile:tire>") doc.to_xml # => "<?xml version=\"1.0\"?>\n" + # "<store>\n" + # " <inventory xmlns:automobile=\"http://alices-autos.com/\" xmlns:bicycle=\"http://bobs-bikes.com/\">\n" + # " <automobile:tire>Michelin model XGV, size 75R</automobile:tire>\n" + # " </inventory>\n" + # "</store>\n" ``` **Example:** adding a default namespace definition ``` doc = Nokogiri::XML("<store><inventory><tire>Michelin model XGV, size 75R</tire></inventory></store>") doc.at_css("tire").add_namespace_definition(nil, "http://bobs-bikes.com/") doc.to_xml # => "<?xml version=\"1.0\"?>\n" + # "<store>\n" + # " <inventory>\n" + # " <tire xmlns=\"http://bobs-bikes.com/\">Michelin model XGV, size 75R</tire>\n" + # " </inventory>\n" + # "</store>\n" ``` Also aliased as: [add\_namespace](node#method-i-add_namespace) add\_next\_sibling(node\_or\_tags) Show source ``` # File lib/nokogiri/xml/node.rb, line 288 def add_next_sibling(node_or_tags) raise ArgumentError, "A document may not have multiple root nodes." if parent&.document? && !(node_or_tags.comment? || node_or_tags.processing_instruction?) add_sibling(:next, node_or_tags) end ``` Insert `node_or_tags` after this [`Node`](node) (as a sibling). `node_or_tags` can be a [`Nokogiri::XML::Node`](node), a ::DocumentFragment, a ::NodeSet, or a String containing markup. Returns the reparented node (if `node_or_tags` is a [`Node`](node)), or [`NodeSet`](nodeset) (if `node_or_tags` is a [`DocumentFragment`](documentfragment), [`NodeSet`](nodeset), or String). Also see related method `after`. Also aliased as: [next=](node#method-i-next-3D) add\_previous\_sibling(node\_or\_tags) Show source ``` # File lib/nokogiri/xml/node.rb, line 271 def add_previous_sibling(node_or_tags) raise ArgumentError, "A document may not have multiple root nodes." if parent&.document? && !(node_or_tags.comment? || node_or_tags.processing_instruction?) add_sibling(:previous, node_or_tags) end ``` Insert `node_or_tags` before this [`Node`](node) (as a sibling). `node_or_tags` can be a [`Nokogiri::XML::Node`](node), a ::DocumentFragment, a ::NodeSet, or a String containing markup. Returns the reparented node (if `node_or_tags` is a [`Node`](node)), or [`NodeSet`](nodeset) (if `node_or_tags` is a [`DocumentFragment`](documentfragment), [`NodeSet`](nodeset), or String). Also see related method `before`. Also aliased as: [previous=](node#method-i-previous-3D) after(node\_or\_tags) Show source ``` # File lib/nokogiri/xml/node.rb, line 318 def after(node_or_tags) add_next_sibling(node_or_tags) self end ``` Insert `node_or_tags` after this node (as a sibling). `node_or_tags` can be a [`Nokogiri::XML::Node`](node), a [`Nokogiri::XML::DocumentFragment`](documentfragment), or a String containing markup. Returns `self`, to support chaining of calls. Also see related method `add_next_sibling`. before(node\_or\_tags) Show source ``` # File lib/nokogiri/xml/node.rb, line 304 def before(node_or_tags) add_previous_sibling(node_or_tags) self end ``` Insert `node_or_tags` before this node (as a sibling). `node_or_tags` can be a [`Nokogiri::XML::Node`](node), a ::DocumentFragment, a ::NodeSet, or a String containing markup. Returns `self`, to support chaining of calls. Also see related method `add_previous_sibling`. children=(node\_or\_tags) Show source ``` # File lib/nokogiri/xml/node.rb, line 349 def children=(node_or_tags) node_or_tags = coerce(node_or_tags) children.unlink if node_or_tags.is_a?(XML::NodeSet) node_or_tags.each { |n| add_child_node_and_reparent_attrs(n) } else add_child_node_and_reparent_attrs(node_or_tags) end end ``` Set the content for this [`Node`](node) `node_or_tags` `node_or_tags` can be a [`Nokogiri::XML::Node`](node), a [`Nokogiri::XML::DocumentFragment`](documentfragment), or a String containing markup. Also see related method `inner_html=` content=(string) Show source ``` # File lib/nokogiri/xml/node.rb, line 411 def content=(string) self.native_content = encode_special_chars(string.to_s) end ``` Set the Node’s content to a [`Text`](text) node containing `string`. The string gets [`XML`](../xml) escaped, not interpreted as markup. default\_namespace=(url) Show source ``` # File lib/nokogiri/xml/node.rb, line 427 def default_namespace=(url) add_namespace_definition(nil, url) end ``` Adds a default namespace supplied as a string `url` href, to self. The consequence is as an xmlns attribute with supplied argument were present in parsed [`XML`](../xml). A default namespace set with this method will now show up in [`#attributes`](node#method-i-attributes), but when this node is serialized to [`XML`](../xml) an β€œxmlns” attribute will appear. See also [`#namespace`](node#method-i-namespace) and [`#namespace=`](node#method-i-namespace-3D) do\_xinclude(options = XML::ParseOptions::DEFAULT\_XML) { |options| ... } Show source ``` # File lib/nokogiri/xml/node.rb, line 454 def do_xinclude(options = XML::ParseOptions::DEFAULT_XML) options = Nokogiri::XML::ParseOptions.new(options) if Integer === options yield options if block_given? # call c extension process_xincludes(options.to_i) end ``` Do xinclude substitution on the subtree below node. If given a block, a [`Nokogiri::XML::ParseOptions`](parseoptions) object initialized from `options`, will be passed to it, allowing more convenient modification of the parser options. inner\_html=(node\_or\_tags) Show source ``` # File lib/nokogiri/xml/node.rb, line 338 def inner_html=(node_or_tags) self.children = node_or_tags end ``` Set the content for this [`Node`](node) to `node_or_tags`. `node_or_tags` can be a [`Nokogiri::XML::Node`](node), a [`Nokogiri::XML::DocumentFragment`](documentfragment), or a String containing markup. ⚠ Please note that despite the name, this method will **not** always parse a String argument as [`HTML`](../html4). A String argument will be parsed with the `DocumentFragment` parser related to this node’s document. For example, if the document is an [`HTML4::Document`](../html4/document) then the string will be parsed as [`HTML4`](../html4) using [`HTML4::DocumentFragment`](../html4/documentfragment); but if the document is an [`XML::Document`](document) then it will parse the string as [`XML`](../xml) using [`XML::DocumentFragment`](documentfragment). Also see related method `children=` name=(new\_name) Alias for: [node\_name=](node#method-i-node_name-3D) namespace=(ns) Show source ``` # File lib/nokogiri/xml/node.rb, line 437 def namespace=(ns) return set_namespace(ns) unless ns unless Nokogiri::XML::Namespace === ns raise TypeError, "#{ns.class} can't be coerced into Nokogiri::XML::Namespace" end if ns.document != document raise ArgumentError, "namespace must be declared on the same document" end set_namespace(ns) end ``` Set the default namespace on this node (as would be defined with an β€œxmlns=” attribute in [`XML`](../xml) source), as a [`Namespace`](namespace) object `ns`. Note that a [`Namespace`](namespace) added this way will NOT be serialized as an xmlns attribute for this node. You probably want [`#default_namespace=`](node#method-i-default_namespace-3D) instead, or perhaps [`#add_namespace_definition`](node#method-i-add_namespace_definition) with a nil prefix argument. next\_sibling Alias for: [next\_sibling](node#method-i-next_sibling) next=(node\_or\_tags) Alias for: [add\_next\_sibling](node#method-i-add_next_sibling) parent=(parent\_node) Show source ``` # File lib/nokogiri/xml/node.rb, line 417 def parent=(parent_node) parent_node.add_child(self) end ``` Set the parent [`Node`](node) for this [`Node`](node) prepend\_child(node\_or\_tags) Show source ``` # File lib/nokogiri/xml/node.rb, line 168 def prepend_child(node_or_tags) if (first = children.first) # Mimic the error add_child would raise. raise "Document already has a root node" if document? && !(node_or_tags.comment? || node_or_tags.processing_instruction?) first.__send__(:add_sibling, :previous, node_or_tags) else add_child(node_or_tags) end end ``` Add `node_or_tags` as the first child of this [`Node`](node). `node_or_tags` can be a [`Nokogiri::XML::Node`](node), a ::DocumentFragment, a ::NodeSet, or a String containing markup. Returns the reparented node (if `node_or_tags` is a [`Node`](node)), or [`NodeSet`](nodeset) (if `node_or_tags` is a [`DocumentFragment`](documentfragment), [`NodeSet`](nodeset), or String). Also see related method `add_child`. previous\_sibling Alias for: [previous\_sibling](node#method-i-previous_sibling) previous=(node\_or\_tags) Alias for: [add\_previous\_sibling](node#method-i-add_previous_sibling) remove() Alias for: [unlink](node#method-i-unlink) replace(node\_or\_tags) Show source ``` # File lib/nokogiri/xml/node.rb, line 369 def replace(node_or_tags) raise("Cannot replace a node with no parent") unless parent # We cannot replace a text node directly, otherwise libxml will return # an internal error at parser.c:13031, I don't know exactly why # libxml is trying to find a parent node that is an element or document # so I can't tell if this is bug in libxml or not. issue #775. if text? replacee = Nokogiri::XML::Node.new("dummy", document) add_previous_sibling_node(replacee) unlink return replacee.replace(node_or_tags) end node_or_tags = parent.coerce(node_or_tags) if node_or_tags.is_a?(XML::NodeSet) node_or_tags.each { |n| add_previous_sibling(n) } unlink else replace_node(node_or_tags) end node_or_tags end ``` Replace this [`Node`](node) with `node_or_tags`. `node_or_tags` can be a [`Nokogiri::XML::Node`](node), a ::DocumentFragment, a ::NodeSet, or a String containing markup. Returns the reparented node (if `node_or_tags` is a [`Node`](node)), or [`NodeSet`](nodeset) (if `node_or_tags` is a [`DocumentFragment`](documentfragment), [`NodeSet`](nodeset), or String). Also see related method `swap`. swap(node\_or\_tags) Show source ``` # File lib/nokogiri/xml/node.rb, line 403 def swap(node_or_tags) replace(node_or_tags) self end ``` Swap this [`Node`](node) for `node_or_tags` `node_or_tags` can be a [`Nokogiri::XML::Node`](node), a ::DocumentFragment, a ::NodeSet, or a String Containing markup. Returns self, to support chaining of calls. Also see related method `replace`. wrap(markup) β†’ self Show source wrap(node) β†’ self ``` # File lib/nokogiri/xml/node.rb, line 223 def wrap(node_or_tags) case node_or_tags when String context_node = parent || document new_parent = context_node.coerce(node_or_tags).first if new_parent.nil? raise "Failed to parse '#{node_or_tags}' in the context of a '#{context_node.name}' element" end when XML::Node new_parent = node_or_tags.dup else raise ArgumentError, "Requires a String or Node argument, and cannot accept a #{node_or_tags.class}" end if parent add_next_sibling(new_parent) else new_parent.unlink end new_parent.add_child(self) self end ``` Wrap this [`Node`](node) with the node parsed from `markup` or a dup of the `node`. Parameters * **markup** (String) Markup that is parsed and used as the wrapper. This node’s parent, if it exists, is used as the context node for parsing; otherwise the associated document is used. If the parsed fragment has multiple roots, the first root node is used as the wrapper. * **node** ([`Nokogiri::XML::Node`](node)) An element that is β€˜#dup`ed and used as the wrapper. Returns `self`, to support chaining. Also see [`NodeSet#wrap`](nodeset#method-i-wrap) **Example** with a `String` argument: ``` doc = Nokogiri::HTML5(<<~HTML) <html><body> <a>asdf</a> </body></html> HTML doc.at_css("a").wrap("<div></div>") doc.to_html # => <html><head></head><body> # <div><a>asdf</a></div> # </body></html> ``` **Example** with a `Node` argument: ``` doc = Nokogiri::HTML5(<<~HTML) <html><body> <a>asdf</a> </body></html> HTML doc.at_css("a").wrap(doc.create_element("div")) doc.to_html # <html><head></head><body> # <div><a>asdf</a></div> # </body></html> ``` %(\*args) Included from [Nokogiri::XML::Searchable](searchable) Alias for: [at](searchable#method-i-at) /(\*args) Included from [Nokogiri::XML::Searchable](searchable) Alias for: [search](searchable#method-i-search) >(selector) β†’ NodeSet Show source ``` # File lib/nokogiri/xml/searchable.rb, line 196 def >(selector) # rubocop:disable Naming/BinaryOperatorParameterName ns = (document.root&.namespaces || {}) xpath(CSS.xpath_for(selector, prefix: "./", ns: ns).first) end ``` Included from [Nokogiri::XML::Searchable](searchable) Search this node’s immediate children using [`CSS`](../css) selector `selector` at(\*paths, [namespace-bindings, xpath-variable-bindings, custom-handler-class]) Show source ``` # File lib/nokogiri/xml/searchable.rb, line 71 def at(*args) search(*args).first end ``` Included from [Nokogiri::XML::Searchable](searchable) Search this object for `paths`, and return only the first result. `paths` must be one or more [`XPath`](xpath) or [`CSS`](../css) queries. See [`Searchable#search`](searchable#method-i-search) for more information. Also aliased as: [%](searchable#method-i-25) at\_css(\*rules, [namespace-bindings, custom-pseudo-class]) Show source ``` # File lib/nokogiri/xml/searchable.rb, line 140 def at_css(*args) css(*args).first end ``` Included from [Nokogiri::XML::Searchable](searchable) Search this object for [`CSS`](../css) `rules`, and return only the first match. `rules` must be one or more [`CSS`](../css) selectors. See [`Searchable#css`](searchable#method-i-css) for more information. at\_xpath(\*paths, [namespace-bindings, variable-bindings, custom-handler-class]) Show source ``` # File lib/nokogiri/xml/searchable.rb, line 188 def at_xpath(*args) xpath(*args).first end ``` Included from [Nokogiri::XML::Searchable](searchable) Search this node for [`XPath`](xpath) `paths`, and return only the first match. `paths` must be one or more [`XPath`](xpath) queries. See [`Searchable#xpath`](searchable#method-i-xpath) for more information. css(\*rules, [namespace-bindings, custom-pseudo-class]) Show source ``` # File lib/nokogiri/xml/searchable.rb, line 126 def css(*args) rules, handler, ns, _ = extract_params(args) css_internal(self, rules, handler, ns) end ``` Included from [Nokogiri::XML::Searchable](searchable) Search this object for [`CSS`](../css) `rules`. `rules` must be one or more [`CSS`](../css) selectors. For example: ``` node.css('title') node.css('body h1.bold') node.css('div + p.green', 'div#one') ``` A hash of namespace bindings may be appended. For example: ``` node.css('bike|tire', {'bike' => 'http://schwinn.com/'}) ``` πŸ’‘ Custom [`CSS`](../css) pseudo classes may also be defined which are mapped to a custom [`XPath`](xpath) function. To define custom pseudo classes, create a class and implement the custom pseudo class you want defined. The first argument to the method will be the matching context [`NodeSet`](nodeset). Any other arguments are ones that you pass in. For example: ``` handler = Class.new { def regex(node_set, regex) node_set.find_all { |node| node['some_attribute'] =~ /#{regex}/ } end }.new node.css('title:regex("\w+")', handler) ``` πŸ’‘ Some [`XPath`](xpath) syntax is supported in [`CSS`](../css) queries. For example, to query for an attribute: ``` node.css('img > @href') # returns all +href+ attributes on an +img+ element node.css('img / @href') # same # ⚠ this returns +class+ attributes from all +div+ elements AND THEIR CHILDREN! node.css('div @class') node.css ``` πŸ’‘ Array-like syntax is supported in [`CSS`](../css) queries as an alternative to using +:nth-child()+. ⚠ NOTE that indices are 1-based like `:nth-child` and not 0-based like Ruby Arrays. For example: ``` # equivalent to 'li:nth-child(2)' node.css('li[2]') # retrieve the second li element in a list ``` ⚠ NOTE that the [`CSS`](../css) query string is case-sensitive with regards to your document type. [`HTML`](../html4) tags will match only lowercase [`CSS`](../css) queries, so if you search for β€œH1” in an [`HTML`](../html4) document, you’ll never find anything. However, β€œH1” might be found in an [`XML`](../xml) document, where tags names are case-sensitive (e.g., β€œH1” is distinct from β€œh1”). search(\*paths, [namespace-bindings, xpath-variable-bindings, custom-handler-class]) Show source ``` # File lib/nokogiri/xml/searchable.rb, line 51 def search(*args) paths, handler, ns, binds = extract_params(args) xpaths = paths.map(&:to_s).map do |path| LOOKS_LIKE_XPATH.match?(path) ? path : xpath_query_from_css_rule(path, ns) end.flatten.uniq xpath(*(xpaths + [ns, handler, binds].compact)) end ``` Included from [Nokogiri::XML::Searchable](searchable) Search this object for `paths`. `paths` must be one or more [`XPath`](xpath) or [`CSS`](../css) queries: ``` node.search("div.employee", ".//title") ``` A hash of namespace bindings may be appended: ``` node.search('.//bike:tire', {'bike' => 'http://schwinn.com/'}) node.search('bike|tire', {'bike' => 'http://schwinn.com/'}) ``` For [`XPath`](xpath) queries, a hash of variable bindings may also be appended to the namespace bindings. For example: ``` node.search('.//address[@domestic=$value]', nil, {:value => 'Yes'}) ``` πŸ’‘ Custom [`XPath`](xpath) functions and [`CSS`](../css) pseudo-selectors may also be defined. To define custom functions create a class and implement the function you want to define. The first argument to the method will be the current matching [`NodeSet`](nodeset). Any other arguments are ones that you pass in. Note that this class may appear anywhere in the argument list. For example: ``` handler = Class.new { def regex node_set, regex node_set.find_all { |node| node['some_attribute'] =~ /#{regex}/ } end }.new node.search('.//title[regex(., "\w+")]', 'div.employee:regex("[0-9]+")', handler) ``` See [`Searchable#xpath`](searchable#method-i-xpath) and [`Searchable#css`](searchable#method-i-css) for further usage help. Also aliased as: [/](searchable#method-i-2F) xpath(\*paths, [namespace-bindings, variable-bindings, custom-handler-class]) Show source ``` # File lib/nokogiri/xml/searchable.rb, line 174 def xpath(*args) paths, handler, ns, binds = extract_params(args) xpath_internal(self, paths, handler, ns, binds) end ``` Included from [Nokogiri::XML::Searchable](searchable) Search this node for [`XPath`](xpath) `paths`. `paths` must be one or more [`XPath`](xpath) queries. ``` node.xpath('.//title') ``` A hash of namespace bindings may be appended. For example: ``` node.xpath('.//foo:name', {'foo' => 'http://example.org/'}) node.xpath('.//xmlns:name', node.root.namespaces) ``` A hash of variable bindings may also be appended to the namespace bindings. For example: ``` node.xpath('.//address[@domestic=$value]', nil, {:value => 'Yes'}) ``` πŸ’‘ Custom [`XPath`](xpath) functions may also be defined. To define custom functions create a class and implement the function you want to define. The first argument to the method will be the current matching [`NodeSet`](nodeset). Any other arguments are ones that you pass in. Note that this class may appear anywhere in the argument list. For example: ``` handler = Class.new { def regex(node_set, regex) node_set.find_all { |node| node['some_attribute'] =~ /#{regex}/ } end }.new node.xpath('.//title[regex(., "\w+")]', handler) ``` canonicalize(mode = XML::XML\_C14N\_1\_0, inclusive\_namespaces = nil, with\_comments = false) Show source ``` # File lib/nokogiri/xml/node.rb, line 1398 def canonicalize(mode = XML::XML_C14N_1_0, inclusive_namespaces = nil, with_comments = false) c14n_root = self document.canonicalize(mode, inclusive_namespaces, with_comments) do |node, parent| tn = node.is_a?(XML::Node) ? node : parent tn == c14n_root || tn.ancestors.include?(c14n_root) end end ``` deconstruct\_keys(array\_of\_names) β†’ Hash Show source ``` # File lib/nokogiri/xml/node.rb, line 1459 def deconstruct_keys(keys) requested_keys = DECONSTRUCT_KEYS & keys {}.tap do |values| requested_keys.each do |key| method = DECONSTRUCT_METHODS[key] || key values[key] = send(method) end end end ``` Returns a hash describing the [`Node`](node), to use in pattern matching. Valid keys and their values: * `name` β†’ (String) The name of this node, or β€œtext” if it is a [`Text`](text) node. * `namespace` β†’ ([`Namespace`](namespace), nil) The namespace of this node, or nil if there is no namespace. * `attributes` β†’ (Array<Attr>) The attributes of this node. * `children` β†’ (Array<Node>) The children of this node. πŸ’‘ Note this includes text nodes. * `elements` β†’ (Array<Node>) The child elements of this node. πŸ’‘ Note this does not include text nodes. * `content` β†’ (String) The contents of all the text nodes in this node’s subtree. See [`#content`](node#method-i-content). * `inner_html` β†’ (String) The inner markup for the children of this node. See [`#inner_html`](node#method-i-inner_html). ⚑ This is an experimental feature, available since v1.14.0 **Example** ``` doc = Nokogiri::XML.parse(<<~XML) <?xml version="1.0"?> <parent xmlns="http://nokogiri.org/ns/default" xmlns:noko="http://nokogiri.org/ns/noko"> <child1 foo="abc" noko:bar="def">First</child1> <noko:child2 foo="qwe" noko:bar="rty">Second</noko:child2> </parent> XML doc.root.deconstruct_keys([:name, :namespace]) # => {:name=>"parent", # :namespace=> # #(Namespace:0x35c { href = "http://nokogiri.org/ns/default" })} doc.root.deconstruct_keys([:inner_html, :content]) # => {:content=>"\n" + " First\n" + " Second\n", # :inner_html=> # "\n" + # " <child1 foo=\"abc\" noko:bar=\"def\">First</child1>\n" + # " <noko:child2 foo=\"qwe\" noko:bar=\"rty\">Second</noko:child2>\n"} doc.root.elements.first.deconstruct_keys([:attributes]) # => {:attributes=> # [#(Attr:0x370 { name = "foo", value = "abc" }), # #(Attr:0x384 { # name = "bar", # namespace = #(Namespace:0x398 { # prefix = "noko", # href = "http://nokogiri.org/ns/noko" # }), # value = "def" # })]} ``` serialize(\*args, &block) Show source ``` # File lib/nokogiri/xml/node.rb, line 1280 def serialize(*args, &block) options = if args.first.is_a?(Hash) args.shift else { encoding: args[0], save_with: args[1], } end options[:encoding] ||= document.encoding encoding = Encoding.find(options[:encoding] || "UTF-8") io = StringIO.new(String.new(encoding: encoding)) write_to(io, options, &block) io.string end ``` Serialize [`Node`](node) using `options`. Save options can also be set using a block. See also [`Nokogiri::XML::Node::SaveOptions`](node/saveoptions) and [Serialization and Generating Output at `Node`](node#class-Nokogiri::XML::Node-label-Serialization+and+Generating+Output). These two statements are equivalent: ``` node.serialize(:encoding => 'UTF-8', :save_with => FORMAT | AS_XML) ``` or ``` node.serialize(:encoding => 'UTF-8') do |config| config.format.as_xml end ``` to\_html(options = {}) Show source ``` # File lib/nokogiri/xml/node.rb, line 1306 def to_html(options = {}) to_format(SaveOptions::DEFAULT_HTML, options) end ``` Serialize this [`Node`](node) to [`HTML`](../html4) ``` doc.to_html ``` See [`Node#write_to`](node#method-i-write_to) for a list of `options`. For formatted output, use [`Node#to_xhtml`](node#method-i-to_xhtml) instead. to\_xhtml(options = {}) Show source ``` # File lib/nokogiri/xml/node.rb, line 1327 def to_xhtml(options = {}) to_format(SaveOptions::DEFAULT_XHTML, options) end ``` Serialize this [`Node`](node) to XHTML using `options` ``` doc.to_xhtml(:indent => 5, :encoding => 'UTF-8') ``` See [`Node#write_to`](node#method-i-write_to) for a list of `options` to\_xml(options = {}) Show source ``` # File lib/nokogiri/xml/node.rb, line 1316 def to_xml(options = {}) options[:save_with] ||= SaveOptions::DEFAULT_XML serialize(options) end ``` Serialize this [`Node`](node) to [`XML`](../xml) using `options` ``` doc.to_xml(:indent => 5, :encoding => 'UTF-8') ``` See [`Node#write_to`](node#method-i-write_to) for a list of `options` write\_html\_to(io, options = {}) Show source ``` # File lib/nokogiri/xml/node.rb, line 1375 def write_html_to(io, options = {}) write_format_to(SaveOptions::DEFAULT_HTML, io, options) end ``` Write [`Node`](node) as [`HTML`](../html4) to `io` with `options` See [`Node#write_to`](node#method-i-write_to) for a list of `options` write\_to(io, \*options) { |config| ... } Show source ``` # File lib/nokogiri/xml/node.rb, line 1348 def write_to(io, *options) options = options.first.is_a?(Hash) ? options.shift : {} encoding = options[:encoding] || options[0] if Nokogiri.jruby? save_options = options[:save_with] || options[1] indent_times = options[:indent] || 0 else save_options = options[:save_with] || options[1] || SaveOptions::FORMAT indent_times = options[:indent] || 2 end indent_text = options[:indent_text] || " " # Any string times 0 returns an empty string. Therefore, use the same # string instead of generating a new empty string for every node with # zero indentation. indentation = indent_times.zero? ? "" : (indent_text * indent_times) config = SaveOptions.new(save_options.to_i) yield config if block_given? native_write_to(io, encoding, indentation, config.options) end ``` Write [`Node`](node) to `io` with `options`. `options` modify the output of this method. Valid options are: * `:encoding` for changing the encoding * `:indent_text` the indentation text, defaults to one space * `:indent` the number of `:indent_text` to use, defaults to 2 * `:save_with` a combination of [`SaveOptions`](node/saveoptions) constants. To save with UTF-8 indented twice: ``` node.write_to(io, :encoding => 'UTF-8', :indent => 2) ``` To save indented with two dashes: ``` node.write_to(io, :indent_text => '-', :indent => 2) ``` write\_xhtml\_to(io, options = {}) Show source ``` # File lib/nokogiri/xml/node.rb, line 1383 def write_xhtml_to(io, options = {}) write_format_to(SaveOptions::DEFAULT_XHTML, io, options) end ``` Write [`Node`](node) as XHTML to `io` with `options` See [`Node#write_to`](node#method-i-write_to) for a list of `options` write\_xml\_to(io, options = {}) Show source ``` # File lib/nokogiri/xml/node.rb, line 1393 def write_xml_to(io, options = {}) options[:save_with] ||= SaveOptions::DEFAULT_XML write_to(io, options) end ``` Write [`Node`](node) as [`XML`](../xml) to `io` with `options` ``` doc.write_xml_to io, :encoding => 'UTF-8' ``` See [`Node#write_to`](node#method-i-write_to) for a list of options child() β†’ Nokogiri::XML::Node Show source ``` static VALUE rb_xml_node_child(VALUE self) { xmlNodePtr node, child; Noko_Node_Get_Struct(self, xmlNode, node); child = node->children; if (!child) { return Qnil; } return noko_xml_node_wrap(Qnil, child); } ``` Returns First of this node’s children, or `nil` if there are no children This is a convenience method and is equivalent to: ``` node.children.first ``` See related: [`#children`](node#method-i-children) children() β†’ Nokogiri::XML::NodeSet Show source ``` static VALUE rb_xml_node_children(VALUE self) { xmlNodePtr node; xmlNodePtr child; xmlNodeSetPtr set; VALUE document; VALUE node_set; Noko_Node_Get_Struct(self, xmlNode, node); child = node->children; set = xmlXPathNodeSetCreate(child); document = DOC_RUBY_OBJECT(node->doc); if (!child) { return noko_xml_node_set_wrap(set, document); } child = child->next; while (NULL != child) { xmlXPathNodeSetAddUnique(set, child); child = child->next; } node_set = noko_xml_node_set_wrap(set, document); return node_set; } ``` Returns [`Nokogiri::XML::NodeSet`](nodeset) containing this node’s children. document() β†’ Nokogiri::XML::Document Show source ``` static VALUE rb_xml_node_document(VALUE self) { xmlNodePtr node; Noko_Node_Get_Struct(self, xmlNode, node); return DOC_RUBY_OBJECT(node->doc); } ``` Returns Parent [`Nokogiri::XML::Document`](document) for this node [](name) β†’ (String, nil) Show source ``` # File lib/nokogiri/xml/node.rb, line 512 def [](name) get(name.to_s) end ``` Fetch an attribute from this node. ⚠ Note that attributes with namespaces cannot be accessed with this method. To access namespaced attributes, use [`#attribute_with_ns`](node#method-i-attribute_with_ns). Returns (String, nil) value of the attribute `name`, or `nil` if no matching attribute exists **Example** ``` doc = Nokogiri::XML("<root><child size='large' class='big wide tall'/></root>") child = doc.at_css("child") child["size"] # => "large" child["class"] # => "big wide tall" ``` **Example:** Namespaced attributes will not be returned. ⚠ Note namespaced attributes may be accessed with [`#attribute`](node#method-i-attribute) or [`#attribute_with_ns`](node#method-i-attribute_with_ns) ``` doc = Nokogiri::XML(<<~EOF) <root xmlns:width='http://example.com/widths'> <child width:size='broad'/> </root> EOF doc.at_css("child")["size"] # => nil doc.at_css("child").attribute("size").value # => "broad" doc.at_css("child").attribute_with_ns("size", "http://example.com/widths").value # => "broad" ``` Also aliased as: [get\_attribute](node#method-i-get_attribute), [attr](node#method-i-attr) []=(name, value) β†’ value Show source ``` # File lib/nokogiri/xml/node.rb, line 550 def []=(name, value) set(name.to_s, value.to_s) end ``` Update the attribute `name` to `value`, or create the attribute if it does not exist. ⚠ Note that attributes with namespaces cannot be accessed with this method. To access namespaced attributes for update, use [`#attribute_with_ns`](node#method-i-attribute_with_ns). To add a namespaced attribute, see the example below. Returns `value` **Example** ``` doc = Nokogiri::XML("<root><child/></root>") child = doc.at_css("child") child["size"] = "broad" child.to_html # => "<child size=\"broad\"></child>" ``` **Example:** Add a namespaced attribute. ``` doc = Nokogiri::XML(<<~EOF) <root xmlns:width='http://example.com/widths'> <child/> </root> EOF child = doc.at_css("child") child["size"] = "broad" ns = doc.root.namespace_definitions.find { |ns| ns.prefix == "width" } child.attribute("size").namespace = ns doc.to_html # => "<root xmlns:width=\"http://example.com/widths\">\n" + # " <child width:size=\"broad\"></child>\n" + # "</root>\n" ``` Also aliased as: [set\_attribute](node#method-i-set_attribute) add\_class(names) β†’ self Show source ``` # File lib/nokogiri/xml/node.rb, line 715 def add_class(names) kwattr_add("class", names) end ``` Ensure [`HTML`](../html4) [`CSS`](../css) classes are present on `self`. Any [`CSS`](../css) classes in `names` that already exist in the β€œclass” attribute are *not* added. Note that any existing duplicates in the β€œclass” attribute are not removed. Compare with [`#append_class`](node#method-i-append_class). This is a convenience function and is equivalent to: ``` node.kwattr_add("class", names) ``` See related: [`#kwattr_add`](node#method-i-kwattr_add), [`#classes`](node#method-i-classes), [`#append_class`](node#method-i-append_class), [`#remove_class`](node#method-i-remove_class) Parameters * `names` (String, Array<String>) [`CSS`](../css) class names to be added to the Node’s β€œclass” attribute. May be a string containing whitespace-delimited names, or an Array of String names. Any class names already present will not be added. Any class names not present will be added. If no β€œclass” attribute exists, one is created. Returns `self` ([`Node`](node)) for ease of chaining method calls. **Example:** Ensure that the node has [`CSS`](../css) class β€œsection” ``` node # => <div></div> node.add_class("section") # => <div class="section"></div> node.add_class("section") # => <div class="section"></div> # duplicate not added ``` **Example:** Ensure that the node has [`CSS`](../css) classes β€œsection” and β€œheader”, via a String argument Note that the [`CSS`](../css) class β€œsection” is not added because it is already present. Note also that the pre-existing duplicate [`CSS`](../css) class β€œsection” is not removed. ``` node # => <div class="section section"></div> node.add_class("section header") # => <div class="section section header"></div> ``` **Example:** Ensure that the node has [`CSS`](../css) classes β€œsection” and β€œheader”, via an Array argument ``` node # => <div></div> node.add_class(["section", "header"]) # => <div class="section header"></div> ``` append\_class(names) β†’ self Show source ``` # File lib/nokogiri/xml/node.rb, line 759 def append_class(names) kwattr_append("class", names) end ``` Add [`HTML`](../html4) [`CSS`](../css) classes to `self`, regardless of duplication. Compare with [`#add_class`](node#method-i-add_class). This is a convenience function and is equivalent to: ``` node.kwattr_append("class", names) ``` See related: [`#kwattr_append`](node#method-i-kwattr_append), [`#classes`](node#method-i-classes), [`#add_class`](node#method-i-add_class), [`#remove_class`](node#method-i-remove_class) Parameters * `names` (String, Array<String>) [`CSS`](../css) class names to be appended to the Node’s β€œclass” attribute. May be a string containing whitespace-delimited names, or an Array of String names. All class names passed in will be appended to the β€œclass” attribute even if they are already present in the attribute value. If no β€œclass” attribute exists, one is created. Returns `self` ([`Node`](node)) for ease of chaining method calls. **Example:** Append β€œsection” to the node’s [`CSS`](../css) β€œclass” attribute ``` node # => <div></div> node.append_class("section") # => <div class="section"></div> node.append_class("section") # => <div class="section section"></div> # duplicate added! ``` **Example:** Append β€œsection” and β€œheader” to the noded’s [`CSS`](../css) β€œclass” attribute, via a String argument Note that the [`CSS`](../css) class β€œsection” is appended even though it is already present ``` node # => <div class="section section"></div> node.append_class("section header") # => <div class="section section section header"></div> ``` **Example:** Append β€œsection” and β€œheader” to the node’s [`CSS`](../css) β€œclass” attribute, via an Array argument ``` node # => <div></div> node.append_class(["section", "header"]) # => <div class="section header"></div> node.append_class(["section", "header"]) # => <div class="section header section header"></div> ``` attr(name) Alias for: [[]](node#method-i-5B-5D) attribute(name) β†’ Nokogiri::XML::Attr Show source ``` static VALUE rb_xml_node_attribute(VALUE self, VALUE name) { xmlNodePtr node; xmlAttrPtr prop; Noko_Node_Get_Struct(self, xmlNode, node); prop = xmlHasProp(node, (xmlChar *)StringValueCStr(name)); if (! prop) { return Qnil; } return noko_xml_node_wrap(Qnil, (xmlNodePtr)prop); } ``` Returns Attribute ([`Nokogiri::XML::Attr`](attr)) belonging to this node with name `name`. ⚠ Note that attribute namespaces are ignored and only the simple (non-namespace-prefixed) name is used to find a matching attribute. In case of a simple name collision, only one of the matching attributes will be returned. In this case, you will need to use [`#attribute_with_ns`](node#method-i-attribute_with_ns). **Example:** ``` doc = Nokogiri::XML("<root><child size='large' class='big wide tall'/></root>") child = doc.at_css("child") child.attribute("size") # => #<Nokogiri::XML::Attr:0x550 name="size" value="large"> child.attribute("class") # => #<Nokogiri::XML::Attr:0x564 name="class" value="big wide tall"> ``` **Example** showing that namespaced attributes will not be returned: ⚠ Note that only one of the two matching attributes is returned. ``` doc = Nokogiri::XML(<<~EOF) <root xmlns:width='http://example.com/widths' xmlns:height='http://example.com/heights'> <child width:size='broad' height:size='tall'/> </root> EOF doc.at_css("child").attribute("size") # => #(Attr:0x550 { # name = "size", # namespace = #(Namespace:0x564 { # prefix = "width", # href = "http://example.com/widths" # }), # value = "broad" # }) ``` attribute\_nodes() β†’ Array<Nokogiri::XML::Attr> Show source ``` static VALUE rb_xml_node_attribute_nodes(VALUE rb_node) { xmlNodePtr c_node; Noko_Node_Get_Struct(rb_node, xmlNode, c_node); return noko_xml_node_attrs(c_node); } ``` Returns Attributes (an Array of [`Nokogiri::XML::Attr`](attr)) belonging to this node. Note that this is the preferred alternative to [`#attributes`](node#method-i-attributes) when the simple (non-namespace-prefixed) attribute names may collide. **Example:** Contrast this with the colliding-name example from [`#attributes`](node#method-i-attributes). ``` doc = Nokogiri::XML(<<~EOF) <root xmlns:width='http://example.com/widths' xmlns:height='http://example.com/heights'> <child width:size='broad' height:size='tall'/> </root> EOF doc.at_css("child").attribute_nodes # => [#(Attr:0x550 { # name = "size", # namespace = #(Namespace:0x564 { # prefix = "width", # href = "http://example.com/widths" # }), # value = "broad" # }), # #(Attr:0x578 { # name = "size", # namespace = #(Namespace:0x58c { # prefix = "height", # href = "http://example.com/heights" # }), # value = "tall" # })] ``` attribute\_with\_ns(name, namespace) β†’ Nokogiri::XML::Attr Show source ``` static VALUE rb_xml_node_attribute_with_ns(VALUE self, VALUE name, VALUE namespace) { xmlNodePtr node; xmlAttrPtr prop; Noko_Node_Get_Struct(self, xmlNode, node); prop = xmlHasNsProp(node, (xmlChar *)StringValueCStr(name), NIL_P(namespace) ? NULL : (xmlChar *)StringValueCStr(namespace)); if (! prop) { return Qnil; } return noko_xml_node_wrap(Qnil, (xmlNodePtr)prop); } ``` Returns Attribute ([`Nokogiri::XML::Attr`](attr)) belonging to this node with matching `name` and `namespace`. * `name` (String): the simple (non-namespace-prefixed) name of the attribute * `namespace` (String): the URI of the attribute’s namespace See related: [`#attribute`](node#method-i-attribute) **Example:** ``` doc = Nokogiri::XML(<<~EOF) <root xmlns:width='http://example.com/widths' xmlns:height='http://example.com/heights'> <child width:size='broad' height:size='tall'/> </root> EOF doc.at_css("child").attribute_with_ns("size", "http://example.com/widths") # => #(Attr:0x550 { # name = "size", # namespace = #(Namespace:0x564 { # prefix = "width", # href = "http://example.com/widths" # }), # value = "broad" # }) doc.at_css("child").attribute_with_ns("size", "http://example.com/heights") # => #(Attr:0x578 { # name = "size", # namespace = #(Namespace:0x58c { # prefix = "height", # href = "http://example.com/heights" # }), # value = "tall" # }) ``` attributes() β†’ Hash<String β‡’ Nokogiri::XML::Attr> Show source ``` # File lib/nokogiri/xml/node.rb, line 609 def attributes attribute_nodes.each_with_object({}) do |node, hash| hash[node.node_name] = node end end ``` Fetch this node’s attributes. ⚠ Because the keys do not include any namespace information for the attribute, in case of a simple name collision, not all attributes will be returned. In this case, you will need to use [`#attribute_nodes`](node#method-i-attribute_nodes). Returns Hash containing attributes belonging to `self`. The hash keys are String attribute names (without the namespace), and the hash values are [`Nokogiri::XML::Attr`](attr). **Example** with no namespaces: ``` doc = Nokogiri::XML("<root><child size='large' class='big wide tall'/></root>") doc.at_css("child").attributes # => {"size"=>#(Attr:0x550 { name = "size", value = "large" }), # "class"=>#(Attr:0x564 { name = "class", value = "big wide tall" })} ``` **Example** with a namespace: ``` doc = Nokogiri::XML("<root xmlns:desc='http://example.com/sizes'><child desc:size='large'/></root>") doc.at_css("child").attributes # => {"size"=> # #(Attr:0x550 { # name = "size", # namespace = #(Namespace:0x564 { # prefix = "desc", # href = "http://example.com/sizes" # }), # value = "large" # })} ``` **Example** with an attribute name collision: ⚠ Note that only one of the attributes is returned in the Hash. ``` doc = Nokogiri::XML(<<~EOF) <root xmlns:width='http://example.com/widths' xmlns:height='http://example.com/heights'> <child width:size='broad' height:size='tall'/> </root> EOF doc.at_css("child").attributes # => {"size"=> # #(Attr:0x550 { # name = "size", # namespace = #(Namespace:0x564 { # prefix = "height", # href = "http://example.com/heights" # }), # value = "tall" # })} ``` classes() β†’ Array<String> Show source ``` # File lib/nokogiri/xml/node.rb, line 669 def classes kwattr_values("class") end ``` Fetch [`CSS`](../css) class names of a [`Node`](node). This is a convenience function and is equivalent to: ``` node.kwattr_values("class") ``` See related: [`#kwattr_values`](node#method-i-kwattr_values), [`#add_class`](node#method-i-add_class), [`#append_class`](node#method-i-append_class), [`#remove_class`](node#method-i-remove_class) Returns The [`CSS`](../css) classes (Array of String) present in the Node’s β€œclass” attribute. If the attribute is empty or non-existent, the return value is an empty array. **Example** ``` node # => <div class="section title header"></div> node.classes # => ["section", "title", "header"] ``` delete(name) Alias for: [remove\_attribute](node#method-i-remove_attribute) each() { |node\_name, value| ... } Show source ``` # File lib/nokogiri/xml/node.rb, line 635 def each attribute_nodes.each do |node| yield [node.node_name, node.value] end end ``` Iterate over each attribute name and value pair for this [`Node`](node). get\_attribute(name) Alias for: [[]](node#method-i-5B-5D) has\_attribute?(p1) Alias for: [key?](node#method-i-key-3F) keys() Show source ``` # File lib/nokogiri/xml/node.rb, line 629 def keys attribute_nodes.map(&:node_name) end ``` Get the attribute names for this [`Node`](node). kwattr\_add(attribute\_name, keywords) β†’ self Show source ``` # File lib/nokogiri/xml/node.rb, line 892 def kwattr_add(attribute_name, keywords) keywords = keywordify(keywords) current_kws = kwattr_values(attribute_name) new_kws = (current_kws + (keywords - current_kws)).join(" ") set_attribute(attribute_name, new_kws) self end ``` Ensure that values are present in a keyword attribute. Any values in `keywords` that already exist in the Node’s attribute values are *not* added. Note that any existing duplicates in the attribute values are not removed. Compare with [`#kwattr_append`](node#method-i-kwattr_append). A β€œkeyword attribute” is a node attribute that contains a set of space-delimited values. Perhaps the most familiar example of this is the [`HTML`](../html4) β€œclass” attribute used to contain [`CSS`](../css) classes. But other keyword attributes exist, for instance [the β€œrel” attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/rel). See also [`#add_class`](node#method-i-add_class), [`#kwattr_values`](node#method-i-kwattr_values), [`#kwattr_append`](node#method-i-kwattr_append), [`#kwattr_remove`](node#method-i-kwattr_remove) Parameters * `attribute_name` (String) The name of the keyword attribute to be modified. * `keywords` (String, Array<String>) Keywords to be added to the attribute named `attribute_name`. May be a string containing whitespace-delimited values, or an Array of String values. Any values already present will not be added. Any values not present will be added. If the named attribute does not exist, it is created. Returns `self` ([`Nokogiri::XML::Node`](node)) for ease of chaining method calls. **Example:** Ensure that a `Node` has β€œnofollow” in its `rel` attribute. Note that duplicates are not added. ``` node # => <a></a> node.kwattr_add("rel", "nofollow") # => <a rel="nofollow"></a> node.kwattr_add("rel", "nofollow") # => <a rel="nofollow"></a> ``` **Example:** Ensure that a `Node` has β€œnofollow” and β€œnoreferrer” in its `rel` attribute, via a String argument. ``` Note that "nofollow" is not added because it is already present. Note also that the pre-existing duplicate "nofollow" is not removed. node # => <a rel="nofollow nofollow"></a> node.kwattr_add("rel", "nofollow noreferrer") # => <a rel="nofollow nofollow noreferrer"></a> ``` **Example:** Ensure that a `Node` has β€œnofollow” and β€œnoreferrer” in its `rel` attribute, via an Array argument. ``` node # => <a></a> node.kwattr_add("rel", ["nofollow", "noreferrer"]) # => <a rel="nofollow noreferrer"></a> ``` Since v1.11.0 kwattr\_append(attribute\_name, keywords) β†’ self Show source ``` # File lib/nokogiri/xml/node.rb, line 945 def kwattr_append(attribute_name, keywords) keywords = keywordify(keywords) current_kws = kwattr_values(attribute_name) new_kws = (current_kws + keywords).join(" ") set_attribute(attribute_name, new_kws) self end ``` Add keywords to a Node’s keyword attribute, regardless of duplication. Compare with [`#kwattr_add`](node#method-i-kwattr_add). A β€œkeyword attribute” is a node attribute that contains a set of space-delimited values. Perhaps the most familiar example of this is the [`HTML`](../html4) β€œclass” attribute used to contain [`CSS`](../css) classes. But other keyword attributes exist, for instance [the β€œrel” attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/rel). See also [`#append_class`](node#method-i-append_class), [`#kwattr_values`](node#method-i-kwattr_values), [`#kwattr_add`](node#method-i-kwattr_add), [`#kwattr_remove`](node#method-i-kwattr_remove) Parameters * `attribute_name` (String) The name of the keyword attribute to be modified. * `keywords` (String, Array<String>) Keywords to be added to the attribute named `attribute_name`. May be a string containing whitespace-delimited values, or an Array of String values. All values passed in will be appended to the named attribute even if they are already present in the attribute. If the named attribute does not exist, it is created. Returns `self` ([`Node`](node)) for ease of chaining method calls. **Example:** Append β€œnofollow” to the `rel` attribute. Note that duplicates are added. ``` node # => <a></a> node.kwattr_append("rel", "nofollow") # => <a rel="nofollow"></a> node.kwattr_append("rel", "nofollow") # => <a rel="nofollow nofollow"></a> ``` **Example:** Append β€œnofollow” and β€œnoreferrer” to the `rel` attribute, via a String argument. Note that β€œnofollow” is appended even though it is already present. ``` node # => <a rel="nofollow"></a> node.kwattr_append("rel", "nofollow noreferrer") # => <a rel="nofollow nofollow noreferrer"></a> ``` **Example:** Append β€œnofollow” and β€œnoreferrer” to the `rel` attribute, via an Array argument. ``` node # => <a></a> node.kwattr_append("rel", ["nofollow", "noreferrer"]) # => <a rel="nofollow noreferrer"></a> ``` Since v1.11.0 kwattr\_remove(attribute\_name, keywords) β†’ self Show source ``` # File lib/nokogiri/xml/node.rb, line 988 def kwattr_remove(attribute_name, keywords) if keywords.nil? remove_attribute(attribute_name) return self end keywords = keywordify(keywords) current_kws = kwattr_values(attribute_name) new_kws = current_kws - keywords if new_kws.empty? remove_attribute(attribute_name) else set_attribute(attribute_name, new_kws.join(" ")) end self end ``` Remove keywords from a keyword attribute. Any matching keywords that exist in the named attribute are removed, including any multiple entries. If no keywords remain after this operation, or if `keywords` is `nil`, the attribute is deleted from the node. A β€œkeyword attribute” is a node attribute that contains a set of space-delimited values. Perhaps the most familiar example of this is the [`HTML`](../html4) β€œclass” attribute used to contain [`CSS`](../css) classes. But other keyword attributes exist, for instance [the β€œrel” attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/rel). See also [`#remove_class`](node#method-i-remove_class), [`#kwattr_values`](node#method-i-kwattr_values), [`#kwattr_add`](node#method-i-kwattr_add), [`#kwattr_append`](node#method-i-kwattr_append) Parameters * `attribute_name` (String) The name of the keyword attribute to be modified. * `keywords` (String, Array<String>) Keywords to be removed from the attribute named `attribute_name`. May be a string containing whitespace-delimited values, or an Array of String values. Any keywords present in the named attribute will be removed. If no keywords remain, or if `keywords` is nil, the attribute is deleted. Returns `self` ([`Node`](node)) for ease of chaining method calls. **Example:** Note that the `rel` attribute is deleted when empty. ``` node # => <a rel="nofollow noreferrer">link</a> node.kwattr_remove("rel", "nofollow") # => <a rel="noreferrer">link</a> node.kwattr_remove("rel", "noreferrer") # => <a>link</a> ``` Since v1.11.0 kwattr\_values(attribute\_name) β†’ Array<String> Show source ``` # File lib/nokogiri/xml/node.rb, line 838 def kwattr_values(attribute_name) keywordify(get_attribute(attribute_name) || []) end ``` Fetch values from a keyword attribute of a [`Node`](node). A β€œkeyword attribute” is a node attribute that contains a set of space-delimited values. Perhaps the most familiar example of this is the [`HTML`](../html4) β€œclass” attribute used to contain [`CSS`](../css) classes. But other keyword attributes exist, for instance [the β€œrel” attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Attributes/rel). See also [`#classes`](node#method-i-classes), [`#kwattr_add`](node#method-i-kwattr_add), [`#kwattr_append`](node#method-i-kwattr_append), [`#kwattr_remove`](node#method-i-kwattr_remove) Parameters * `attribute_name` (String) The name of the keyword attribute to be inspected. Returns (Array<String>) The values present in the Node’s `attribute_name` attribute. If the attribute is empty or non-existent, the return value is an empty array. **Example:** ``` node # => <a rel="nofollow noopener external">link</a> node.kwattr_values("rel") # => ["nofollow", "noopener", "external"] ``` Since v1.11.0 remove\_attribute(name) Show source ``` # File lib/nokogiri/xml/node.rb, line 643 def remove_attribute(name) attr = attributes[name].remove if key?(name) clear_xpath_context if Nokogiri.jruby? attr end ``` Remove the attribute named `name` Also aliased as: [delete](node#method-i-delete) remove\_class(css\_classes) β†’ self Show source ``` # File lib/nokogiri/xml/node.rb, line 809 def remove_class(names = nil) kwattr_remove("class", names) end ``` Remove [`HTML`](../html4) [`CSS`](../css) classes from this node. Any [`CSS`](../css) class names in `css_classes` that exist in this node’s β€œclass” attribute are removed, including any multiple entries. If no [`CSS`](../css) classes remain after this operation, or if `css_classes` is `nil`, the β€œclass” attribute is deleted from the node. This is a convenience function and is equivalent to: ``` node.kwattr_remove("class", css_classes) ``` Also see [`#kwattr_remove`](node#method-i-kwattr_remove), [`#classes`](node#method-i-classes), [`#add_class`](node#method-i-add_class), [`#append_class`](node#method-i-append_class) Parameters * `css_classes` (String, Array<String>) [`CSS`](../css) class names to be removed from the Node’s β€œclass” attribute. May be a string containing whitespace-delimited names, or an Array of String names. Any class names already present will be removed. If no [`CSS`](../css) classes remain, the β€œclass” attribute is deleted. Returns `self` ([`Nokogiri::XML::Node`](node)) for ease of chaining method calls. **Example**: Deleting a [`CSS`](../css) class Note that all instances of the class β€œsection” are removed from the β€œclass” attribute. ``` node # => <div class="section header section"></div> node.remove_class("section") # => <div class="header"></div> ``` **Example**: Deleting the only remaining [`CSS`](../css) class Note that the attribute is removed once there are no remaining classes. ``` node # => <div class="section"></div> node.remove_class("section") # => <div></div> ``` **Example**: Deleting multiple [`CSS`](../css) classes Note that the β€œclass” attribute is deleted once it’s empty. ``` node # => <div class="section header float"></div> node.remove_class(["section", "float"]) # => <div class="header"></div> ``` []=(name, value) β†’ value Alias for: [[]=](node#method-i-5B-5D-3D) value?(value) Show source ``` # File lib/nokogiri/xml/node.rb, line 623 def value?(value) values.include?(value) end ``` Does this Node’s attributes include <value> values() Show source ``` # File lib/nokogiri/xml/node.rb, line 617 def values attribute_nodes.map(&:value) end ``` Get the attribute values for this [`Node`](node).
programming_docs
nokogiri module Nokogiri::XML::XPath module Nokogiri::XML::XPath ============================ CURRENT\_SEARCH\_PREFIX The [`XPath`](xpath) search prefix to search direct descendants of the current element, `./` GLOBAL\_SEARCH\_PREFIX The [`XPath`](xpath) search prefix to search globally, `//` ROOT\_SEARCH\_PREFIX The [`XPath`](xpath) search prefix to search direct descendants of the root element, `/` SUBTREE\_SEARCH\_PREFIX The [`XPath`](xpath) search prefix to search anywhere in the current element’s subtree, `.//` nokogiri class Nokogiri::XML::DTD class Nokogiri::XML::DTD ========================= Parent: cNokogiriXmlNode [`Nokogiri::XML::DTD`](dtd) wraps [`DTD`](dtd) nodes in an [`XML`](../xml) document attributes Show source ``` static VALUE attributes(VALUE self) { xmlDtdPtr dtd; VALUE hash; Noko_Node_Get_Struct(self, xmlDtd, dtd); hash = rb_hash_new(); if (!dtd->attributes) { return hash; } xmlHashScan((xmlHashTablePtr)dtd->attributes, element_copier, (void *)hash); return hash; } ``` Get a hash of the attributes for this [`DTD`](dtd). each() { |key, value| ... } Show source ``` # File lib/nokogiri/xml/dtd.rb, line 17 def each attributes.each do |key, value| yield([key, value]) end end ``` elements Show source ``` static VALUE elements(VALUE self) { xmlDtdPtr dtd; VALUE hash; Noko_Node_Get_Struct(self, xmlDtd, dtd); if (!dtd->elements) { return Qnil; } hash = rb_hash_new(); xmlHashScan((xmlHashTablePtr)dtd->elements, element_copier, (void *)hash); return hash; } ``` Get a hash of the elements for this [`DTD`](dtd). entities Show source ``` static VALUE entities(VALUE self) { xmlDtdPtr dtd; VALUE hash; Noko_Node_Get_Struct(self, xmlDtd, dtd); if (!dtd->entities) { return Qnil; } hash = rb_hash_new(); xmlHashScan((xmlHashTablePtr)dtd->entities, element_copier, (void *)hash); return hash; } ``` Get a hash of the elements for this [`DTD`](dtd). external\_id Show source ``` static VALUE external_id(VALUE self) { xmlDtdPtr dtd; Noko_Node_Get_Struct(self, xmlDtd, dtd); if (!dtd->ExternalID) { return Qnil; } return NOKOGIRI_STR_NEW2(dtd->ExternalID); } ``` Get the External ID for this [`DTD`](dtd) html5\_dtd?() Show source ``` # File lib/nokogiri/xml/dtd.rb, line 27 def html5_dtd? html_dtd? && external_id.nil? && (system_id.nil? || system_id == "about:legacy-compat") end ``` html\_dtd?() Show source ``` # File lib/nokogiri/xml/dtd.rb, line 23 def html_dtd? name.casecmp("html").zero? end ``` keys() Show source ``` # File lib/nokogiri/xml/dtd.rb, line 13 def keys attributes.keys end ``` notations() β†’ Hash<name(String)β‡’Notation> Show source ``` static VALUE notations(VALUE self) { xmlDtdPtr dtd; VALUE hash; Noko_Node_Get_Struct(self, xmlDtd, dtd); if (!dtd->notations) { return Qnil; } hash = rb_hash_new(); xmlHashScan((xmlHashTablePtr)dtd->notations, notation_copier, (void *)hash); return hash; } ``` Returns All the notations for this [`DTD`](dtd) in a Hash of [`Notation`](notation) `name` to [`Notation`](notation). system\_id Show source ``` static VALUE system_id(VALUE self) { xmlDtdPtr dtd; Noko_Node_Get_Struct(self, xmlDtd, dtd); if (!dtd->SystemID) { return Qnil; } return NOKOGIRI_STR_NEW2(dtd->SystemID); } ``` Get the System ID for this [`DTD`](dtd) validate(document) Show source ``` static VALUE validate(VALUE self, VALUE document) { xmlDocPtr doc; xmlDtdPtr dtd; xmlValidCtxtPtr ctxt; VALUE error_list; Noko_Node_Get_Struct(self, xmlDtd, dtd); Noko_Node_Get_Struct(document, xmlDoc, doc); error_list = rb_ary_new(); ctxt = xmlNewValidCtxt(); xmlSetStructuredErrorFunc((void *)error_list, Nokogiri_error_array_pusher); xmlValidateDtd(ctxt, doc, dtd); xmlSetStructuredErrorFunc(NULL, NULL); xmlFreeValidCtxt(ctxt); return error_list; } ``` Validate `document` returning a list of errors nokogiri class Nokogiri::XML::Builder class Nokogiri::XML::Builder ============================= Parent: [Object](https://nokogiri.org/rdoc/Object.html) Included modules: [Nokogiri::ClassResolver](../classresolver) [`Nokogiri`](../../nokogiri) builder can be used for building [`XML`](../xml) and [`HTML`](../html4) documents. Synopsis: --------- ``` builder = Nokogiri::XML::Builder.new do |xml| xml.root { xml.products { xml.widget { xml.id_ "10" xml.name "Awesome widget" } } } end puts builder.to_xml ``` Will output: ``` <?xml version="1.0"?> <root> <products> <widget> <id>10</id> <name>Awesome widget</name> </widget> </products> </root> ``` ### [`Builder`](builder) scope The builder allows two forms. When the builder is supplied with a block that has a parameter, the outside scope is maintained. This means you can access variables that are outside your builder. If you don’t need outside scope, you can use the builder without the β€œxml” prefix like this: ``` builder = Nokogiri::XML::Builder.new do root { products { widget { id_ "10" name "Awesome widget" } } } end ``` Special Tags ------------ The builder works by taking advantage of method\_missing. Unfortunately some methods are defined in ruby that are difficult or dangerous to remove. You may want to create tags with the name β€œtype”, β€œclass”, and β€œid” for example. In that case, you can use an underscore to disambiguate your tag name from the method call. Here is an example of using the underscore to disambiguate tag names from ruby methods: ``` @objects = [Object.new, Object.new, Object.new] builder = Nokogiri::XML::Builder.new do |xml| xml.root { xml.objects { @objects.each do |o| xml.object { xml.type_ o.type xml.class_ o.class.name xml.id_ o.id } end } } end puts builder.to_xml ``` The underscore may be used with any tag name, and the last underscore will just be removed. This code will output the following XML: ``` <?xml version="1.0"?> <root> <objects> <object> <type>Object</type> <class>Object</class> <id>48390</id> </object> <object> <type>Object</type> <class>Object</class> <id>48380</id> </object> <object> <type>Object</type> <class>Object</class> <id>48370</id> </object> </objects> </root> ``` Tag Attributes -------------- Tag attributes may be supplied as method arguments. Here is our previous example, but using attributes rather than tags: ``` @objects = [Object.new, Object.new, Object.new] builder = Nokogiri::XML::Builder.new do |xml| xml.root { xml.objects { @objects.each do |o| xml.object(:type => o.type, :class => o.class, :id => o.id) end } } end puts builder.to_xml ``` ### Tag Attribute Short Cuts A couple attribute short cuts are available when building tags. The short cuts are available by special method calls when building a tag. This example builds an β€œobject” tag with the class attribute β€œclassy” and the id of β€œthing”: ``` builder = Nokogiri::XML::Builder.new do |xml| xml.root { xml.objects { xml.object.classy.thing! } } end puts builder.to_xml ``` Which will output: ``` <?xml version="1.0"?> <root> <objects> <object class="classy" id="thing"/> </objects> </root> ``` All other options are still supported with this syntax, including blocks and extra tag attributes. Namespaces ---------- Namespaces are added similarly to attributes. [`Nokogiri::XML::Builder`](builder) assumes that when an attribute starts with β€œxmlns”, it is meant to be a namespace: ``` builder = Nokogiri::XML::Builder.new { |xml| xml.root('xmlns' => 'default', 'xmlns:foo' => 'bar') do xml.tenderlove end } puts builder.to_xml ``` Will output [`XML`](../xml) like this: ``` <?xml version="1.0"?> <root xmlns:foo="bar" xmlns="default"> <tenderlove/> </root> ``` ### Referencing declared namespaces Tags that reference non-default namespaces (i.e. a tag β€œfoo:bar”) can be built by using the [`Nokogiri::XML::Builder#[]`](builder#method-i-5B-5D) method. For example: ``` builder = Nokogiri::XML::Builder.new do |xml| xml.root('xmlns:foo' => 'bar') { xml.objects { xml['foo'].object.classy.thing! } } end puts builder.to_xml ``` Will output this XML: ``` <?xml version="1.0"?> <root xmlns:foo="bar"> <objects> <foo:object class="classy" id="thing"/> </objects> </root> ``` Note the β€œfoo:object” tag. ### [`Namespace`](namespace) inheritance In the [`Builder`](builder) context, children will inherit their parent’s namespace. This is the same behavior as if the underlying {XML::Document} set `namespace_inheritance` to `true`: ``` result = Nokogiri::XML::Builder.new do |xml| xml["soapenv"].Envelope("xmlns:soapenv" => "http://schemas.xmlsoap.org/soap/envelope/") do xml.Header end end result.doc.to_xml # => <?xml version="1.0" encoding="utf-8"?> # <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"> # <soapenv:Header/> # </soapenv:Envelope> ``` Users may turn this behavior off by passing a keyword argument `namespace_inheritance:false` to the initializer: ``` result = Nokogiri::XML::Builder.new(namespace_inheritance: false) do |xml| xml["soapenv"].Envelope("xmlns:soapenv" => "http://schemas.xmlsoap.org/soap/envelope/") do xml.Header xml["soapenv"].Body # users may explicitly opt into the namespace end end result.doc.to_xml # => <?xml version="1.0" encoding="utf-8"?> # <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"> # <Header/> # <soapenv:Body/> # </soapenv:Envelope> ``` For more information on namespace inheritance, please see {XML::Document#namespace\_inheritance} [`Document`](document) Types ----------------------------- To create a document type ([`DTD`](dtd)), use the [`Builder#doc`](builder#attribute-i-doc) method to get the current context document. Then call [`Node#create_internal_subset`](node#method-i-create_internal_subset) to create the [`DTD`](dtd) node. For example, this Ruby: ``` builder = Nokogiri::XML::Builder.new do |xml| xml.doc.create_internal_subset( 'html', "-//W3C//DTD HTML 4.01 Transitional//EN", "http://www.w3.org/TR/html4/loose.dtd" ) xml.root do xml.foo end end puts builder.to_xml ``` Will output this xml: ``` <?xml version="1.0"?> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <root> <foo/> </root> ``` DEFAULT\_DOCUMENT\_OPTIONS VALID\_NAMESPACES Included from [Nokogiri::ClassResolver](../classresolver) [`related_class`](builder#method-i-related_class) restricts matching namespaces to those matching this set. context[RW] A context object for use when the block has no arguments doc[RW] The current [`Document`](document) object being built parent[RW] The parent of the current node being built new(options = {}, root = nil) { |self| ... } Show source ``` # File lib/nokogiri/xml/builder.rb, line 307 def initialize(options = {}, root = nil, &block) if root @doc = root.document @parent = root else @parent = @doc = related_class("Document").new end @context = nil @arity = nil @ns = nil options = DEFAULT_DOCUMENT_OPTIONS.merge(options) options.each do |k, v| @doc.send(:"#{k}=", v) end return unless block @arity = block.arity if @arity <= 0 @context = eval("self", block.binding) instance_eval(&block) else yield self end @parent = @doc end ``` Create a new [`Builder`](builder) object. `options` are sent to the top level [`Document`](document) that is being built. Building a document with a particular encoding for example: ``` Nokogiri::XML::Builder.new(:encoding => 'UTF-8') do |xml| ... end ``` with(root, &block) Show source ``` # File lib/nokogiri/xml/builder.rb, line 294 def self.with(root, &block) new({}, root, &block) end ``` Create a builder with an existing root object. This is for use when you have an existing document that you would like to augment with builder methods. The builder context created will start with the given `root` node. For example: ``` doc = Nokogiri::XML(File.read('somedoc.xml')) Nokogiri::XML::Builder.with(doc.at_css('some_tag')) do |xml| # ... Use normal builder methods here ... xml.awesome # add the "awesome" tag below "some_tag" end ``` <<(string) Show source ``` # File lib/nokogiri/xml/builder.rb, line 390 def <<(string) @doc.fragment(string).children.each { |x| insert(x) } end ``` Append the given raw [`XML`](../xml) `string` to the document [](ns) Show source ``` # File lib/nokogiri/xml/builder.rb, line 358 def [](ns) if @parent != @doc @ns = @parent.namespace_definitions.find { |x| x.prefix == ns.to_s } end return self if @ns @parent.ancestors.each do |a| next if a == doc @ns = a.namespace_definitions.find { |x| x.prefix == ns.to_s } return self if @ns end @ns = { pending: ns.to_s } self end ``` Build a tag that is associated with namespace `ns`. Raises an ArgumentError if `ns` has not been defined higher in the tree. cdata(string) Show source ``` # File lib/nokogiri/xml/builder.rb, line 345 def cdata(string) insert(doc.create_cdata(string)) end ``` Create a [`CDATA`](cdata) [`Node`](node) with content of `string` comment(string) Show source ``` # File lib/nokogiri/xml/builder.rb, line 351 def comment(string) insert(doc.create_comment(string)) end ``` Create a [`Comment`](comment) [`Node`](node) with content of `string` related\_class(class\_name) β†’ Class Show source ``` # File lib/nokogiri/class_resolver.rb, line 46 def related_class(class_name) klass = nil inspecting = self.class while inspecting namespace_path = inspecting.name.split("::")[0..-2] inspecting = inspecting.superclass next unless VALID_NAMESPACES.include?(namespace_path.last) related_class_name = (namespace_path << class_name).join("::") klass = begin Object.const_get(related_class_name) rescue NameError nil end break if klass end klass end ``` Included from [Nokogiri::ClassResolver](../classresolver) Find a class constant within the Some examples: ``` Nokogiri::XML::Document.new.related_class("DocumentFragment") # => Nokogiri::XML::DocumentFragment Nokogiri::HTML4::Document.new.related_class("DocumentFragment") # => Nokogiri::HTML4::DocumentFragment ``` Note this will also work for subclasses that follow the same convention, e.g.: ``` Loofah::HTML::Document.new.related_class("DocumentFragment") # => Loofah::HTML::DocumentFragment ``` And even if it’s a subclass, this will iterate through the superclasses: ``` class ThisIsATopLevelClass < Nokogiri::HTML4::Builder ; end ThisIsATopLevelClass.new.related_class("Document") # => Nokogiri::HTML4::Document ``` text(string) Show source ``` # File lib/nokogiri/xml/builder.rb, line 339 def text(string) insert(@doc.create_text_node(string)) end ``` Create a [`Text`](text) [`Node`](node) with content of `string` to\_xml(\*args) Show source ``` # File lib/nokogiri/xml/builder.rb, line 377 def to_xml(*args) if Nokogiri.jruby? options = args.first.is_a?(Hash) ? args.shift : {} unless options[:save_with] options[:save_with] = Node::SaveOptions::AS_BUILDER end args.insert(0, options) end @doc.to_xml(*args) end ``` Convert this [`Builder`](builder) object to [`XML`](../xml) nokogiri class Nokogiri::XML::CDATA class Nokogiri::XML::CDATA =========================== Parent: cNokogiriXmlText CData represents a CData node in an xml document. new(document, content) Show source ``` static VALUE new (int argc, VALUE *argv, VALUE klass) { xmlDocPtr xml_doc; xmlNodePtr node; VALUE doc; VALUE content; VALUE rest; VALUE rb_node; xmlChar *content_str = NULL; int content_str_len = 0; rb_scan_args(argc, argv, "2*", &doc, &content, &rest); Noko_Node_Get_Struct(doc, xmlDoc, xml_doc); if (!NIL_P(content)) { content_str = (xmlChar *)StringValuePtr(content); content_str_len = RSTRING_LENINT(content); } node = xmlNewCDataBlock(xml_doc->doc, content_str, content_str_len); noko_xml_document_pin_node(node); rb_node = noko_xml_node_wrap(klass, node); rb_obj_call_init(rb_node, argc, argv); if (rb_block_given_p()) { rb_yield(rb_node); } return rb_node; } ``` Create a new [`CDATA`](cdata) element on the `document` with `content` If `content` cannot be implicitly converted to a string, this method will raise a TypeError exception. name() Show source ``` # File lib/nokogiri/xml/cdata.rb, line 8 def name "#cdata-section" end ``` Get the name of this [`CDATA`](cdata) node nokogiri class Nokogiri::XML::Schema class Nokogiri::XML::Schema ============================ Parent: [Object](https://nokogiri.org/rdoc/Object.html) [`Nokogiri::XML::Schema`](schema) is used for validating [`XML`](../xml) against a schema (usually from an xsd file). Synopsis -------- Validate an [`XML`](../xml) document against a [`Schema`](schema). Loop over the errors that are returned and print them out: ``` xsd = Nokogiri::XML::Schema(File.read(PO_SCHEMA_FILE)) doc = Nokogiri::XML(File.read(PO_XML_FILE)) xsd.validate(doc).each do |error| puts error.message end ``` The list of errors are [`Nokogiri::XML::SyntaxError`](syntaxerror) objects. NOTE: As of v1.11.0, [`Schema`](schema) treats inputs as UNTRUSTED by default, and so external entities are not resolved from the network (β€˜http://` or `ftp://`). Previously, parsing treated documents as β€œtrusted” by default which was counter to Nokogiri’s β€œuntrusted by default” security policy. If a document is trusted, then the caller may turn off the NONET option via the [`ParseOptions`](parseoptions) to re-enable external entity resolution over a network connection. errors[RW] Errors while parsing the schema file parse\_options[RW] The [`Nokogiri::XML::ParseOptions`](parseoptions) used to parse the schema from\_document(doc) Show source ``` static VALUE from_document(int argc, VALUE *argv, VALUE klass) { VALUE document; VALUE parse_options; int parse_options_int; xmlDocPtr doc; xmlSchemaParserCtxtPtr ctx; xmlSchemaPtr schema; VALUE errors; VALUE rb_schema; int scanned_args = 0; xmlExternalEntityLoader old_loader = 0; scanned_args = rb_scan_args(argc, argv, "11", &document, &parse_options); Noko_Node_Get_Struct(document, xmlDoc, doc); doc = doc->doc; /* In case someone passes us a node. ugh. */ if (scanned_args == 1) { parse_options = rb_const_get_at(rb_const_get_at(mNokogiriXml, rb_intern("ParseOptions")), rb_intern("DEFAULT_SCHEMA")); } parse_options_int = (int)NUM2INT(rb_funcall(parse_options, rb_intern("to_i"), 0)); if (has_blank_nodes_p(DOC_NODE_CACHE(doc))) { rb_raise(rb_eArgError, "Creating a schema from a document that has blank nodes exposed to Ruby is dangerous"); } ctx = xmlSchemaNewDocParserCtxt(doc); errors = rb_ary_new(); xmlSetStructuredErrorFunc((void *)errors, Nokogiri_error_array_pusher); #ifdef HAVE_XMLSCHEMASETPARSERSTRUCTUREDERRORS xmlSchemaSetParserStructuredErrors( ctx, Nokogiri_error_array_pusher, (void *)errors ); #endif if (parse_options_int & XML_PARSE_NONET) { old_loader = xmlGetExternalEntityLoader(); xmlSetExternalEntityLoader(xmlNoNetExternalEntityLoader); } schema = xmlSchemaParse(ctx); if (old_loader) { xmlSetExternalEntityLoader(old_loader); } xmlSetStructuredErrorFunc(NULL, NULL); xmlSchemaFreeParserCtxt(ctx); if (NULL == schema) { xmlErrorPtr error = xmlGetLastError(); if (error) { Nokogiri_error_raise(NULL, error); } else { rb_raise(rb_eRuntimeError, "Could not parse document"); } return Qnil; } rb_schema = Data_Wrap_Struct(klass, 0, dealloc, schema); rb_iv_set(rb_schema, "@errors", errors); rb_iv_set(rb_schema, "@parse_options", parse_options); return rb_schema; return Qnil; } ``` Create a new [`Schema`](schema) from the [`Nokogiri::XML::Document`](document) `doc` new(string\_or\_io, options = ParseOptions::DEFAULT\_SCHEMA) Show source ``` # File lib/nokogiri/xml/schema.rb, line 46 def self.new(string_or_io, options = ParseOptions::DEFAULT_SCHEMA) from_document(Nokogiri::XML(string_or_io), options) end ``` Create a new [`Nokogiri::XML::Schema`](schema) object using a `string_or_io` object. read\_memory(string) Show source ``` static VALUE read_memory(int argc, VALUE *argv, VALUE klass) { VALUE content; VALUE parse_options; int parse_options_int; xmlSchemaParserCtxtPtr ctx; xmlSchemaPtr schema; VALUE errors; VALUE rb_schema; int scanned_args = 0; xmlExternalEntityLoader old_loader = 0; scanned_args = rb_scan_args(argc, argv, "11", &content, &parse_options); if (scanned_args == 1) { parse_options = rb_const_get_at(rb_const_get_at(mNokogiriXml, rb_intern("ParseOptions")), rb_intern("DEFAULT_SCHEMA")); } parse_options_int = (int)NUM2INT(rb_funcall(parse_options, rb_intern("to_i"), 0)); ctx = xmlSchemaNewMemParserCtxt((const char *)StringValuePtr(content), (int)RSTRING_LEN(content)); errors = rb_ary_new(); xmlSetStructuredErrorFunc((void *)errors, Nokogiri_error_array_pusher); #ifdef HAVE_XMLSCHEMASETPARSERSTRUCTUREDERRORS xmlSchemaSetParserStructuredErrors( ctx, Nokogiri_error_array_pusher, (void *)errors ); #endif if (parse_options_int & XML_PARSE_NONET) { old_loader = xmlGetExternalEntityLoader(); xmlSetExternalEntityLoader(xmlNoNetExternalEntityLoader); } schema = xmlSchemaParse(ctx); if (old_loader) { xmlSetExternalEntityLoader(old_loader); } xmlSetStructuredErrorFunc(NULL, NULL); xmlSchemaFreeParserCtxt(ctx); if (NULL == schema) { xmlErrorPtr error = xmlGetLastError(); if (error) { Nokogiri_error_raise(NULL, error); } else { rb_raise(rb_eRuntimeError, "Could not parse document"); } return Qnil; } rb_schema = Data_Wrap_Struct(klass, 0, dealloc, schema); rb_iv_set(rb_schema, "@errors", errors); rb_iv_set(rb_schema, "@parse_options", parse_options); return rb_schema; } ``` Create a new [`Schema`](schema) from the contents of `string` valid?(thing) Show source ``` # File lib/nokogiri/xml/schema.rb, line 68 def valid?(thing) validate(thing).empty? end ``` Returns true if `thing` is a valid [`Nokogiri::XML::Document`](document) or file. validate(thing) Show source ``` # File lib/nokogiri/xml/schema.rb, line 55 def validate(thing) if thing.is_a?(Nokogiri::XML::Document) validate_document(thing) elsif File.file?(thing) validate_file(thing) else raise ArgumentError, "Must provide Nokogiri::Xml::Document or the name of an existing file" end end ``` Validate `thing` against this schema. `thing` can be a [`Nokogiri::XML::Document`](document) object, or a filename. An Array of [`Nokogiri::XML::SyntaxError`](syntaxerror) objects found while validating the `thing` is returned.
programming_docs
nokogiri class Nokogiri::XML::Attr class Nokogiri::XML::Attr ========================== Parent: cNokogiriXmlNode [`Attr`](attr) represents a [`Attr`](attr) node in an xml document. new(document, name) Show source ``` static VALUE new (int argc, VALUE *argv, VALUE klass) { xmlDocPtr xml_doc; VALUE document; VALUE name; VALUE rest; xmlAttrPtr node; VALUE rb_node; rb_scan_args(argc, argv, "2*", &document, &name, &rest); if (! rb_obj_is_kind_of(document, cNokogiriXmlDocument)) { rb_raise(rb_eArgError, "parameter must be a Nokogiri::XML::Document"); } Noko_Node_Get_Struct(document, xmlDoc, xml_doc); node = xmlNewDocProp( xml_doc, (const xmlChar *)StringValueCStr(name), NULL ); noko_xml_document_pin_node((xmlNodePtr)node); rb_node = noko_xml_node_wrap(klass, (xmlNodePtr)node); rb_obj_call_init(rb_node, argc, argv); if (rb_block_given_p()) { rb_yield(rb_node); } return rb_node; } ``` Create a new [`Attr`](attr) element on the `document` with `name` content=(p1) Alias for: [value=](attr#method-i-value-3D) deconstruct\_keys(array\_of\_names) β†’ Hash Show source ``` # File lib/nokogiri/xml/attr.rb, line 55 def deconstruct_keys(keys) { name: name, value: value, namespace: namespace } end ``` Returns a hash describing the [`Attr`](attr), to use in pattern matching. Valid keys and their values: * `name` β†’ (String) The name of the attribute. * `value` β†’ (String) The value of the attribute. * `namespace` β†’ ([`Namespace`](namespace), nil) The [`Namespace`](namespace) of the attribute, or `nil` if there is no namespace. ⚑ This is an experimental feature, available since v1.14.0 **Example** ``` doc = Nokogiri::XML.parse(<<~XML) <?xml version="1.0"?> <root xmlns="http://nokogiri.org/ns/default" xmlns:noko="http://nokogiri.org/ns/noko"> <child1 foo="abc" noko:bar="def"/> </root> XML attributes = doc.root.elements.first.attribute_nodes # => [#(Attr:0x35c { name = "foo", value = "abc" }), # #(Attr:0x370 { # name = "bar", # namespace = #(Namespace:0x384 { # prefix = "noko", # href = "http://nokogiri.org/ns/noko" # }), # value = "def" # })] attributes.first.deconstruct_keys([:name, :value, :namespace]) # => {:name=>"foo", :value=>"abc", :namespace=>nil} attributes.last.deconstruct_keys([:name, :value, :namespace]) # => {:name=>"bar", # :value=>"def", # :namespace=> # #(Namespace:0x384 { # prefix = "noko", # href = "http://nokogiri.org/ns/noko" # })} ``` value=(content) Show source ``` static VALUE set_value(VALUE self, VALUE content) { xmlAttrPtr attr; xmlChar *value; xmlNode *cur; Noko_Node_Get_Struct(self, xmlAttr, attr); if (attr->children) { xmlFreeNodeList(attr->children); } attr->children = attr->last = NULL; if (content == Qnil) { return content; } value = xmlEncodeEntitiesReentrant(attr->doc, (unsigned char *)StringValueCStr(content)); if (xmlStrlen(value) == 0) { attr->children = xmlNewDocText(attr->doc, value); } else { attr->children = xmlStringGetNodeList(attr->doc, value); } xmlFree(value); for (cur = attr->children; cur; cur = cur->next) { cur->parent = (xmlNode *)attr; cur->doc = attr->doc; if (cur->next == NULL) { attr->last = cur; } } return content; } ``` Set the value for this [`Attr`](attr) to `content`. Use β€˜nil` to remove the value (e.g., a [`HTML`](../html4) boolean attribute). Also aliased as: [content=](attr#method-i-content-3D) nokogiri class Nokogiri::XML::Namespace class Nokogiri::XML::Namespace =============================== Parent: [Object](https://nokogiri.org/rdoc/Object.html) Included modules: [Nokogiri::XML::PP::Node](pp/node) document[R] deconstruct\_keys(array\_of\_names) β†’ Hash Show source ``` # File lib/nokogiri/xml/namespace.rb, line 47 def deconstruct_keys(keys) { prefix: prefix, href: href } end ``` Returns a hash describing the [`Namespace`](namespace), to use in pattern matching. Valid keys and their values: * `prefix` β†’ (String, nil) The namespace’s prefix, or `nil` if there is no prefix (e.g., default namespace). * `href` β†’ (String) The namespace’s URI ⚑ This is an experimental feature, available since v1.14.0 **Example** ``` doc = Nokogiri::XML.parse(<<~XML) <?xml version="1.0"?> <root xmlns="http://nokogiri.org/ns/default" xmlns:noko="http://nokogiri.org/ns/noko"> <child1 foo="abc" noko:bar="def"/> <noko:child2 foo="qwe" noko:bar="rty"/> </root> XML doc.root.elements.first.namespace # => #(Namespace:0x35c { href = "http://nokogiri.org/ns/default" }) doc.root.elements.first.namespace.deconstruct_keys([:prefix, :href]) # => {:prefix=>nil, :href=>"http://nokogiri.org/ns/default"} doc.root.elements.last.namespace # => #(Namespace:0x370 { # prefix = "noko", # href = "http://nokogiri.org/ns/noko" # }) doc.root.elements.last.namespace.deconstruct_keys([:prefix, :href]) # => {:prefix=>"noko", :href=>"http://nokogiri.org/ns/noko"} ``` href() β†’ String Show source ``` static VALUE href(VALUE self) { xmlNsPtr ns; Noko_Namespace_Get_Struct(self, xmlNs, ns); if (!ns->href) { return Qnil; } return NOKOGIRI_STR_NEW2(ns->href); } ``` Returns the URI reference for this [`Namespace`](namespace). **Example** ``` doc = Nokogiri::XML.parse(<<~XML) <?xml version="1.0"?> <root xmlns="http://nokogiri.org/ns/default" xmlns:noko="http://nokogiri.org/ns/noko"> <child1 foo="abc" noko:bar="def"/> <noko:child2 foo="qwe" noko:bar="rty"/> </root> XML doc.root.elements.first.namespace.href # => "http://nokogiri.org/ns/default" doc.root.elements.last.namespace.href # => "http://nokogiri.org/ns/noko" ``` prefix() β†’ String or nil Show source ``` static VALUE prefix(VALUE self) { xmlNsPtr ns; Noko_Namespace_Get_Struct(self, xmlNs, ns); if (!ns->prefix) { return Qnil; } return NOKOGIRI_STR_NEW2(ns->prefix); } ``` Return the prefix for this [`Namespace`](namespace), or `nil` if there is no prefix (e.g., default namespace). **Example** ``` doc = Nokogiri::XML.parse(<<~XML) <?xml version="1.0"?> <root xmlns="http://nokogiri.org/ns/default" xmlns:noko="http://nokogiri.org/ns/noko"> <child1 foo="abc" noko:bar="def"/> <noko:child2 foo="qwe" noko:bar="rty"/> </root> XML doc.root.elements.first.namespace.prefix # => nil doc.root.elements.last.namespace.prefix # => "noko" ``` nokogiri class Nokogiri::XML::Document class Nokogiri::XML::Document ============================== Parent: cNokogiriXmlNode [`Nokogiri::XML::Document`](document) wraps an xml document. [`Nokogiri::XML::Document`](document) is the main entry point for dealing with [`XML`](../xml) documents. The [`Document`](document) is created by parsing an [`XML`](../xml) document. See [`Nokogiri::XML::Document.parse`](document#method-c-parse) for more information on parsing. For searching a [`Document`](document), see [`Nokogiri::XML::Searchable#css`](searchable#method-i-css) and [`Nokogiri::XML::Searchable#xpath`](searchable#method-i-xpath) NCNAME\_CHAR NCNAME\_RE NCNAME\_START\_CHAR See [www.w3.org/TR/REC-xml-names/#ns-decl](http://www.w3.org/TR/REC-xml-names/#ns-decl) for more details. Note that we’re not attempting to handle unicode characters partly because libxml2 doesn’t handle unicode characters in NCNAMEs. errors[RW] The errors found while parsing a document. Returns Array<Nokogiri::XML::SyntaxError> namespace\_inheritance[RW] When β€˜true`, reparented elements without a namespace will inherit their new parent’s namespace (if one exists). Defaults to β€˜false`. Returns Boolean **Example:** Default behavior of namespace inheritance ``` xml = <<~EOF <root xmlns:foo="http://nokogiri.org/default_ns/test/foo"> <foo:parent> </foo:parent> </root> EOF doc = Nokogiri::XML(xml) parent = doc.at_xpath("//foo:parent", "foo" => "http://nokogiri.org/default_ns/test/foo") parent.add_child("<child></child>") doc.to_xml # => <?xml version="1.0"?> # <root xmlns:foo="http://nokogiri.org/default_ns/test/foo"> # <foo:parent> # <child/> # </foo:parent> # </root> ``` **Example:** Setting namespace inheritance to β€˜true` ``` xml = <<~EOF <root xmlns:foo="http://nokogiri.org/default_ns/test/foo"> <foo:parent> </foo:parent> </root> EOF doc = Nokogiri::XML(xml) doc.namespace_inheritance = true parent = doc.at_xpath("//foo:parent", "foo" => "http://nokogiri.org/default_ns/test/foo") parent.add_child("<child></child>") doc.to_xml # => <?xml version="1.0"?> # <root xmlns:foo="http://nokogiri.org/default_ns/test/foo"> # <foo:parent> # <foo:child/> # </foo:parent> # </root> ``` Since v1.12.4 new(version = default) Show source ``` static VALUE new (int argc, VALUE *argv, VALUE klass) { xmlDocPtr doc; VALUE version, rest, rb_doc ; rb_scan_args(argc, argv, "0*", &rest); version = rb_ary_entry(rest, (long)0); if (NIL_P(version)) { version = rb_str_new2("1.0"); } doc = xmlNewDoc((xmlChar *)StringValueCStr(version)); rb_doc = noko_xml_document_wrap_with_init_args(klass, doc, argc, argv); return rb_doc ; } ``` Create a new document with `version` (defaults to β€œ1.0”) parse(string\_or\_io, url = nil, encoding = nil, options = ParseOptions::DEFAULT\_XML) { |options| ... } Show source ``` # File lib/nokogiri/xml/document.rb, line 48 def parse(string_or_io, url = nil, encoding = nil, options = ParseOptions::DEFAULT_XML) options = Nokogiri::XML::ParseOptions.new(options) if Integer === options yield options if block_given? url ||= string_or_io.respond_to?(:path) ? string_or_io.path : nil if empty_doc?(string_or_io) if options.strict? raise Nokogiri::XML::SyntaxError, "Empty document" else return encoding ? new.tap { |i| i.encoding = encoding } : new end end doc = if string_or_io.respond_to?(:read) if string_or_io.is_a?(Pathname) # resolve the Pathname to the file and open it as an IO object, see #2110 string_or_io = string_or_io.expand_path.open url ||= string_or_io.path end read_io(string_or_io, url, encoding, options.to_i) else # read_memory pukes on empty docs read_memory(string_or_io, url, encoding, options.to_i) end # do xinclude processing doc.do_xinclude(options) if options.xinclude? doc end ``` Parse an [`XML`](../xml) file. `string_or_io` may be a String, or any object that responds to *read* and *close* such as an IO, or StringIO. `url` (optional) is the URI where this document is located. `encoding` (optional) is the encoding that should be used when processing the document. `options` (optional) is a configuration object that sets options during parsing, such as Nokogiri::XML::ParseOptions::RECOVER. See the [`Nokogiri::XML::ParseOptions`](parseoptions) for more information. `block` (optional) is passed a configuration object on which parse options may be set. By default, [`Nokogiri`](../../nokogiri) treats documents as untrusted, and so does not attempt to load DTDs or access the network. See [`Nokogiri::XML::ParseOptions`](parseoptions) for a complete list of options; and that module’s DEFAULT\_XML constant for what’s set (and not set) by default. [`Nokogiri.XML()`](../../nokogiri#method-c-XML) is a convenience method which will call this method. read\_io(io, url, encoding, options) Show source ``` static VALUE read_io(VALUE klass, VALUE io, VALUE url, VALUE encoding, VALUE options) { const char *c_url = NIL_P(url) ? NULL : StringValueCStr(url); const char *c_enc = NIL_P(encoding) ? NULL : StringValueCStr(encoding); VALUE error_list = rb_ary_new(); VALUE document; xmlDocPtr doc; xmlResetLastError(); xmlSetStructuredErrorFunc((void *)error_list, Nokogiri_error_array_pusher); doc = xmlReadIO( (xmlInputReadCallback)noko_io_read, (xmlInputCloseCallback)noko_io_close, (void *)io, c_url, c_enc, (int)NUM2INT(options) ); xmlSetStructuredErrorFunc(NULL, NULL); if (doc == NULL) { xmlErrorPtr error; xmlFreeDoc(doc); error = xmlGetLastError(); if (error) { rb_exc_raise(Nokogiri_wrap_xml_syntax_error(error)); } else { rb_raise(rb_eRuntimeError, "Could not parse document"); } return Qnil; } document = noko_xml_document_wrap(klass, doc); rb_iv_set(document, "@errors", error_list); return document; } ``` Create a new document from an IO object read\_memory(string, url, encoding, options) Show source ``` static VALUE read_memory(VALUE klass, VALUE string, VALUE url, VALUE encoding, VALUE options) { const char *c_buffer = StringValuePtr(string); const char *c_url = NIL_P(url) ? NULL : StringValueCStr(url); const char *c_enc = NIL_P(encoding) ? NULL : StringValueCStr(encoding); int len = (int)RSTRING_LEN(string); VALUE error_list = rb_ary_new(); VALUE document; xmlDocPtr doc; xmlResetLastError(); xmlSetStructuredErrorFunc((void *)error_list, Nokogiri_error_array_pusher); doc = xmlReadMemory(c_buffer, len, c_url, c_enc, (int)NUM2INT(options)); xmlSetStructuredErrorFunc(NULL, NULL); if (doc == NULL) { xmlErrorPtr error; xmlFreeDoc(doc); error = xmlGetLastError(); if (error) { rb_exc_raise(Nokogiri_wrap_xml_syntax_error(error)); } else { rb_raise(rb_eRuntimeError, "Could not parse document"); } return Qnil; } document = noko_xml_document_wrap(klass, doc); rb_iv_set(document, "@errors", error_list); return document; } ``` Create a new document from a String wrap(java\_document) β†’ Nokogiri::XML::Document Show source ``` # File lib/nokogiri/xml/document.rb, line 91 ``` ⚠ This method is only available when running JRuby. Create a [`Document`](document) using an existing Java DOM document object. The returned [`Document`](document) shares the same underlying data structure as the Java object, so changes in one are reflected in the other. Parameters * β€˜java\_document` (Java::OrgW3cDom::Document) (The class `Java::OrgW3cDom::Document` is also accessible as `org.w3c.dom.Document`.) Returns [`Nokogiri::XML::Document`](document) See also #to\_java canonicalize(mode=XML\_C14N\_1\_0,inclusive\_namespaces=nil,with\_comments=false) Show source canonicalize { |obj, parent| ... } ``` static VALUE rb_xml_document_canonicalize(int argc, VALUE *argv, VALUE self) { VALUE rb_mode; VALUE rb_namespaces; VALUE rb_comments_p; int c_mode = 0; xmlChar **c_namespaces; xmlDocPtr c_doc; xmlOutputBufferPtr c_obuf; xmlC14NIsVisibleCallback c_callback_wrapper = NULL; void *rb_callback = NULL; VALUE rb_cStringIO; VALUE rb_io; rb_scan_args(argc, argv, "03", &rb_mode, &rb_namespaces, &rb_comments_p); if (!NIL_P(rb_mode)) { Check_Type(rb_mode, T_FIXNUM); c_mode = NUM2INT(rb_mode); } if (!NIL_P(rb_namespaces)) { Check_Type(rb_namespaces, T_ARRAY); if (c_mode == XML_C14N_1_0 || c_mode == XML_C14N_1_1) { rb_raise(rb_eRuntimeError, "This canonicalizer does not support this operation"); } } Data_Get_Struct(self, xmlDoc, c_doc); rb_cStringIO = rb_const_get_at(rb_cObject, rb_intern("StringIO")); rb_io = rb_class_new_instance(0, 0, rb_cStringIO); c_obuf = xmlAllocOutputBuffer(NULL); c_obuf->writecallback = (xmlOutputWriteCallback)noko_io_write; c_obuf->closecallback = (xmlOutputCloseCallback)noko_io_close; c_obuf->context = (void *)rb_io; if (rb_block_given_p()) { c_callback_wrapper = block_caller; rb_callback = (void *)rb_block_proc(); } if (NIL_P(rb_namespaces)) { c_namespaces = NULL; } else { long ns_len = RARRAY_LEN(rb_namespaces); c_namespaces = ruby_xcalloc((size_t)ns_len + 1, sizeof(xmlChar *)); for (int j = 0 ; j < ns_len ; j++) { VALUE entry = rb_ary_entry(rb_namespaces, j); c_namespaces[j] = (xmlChar *)StringValueCStr(entry); } } xmlC14NExecute(c_doc, c_callback_wrapper, rb_callback, c_mode, c_namespaces, (int)RTEST(rb_comments_p), c_obuf); ruby_xfree(c_namespaces); xmlOutputBufferClose(c_obuf); return rb_funcall(rb_io, rb_intern("string"), 0); } ``` Canonicalize a document and return the results. Takes an optional block that takes two parameters: the `obj` and that node’s `parent`. The `obj` will be either a [`Nokogiri::XML::Node`](node), or a [`Nokogiri::XML::Namespace`](namespace) The block must return a non-nil, non-false value if the `obj` passed in should be included in the canonicalized document. create\_entity(name, type, external\_id, system\_id, content) Show source ``` static VALUE create_entity(int argc, VALUE *argv, VALUE self) { VALUE name; VALUE type; VALUE external_id; VALUE system_id; VALUE content; xmlEntityPtr ptr; xmlDocPtr doc ; Data_Get_Struct(self, xmlDoc, doc); rb_scan_args(argc, argv, "14", &name, &type, &external_id, &system_id, &content); xmlResetLastError(); ptr = xmlAddDocEntity( doc, (xmlChar *)(NIL_P(name) ? NULL : StringValueCStr(name)), (int)(NIL_P(type) ? XML_INTERNAL_GENERAL_ENTITY : NUM2INT(type)), (xmlChar *)(NIL_P(external_id) ? NULL : StringValueCStr(external_id)), (xmlChar *)(NIL_P(system_id) ? NULL : StringValueCStr(system_id)), (xmlChar *)(NIL_P(content) ? NULL : StringValueCStr(content)) ); if (NULL == ptr) { xmlErrorPtr error = xmlGetLastError(); if (error) { rb_exc_raise(Nokogiri_wrap_xml_syntax_error(error)); } else { rb_raise(rb_eRuntimeError, "Could not create entity"); } return Qnil; } return noko_xml_node_wrap(cNokogiriXmlEntityDecl, (xmlNodePtr)ptr); } ``` Create a new entity named `name`. `type` is an integer representing the type of entity to be created, and it defaults to Nokogiri::XML::EntityDecl::INTERNAL\_GENERAL. See the constants on [`Nokogiri::XML::EntityDecl`](entitydecl) for more information. `external_id`, `system_id`, and `content` set the External ID, System ID, and content respectively. All of these parameters are optional. dup Show source ``` static VALUE duplicate_document(int argc, VALUE *argv, VALUE self) { xmlDocPtr doc, dup; VALUE copy; VALUE level; if (rb_scan_args(argc, argv, "01", &level) == 0) { level = INT2NUM((long)1); } Data_Get_Struct(self, xmlDoc, doc); dup = xmlCopyDoc(doc, (int)NUM2INT(level)); if (dup == NULL) { return Qnil; } dup->type = doc->type; copy = noko_xml_document_wrap(rb_obj_class(self), dup); rb_iv_set(copy, "@errors", rb_iv_get(self, "@errors")); return copy ; } ``` Copy this [`Document`](document). An optional depth may be passed in, but it defaults to a deep copy. 0 is a shallow copy, 1 is a deep copy. encoding Show source ``` static VALUE encoding(VALUE self) { xmlDocPtr doc; Data_Get_Struct(self, xmlDoc, doc); if (!doc->encoding) { return Qnil; } return NOKOGIRI_STR_NEW2(doc->encoding); } ``` Get the encoding for this [`Document`](document) encoding= encoding Show source ``` static VALUE set_encoding(VALUE self, VALUE encoding) { xmlDocPtr doc; Data_Get_Struct(self, xmlDoc, doc); if (doc->encoding) { xmlFree(DISCARD_CONST_QUAL_XMLCHAR(doc->encoding)); } doc->encoding = xmlStrdup((xmlChar *)StringValueCStr(encoding)); return encoding; } ``` Set the encoding string for this [`Document`](document) remove\_namespaces! Show source ``` static VALUE remove_namespaces_bang(VALUE self) { xmlDocPtr doc ; Data_Get_Struct(self, xmlDoc, doc); recursively_remove_namespaces_from_node((xmlNodePtr)doc); return self; } ``` Remove all namespaces from all nodes in the document. This could be useful for developers who either don’t understand namespaces or don’t care about them. The following example shows a use case, and you can decide for yourself whether this is a good thing or not: ``` doc = Nokogiri::XML <<-EOXML <root> <car xmlns:part="http://general-motors.com/"> <part:tire>Michelin Model XGV</part:tire> </car> <bicycle xmlns:part="http://schwinn.com/"> <part:tire>I'm a bicycle tire!</part:tire> </bicycle> </root> EOXML doc.xpath("//tire").to_s # => "" doc.xpath("//part:tire", "part" => "http://general-motors.com/").to_s # => "<part:tire>Michelin Model XGV</part:tire>" doc.xpath("//part:tire", "part" => "http://schwinn.com/").to_s # => "<part:tire>I'm a bicycle tire!</part:tire>" doc.remove_namespaces! doc.xpath("//tire").to_s # => "<tire>Michelin Model XGV</tire><tire>I'm a bicycle tire!</tire>" doc.xpath("//part:tire", "part" => "http://general-motors.com/").to_s # => "" doc.xpath("//part:tire", "part" => "http://schwinn.com/").to_s # => "" ``` For more information on why this probably is **not** a good thing in general, please direct your browser to [tenderlovemaking.com/2009/04/23/namespaces-in-xml.html](http://tenderlovemaking.com/2009/04/23/namespaces-in-xml.html) root Show source ``` static VALUE rb_xml_document_root(VALUE self) { xmlDocPtr c_document; xmlNodePtr c_root; Data_Get_Struct(self, xmlDoc, c_document); c_root = xmlDocGetRootElement(c_document); if (!c_root) { return Qnil; } return noko_xml_node_wrap(Qnil, c_root) ; } ``` Get the root node for this document. root= Show source ``` static VALUE rb_xml_document_root_set(VALUE self, VALUE rb_new_root) { xmlDocPtr c_document; xmlNodePtr c_new_root = NULL, c_current_root; Data_Get_Struct(self, xmlDoc, c_document); c_current_root = xmlDocGetRootElement(c_document); if (c_current_root) { xmlUnlinkNode(c_current_root); noko_xml_document_pin_node(c_current_root); } if (!NIL_P(rb_new_root)) { if (!rb_obj_is_kind_of(rb_new_root, cNokogiriXmlNode)) { rb_raise(rb_eArgError, "expected Nokogiri::XML::Node but received %"PRIsVALUE, rb_obj_class(rb_new_root)); } Noko_Node_Get_Struct(rb_new_root, xmlNode, c_new_root); /* If the new root's document is not the same as the current document, * then we need to dup the node in to this document. */ if (c_new_root->doc != c_document) { c_new_root = xmlDocCopyNode(c_new_root, c_document, 1); if (!c_new_root) { rb_raise(rb_eRuntimeError, "Could not reparent node (xmlDocCopyNode)"); } } } xmlDocSetRootElement(c_document, c_new_root); return rb_new_root; } ``` Set the root element on this document to\_java() β†’ Java::OrgW3cDom::Document Show source ``` # File lib/nokogiri/xml/document.rb, line 109 ``` ⚠ This method is only available when running JRuby. Returns the underlying Java DOM document object for this document. The returned Java object shares the same underlying data structure as this document, so changes in one are reflected in the other. Returns Java::OrgW3cDom::Document (The class β€˜Java::OrgW3cDom::Document` is also accessible as `org.w3c.dom.Document`.) See also [`Document.wrap`](document#method-c-wrap) url Show source ``` static VALUE url(VALUE self) { xmlDocPtr doc; Data_Get_Struct(self, xmlDoc, doc); if (doc->URL) { return NOKOGIRI_STR_NEW2(doc->URL); } return Qnil; } ``` Get the url name for this document. version Show source ``` static VALUE version(VALUE self) { xmlDocPtr doc; Data_Get_Struct(self, xmlDoc, doc); if (!doc->version) { return Qnil; } return NOKOGIRI_STR_NEW2(doc->version); } ``` Get the [`XML`](../xml) version for this [`Document`](document)
programming_docs
nokogiri class Nokogiri::XML::Reader class Nokogiri::XML::Reader ============================ Parent: [Object](https://nokogiri.org/rdoc/Object.html) Included modules: The [`Reader`](reader) parser allows you to effectively pull parse an [`XML`](../xml) document. Once instantiated, call [`Nokogiri::XML::Reader#each`](reader#method-i-each) to iterate over each node. Note that you may only iterate over the document once! [`Nokogiri::XML::Reader`](reader) parses an [`XML`](../xml) document similar to the way a cursor would move. The [`Reader`](reader) is given an [`XML`](../xml) document, and yields nodes to an each block. Here is an example of usage: ``` reader = Nokogiri::XML::Reader(<<-eoxml) <x xmlns:tenderlove='http://tenderlovemaking.com/'> <tenderlove:foo awesome='true'>snuggles!</tenderlove:foo> </x> eoxml reader.each do |node| # node is an instance of Nokogiri::XML::Reader puts node.name end ``` Note that [`Nokogiri::XML::Reader#each`](reader#method-i-each) can only be called once!! Once the cursor moves through the entire document, you must parse the document again. So make sure that you capture any information you need during the first iteration. The [`Reader`](reader) parser is good for when you need the speed of a [`SAX`](sax) parser, but do not want to write a [`Document`](document) handler. TYPE\_ATTRIBUTE Attribute node type TYPE\_CDATA [`CDATA`](cdata) node type TYPE\_COMMENT [`Comment`](comment) node type TYPE\_DOCUMENT [`Document`](document) node type TYPE\_DOCUMENT\_FRAGMENT [`Document`](document) Fragment node type TYPE\_DOCUMENT\_TYPE [`Document`](document) Type node type TYPE\_ELEMENT [`Element`](element) node type TYPE\_END\_ELEMENT [`Element`](element) end node type TYPE\_END\_ENTITY Entity end node type TYPE\_ENTITY Entity node type TYPE\_ENTITY\_REFERENCE Entity Reference node type TYPE\_NONE TYPE\_NOTATION [`Notation`](notation) node type TYPE\_PROCESSING\_INSTRUCTION PI node type TYPE\_SIGNIFICANT\_WHITESPACE Significant Whitespace node type TYPE\_TEXT [`Text`](text) node type TYPE\_WHITESPACE Whitespace node type TYPE\_XML\_DECLARATION [`XML`](../xml) Declaration node type errors[RW] A list of errors encountered while parsing source[R] The [`XML`](../xml) source from\_io(io, url = nil, encoding = nil, options = 0) Show source ``` static VALUE from_io(int argc, VALUE *argv, VALUE klass) { VALUE rb_io, rb_url, encoding, rb_options; xmlTextReaderPtr reader; const char *c_url = NULL; const char *c_encoding = NULL; int c_options = 0; VALUE rb_reader, args[3]; rb_scan_args(argc, argv, "13", &rb_io, &rb_url, &encoding, &rb_options); if (!RTEST(rb_io)) { rb_raise(rb_eArgError, "io cannot be nil"); } if (RTEST(rb_url)) { c_url = StringValueCStr(rb_url); } if (RTEST(encoding)) { c_encoding = StringValueCStr(encoding); } if (RTEST(rb_options)) { c_options = (int)NUM2INT(rb_options); } reader = xmlReaderForIO( (xmlInputReadCallback)noko_io_read, (xmlInputCloseCallback)noko_io_close, (void *)rb_io, c_url, c_encoding, c_options ); if (reader == NULL) { xmlFreeTextReader(reader); rb_raise(rb_eRuntimeError, "couldn't create a parser"); } rb_reader = Data_Wrap_Struct(klass, NULL, dealloc, reader); args[0] = rb_io; args[1] = rb_url; args[2] = encoding; rb_obj_call_init(rb_reader, 3, args); return rb_reader; } ``` Create a new reader that parses `io` from\_memory(string, url = nil, encoding = nil, options = 0) Show source ``` static VALUE from_memory(int argc, VALUE *argv, VALUE klass) { VALUE rb_buffer, rb_url, encoding, rb_options; xmlTextReaderPtr reader; const char *c_url = NULL; const char *c_encoding = NULL; int c_options = 0; VALUE rb_reader, args[3]; rb_scan_args(argc, argv, "13", &rb_buffer, &rb_url, &encoding, &rb_options); if (!RTEST(rb_buffer)) { rb_raise(rb_eArgError, "string cannot be nil"); } if (RTEST(rb_url)) { c_url = StringValueCStr(rb_url); } if (RTEST(encoding)) { c_encoding = StringValueCStr(encoding); } if (RTEST(rb_options)) { c_options = (int)NUM2INT(rb_options); } reader = xmlReaderForMemory( StringValuePtr(rb_buffer), (int)RSTRING_LEN(rb_buffer), c_url, c_encoding, c_options ); if (reader == NULL) { xmlFreeTextReader(reader); rb_raise(rb_eRuntimeError, "couldn't create a parser"); } rb_reader = Data_Wrap_Struct(klass, NULL, dealloc, reader); args[0] = rb_buffer; args[1] = rb_url; args[2] = encoding; rb_obj_call_init(rb_reader, 3, args); return rb_reader; } ``` Create a new reader that parses `string` attribute(name) Show source ``` static VALUE reader_attribute(VALUE self, VALUE name) { xmlTextReaderPtr reader; xmlChar *value ; VALUE rb_value; Data_Get_Struct(self, xmlTextReader, reader); if (NIL_P(name)) { return Qnil; } name = StringValue(name) ; value = xmlTextReaderGetAttribute(reader, (xmlChar *)StringValueCStr(name)); if (value == NULL) { return Qnil; } rb_value = NOKOGIRI_STR_NEW2(value); xmlFree(value); return rb_value; } ``` Get the value of attribute named `name` attribute\_at(index) Show source ``` static VALUE attribute_at(VALUE self, VALUE index) { xmlTextReaderPtr reader; xmlChar *value; VALUE rb_value; Data_Get_Struct(self, xmlTextReader, reader); if (NIL_P(index)) { return Qnil; } index = rb_Integer(index); value = xmlTextReaderGetAttributeNo( reader, (int)NUM2INT(index) ); if (value == NULL) { return Qnil; } rb_value = NOKOGIRI_STR_NEW2(value); xmlFree(value); return rb_value; } ``` Get the value of attribute at `index` attribute\_count Show source ``` static VALUE attribute_count(VALUE self) { xmlTextReaderPtr reader; int count; Data_Get_Struct(self, xmlTextReader, reader); count = xmlTextReaderAttributeCount(reader); if (count == -1) { return Qnil; } return INT2NUM(count); } ``` Get the number of attributes for the current node attribute\_hash() β†’ Hash<String β‡’ String> Show source ``` static VALUE rb_xml_reader_attribute_hash(VALUE rb_reader) { VALUE rb_attributes = rb_hash_new(); xmlTextReaderPtr c_reader; xmlNodePtr c_node; xmlAttrPtr c_property; VALUE rb_errors; Data_Get_Struct(rb_reader, xmlTextReader, c_reader); if (!has_attributes(c_reader)) { return rb_attributes; } rb_errors = rb_funcall(rb_reader, rb_intern("errors"), 0); xmlSetStructuredErrorFunc((void *)rb_errors, Nokogiri_error_array_pusher); c_node = xmlTextReaderExpand(c_reader); xmlSetStructuredErrorFunc(NULL, NULL); if (c_node == NULL) { if (RARRAY_LEN(rb_errors) > 0) { VALUE rb_error = rb_ary_entry(rb_errors, 0); VALUE exception_message = rb_funcall(rb_error, rb_intern("to_s"), 0); rb_exc_raise(rb_class_new_instance(1, &exception_message, cNokogiriXmlSyntaxError)); } return Qnil; } c_property = c_node->properties; while (c_property != NULL) { VALUE rb_name = NOKOGIRI_STR_NEW2(c_property->name); VALUE rb_value = Qnil; xmlChar *c_value = xmlNodeGetContent((xmlNode *)c_property); if (c_value) { rb_value = NOKOGIRI_STR_NEW2(c_value); xmlFree(c_value); } rb_hash_aset(rb_attributes, rb_name, rb_value); c_property = c_property->next; } return rb_attributes; } ``` Get the attributes of the current node as a Hash of names and values. See related: [`#attributes`](reader#method-i-attributes) and [`#namespaces`](reader#method-i-namespaces) attribute\_nodes() β†’ Array<Nokogiri::XML::Attr> Show source ``` static VALUE rb_xml_reader_attribute_nodes(VALUE rb_reader) { xmlTextReaderPtr c_reader; xmlNodePtr c_node; VALUE attr_nodes; int j; // TODO: deprecated, remove in Nokogiri v1.15, see https://github.com/sparklemotion/nokogiri/issues/2598 // After removal, we can also remove all the "node_has_a_document" special handling from xml_node.c NOKO_WARN_DEPRECATION("Reader#attribute_nodes is deprecated and will be removed in a future version of Nokogiri. Please use Reader#attribute_hash instead."); Data_Get_Struct(rb_reader, xmlTextReader, c_reader); if (! has_attributes(c_reader)) { return rb_ary_new() ; } c_node = xmlTextReaderExpand(c_reader); if (c_node == NULL) { return Qnil; } attr_nodes = noko_xml_node_attrs(c_node); /* ensure that the Reader won't be GCed as long as a node is referenced */ for (j = 0 ; j < RARRAY_LEN(attr_nodes) ; j++) { rb_iv_set(rb_ary_entry(attr_nodes, j), "@reader", rb_reader); } return attr_nodes; } ``` Get the attributes of the current node as an Array of XML:Attr ⚠ This method is deprecated and unsafe to use. It will be removed in a future version of [`Nokogiri`](../../nokogiri). See related: [`#attribute_hash`](reader#method-i-attribute_hash), [`#attributes`](reader#method-i-attributes) attributes() Show source ``` # File lib/nokogiri/xml/reader.rb, line 92 def attributes attribute_hash.merge(namespaces) end ``` Get the attributes and namespaces of the current node as a Hash. This is the union of [`Reader#attribute_hash`](reader#method-i-attribute_hash) and [`Reader#namespaces`](reader#method-i-namespaces) Returns (Hash<String, String>) Attribute names and values, and namespace prefixes and hrefs. attributes? Show source ``` static VALUE attributes_eh(VALUE self) { xmlTextReaderPtr reader; int eh; Data_Get_Struct(self, xmlTextReader, reader); eh = has_attributes(reader); if (eh == 0) { return Qfalse; } if (eh == 1) { return Qtrue; } return Qnil; } ``` Does this node have attributes? base\_uri Show source ``` static VALUE rb_xml_reader_base_uri(VALUE rb_reader) { VALUE rb_base_uri; xmlTextReaderPtr c_reader; xmlChar *c_base_uri; Data_Get_Struct(rb_reader, xmlTextReader, c_reader); c_base_uri = xmlTextReaderBaseUri(c_reader); if (c_base_uri == NULL) { return Qnil; } rb_base_uri = NOKOGIRI_STR_NEW2(c_base_uri); xmlFree(c_base_uri); return rb_base_uri; } ``` Get the xml:base of the node default? Show source ``` static VALUE default_eh(VALUE self) { xmlTextReaderPtr reader; int eh; Data_Get_Struct(self, xmlTextReader, reader); eh = xmlTextReaderIsDefault(reader); if (eh == 0) { return Qfalse; } if (eh == 1) { return Qtrue; } return Qnil; } ``` Was an attribute generated from the default value in the [`DTD`](dtd) or schema? depth Show source ``` static VALUE depth(VALUE self) { xmlTextReaderPtr reader; int depth; Data_Get_Struct(self, xmlTextReader, reader); depth = xmlTextReaderDepth(reader); if (depth == -1) { return Qnil; } return INT2NUM(depth); } ``` Get the depth of the node each() { |cursor| ... } Show source ``` # File lib/nokogiri/xml/reader.rb, line 98 def each while (cursor = read) yield cursor end end ``` Move the cursor through the document yielding the cursor to the block empty\_element? # β†’ true or false Show source ``` static VALUE empty_element_p(VALUE self) { xmlTextReaderPtr reader; Data_Get_Struct(self, xmlTextReader, reader); if (xmlTextReaderIsEmptyElement(reader)) { return Qtrue; } return Qfalse; } ``` Returns true if the current node is empty, otherwise false. Also aliased as: [self\_closing?](reader#method-i-self_closing-3F) encoding() Show source ``` static VALUE rb_xml_reader_encoding(VALUE rb_reader) { xmlTextReaderPtr c_reader; const char *parser_encoding; VALUE constructor_encoding; constructor_encoding = rb_iv_get(rb_reader, "@encoding"); if (RTEST(constructor_encoding)) { return constructor_encoding; } Data_Get_Struct(rb_reader, xmlTextReader, c_reader); parser_encoding = (const char *)xmlTextReaderConstEncoding(c_reader); if (parser_encoding == NULL) { return Qnil; } return NOKOGIRI_STR_NEW2(parser_encoding); } ``` inner\_xml Show source ``` static VALUE inner_xml(VALUE self) { xmlTextReaderPtr reader; xmlChar *value; VALUE str; Data_Get_Struct(self, xmlTextReader, reader); value = xmlTextReaderReadInnerXml(reader); str = Qnil; if (value) { str = NOKOGIRI_STR_NEW2((char *)value); xmlFree(value); } return str; } ``` Read the contents of the current node, including child nodes and markup. Returns a utf-8 encoded string. lang Show source ``` static VALUE lang(VALUE self) { xmlTextReaderPtr reader; const char *lang; Data_Get_Struct(self, xmlTextReader, reader); lang = (const char *)xmlTextReaderConstXmlLang(reader); if (lang == NULL) { return Qnil; } return NOKOGIRI_STR_NEW2(lang); } ``` Get the xml:lang scope within which the node resides. local\_name Show source ``` static VALUE local_name(VALUE self) { xmlTextReaderPtr reader; const char *name; Data_Get_Struct(self, xmlTextReader, reader); name = (const char *)xmlTextReaderConstLocalName(reader); if (name == NULL) { return Qnil; } return NOKOGIRI_STR_NEW2(name); } ``` Get the local name of the node name Show source ``` static VALUE name(VALUE self) { xmlTextReaderPtr reader; const char *name; Data_Get_Struct(self, xmlTextReader, reader); name = (const char *)xmlTextReaderConstName(reader); if (name == NULL) { return Qnil; } return NOKOGIRI_STR_NEW2(name); } ``` Get the name of the node. Returns a utf-8 encoded string. namespace\_uri Show source ``` static VALUE namespace_uri(VALUE self) { xmlTextReaderPtr reader; const char *uri; Data_Get_Struct(self, xmlTextReader, reader); uri = (const char *)xmlTextReaderConstNamespaceUri(reader); if (uri == NULL) { return Qnil; } return NOKOGIRI_STR_NEW2(uri); } ``` Get the URI defining the namespace associated with the node namespaces Show source ``` static VALUE rb_xml_reader_namespaces(VALUE rb_reader) { VALUE rb_namespaces = rb_hash_new() ; xmlTextReaderPtr c_reader; xmlNodePtr c_node; VALUE rb_errors; Data_Get_Struct(rb_reader, xmlTextReader, c_reader); if (! has_attributes(c_reader)) { return rb_namespaces ; } rb_errors = rb_funcall(rb_reader, rb_intern("errors"), 0); xmlSetStructuredErrorFunc((void *)rb_errors, Nokogiri_error_array_pusher); c_node = xmlTextReaderExpand(c_reader); xmlSetStructuredErrorFunc(NULL, NULL); if (c_node == NULL) { if (RARRAY_LEN(rb_errors) > 0) { VALUE rb_error = rb_ary_entry(rb_errors, 0); VALUE exception_message = rb_funcall(rb_error, rb_intern("to_s"), 0); rb_exc_raise(rb_class_new_instance(1, &exception_message, cNokogiriXmlSyntaxError)); } return Qnil; } Nokogiri_xml_node_namespaces(c_node, rb_namespaces); return rb_namespaces ; } ``` Get a hash of namespaces for this [`Node`](node) node\_type Show source ``` static VALUE node_type(VALUE self) { xmlTextReaderPtr reader; Data_Get_Struct(self, xmlTextReader, reader); return INT2NUM(xmlTextReaderNodeType(reader)); } ``` Get the type of readers current node outer\_xml Show source ``` static VALUE outer_xml(VALUE self) { xmlTextReaderPtr reader; xmlChar *value; VALUE str = Qnil; Data_Get_Struct(self, xmlTextReader, reader); value = xmlTextReaderReadOuterXml(reader); if (value) { str = NOKOGIRI_STR_NEW2((char *)value); xmlFree(value); } return str; } ``` Read the current node and its contents, including child nodes and markup. Returns a utf-8 encoded string. prefix Show source ``` static VALUE prefix(VALUE self) { xmlTextReaderPtr reader; const char *prefix; Data_Get_Struct(self, xmlTextReader, reader); prefix = (const char *)xmlTextReaderConstPrefix(reader); if (prefix == NULL) { return Qnil; } return NOKOGIRI_STR_NEW2(prefix); } ``` Get the shorthand reference to the namespace associated with the node. read Show source ``` static VALUE read_more(VALUE self) { xmlTextReaderPtr reader; xmlErrorPtr error; VALUE error_list; int ret; Data_Get_Struct(self, xmlTextReader, reader); error_list = rb_funcall(self, rb_intern("errors"), 0); xmlSetStructuredErrorFunc((void *)error_list, Nokogiri_error_array_pusher); ret = xmlTextReaderRead(reader); xmlSetStructuredErrorFunc(NULL, NULL); if (ret == 1) { return self; } if (ret == 0) { return Qnil; } error = xmlGetLastError(); if (error) { rb_exc_raise(Nokogiri_wrap_xml_syntax_error(error)); } else { rb_raise(rb_eRuntimeError, "Error pulling: %d", ret); } return Qnil; } ``` Move the [`Reader`](reader) forward through the [`XML`](../xml) document. self\_closing?() Alias for: [empty\_element?](reader#method-i-empty_element-3F) state Show source ``` static VALUE state(VALUE self) { xmlTextReaderPtr reader; Data_Get_Struct(self, xmlTextReader, reader); return INT2NUM(xmlTextReaderReadState(reader)); } ``` Get the state of the reader value Show source ``` static VALUE value(VALUE self) { xmlTextReaderPtr reader; const char *value; Data_Get_Struct(self, xmlTextReader, reader); value = (const char *)xmlTextReaderConstValue(reader); if (value == NULL) { return Qnil; } return NOKOGIRI_STR_NEW2(value); } ``` Get the text value of the node if present. Returns a utf-8 encoded string. value? Show source ``` static VALUE value_eh(VALUE self) { xmlTextReaderPtr reader; int eh; Data_Get_Struct(self, xmlTextReader, reader); eh = xmlTextReaderHasValue(reader); if (eh == 0) { return Qfalse; } if (eh == 1) { return Qtrue; } return Qnil; } ``` Does this node have a text value? xml\_version Show source ``` static VALUE xml_version(VALUE self) { xmlTextReaderPtr reader; const char *version; Data_Get_Struct(self, xmlTextReader, reader); version = (const char *)xmlTextReaderConstXmlVersion(reader); if (version == NULL) { return Qnil; } return NOKOGIRI_STR_NEW2(version); } ``` Get the [`XML`](../xml) version of the document being read nokogiri class Nokogiri::XML::EntityDecl class Nokogiri::XML::EntityDecl ================================ Parent: cNokogiriXmlNode new(name, doc, \*args) Show source ``` # File lib/nokogiri/xml/entity_decl.rb, line 12 def self.new(name, doc, *args) doc.create_entity(name, *args) end ``` content Show source ``` static VALUE get_content(VALUE self) { xmlEntityPtr node; Noko_Node_Get_Struct(self, xmlEntity, node); if (!node->content) { return Qnil; } return NOKOGIRI_STR_NEW(node->content, node->length); } ``` Get the content entity\_type Show source ``` static VALUE entity_type(VALUE self) { xmlEntityPtr node; Noko_Node_Get_Struct(self, xmlEntity, node); return INT2NUM((int)node->etype); } ``` Get the entity type external\_id Show source ``` static VALUE external_id(VALUE self) { xmlEntityPtr node; Noko_Node_Get_Struct(self, xmlEntity, node); if (!node->ExternalID) { return Qnil; } return NOKOGIRI_STR_NEW2(node->ExternalID); } ``` Get the external identifier for PUBLIC inspect() Show source ``` # File lib/nokogiri/xml/entity_decl.rb, line 16 def inspect "#<#{self.class.name}:#{format("0x%x", object_id)} #{to_s.inspect}>" end ``` original\_content Show source ``` static VALUE original_content(VALUE self) { xmlEntityPtr node; Noko_Node_Get_Struct(self, xmlEntity, node); if (!node->orig) { return Qnil; } return NOKOGIRI_STR_NEW2(node->orig); } ``` Get the [`original_content`](entitydecl#method-i-original_content) before ref substitution system\_id Show source ``` static VALUE system_id(VALUE self) { xmlEntityPtr node; Noko_Node_Get_Struct(self, xmlEntity, node); if (!node->SystemID) { return Qnil; } return NOKOGIRI_STR_NEW2(node->SystemID); } ``` Get the URI for a SYSTEM or PUBLIC Entity
programming_docs
nokogiri class Nokogiri::XML::NodeSet class Nokogiri::XML::NodeSet ============================= Parent: [Object](https://nokogiri.org/rdoc/Object.html) Included modules: [Nokogiri::XML::Searchable](searchable) A [`NodeSet`](nodeset) contains a list of [`Nokogiri::XML::Node`](node) objects. Typically a [`NodeSet`](nodeset) is return as a result of searching a [`Document`](document) via [`Nokogiri::XML::Searchable#css`](searchable#method-i-css) or [`Nokogiri::XML::Searchable#xpath`](searchable#method-i-xpath) LOOKS\_LIKE\_XPATH Included from [Nokogiri::XML::Searchable](searchable) Regular expression used by [`Searchable#search`](searchable#method-i-search) to determine if a query string is [`CSS`](../css) or [`XPath`](xpath) document[RW] The [`Document`](document) this [`NodeSet`](nodeset) is associated with new(document, list = []) { |self| ... } Show source ``` # File lib/nokogiri/xml/node_set.rb, line 20 def initialize(document, list = []) @document = document document.decorate(self) list.each { |x| self << x } yield self if block_given? end ``` Create a [`NodeSet`](nodeset) with `document` defaulting to `list` search \*paths, [namespace-bindings, xpath-variable-bindings, custom-handler-class] Alias for: [at](nodeset#method-i-at) &(node\_set) Show source ``` static VALUE intersection(VALUE self, VALUE rb_other) { xmlNodeSetPtr node_set, other ; xmlNodeSetPtr intersection; if (!rb_obj_is_kind_of(rb_other, cNokogiriXmlNodeSet)) { rb_raise(rb_eArgError, "node_set must be a Nokogiri::XML::NodeSet"); } Data_Get_Struct(self, xmlNodeSet, node_set); Data_Get_Struct(rb_other, xmlNodeSet, other); intersection = xmlXPathIntersection(node_set, other); return noko_xml_node_set_wrap(intersection, rb_iv_get(self, "@document")); } ``` Set Intersection β€” Returns a new [`NodeSet`](nodeset) containing nodes common to the two NodeSets. +(p1) Alias for: [|](nodeset#method-i-7C) -(node\_set) Show source ``` static VALUE minus(VALUE self, VALUE rb_other) { xmlNodeSetPtr node_set, other; xmlNodeSetPtr new; int j ; if (!rb_obj_is_kind_of(rb_other, cNokogiriXmlNodeSet)) { rb_raise(rb_eArgError, "node_set must be a Nokogiri::XML::NodeSet"); } Data_Get_Struct(self, xmlNodeSet, node_set); Data_Get_Struct(rb_other, xmlNodeSet, other); new = xmlXPathNodeSetMerge(NULL, node_set); for (j = 0 ; j < other->nodeNr ; ++j) { xpath_node_set_del(new, other->nodeTab[j]); } return noko_xml_node_set_wrap(new, rb_iv_get(self, "@document")); } ``` Difference - returns a new [`NodeSet`](nodeset) that is a copy of this [`NodeSet`](nodeset), removing each item that also appears in `node_set` <<(p1) Alias for: [push](nodeset#method-i-push) ==(other) Show source ``` # File lib/nokogiri/xml/node_set.rb, line 393 def ==(other) return false unless other.is_a?(Nokogiri::XML::NodeSet) return false unless length == other.length each_with_index do |node, i| return false unless node == other[i] end true end ``` Equality – Two NodeSets are equal if the contain the same number of elements and if each element is equal to the corresponding element in the other [`NodeSet`](nodeset) [index] β†’ Node or nil Show source [start, length] β†’ NodeSet or nil [range] β†’ NodeSet or nil ``` static VALUE slice(int argc, VALUE *argv, VALUE self) { VALUE arg ; long beg, len ; xmlNodeSetPtr node_set; Data_Get_Struct(self, xmlNodeSet, node_set); if (argc == 2) { beg = NUM2LONG(argv[0]); len = NUM2LONG(argv[1]); if (beg < 0) { beg += node_set->nodeNr ; } return subseq(self, beg, len); } if (argc != 1) { rb_scan_args(argc, argv, "11", NULL, NULL); } arg = argv[0]; if (FIXNUM_P(arg)) { return index_at(self, FIX2LONG(arg)); } /* if arg is Range */ switch (rb_range_beg_len(arg, &beg, &len, (long)node_set->nodeNr, 0)) { case Qfalse: break; case Qnil: return Qnil; default: return subseq(self, beg, len); } return index_at(self, NUM2LONG(arg)); } ``` [`Element`](element) reference - returns the node at `index`, or returns a [`NodeSet`](nodeset) containing nodes starting at `start` and continuing for `length` elements, or returns a [`NodeSet`](nodeset) containing nodes specified by `range`. Negative `indices` count backward from the end of the `node_set` (-1 is the last node). Returns nil if the `index` (or `start`) are out of range. Also aliased as: [slice](nodeset#method-i-slice) add\_class(name) Show source ``` # File lib/nokogiri/xml/node_set.rb, line 139 def add_class(name) each do |el| el.add_class(name) end self end ``` Add the class attribute `name` to all [`Node`](node) objects in the [`NodeSet`](nodeset). See [`Nokogiri::XML::Node#add_class`](node#method-i-add_class) for more information. after(datum) Show source ``` # File lib/nokogiri/xml/node_set.rb, line 69 def after(datum) last.after(datum) end ``` Insert `datum` after the last [`Node`](node) in this [`NodeSet`](nodeset) append\_class(name) Show source ``` # File lib/nokogiri/xml/node_set.rb, line 151 def append_class(name) each do |el| el.append_class(name) end self end ``` Append the class attribute `name` to all [`Node`](node) objects in the [`NodeSet`](nodeset). See [`Nokogiri::XML::Node#append_class`](node#method-i-append_class) for more information. search \*paths, [namespace-bindings, xpath-variable-bindings, custom-handler-class] Show source ``` # File lib/nokogiri/xml/node_set.rb, line 119 def at(*args) if args.length == 1 && args.first.is_a?(Numeric) return self[args.first] end super(*args) end ``` Search this object for `paths`, and return only the first result. `paths` must be one or more [`XPath`](xpath) or [`CSS`](../css) queries. See [`Searchable#search`](searchable#method-i-search) for more information. Or, if passed an integer, index into the NodeSet: ``` node_set.at(3) # same as node_set[3] ``` Calls superclass method [`Nokogiri::XML::Searchable#at`](searchable#method-i-at) Also aliased as: [%](nodeset#method-i-25) attr(key, value = nil) { |node| ... } Show source ``` # File lib/nokogiri/xml/node_set.rb, line 203 def attr(key, value = nil, &block) unless key.is_a?(Hash) || (key && (value || block)) return first&.attribute(key) end hash = key.is_a?(Hash) ? key : { key => value } hash.each do |k, v| each do |node| node[k] = v || yield(node) end end self end ``` Set attributes on each [`Node`](node) in the [`NodeSet`](nodeset), or get an attribute from the first [`Node`](node) in the [`NodeSet`](nodeset). To get an attribute from the first [`Node`](node) in a NodeSet: ``` node_set.attr("href") # => "https://www.nokogiri.org" ``` Note that an empty [`NodeSet`](nodeset) will return nil when `#attr` is called as a getter. To set an attribute on each node, `key` can either be an attribute name, or a Hash of attribute names and values. When called as a setter, `#attr` returns the [`NodeSet`](nodeset). If `key` is an attribute name, then either `value` or `block` must be passed. If `key` is a Hash then attributes will be set for each key/value pair: ``` node_set.attr("href" => "https://www.nokogiri.org", "class" => "member") ``` If `value` is passed, it will be used as the attribute value for all nodes: ``` node_set.attr("href", "https://www.nokogiri.org") ``` If `block` is passed, it will be called on each [`Node`](node) object in the [`NodeSet`](nodeset) and the return value used as the attribute value for that node: ``` node_set.attr("class") { |node| node.name } ``` Also aliased as: [set](nodeset#method-i-set), [attribute](nodeset#method-i-attribute) attribute(key, value = nil, &block) Alias for: [attr](nodeset#method-i-attr) before(datum) Show source ``` # File lib/nokogiri/xml/node_set.rb, line 63 def before(datum) first.before(datum) end ``` Insert `datum` before the first [`Node`](node) in this [`NodeSet`](nodeset) children() Show source ``` # File lib/nokogiri/xml/node_set.rb, line 406 def children node_set = NodeSet.new(document) each do |node| node.children.each { |n| node_set.push(n) } end node_set end ``` Returns a new [`NodeSet`](nodeset) containing all the children of all the nodes in the [`NodeSet`](nodeset) dup Alias for: [dup](nodeset#method-i-dup) css \*rules, [namespace-bindings, custom-pseudo-class] Show source ``` # File lib/nokogiri/xml/node_set.rb, line 83 def css(*args) rules, handler, ns, _ = extract_params(args) paths = css_rules_to_xpath(rules, ns) inject(NodeSet.new(document)) do |set, node| set + xpath_internal(node, paths, handler, ns, nil) end end ``` Search this node set for [`CSS`](../css) `rules`. `rules` must be one or more [`CSS`](../css) selectors. For example: For more information see [`Nokogiri::XML::Searchable#css`](searchable#method-i-css) deconstruct() β†’ Array Show source ``` # File lib/nokogiri/xml/node_set.rb, line 440 def deconstruct to_a end ``` Returns the members of this [`NodeSet`](nodeset) as an array, to use in pattern matching. ⚑ This is an experimental feature, available since v1.14.0 delete(node) Show source ``` static VALUE delete (VALUE self, VALUE rb_node) { xmlNodeSetPtr node_set; xmlNodePtr node; Check_Node_Set_Node_Type(rb_node); Data_Get_Struct(self, xmlNodeSet, node_set); Noko_Node_Get_Struct(rb_node, xmlNode, node); if (xmlXPathNodeSetContains(node_set, node)) { xpath_node_set_del(node_set, node); return rb_node; } return Qnil ; } ``` Delete `node` from the Nodeset, if it is a member. Returns the deleted node if found, otherwise returns nil. dup Show source ``` static VALUE duplicate(VALUE self) { xmlNodeSetPtr node_set; xmlNodeSetPtr dupl; Data_Get_Struct(self, xmlNodeSet, node_set); dupl = xmlXPathNodeSetMerge(NULL, node_set); return noko_xml_node_set_wrap(dupl, rb_iv_get(self, "@document")); } ``` Duplicate this [`NodeSet`](nodeset). Note that the Nodes contained in the [`NodeSet`](nodeset) are not duplicated (similar to how Array and other Enumerable classes work). Also aliased as: [clone](nodeset#method-i-clone) each() { |self| ... } Show source ``` # File lib/nokogiri/xml/node_set.rb, line 231 def each return to_enum unless block_given? 0.upto(length - 1) do |x| yield self[x] end self end ``` Iterate over each node, yielding to `block` empty?() Show source ``` # File lib/nokogiri/xml/node_set.rb, line 45 def empty? length == 0 end ``` Is this [`NodeSet`](nodeset) empty? filter(expr) Show source ``` # File lib/nokogiri/xml/node_set.rb, line 130 def filter(expr) find_all { |node| node.matches?(expr) } end ``` Filter this list for nodes that match `expr` first(n = nil) Show source ``` # File lib/nokogiri/xml/node_set.rb, line 29 def first(n = nil) return self[0] unless n list = [] [n, length].min.times { |i| list << self[i] } list end ``` Get the first element of the [`NodeSet`](nodeset). include?(node) Show source ``` static VALUE include_eh(VALUE self, VALUE rb_node) { xmlNodeSetPtr node_set; xmlNodePtr node; Check_Node_Set_Node_Type(rb_node); Data_Get_Struct(self, xmlNodeSet, node_set); Noko_Node_Get_Struct(rb_node, xmlNode, node); return (xmlXPathNodeSetContains(node_set, node) ? Qtrue : Qfalse); } ``` Returns true if any member of node set equals `node`. index(node = nil) { |member| ... } Show source ``` # File lib/nokogiri/xml/node_set.rb, line 51 def index(node = nil) if node warn("given block not used") if block_given? each_with_index { |member, j| return j if member == node } elsif block_given? each_with_index { |member, j| return j if yield(member) } end nil end ``` Returns the index of the first node in self that is == to `node` or meets the given block. Returns nil if no match is found. inner\_html(\*args) Show source ``` # File lib/nokogiri/xml/node_set.rb, line 260 def inner_html(*args) collect { |j| j.inner_html(*args) }.join("") end ``` Get the inner html of all contained [`Node`](node) objects inner\_text() Show source ``` # File lib/nokogiri/xml/node_set.rb, line 253 def inner_text collect(&:inner_text).join("") end ``` Get the inner text of all contained [`Node`](node) objects Note: This joins the text of all [`Node`](node) objects in the NodeSet: ``` doc = Nokogiri::XML('<xml><a><d>foo</d><d>bar</d></a></xml>') doc.css('d').text # => "foobar" ``` Instead, if you want to return the text of all nodes in the NodeSet: ``` doc.css('d').map(&:text) # => ["foo", "bar"] ``` See [`Nokogiri::XML::Node#content`](node#method-i-content) for more information. Also aliased as: [text](nodeset#method-i-text) inspect() Show source ``` # File lib/nokogiri/xml/node_set.rb, line 427 def inspect "[#{map(&:inspect).join(", ")}]" end ``` Return a nicely formated string representation last() Show source ``` # File lib/nokogiri/xml/node_set.rb, line 39 def last self[-1] end ``` Get the last element of the [`NodeSet`](nodeset). length Show source ``` static VALUE length(VALUE self) { xmlNodeSetPtr node_set; Data_Get_Struct(self, xmlNodeSet, node_set); return node_set ? INT2NUM(node_set->nodeNr) : INT2NUM(0); } ``` Get the length of the node set Also aliased as: [size](nodeset#method-i-size) pop() Show source ``` # File lib/nokogiri/xml/node_set.rb, line 374 def pop return nil if length == 0 delete(last) end ``` Removes the last element from set and returns it, or `nil` if the set is empty push(node) Show source ``` static VALUE push(VALUE self, VALUE rb_node) { xmlNodeSetPtr node_set; xmlNodePtr node; Check_Node_Set_Node_Type(rb_node); Data_Get_Struct(self, xmlNodeSet, node_set); Noko_Node_Get_Struct(rb_node, xmlNode, node); xmlXPathNodeSetAdd(node_set, node); return self; } ``` Append `node` to the [`NodeSet`](nodeset). Also aliased as: [<<](nodeset#method-i-3C-3C) unlink Alias for: [unlink](nodeset#method-i-unlink) remove\_attr(name) Show source ``` # File lib/nokogiri/xml/node_set.rb, line 223 def remove_attr(name) each { |el| el.delete(name) } self end ``` Remove the attributed named `name` from all [`Node`](node) objects in the [`NodeSet`](nodeset) Also aliased as: [remove\_attribute](nodeset#method-i-remove_attribute) remove\_attribute(name) Alias for: [remove\_attr](nodeset#method-i-remove_attr) remove\_class(name = nil) Show source ``` # File lib/nokogiri/xml/node_set.rb, line 163 def remove_class(name = nil) each do |el| el.remove_class(name) end self end ``` Remove the class attribute `name` from all [`Node`](node) objects in the [`NodeSet`](nodeset). See [`Nokogiri::XML::Node#remove_class`](node#method-i-remove_class) for more information. reverse() Show source ``` # File lib/nokogiri/xml/node_set.rb, line 417 def reverse node_set = NodeSet.new(document) (length - 1).downto(0) do |x| node_set.push(self[x]) end node_set end ``` Returns a new [`NodeSet`](nodeset) containing all the nodes in the [`NodeSet`](nodeset) in reverse order set(key, value = nil, &block) Alias for: [attr](nodeset#method-i-attr) shift() Show source ``` # File lib/nokogiri/xml/node_set.rb, line 383 def shift return nil if length == 0 delete(first) end ``` Returns the first element of the [`NodeSet`](nodeset) and removes it. Returns `nil` if the set is empty. length Alias for: [length](nodeset#method-i-length) slice(index) β†’ Node or nil slice(start, length) β†’ NodeSet or nil slice(range) β†’ NodeSet or nil [`Element`](element) reference - returns the node at `index`, or returns a [`NodeSet`](nodeset) containing nodes starting at `start` and continuing for `length` elements, or returns a [`NodeSet`](nodeset) containing nodes specified by `range`. Negative `indices` count backward from the end of the `node_set` (-1 is the last node). Returns nil if the `index` (or `start`) are out of range. Alias for: [[]](nodeset#method-i-5B-5D) text() Alias for: [inner\_text](nodeset#method-i-inner_text) to\_a Show source ``` static VALUE to_array(VALUE self) { xmlNodeSetPtr node_set ; VALUE list; int i; Data_Get_Struct(self, xmlNodeSet, node_set); list = rb_ary_new2(node_set->nodeNr); for (i = 0; i < node_set->nodeNr; i++) { VALUE elt = noko_xml_node_wrap_node_set_result(node_set->nodeTab[i], self); rb_ary_push(list, elt); } return list; } ``` Return this list as an Array Also aliased as: [to\_ary](nodeset#method-i-to_ary) to\_a Alias for: [to\_a](nodeset#method-i-to_a) to\_html(\*args) Show source ``` # File lib/nokogiri/xml/node_set.rb, line 341 def to_html(*args) if Nokogiri.jruby? options = args.first.is_a?(Hash) ? args.shift : {} options[:save_with] ||= Node::SaveOptions::DEFAULT_HTML args.insert(0, options) end if empty? encoding = (args.first.is_a?(Hash) ? args.first[:encoding] : nil) encoding ||= document.encoding encoding.nil? ? "" : "".encode(encoding) else map { |x| x.to_html(*args) }.join end end ``` Convert this [`NodeSet`](nodeset) to [`HTML`](../html4) to\_s() Show source ``` # File lib/nokogiri/xml/node_set.rb, line 335 def to_s map(&:to_s).join end ``` Convert this [`NodeSet`](nodeset) to a string. to\_xhtml(\*args) Show source ``` # File lib/nokogiri/xml/node_set.rb, line 358 def to_xhtml(*args) map { |x| x.to_xhtml(*args) }.join end ``` Convert this [`NodeSet`](nodeset) to XHTML to\_xml(\*args) Show source ``` # File lib/nokogiri/xml/node_set.rb, line 364 def to_xml(*args) map { |x| x.to_xml(*args) }.join end ``` Convert this [`NodeSet`](nodeset) to [`XML`](../xml) unlink Show source ``` static VALUE unlink_nodeset(VALUE self) { xmlNodeSetPtr node_set; int j, nodeNr ; Data_Get_Struct(self, xmlNodeSet, node_set); nodeNr = node_set->nodeNr ; for (j = 0 ; j < nodeNr ; j++) { if (! NOKOGIRI_NAMESPACE_EH(node_set->nodeTab[j])) { VALUE node ; xmlNodePtr node_ptr; node = noko_xml_node_wrap(Qnil, node_set->nodeTab[j]); rb_funcall(node, rb_intern("unlink"), 0); /* modifies the C struct out from under the object */ Noko_Node_Get_Struct(node, xmlNode, node_ptr); node_set->nodeTab[j] = node_ptr ; } } return self ; } ``` Unlink this [`NodeSet`](nodeset) and all [`Node`](node) objects it contains from their current context. Also aliased as: [remove](nodeset#method-i-remove) wrap(markup) β†’ self Show source wrap(node) β†’ self ``` # File lib/nokogiri/xml/node_set.rb, line 328 def wrap(node_or_tags) map { |node| node.wrap(node_or_tags) } self end ``` Wrap each member of this [`NodeSet`](nodeset) with the node parsed from `markup` or a dup of the `node`. Parameters * **markup** (String) Markup that is parsed, once per member of the [`NodeSet`](nodeset), and used as the wrapper. Each node’s parent, if it exists, is used as the context node for parsing; otherwise the associated document is used. If the parsed fragment has multiple roots, the first root node is used as the wrapper. * **node** ([`Nokogiri::XML::Node`](node)) An element that is β€˜#dup`ed and used as the wrapper. Returns `self`, to support chaining. ⚠ Note that if a `String` is passed, the markup will be parsed **once per node** in the [`NodeSet`](nodeset). You can avoid this overhead in cases where you know exactly the wrapper you wish to use by passing a `Node` instead. Also see [`Node#wrap`](node#method-i-wrap) **Example** with a `String` argument: ``` doc = Nokogiri::HTML5(<<~HTML) <html><body> <a>a</a> <a>b</a> <a>c</a> <a>d</a> </body></html> HTML doc.css("a").wrap("<div></div>") doc.to_html # => <html><head></head><body> # <div><a>a</a></div> # <div><a>b</a></div> # <div><a>c</a></div> # <div><a>d</a></div> # </body></html> ``` **Example** with a `Node` argument πŸ’‘ Note that this is faster than the equivalent call passing a `String` because it avoids having to reparse the wrapper markup for each node. ``` doc = Nokogiri::HTML5(<<~HTML) <html><body> <a>a</a> <a>b</a> <a>c</a> <a>d</a> </body></html> HTML doc.css("a").wrap(doc.create_element("div")) doc.to_html # => <html><head></head><body> # <div><a>a</a></div> # <div><a>b</a></div> # <div><a>c</a></div> # <div><a>d</a></div> # </body></html> ``` xpath \*paths, [namespace-bindings, variable-bindings, custom-handler-class] Show source ``` # File lib/nokogiri/xml/node_set.rb, line 99 def xpath(*args) paths, handler, ns, binds = extract_params(args) inject(NodeSet.new(document)) do |set, node| set + xpath_internal(node, paths, handler, ns, binds) end end ``` Search this node set for [`XPath`](xpath) `paths`. `paths` must be one or more [`XPath`](xpath) queries. For more information see [`Nokogiri::XML::Searchable#xpath`](searchable#method-i-xpath) |(node\_set) Show source ``` static VALUE rb_xml_node_set_union(VALUE rb_node_set, VALUE rb_other) { xmlNodeSetPtr c_node_set, c_other; xmlNodeSetPtr c_new_node_set; if (!rb_obj_is_kind_of(rb_other, cNokogiriXmlNodeSet)) { rb_raise(rb_eArgError, "node_set must be a Nokogiri::XML::NodeSet"); } Data_Get_Struct(rb_node_set, xmlNodeSet, c_node_set); Data_Get_Struct(rb_other, xmlNodeSet, c_other); c_new_node_set = xmlXPathNodeSetMerge(NULL, c_node_set); c_new_node_set = xmlXPathNodeSetMerge(c_new_node_set, c_other); return noko_xml_node_set_wrap(c_new_node_set, rb_iv_get(rb_node_set, "@document")); } ``` Returns a new set built by merging the set and the elements of the given set. Also aliased as: [+](nodeset#method-i-2B) /(\*args) Included from [Nokogiri::XML::Searchable](searchable) Alias for: [search](searchable#method-i-search) >(selector) β†’ NodeSet Show source ``` # File lib/nokogiri/xml/searchable.rb, line 196 def >(selector) # rubocop:disable Naming/BinaryOperatorParameterName ns = (document.root&.namespaces || {}) xpath(CSS.xpath_for(selector, prefix: "./", ns: ns).first) end ``` Included from [Nokogiri::XML::Searchable](searchable) Search this node’s immediate children using [`CSS`](../css) selector `selector` at\_css(\*rules, [namespace-bindings, custom-pseudo-class]) Show source ``` # File lib/nokogiri/xml/searchable.rb, line 140 def at_css(*args) css(*args).first end ``` Included from [Nokogiri::XML::Searchable](searchable) Search this object for [`CSS`](../css) `rules`, and return only the first match. `rules` must be one or more [`CSS`](../css) selectors. See [`Searchable#css`](searchable#method-i-css) for more information. at\_xpath(\*paths, [namespace-bindings, variable-bindings, custom-handler-class]) Show source ``` # File lib/nokogiri/xml/searchable.rb, line 188 def at_xpath(*args) xpath(*args).first end ``` Included from [Nokogiri::XML::Searchable](searchable) Search this node for [`XPath`](xpath) `paths`, and return only the first match. `paths` must be one or more [`XPath`](xpath) queries. See [`Searchable#xpath`](searchable#method-i-xpath) for more information. search(\*paths, [namespace-bindings, xpath-variable-bindings, custom-handler-class]) Show source ``` # File lib/nokogiri/xml/searchable.rb, line 51 def search(*args) paths, handler, ns, binds = extract_params(args) xpaths = paths.map(&:to_s).map do |path| LOOKS_LIKE_XPATH.match?(path) ? path : xpath_query_from_css_rule(path, ns) end.flatten.uniq xpath(*(xpaths + [ns, handler, binds].compact)) end ``` Included from [Nokogiri::XML::Searchable](searchable) Search this object for `paths`. `paths` must be one or more [`XPath`](xpath) or [`CSS`](../css) queries: ``` node.search("div.employee", ".//title") ``` A hash of namespace bindings may be appended: ``` node.search('.//bike:tire', {'bike' => 'http://schwinn.com/'}) node.search('bike|tire', {'bike' => 'http://schwinn.com/'}) ``` For [`XPath`](xpath) queries, a hash of variable bindings may also be appended to the namespace bindings. For example: ``` node.search('.//address[@domestic=$value]', nil, {:value => 'Yes'}) ``` πŸ’‘ Custom [`XPath`](xpath) functions and [`CSS`](../css) pseudo-selectors may also be defined. To define custom functions create a class and implement the function you want to define. The first argument to the method will be the current matching [`NodeSet`](nodeset). Any other arguments are ones that you pass in. Note that this class may appear anywhere in the argument list. For example: ``` handler = Class.new { def regex node_set, regex node_set.find_all { |node| node['some_attribute'] =~ /#{regex}/ } end }.new node.search('.//title[regex(., "\w+")]', 'div.employee:regex("[0-9]+")', handler) ``` See [`Searchable#xpath`](searchable#method-i-xpath) and [`Searchable#css`](searchable#method-i-css) for further usage help. Also aliased as: [/](searchable#method-i-2F)
programming_docs
nokogiri class Nokogiri::XML::EntityReference class Nokogiri::XML::EntityReference ===================================== Parent: cNokogiriXmlNode [`EntityReference`](entityreference) represents an [`EntityReference`](entityreference) node in an xml document. new(document, content) Show source ``` static VALUE new (int argc, VALUE *argv, VALUE klass) { xmlDocPtr xml_doc; xmlNodePtr node; VALUE document; VALUE name; VALUE rest; VALUE rb_node; rb_scan_args(argc, argv, "2*", &document, &name, &rest); Data_Get_Struct(document, xmlDoc, xml_doc); node = xmlNewReference( xml_doc, (const xmlChar *)StringValueCStr(name) ); noko_xml_document_pin_node(node); rb_node = noko_xml_node_wrap(klass, node); rb_obj_call_init(rb_node, argc, argv); if (rb_block_given_p()) { rb_yield(rb_node); } return rb_node; } ``` Create a new [`EntityReference`](entityreference) element on the `document` with `name` children() Show source ``` # File lib/nokogiri/xml/entity_reference.rb, line 6 def children # libxml2 will create a malformed child node for predefined # entities. because any use of that child is likely to cause a # segfault, we shall pretend that it doesn't exist. # # see https://github.com/sparklemotion/nokogiri/issues/1238 for details NodeSet.new(document) end ``` inspect\_attributes() Show source ``` # File lib/nokogiri/xml/entity_reference.rb, line 15 def inspect_attributes [:name] end ``` nokogiri class Nokogiri::XML::CharacterData class Nokogiri::XML::CharacterData =================================== Parent: cNokogiriXmlNode Included modules: [Nokogiri::XML::PP::CharacterData](pp/characterdata) nokogiri class Nokogiri::XML::AttributeDecl class Nokogiri::XML::AttributeDecl =================================== Parent: cNokogiriXmlNode Represents an attribute declaration in a [`DTD`](dtd) attribute\_type Show source ``` static VALUE attribute_type(VALUE self) { xmlAttributePtr node; Noko_Node_Get_Struct(self, xmlAttribute, node); return INT2NUM(node->atype); } ``` The [`attribute_type`](attributedecl#method-i-attribute_type) for this [`AttributeDecl`](attributedecl) default Show source ``` static VALUE default_value(VALUE self) { xmlAttributePtr node; Noko_Node_Get_Struct(self, xmlAttribute, node); if (node->defaultValue) { return NOKOGIRI_STR_NEW2(node->defaultValue); } return Qnil; } ``` The default value enumeration Show source ``` static VALUE enumeration(VALUE self) { xmlAttributePtr node; xmlEnumerationPtr enm; VALUE list; Noko_Node_Get_Struct(self, xmlAttribute, node); list = rb_ary_new(); enm = node->tree; while (enm) { rb_ary_push(list, NOKOGIRI_STR_NEW2(enm->name)); enm = enm->next; } return list; } ``` An enumeration of possible values inspect() Show source ``` # File lib/nokogiri/xml/attribute_decl.rb, line 15 def inspect "#<#{self.class.name}:#{format("0x%x", object_id)} #{to_s.inspect}>" end ``` nokogiri class Nokogiri::XML::Comment class Nokogiri::XML::Comment ============================= Parent: cNokogiriXmlCharacterData [`Comment`](comment) represents a comment node in an xml document. new(document\_or\_node, content) Show source ``` static VALUE new (int argc, VALUE *argv, VALUE klass) { xmlDocPtr xml_doc; xmlNodePtr node; VALUE document; VALUE content; VALUE rest; VALUE rb_node; rb_scan_args(argc, argv, "2*", &document, &content, &rest); if (rb_obj_is_kind_of(document, cNokogiriXmlNode)) { document = rb_funcall(document, document_id, 0); } else if (!rb_obj_is_kind_of(document, cNokogiriXmlDocument) && !rb_obj_is_kind_of(document, cNokogiriXmlDocumentFragment)) { rb_raise(rb_eArgError, "first argument must be a XML::Document or XML::Node"); } Data_Get_Struct(document, xmlDoc, xml_doc); node = xmlNewDocComment( xml_doc, (const xmlChar *)StringValueCStr(content) ); rb_node = noko_xml_node_wrap(klass, node); rb_obj_call_init(rb_node, argc, argv); noko_xml_document_pin_node(node); if (rb_block_given_p()) { rb_yield(rb_node); } return rb_node; } ``` Create a new [`Comment`](comment) element on the `document` with `content`. Alternatively, if a `node` is passed, the `node`β€˜s document is used. nokogiri class Nokogiri::XML::ElementDecl class Nokogiri::XML::ElementDecl ================================= Parent: cNokogiriXmlNode content Show source ``` static VALUE content(VALUE self) { xmlElementPtr node; Noko_Node_Get_Struct(self, xmlElement, node); if (!node->content) { return Qnil; } return noko_xml_element_content_wrap( rb_funcall(self, id_document, 0), node->content ); } ``` The allowed content for this [`ElementDecl`](elementdecl) element\_type Show source ``` static VALUE element_type(VALUE self) { xmlElementPtr node; Noko_Node_Get_Struct(self, xmlElement, node); return INT2NUM(node->etype); } ``` The [`element_type`](elementdecl#method-i-element_type) inspect() Show source ``` # File lib/nokogiri/xml/element_decl.rb, line 10 def inspect "#<#{self.class.name}:#{format("0x%x", object_id)} #{to_s.inspect}>" end ``` prefix Show source ``` static VALUE prefix(VALUE self) { xmlElementPtr node; Noko_Node_Get_Struct(self, xmlElement, node); if (!node->prefix) { return Qnil; } return NOKOGIRI_STR_NEW2(node->prefix); } ``` The namespace prefix for this [`ElementDecl`](elementdecl) nokogiri class Nokogiri::XML::ElementContent class Nokogiri::XML::ElementContent ==================================== Parent: [Object](https://nokogiri.org/rdoc/Object.html) Represents the allowed content in an [`Element`](element) Declaration inside a DTD: ``` <?xml version="1.0"?><?TEST-STYLE PIDATA?> <!DOCTYPE staff SYSTEM "staff.dtd" [ <!ELEMENT div1 (head, (p | list | note)*, div2*)> ]> </root> ``` [`ElementContent`](elementcontent) represents the tree inside the <!ELEMENT> tag shown above that lists the possible content for the div1 tag. ELEMENT MULT ONCE Possible content occurrences OPT OR PCDATA Possible definitions of type PLUS SEQ document[R] children() Show source ``` # File lib/nokogiri/xml/element_content.rb, line 33 def children [c1, c2].compact end ``` Get the children of this [`ElementContent`](elementcontent) node name Show source ``` static VALUE get_name(VALUE self) { xmlElementContentPtr elem; Data_Get_Struct(self, xmlElementContent, elem); if (!elem->name) { return Qnil; } return NOKOGIRI_STR_NEW2(elem->name); } ``` Get the require element `name` occur Show source ``` static VALUE get_occur(VALUE self) { xmlElementContentPtr elem; Data_Get_Struct(self, xmlElementContent, elem); return INT2NUM(elem->ocur); } ``` Get the element content `occur` flag. Possible values are [`ONCE`](elementcontent#ONCE), [`OPT`](elementcontent#OPT), [`MULT`](elementcontent#MULT) or [`PLUS`](elementcontent#PLUS). prefix Show source ``` static VALUE get_prefix(VALUE self) { xmlElementContentPtr elem; Data_Get_Struct(self, xmlElementContent, elem); if (!elem->prefix) { return Qnil; } return NOKOGIRI_STR_NEW2(elem->prefix); } ``` Get the element content namespace `prefix`. type Show source ``` static VALUE get_type(VALUE self) { xmlElementContentPtr elem; Data_Get_Struct(self, xmlElementContent, elem); return INT2NUM(elem->type); } ``` Get the element content `type`. Possible values are [`PCDATA`](elementcontent#PCDATA), [`ELEMENT`](elementcontent#ELEMENT), [`SEQ`](elementcontent#SEQ), or [`OR`](elementcontent#OR). nokogiri class Nokogiri::XML::XPathContext class Nokogiri::XML::XPathContext ================================== Parent: [Object](https://nokogiri.org/rdoc/Object.html) [`XPathContext`](xpathcontext) is the entry point for searching a [`Document`](document) by using [`XPath`](xpath). new(node) Show source ``` static VALUE rb_xml_xpath_context_new(VALUE klass, VALUE nodeobj) { xmlNodePtr node; xmlXPathContextPtr ctx; VALUE self; Noko_Node_Get_Struct(nodeobj, xmlNode, node); #if LIBXML_VERSION < 21000 /* deprecated in 40483d0 */ xmlXPathInit(); #endif ctx = xmlXPathNewContext(node->doc); ctx->node = node; xmlXPathRegisterNs(ctx, NOKOGIRI_PREFIX, NOKOGIRI_URI); xmlXPathRegisterNs(ctx, NOKOGIRI_BUILTIN_PREFIX, NOKOGIRI_BUILTIN_URI); xmlXPathRegisterFuncNS(ctx, (const xmlChar *)"css-class", NOKOGIRI_BUILTIN_URI, xpath_builtin_css_class); xmlXPathRegisterFuncNS(ctx, (const xmlChar *)"local-name-is", NOKOGIRI_BUILTIN_URI, xpath_builtin_local_name_is); self = Data_Wrap_Struct(klass, 0, xml_xpath_context_deallocate, ctx); return self; } ``` Create a new [`XPathContext`](xpathcontext) with `node` as the reference point. evaluate(search\_path, handler = nil) Show source ``` static VALUE rb_xml_xpath_context_evaluate(int argc, VALUE *argv, VALUE self) { VALUE search_path, xpath_handler; VALUE retval = Qnil; xmlXPathContextPtr ctx; xmlXPathObjectPtr xpath; xmlChar *query; VALUE errors = rb_ary_new(); Data_Get_Struct(self, xmlXPathContext, ctx); if (rb_scan_args(argc, argv, "11", &search_path, &xpath_handler) == 1) { xpath_handler = Qnil; } query = (xmlChar *)StringValueCStr(search_path); if (Qnil != xpath_handler) { /* FIXME: not sure if this is the correct place to shove private data. */ ctx->userData = (void *)xpath_handler; xmlXPathRegisterFuncLookup(ctx, handler_lookup, (void *)xpath_handler); } xmlSetStructuredErrorFunc((void *)errors, Nokogiri_error_array_pusher); xmlSetGenericErrorFunc((void *)errors, generic_exception_pusher); xpath = xmlXPathEvalExpression(query, ctx); xmlSetStructuredErrorFunc(NULL, NULL); xmlSetGenericErrorFunc(NULL, NULL); if (xpath == NULL) { rb_exc_raise(rb_ary_entry(errors, 0)); } retval = xpath2ruby(xpath, ctx); if (retval == Qundef) { retval = noko_xml_node_set_wrap(NULL, DOC_RUBY_OBJECT(ctx->doc)); } xmlXPathFreeNodeSetList(xpath); return retval; } ``` Evaluate the `search_path` returning an [`XML::XPath`](xpath) object. register\_namespaces(namespaces) Show source ``` # File lib/nokogiri/xml/xpath_context.rb, line 8 def register_namespaces(namespaces) namespaces.each do |k, v| k = k.to_s.gsub(/.*:/, "") # strip off 'xmlns:' or 'xml:' register_ns(k, v) end end ``` Register namespaces in `namespaces` register\_ns(prefix, uri) Show source ``` static VALUE rb_xml_xpath_context_register_ns(VALUE self, VALUE prefix, VALUE uri) { xmlXPathContextPtr ctx; Data_Get_Struct(self, xmlXPathContext, ctx); xmlXPathRegisterNs(ctx, (const xmlChar *)StringValueCStr(prefix), (const xmlChar *)StringValueCStr(uri) ); return self; } ``` Register the namespace with `prefix` and `uri`. register\_variable(name, value) Show source ``` static VALUE rb_xml_xpath_context_register_variable(VALUE self, VALUE name, VALUE value) { xmlXPathContextPtr ctx; xmlXPathObjectPtr xmlValue; Data_Get_Struct(self, xmlXPathContext, ctx); xmlValue = xmlXPathNewCString(StringValueCStr(value)); xmlXPathRegisterVariable(ctx, (const xmlChar *)StringValueCStr(name), xmlValue ); return self; } ``` Register the variable `name` with `value`. nokogiri class Nokogiri::XML::RelaxNG class Nokogiri::XML::RelaxNG ============================= Parent: cNokogiriXmlSchema [`Nokogiri::XML::RelaxNG`](relaxng) is used for validating [`XML`](../xml) against a [`RelaxNG`](relaxng) schema. Synopsis -------- Validate an [`XML`](../xml) document against a [`RelaxNG`](relaxng) schema. Loop over the errors that are returned and print them out: ``` schema = Nokogiri::XML::RelaxNG(File.open(ADDRESS_SCHEMA_FILE)) doc = Nokogiri::XML(File.open(ADDRESS_XML_FILE)) schema.validate(doc).each do |error| puts error.message end ``` The list of errors are [`Nokogiri::XML::SyntaxError`](syntaxerror) objects. NOTE: [`RelaxNG`](relaxng) input is always treated as TRUSTED documents, meaning that they will cause the underlying parsing libraries to access network resources. This is counter to Nokogiri’s β€œuntrusted by default” security policy, but is a limitation of the underlying libraries. from\_document(doc) Show source ``` static VALUE from_document(int argc, VALUE *argv, VALUE klass) { VALUE document; VALUE parse_options; xmlDocPtr doc; xmlRelaxNGParserCtxtPtr ctx; xmlRelaxNGPtr schema; VALUE errors; VALUE rb_schema; int scanned_args = 0; scanned_args = rb_scan_args(argc, argv, "11", &document, &parse_options); Data_Get_Struct(document, xmlDoc, doc); doc = doc->doc; /* In case someone passes us a node. ugh. */ if (scanned_args == 1) { parse_options = rb_const_get_at(rb_const_get_at(mNokogiriXml, rb_intern("ParseOptions")), rb_intern("DEFAULT_SCHEMA")); } ctx = xmlRelaxNGNewDocParserCtxt(doc); errors = rb_ary_new(); xmlSetStructuredErrorFunc((void *)errors, Nokogiri_error_array_pusher); #ifdef HAVE_XMLRELAXNGSETPARSERSTRUCTUREDERRORS xmlRelaxNGSetParserStructuredErrors( ctx, Nokogiri_error_array_pusher, (void *)errors ); #endif schema = xmlRelaxNGParse(ctx); xmlSetStructuredErrorFunc(NULL, NULL); xmlRelaxNGFreeParserCtxt(ctx); if (NULL == schema) { xmlErrorPtr error = xmlGetLastError(); if (error) { Nokogiri_error_raise(NULL, error); } else { rb_raise(rb_eRuntimeError, "Could not parse document"); } return Qnil; } rb_schema = Data_Wrap_Struct(klass, 0, dealloc, schema); rb_iv_set(rb_schema, "@errors", errors); rb_iv_set(rb_schema, "@parse_options", parse_options); return rb_schema; } ``` Create a new [`RelaxNG`](relaxng) schema from the [`Nokogiri::XML::Document`](document) `doc` read\_memory(string) Show source ``` static VALUE read_memory(int argc, VALUE *argv, VALUE klass) { VALUE content; VALUE parse_options; xmlRelaxNGParserCtxtPtr ctx; xmlRelaxNGPtr schema; VALUE errors; VALUE rb_schema; int scanned_args = 0; scanned_args = rb_scan_args(argc, argv, "11", &content, &parse_options); if (scanned_args == 1) { parse_options = rb_const_get_at(rb_const_get_at(mNokogiriXml, rb_intern("ParseOptions")), rb_intern("DEFAULT_SCHEMA")); } ctx = xmlRelaxNGNewMemParserCtxt((const char *)StringValuePtr(content), (int)RSTRING_LEN(content)); errors = rb_ary_new(); xmlSetStructuredErrorFunc((void *)errors, Nokogiri_error_array_pusher); #ifdef HAVE_XMLRELAXNGSETPARSERSTRUCTUREDERRORS xmlRelaxNGSetParserStructuredErrors( ctx, Nokogiri_error_array_pusher, (void *)errors ); #endif schema = xmlRelaxNGParse(ctx); xmlSetStructuredErrorFunc(NULL, NULL); xmlRelaxNGFreeParserCtxt(ctx); if (NULL == schema) { xmlErrorPtr error = xmlGetLastError(); if (error) { Nokogiri_error_raise(NULL, error); } else { rb_raise(rb_eRuntimeError, "Could not parse document"); } return Qnil; } rb_schema = Data_Wrap_Struct(klass, 0, dealloc, schema); rb_iv_set(rb_schema, "@errors", errors); rb_iv_set(rb_schema, "@parse_options", parse_options); return rb_schema; } ``` Create a new [`RelaxNG`](relaxng) from the contents of `string` nokogiri class Nokogiri::XML::ParseOptions class Nokogiri::XML::ParseOptions ================================== Parent: [Object](https://nokogiri.org/rdoc/Object.html) Options that control the parsing behavior for [`XML::Document`](document), [`XML::DocumentFragment`](documentfragment), [`HTML4::Document`](../html4/document), [`HTML4::DocumentFragment`](../html4/documentfragment), [`XSLT::Stylesheet`](../xslt/stylesheet), and [`XML::Schema`](schema). These options directly expose libxml2’s parse options, which are all boolean in the sense that an option is β€œon” or β€œoff”. πŸ’‘ Note that [`HTML5`](../html5) parsing has a separate, orthogonal set of options due to the nature of the [`HTML5`](../html5) specification. See [`Nokogiri::HTML5`](../html5). ⚠ Not all parse options are supported on JRuby. [`Nokogiri`](../../nokogiri) will attempt to invoke the equivalent behavior in Xerces/NekoHTML on JRuby when it’s possible. Setting and unsetting parse options ----------------------------------- You can build your own combinations of parse options by using any of the following methods: [`ParseOptions`](parseoptions) method chaining Every option has an equivalent method in lowercase. You can chain these methods together to set various combinations. ``` # Set the HUGE & PEDANTIC options po = Nokogiri::XML::ParseOptions.new.huge.pedantic doc = Nokogiri::XML::Document.parse(xml, nil, nil, po) ``` Every option has an equivalent `no{option}` method in lowercase. You can call these methods on an instance of [`ParseOptions`](parseoptions) to unset the option. ``` # Set the HUGE & PEDANTIC options po = Nokogiri::XML::ParseOptions.new.huge.pedantic # later we want to modify the options po.nohuge # Unset the HUGE option po.nopedantic # Unset the PEDANTIC option ``` πŸ’‘ Note that some options begin with β€œno” leading to the logical but perhaps unintuitive double negative: ``` po.nocdata # Set the NOCDATA parse option po.nonocdata # Unset the NOCDATA parse option ``` πŸ’‘ Note that negation is not available for [`STRICT`](parseoptions#STRICT), which is itself a negation of all other features. Using Ruby Blocks Most parsing methods will accept a block for configuration of parse options, and we recommend chaining the setter methods: ``` doc = Nokogiri::XML::Document.parse(xml) { |config| config.huge.pedantic } ``` [`ParseOptions`](parseoptions) constants You can also use the constants declared under [`Nokogiri::XML::ParseOptions`](parseoptions) to set various combinations. They are bits in a bitmask, and so can be combined with bitwise operators: ``` po = Nokogiri::XML::ParseOptions.new(Nokogiri::XML::ParseOptions::HUGE | Nokogiri::XML::ParseOptions::PEDANTIC) doc = Nokogiri::XML::Document.parse(xml, nil, nil, po) ``` BIG\_LINES Support line numbers up to `long int` (default is a `short int`). On by default for for [`XML::Document`](document), [`XML::DocumentFragment`](documentfragment), [`HTML4::Document`](../html4/document), [`HTML4::DocumentFragment`](../html4/documentfragment), [`XSLT::Stylesheet`](../xslt/stylesheet), and [`XML::Schema`](schema). COMPACT Compact small text nodes. Off by default. ⚠ No modification of the DOM tree is allowed after parsing. libxml2 may crash if you try to modify the tree. DEFAULT\_HTML The options mask used by default used for parsing [`HTML4::Document`](../html4/document) and [`HTML4::DocumentFragment`](../html4/documentfragment) DEFAULT\_SCHEMA The options mask used by default used for parsing [`XML::Schema`](schema) DEFAULT\_XML The options mask used by default for parsing [`XML::Document`](document) and [`XML::DocumentFragment`](documentfragment) DEFAULT\_XSLT The options mask used by default used for parsing [`XSLT::Stylesheet`](../xslt/stylesheet) DTDATTR Default [`DTD`](dtd) attributes. On by default for [`XSLT::Stylesheet`](../xslt/stylesheet). DTDLOAD Load external subsets. On by default for [`XSLT::Stylesheet`](../xslt/stylesheet). ⚠ **It is UNSAFE to set this option** when parsing untrusted documents. DTDVALID Validate with the [`DTD`](dtd). Off by default. HUGE Relax any hardcoded limit from the parser. Off by default. ⚠ There may be a performance penalty when this option is set. NOBASEFIX Do not fixup XInclude xml:base uris. Off by default NOBLANKS Remove blank nodes. Off by default. NOCDATA Merge [`CDATA`](cdata) as text nodes. On by default for [`XSLT::Stylesheet`](../xslt/stylesheet). NODICT Do not reuse the context dictionary. Off by default. NOENT Substitute entities. Off by default. ⚠ This option enables entity substitution, contrary to what the name implies. ⚠ **It is UNSAFE to set this option** when parsing untrusted documents. NOERROR Suppress error reports. On by default for [`HTML4::Document`](../html4/document) and [`HTML4::DocumentFragment`](../html4/documentfragment) NONET Forbid network access. On by default for [`XML::Document`](document), [`XML::DocumentFragment`](documentfragment), [`HTML4::Document`](../html4/document), [`HTML4::DocumentFragment`](../html4/documentfragment), [`XSLT::Stylesheet`](../xslt/stylesheet), and [`XML::Schema`](schema). ⚠ **It is UNSAFE to unset this option** when parsing untrusted documents. NOWARNING Suppress warning reports. On by default for [`HTML4::Document`](../html4/document) and [`HTML4::DocumentFragment`](../html4/documentfragment) NOXINCNODE Do not generate XInclude START/END nodes. Off by default. NSCLEAN Remove redundant namespaces declarations. Off by default. OLD10 Parse using XML-1.0 before update 5. Off by default PEDANTIC Enable pedantic error reporting. Off by default. RECOVER Recover from errors. On by default for [`XML::Document`](document), [`XML::DocumentFragment`](documentfragment), [`HTML4::Document`](../html4/document), [`HTML4::DocumentFragment`](../html4/documentfragment), [`XSLT::Stylesheet`](../xslt/stylesheet), and [`XML::Schema`](schema). SAX1 Use the [`SAX1`](parseoptions#SAX1) interface internally. Off by default. STRICT Strict parsing XINCLUDE Implement XInclude substitution. Off by default. options[RW] to\_i[RW] new(options = STRICT) Show source ``` # File lib/nokogiri/xml/parse_options.rb, line 165 def initialize(options = STRICT) @options = options end ``` ==(other) Show source ``` # File lib/nokogiri/xml/parse_options.rb, line 198 def ==(other) other.to_i == to_i end ``` inspect() Show source ``` # File lib/nokogiri/xml/parse_options.rb, line 204 def inspect options = [] self.class.constants.each do |k| options << k.downcase if send(:"#{k.downcase}?") end super.sub(/>$/, " " + options.join(", ") + ">") end ``` Calls superclass method strict() Show source ``` # File lib/nokogiri/xml/parse_options.rb, line 189 def strict @options &= ~RECOVER self end ``` strict?() Show source ``` # File lib/nokogiri/xml/parse_options.rb, line 194 def strict? @options & RECOVER == STRICT end ```
programming_docs
nokogiri module Nokogiri::XML::SAX module Nokogiri::XML::SAX ========================== [`SAX`](sax) Parsers are event driven parsers. [`Nokogiri`](../../nokogiri) provides two different event based parsers when dealing with [`XML`](../xml). If you want to do [`SAX`](sax) style parsing using [`HTML`](../html4), check out [`Nokogiri::HTML4::SAX`](../html4/sax). The basic way a [`SAX`](sax) style parser works is by creating a parser, telling the parser about the events we’re interested in, then giving the parser some [`XML`](../xml) to process. The parser will notify you when it encounters events you said you would like to know about. To register for events, you simply subclass [`Nokogiri::XML::SAX::Document`](sax/document), and implement the methods for which you would like notification. For example, if I want to be notified when a document ends, and when an element starts, I would write a class like this: ``` class MyDocument < Nokogiri::XML::SAX::Document def end_document puts "the document has ended" end def start_element name, attributes = [] puts "#{name} started" end end ``` Then I would instantiate a [`SAX`](sax) parser with this document, and feed the parser some [`XML`](../xml) ``` # Create a new parser parser = Nokogiri::XML::SAX::Parser.new(MyDocument.new) # Feed the parser some XML parser.parse(File.open(ARGV[0])) ``` Now my document handler will be called when each node starts, and when then document ends. To see what kinds of events are available, take a look at [`Nokogiri::XML::SAX::Document`](sax/document). Two [`SAX`](sax) parsers for [`XML`](../xml) are available, a parser that reads from a string or IO object as it feels necessary, and a parser that lets you spoon feed it [`XML`](../xml). If you want to let [`Nokogiri`](../../nokogiri) deal with reading your [`XML`](../xml), use the [`Nokogiri::XML::SAX::Parser`](sax/parser). If you want to have fine grain control over the [`XML`](../xml) input, use the [`Nokogiri::XML::SAX::PushParser`](sax/pushparser). nokogiri class Nokogiri::XML::ProcessingInstruction class Nokogiri::XML::ProcessingInstruction =========================================== Parent: cNokogiriXmlNode [`ProcessingInstruction`](processinginstruction) represents a [`ProcessingInstruction`](processinginstruction) node in an xml document. new(document, name, content) Show source ``` static VALUE new (int argc, VALUE *argv, VALUE klass) { xmlDocPtr xml_doc; xmlNodePtr node; VALUE document; VALUE name; VALUE content; VALUE rest; VALUE rb_node; rb_scan_args(argc, argv, "3*", &document, &name, &content, &rest); Data_Get_Struct(document, xmlDoc, xml_doc); node = xmlNewDocPI( xml_doc, (const xmlChar *)StringValueCStr(name), (const xmlChar *)StringValueCStr(content) ); noko_xml_document_pin_node(node); rb_node = noko_xml_node_wrap(klass, node); rb_obj_call_init(rb_node, argc, argv); if (rb_block_given_p()) { rb_yield(rb_node); } return rb_node; } ``` Create a new [`ProcessingInstruction`](processinginstruction) element on the `document` with `name` and `content` new(document, name, content) Show source ``` # File lib/nokogiri/xml/processing_instruction.rb, line 6 def initialize(document, name, content) super(document, name) end ``` Calls superclass method nokogiri module Nokogiri::XML::Searchable module Nokogiri::XML::Searchable ================================= The [`Searchable`](searchable) module declares the interface used for searching your DOM. It implements the public methods [`#search`](searchable#method-i-search), [`#css`](searchable#method-i-css), and [`#xpath`](searchable#method-i-xpath), as well as allowing specific implementations to specialize some of the important behaviors. LOOKS\_LIKE\_XPATH Regular expression used by [`Searchable#search`](searchable#method-i-search) to determine if a query string is [`CSS`](../css) or [`XPath`](xpath) %(\*args) Alias for: [at](searchable#method-i-at) /(\*args) Alias for: [search](searchable#method-i-search) >(selector) β†’ NodeSet Show source ``` # File lib/nokogiri/xml/searchable.rb, line 196 def >(selector) # rubocop:disable Naming/BinaryOperatorParameterName ns = (document.root&.namespaces || {}) xpath(CSS.xpath_for(selector, prefix: "./", ns: ns).first) end ``` Search this node’s immediate children using [`CSS`](../css) selector `selector` at(\*paths, [namespace-bindings, xpath-variable-bindings, custom-handler-class]) Show source ``` # File lib/nokogiri/xml/searchable.rb, line 71 def at(*args) search(*args).first end ``` Search this object for `paths`, and return only the first result. `paths` must be one or more [`XPath`](xpath) or [`CSS`](../css) queries. See [`Searchable#search`](searchable#method-i-search) for more information. Also aliased as: [%](searchable#method-i-25) at\_css(\*rules, [namespace-bindings, custom-pseudo-class]) Show source ``` # File lib/nokogiri/xml/searchable.rb, line 140 def at_css(*args) css(*args).first end ``` Search this object for [`CSS`](../css) `rules`, and return only the first match. `rules` must be one or more [`CSS`](../css) selectors. See [`Searchable#css`](searchable#method-i-css) for more information. at\_xpath(\*paths, [namespace-bindings, variable-bindings, custom-handler-class]) Show source ``` # File lib/nokogiri/xml/searchable.rb, line 188 def at_xpath(*args) xpath(*args).first end ``` Search this node for [`XPath`](xpath) `paths`, and return only the first match. `paths` must be one or more [`XPath`](xpath) queries. See [`Searchable#xpath`](searchable#method-i-xpath) for more information. css(\*rules, [namespace-bindings, custom-pseudo-class]) Show source ``` # File lib/nokogiri/xml/searchable.rb, line 126 def css(*args) rules, handler, ns, _ = extract_params(args) css_internal(self, rules, handler, ns) end ``` Search this object for [`CSS`](../css) `rules`. `rules` must be one or more [`CSS`](../css) selectors. For example: ``` node.css('title') node.css('body h1.bold') node.css('div + p.green', 'div#one') ``` A hash of namespace bindings may be appended. For example: ``` node.css('bike|tire', {'bike' => 'http://schwinn.com/'}) ``` πŸ’‘ Custom [`CSS`](../css) pseudo classes may also be defined which are mapped to a custom [`XPath`](xpath) function. To define custom pseudo classes, create a class and implement the custom pseudo class you want defined. The first argument to the method will be the matching context [`NodeSet`](nodeset). Any other arguments are ones that you pass in. For example: ``` handler = Class.new { def regex(node_set, regex) node_set.find_all { |node| node['some_attribute'] =~ /#{regex}/ } end }.new node.css('title:regex("\w+")', handler) ``` πŸ’‘ Some [`XPath`](xpath) syntax is supported in [`CSS`](../css) queries. For example, to query for an attribute: ``` node.css('img > @href') # returns all +href+ attributes on an +img+ element node.css('img / @href') # same # ⚠ this returns +class+ attributes from all +div+ elements AND THEIR CHILDREN! node.css('div @class') node.css ``` πŸ’‘ Array-like syntax is supported in [`CSS`](../css) queries as an alternative to using +:nth-child()+. ⚠ NOTE that indices are 1-based like `:nth-child` and not 0-based like Ruby Arrays. For example: ``` # equivalent to 'li:nth-child(2)' node.css('li[2]') # retrieve the second li element in a list ``` ⚠ NOTE that the [`CSS`](../css) query string is case-sensitive with regards to your document type. [`HTML`](../html4) tags will match only lowercase [`CSS`](../css) queries, so if you search for β€œH1” in an [`HTML`](../html4) document, you’ll never find anything. However, β€œH1” might be found in an [`XML`](../xml) document, where tags names are case-sensitive (e.g., β€œH1” is distinct from β€œh1”). search(\*paths, [namespace-bindings, xpath-variable-bindings, custom-handler-class]) Show source ``` # File lib/nokogiri/xml/searchable.rb, line 51 def search(*args) paths, handler, ns, binds = extract_params(args) xpaths = paths.map(&:to_s).map do |path| LOOKS_LIKE_XPATH.match?(path) ? path : xpath_query_from_css_rule(path, ns) end.flatten.uniq xpath(*(xpaths + [ns, handler, binds].compact)) end ``` Search this object for `paths`. `paths` must be one or more [`XPath`](xpath) or [`CSS`](../css) queries: ``` node.search("div.employee", ".//title") ``` A hash of namespace bindings may be appended: ``` node.search('.//bike:tire', {'bike' => 'http://schwinn.com/'}) node.search('bike|tire', {'bike' => 'http://schwinn.com/'}) ``` For [`XPath`](xpath) queries, a hash of variable bindings may also be appended to the namespace bindings. For example: ``` node.search('.//address[@domestic=$value]', nil, {:value => 'Yes'}) ``` πŸ’‘ Custom [`XPath`](xpath) functions and [`CSS`](../css) pseudo-selectors may also be defined. To define custom functions create a class and implement the function you want to define. The first argument to the method will be the current matching [`NodeSet`](nodeset). Any other arguments are ones that you pass in. Note that this class may appear anywhere in the argument list. For example: ``` handler = Class.new { def regex node_set, regex node_set.find_all { |node| node['some_attribute'] =~ /#{regex}/ } end }.new node.search('.//title[regex(., "\w+")]', 'div.employee:regex("[0-9]+")', handler) ``` See [`Searchable#xpath`](searchable#method-i-xpath) and [`Searchable#css`](searchable#method-i-css) for further usage help. Also aliased as: [/](searchable#method-i-2F) xpath(\*paths, [namespace-bindings, variable-bindings, custom-handler-class]) Show source ``` # File lib/nokogiri/xml/searchable.rb, line 174 def xpath(*args) paths, handler, ns, binds = extract_params(args) xpath_internal(self, paths, handler, ns, binds) end ``` Search this node for [`XPath`](xpath) `paths`. `paths` must be one or more [`XPath`](xpath) queries. ``` node.xpath('.//title') ``` A hash of namespace bindings may be appended. For example: ``` node.xpath('.//foo:name', {'foo' => 'http://example.org/'}) node.xpath('.//xmlns:name', node.root.namespaces) ``` A hash of variable bindings may also be appended to the namespace bindings. For example: ``` node.xpath('.//address[@domestic=$value]', nil, {:value => 'Yes'}) ``` πŸ’‘ Custom [`XPath`](xpath) functions may also be defined. To define custom functions create a class and implement the function you want to define. The first argument to the method will be the current matching [`NodeSet`](nodeset). Any other arguments are ones that you pass in. Note that this class may appear anywhere in the argument list. For example: ``` handler = Class.new { def regex(node_set, regex) node_set.find_all { |node| node['some_attribute'] =~ /#{regex}/ } end }.new node.xpath('.//title[regex(., "\w+")]', handler) ``` nokogiri class Nokogiri::XML::DocumentFragment class Nokogiri::XML::DocumentFragment ====================================== Parent: cNokogiriXmlNode [`DocumentFragment`](documentfragment) represents a [`DocumentFragment`](documentfragment) node in an xml document. new(document) Show source ``` static VALUE new (int argc, VALUE *argv, VALUE klass) { xmlDocPtr xml_doc; xmlNodePtr node; VALUE document; VALUE rest; VALUE rb_node; rb_scan_args(argc, argv, "1*", &document, &rest); Data_Get_Struct(document, xmlDoc, xml_doc); node = xmlNewDocFragment(xml_doc->doc); noko_xml_document_pin_node(node); rb_node = noko_xml_node_wrap(klass, node); rb_obj_call_init(rb_node, argc, argv); return rb_node; } ``` Create a new [`DocumentFragment`](documentfragment) element on the `document` new(document, tags = nil, ctx = nil, options = ParseOptions::DEFAULT\_XML) { |options| ... } Show source ``` # File lib/nokogiri/xml/document_fragment.rb, line 19 def initialize(document, tags = nil, ctx = nil, options = ParseOptions::DEFAULT_XML) return self unless tags options = Nokogiri::XML::ParseOptions.new(options) if Integer === options yield options if block_given? children = if ctx # Fix for issue#490 if Nokogiri.jruby? # fix for issue #770 ctx.parse("<root #{namespace_declarations(ctx)}>#{tags}</root>", options).children else ctx.parse(tags, options) end else wrapper_doc = XML::Document.parse("<root>#{tags}</root>", nil, nil, options) self.errors = wrapper_doc.errors wrapper_doc.xpath("/root/node()") end children.each { |child| child.parent = self } end ``` Create a new [`DocumentFragment`](documentfragment) from `tags`. If `ctx` is present, it is used as a context node for the subtree created, e.g., namespaces will be resolved relative to `ctx`. parse(tags, options = ParseOptions::DEFAULT\_XML, &block) Show source ``` # File lib/nokogiri/xml/document_fragment.rb, line 9 def self.parse(tags, options = ParseOptions::DEFAULT_XML, &block) new(XML::Document.new, tags, nil, options, &block) end ``` Create a [`Nokogiri::XML::DocumentFragment`](documentfragment) from `tags` css \*rules, [namespace-bindings, custom-pseudo-class] Show source ``` # File lib/nokogiri/xml/document_fragment.rb, line 102 def css(*args) if children.any? children.css(*args) # 'children' is a smell here else NodeSet.new(document) end end ``` Search this fragment for [`CSS`](../css) `rules`. `rules` must be one or more [`CSS`](../css) selectors. For example: For more information see [`Nokogiri::XML::Searchable#css`](searchable#method-i-css) deconstruct() β†’ Array Show source ``` # File lib/nokogiri/xml/document_fragment.rb, line 190 def deconstruct children.to_a end ``` Returns the root nodes of this document fragment as an array, to use in pattern matching. πŸ’‘ Note that text nodes are returned as well as elements. If you wish to operate only on root elements, you should deconstruct the array returned by `DocumentFragment#elements`. ⚑ This is an experimental feature, available since v1.14.0 **Example** ``` frag = Nokogiri::HTML5.fragment(<<~HTML) <div>Start</div> This is a <a href="#jump">shortcut</a> for you. <div>End</div> HTML frag.deconstruct # => [#(Element:0x35c { name = "div", children = [ #(Text "Start")] }), # #(Text "\n" + "This is a "), # #(Element:0x370 { # name = "a", # attributes = [ #(Attr:0x384 { name = "href", value = "#jump" })], # children = [ #(Text "shortcut")] # }), # #(Text " for you.\n"), # #(Element:0x398 { name = "div", children = [ #(Text "End")] }), # #(Text "\n")] ``` **Example** only the elements, not the text nodes. ``` frag.elements.deconstruct # => [#(Element:0x35c { name = "div", children = [ #(Text "Start")] }), # #(Element:0x370 { # name = "a", # attributes = [ #(Attr:0x384 { name = "href", value = "#jump" })], # children = [ #(Text "shortcut")] # }), # #(Element:0x398 { name = "div", children = [ #(Text "End")] })] ``` dup() Show source ``` # File lib/nokogiri/xml/document_fragment.rb, line 42 def dup new_document = document.dup new_fragment = self.class.new(new_document) children.each do |child| child.dup(1, new_document).parent = new_fragment end new_fragment end ``` errors() Show source ``` # File lib/nokogiri/xml/document_fragment.rb, line 136 def errors document.errors end ``` A list of [`Nokogiri::XML::SyntaxError`](syntaxerror) found when parsing a document fragment(data) Show source ``` # File lib/nokogiri/xml/document_fragment.rb, line 144 def fragment(data) document.fragment(data) end ``` name() Show source ``` # File lib/nokogiri/xml/document_fragment.rb, line 54 def name "#document-fragment" end ``` return the name for [`DocumentFragment`](documentfragment) search \*paths, [namespace-bindings, xpath-variable-bindings, custom-handler-class] Show source ``` # File lib/nokogiri/xml/document_fragment.rb, line 121 def search(*rules) rules, handler, ns, binds = extract_params(rules) rules.inject(NodeSet.new(document)) do |set, rule| set + if Searchable::LOOKS_LIKE_XPATH.match?(rule) xpath(*[rule, ns, handler, binds].compact) else children.css(*[rule, ns, handler].compact) # 'children' is a smell here end end end ``` Search this fragment for `paths`. `paths` must be one or more [`XPath`](xpath) or [`CSS`](../css) queries. For more information see [`Nokogiri::XML::Searchable#search`](searchable#method-i-search) serialize() Alias for: [to\_s](documentfragment#method-i-to_s) to\_html(\*args) Show source ``` # File lib/nokogiri/xml/document_fragment.rb, line 67 def to_html(*args) if Nokogiri.jruby? options = args.first.is_a?(Hash) ? args.shift : {} options[:save_with] ||= Node::SaveOptions::DEFAULT_HTML args.insert(0, options) end children.to_html(*args) end ``` Convert this [`DocumentFragment`](documentfragment) to html See [`Nokogiri::XML::NodeSet#to_html`](nodeset#method-i-to_html) to\_s() Show source ``` # File lib/nokogiri/xml/document_fragment.rb, line 60 def to_s children.to_s end ``` Convert this [`DocumentFragment`](documentfragment) to a string Also aliased as: [serialize](documentfragment#method-i-serialize) to\_xhtml(\*args) Show source ``` # File lib/nokogiri/xml/document_fragment.rb, line 79 def to_xhtml(*args) if Nokogiri.jruby? options = args.first.is_a?(Hash) ? args.shift : {} options[:save_with] ||= Node::SaveOptions::DEFAULT_XHTML args.insert(0, options) end children.to_xhtml(*args) end ``` Convert this [`DocumentFragment`](documentfragment) to xhtml See [`Nokogiri::XML::NodeSet#to_xhtml`](nodeset#method-i-to_xhtml) to\_xml(\*args) Show source ``` # File lib/nokogiri/xml/document_fragment.rb, line 91 def to_xml(*args) children.to_xml(*args) end ``` Convert this [`DocumentFragment`](documentfragment) to xml See [`Nokogiri::XML::NodeSet#to_xml`](nodeset#method-i-to_xml) nokogiri class Nokogiri::XML::SyntaxError class Nokogiri::XML::SyntaxError ================================= Parent: cNokogiriSyntaxError The [`XML::SyntaxError`](syntaxerror) is raised on parse errors This class provides information about [`XML`](../xml) SyntaxErrors. These exceptions are typically stored on [`Nokogiri::XML::Document#errors`](document#attribute-i-errors). code[R] column[R] domain[R] file[R] int1[R] level[R] line[R] str1[R] str2[R] str3[R] error?() Show source ``` # File lib/nokogiri/xml/syntax_error.rb, line 34 def error? level == 2 end ``` return true if this is an error fatal?() Show source ``` # File lib/nokogiri/xml/syntax_error.rb, line 40 def fatal? level == 3 end ``` return true if this error is fatal none?() Show source ``` # File lib/nokogiri/xml/syntax_error.rb, line 22 def none? level == 0 end ``` return true if this is a non error to\_s() Show source ``` # File lib/nokogiri/xml/syntax_error.rb, line 44 def to_s message = super.chomp [location_to_s, level_to_s, message] .compact.join(": ") .force_encoding(message.encoding) end ``` Calls superclass method warning?() Show source ``` # File lib/nokogiri/xml/syntax_error.rb, line 28 def warning? level == 1 end ``` return true if this is a warning nokogiri class Nokogiri::XML::Notation class Nokogiri::XML::Notation ============================== Parent: Struct.new(:name, :public\_id, :system\_id) Struct representing an [XML Schema Notation](https://www.w3.org/TR/xml/#Notations) name[RW] The name for the element. public\_id[RW] The URI corresponding to the public identifier system\_id[RW] The URI corresponding to the system identifier
programming_docs
nokogiri class Nokogiri::XML::XPath::SyntaxError class Nokogiri::XML::XPath::SyntaxError ======================================== Parent: cNokogiriXmlSyntaxError to\_s() Show source ``` # File lib/nokogiri/xml/xpath/syntax_error.rb, line 7 def to_s [super.chomp, str1].compact.join(": ") end ``` Calls superclass method nokogiri class Nokogiri::XML::SAX::ParserContext class Nokogiri::XML::SAX::ParserContext ======================================== Parent: [Object](https://nokogiri.org/rdoc/Object.html) Context for [`XML`](../../xml) [`SAX`](../sax) parsers. This class is usually not instantiated by the user. Instead, you should be looking at [`Nokogiri::XML::SAX::Parser`](parser) parse\_file(filename) Show source ``` static VALUE parse_file(VALUE klass, VALUE filename) { xmlParserCtxtPtr ctxt = xmlCreateFileParserCtxt(StringValueCStr(filename)); return Data_Wrap_Struct(klass, NULL, deallocate, ctxt); } ``` Parse file given `filename` parse\_io(io, encoding) Show source ``` static VALUE parse_io(VALUE klass, VALUE io, VALUE encoding) { xmlParserCtxtPtr ctxt; xmlCharEncoding enc = (xmlCharEncoding)NUM2INT(encoding); if (!rb_respond_to(io, id_read)) { rb_raise(rb_eTypeError, "argument expected to respond to :read"); } ctxt = xmlCreateIOParserCtxt(NULL, NULL, (xmlInputReadCallback)noko_io_read, (xmlInputCloseCallback)noko_io_close, (void *)io, enc); if (ctxt->sax) { xmlFree(ctxt->sax); ctxt->sax = NULL; } return Data_Wrap_Struct(klass, NULL, deallocate, ctxt); } ``` Parse `io` object with `encoding` parse\_memory(data) Show source ``` static VALUE parse_memory(VALUE klass, VALUE data) { xmlParserCtxtPtr ctxt; Check_Type(data, T_STRING); if (!(int)RSTRING_LEN(data)) { rb_raise(rb_eRuntimeError, "data cannot be empty"); } ctxt = xmlCreateMemoryParserCtxt(StringValuePtr(data), (int)RSTRING_LEN(data)); if (ctxt->sax) { xmlFree(ctxt->sax); ctxt->sax = NULL; } return Data_Wrap_Struct(klass, NULL, deallocate, ctxt); } ``` Parse the [`XML`](../../xml) stored in memory in `data` new(thing, encoding = "UTF-8") Show source ``` # File lib/nokogiri/xml/sax/parser_context.rb, line 11 def self.new(thing, encoding = "UTF-8") if [:read, :close].all? { |x| thing.respond_to?(x) } io(thing, Parser::ENCODINGS[encoding]) else memory(thing) end end ``` column Show source ``` static VALUE column(VALUE self) { xmlParserCtxtPtr ctxt; xmlParserInputPtr io; Data_Get_Struct(self, xmlParserCtxt, ctxt); io = ctxt->input; if (io) { return INT2NUM(io->col); } return Qnil; } ``` Get the current column the parser context is processing. line Show source ``` static VALUE line(VALUE self) { xmlParserCtxtPtr ctxt; xmlParserInputPtr io; Data_Get_Struct(self, xmlParserCtxt, ctxt); io = ctxt->input; if (io) { return INT2NUM(io->line); } return Qnil; } ``` Get the current line the parser context is processing. parse\_with(sax\_handler) Show source ``` static VALUE parse_with(VALUE self, VALUE sax_handler) { xmlParserCtxtPtr ctxt; xmlSAXHandlerPtr sax; if (!rb_obj_is_kind_of(sax_handler, cNokogiriXmlSaxParser)) { rb_raise(rb_eArgError, "argument must be a Nokogiri::XML::SAX::Parser"); } Data_Get_Struct(self, xmlParserCtxt, ctxt); Data_Get_Struct(sax_handler, xmlSAXHandler, sax); /* Free the sax handler since we'll assign our own */ if (ctxt->sax && ctxt->sax != (xmlSAXHandlerPtr)&xmlDefaultSAXHandler) { xmlFree(ctxt->sax); } ctxt->sax = sax; ctxt->userData = (void *)NOKOGIRI_SAX_TUPLE_NEW(ctxt, sax_handler); xmlSetStructuredErrorFunc(NULL, NULL); rb_ensure(parse_doc, (VALUE)ctxt, parse_doc_finalize, (VALUE)ctxt); return Qnil; } ``` Use `sax_handler` and parse the current document recovery Show source ``` static VALUE get_recovery(VALUE self) { xmlParserCtxtPtr ctxt; Data_Get_Struct(self, xmlParserCtxt, ctxt); if (ctxt->recovery == 0) { return Qfalse; } else { return Qtrue; } } ``` Should this parser recover from structural errors? It will not stop processing file on structural errors if set to true recovery=(boolean) Show source ``` static VALUE set_recovery(VALUE self, VALUE value) { xmlParserCtxtPtr ctxt; Data_Get_Struct(self, xmlParserCtxt, ctxt); if (value == Qfalse) { ctxt->recovery = 0; } else { ctxt->recovery = 1; } return value; } ``` Should this parser recover from structural errors? It will not stop processing file on structural errors if set to true replace\_entities Show source ``` static VALUE get_replace_entities(VALUE self) { xmlParserCtxtPtr ctxt; Data_Get_Struct(self, xmlParserCtxt, ctxt); if (0 == ctxt->replaceEntities) { return Qfalse; } else { return Qtrue; } } ``` Should this parser replace entities? &amp; will get converted to β€˜&’ if set to true replace\_entities=(boolean) Show source ``` static VALUE set_replace_entities(VALUE self, VALUE value) { xmlParserCtxtPtr ctxt; Data_Get_Struct(self, xmlParserCtxt, ctxt); if (Qfalse == value) { ctxt->replaceEntities = 0; } else { ctxt->replaceEntities = 1; } return value; } ``` Should this parser replace entities? &amp; will get converted to β€˜&’ if set to true nokogiri class Nokogiri::XML::SAX::Parser class Nokogiri::XML::SAX::Parser ================================= Parent: [Object](https://nokogiri.org/rdoc/Object.html) This parser is a [`SAX`](../sax) style parser that reads it’s input as it deems necessary. The parser takes a [`Nokogiri::XML::SAX::Document`](document), an optional encoding, then given an [`XML`](../../xml) input, sends messages to the [`Nokogiri::XML::SAX::Document`](document). Here is an example of using this parser: ``` # Create a subclass of Nokogiri::XML::SAX::Document and implement # the events we care about: class MyDoc < Nokogiri::XML::SAX::Document def start_element name, attrs = [] puts "starting: #{name}" end def end_element name puts "ending: #{name}" end end # Create our parser parser = Nokogiri::XML::SAX::Parser.new(MyDoc.new) # Send some XML to the parser parser.parse(File.open(ARGV[0])) ``` For more information about [`SAX`](../sax) parsers, see [`Nokogiri::XML::SAX`](../sax). Also see [`Nokogiri::XML::SAX::Document`](document) for the available events. ENCODINGS Encodinds this parser supports document[RW] The [`Nokogiri::XML::SAX::Document`](document) where events will be sent. encoding[RW] The encoding beings used for this document. new(doc = Nokogiri::XML::SAX::Document.new, encoding = "UTF-8") Show source ``` # File lib/nokogiri/xml/sax/parser.rb, line 72 def initialize(doc = Nokogiri::XML::SAX::Document.new, encoding = "UTF-8") @encoding = check_encoding(encoding) @document = doc @warned = false end ``` Create a new [`Parser`](parser) with `doc` and `encoding` parse(thing, &block) Show source ``` # File lib/nokogiri/xml/sax/parser.rb, line 81 def parse(thing, &block) if thing.respond_to?(:read) && thing.respond_to?(:close) parse_io(thing, &block) else parse_memory(thing, &block) end end ``` Parse given `thing` which may be a string containing xml, or an IO object. parse\_file(filename) { |ctx| ... } Show source ``` # File lib/nokogiri/xml/sax/parser.rb, line 99 def parse_file(filename) raise ArgumentError unless filename raise Errno::ENOENT unless File.exist?(filename) raise Errno::EISDIR if File.directory?(filename) ctx = ParserContext.file(filename) yield ctx if block_given? ctx.parse_with(self) end ``` Parse a file with `filename` parse\_io(io, encoding = @encoding) { |ctx| ... } Show source ``` # File lib/nokogiri/xml/sax/parser.rb, line 91 def parse_io(io, encoding = @encoding) ctx = ParserContext.io(io, ENCODINGS[check_encoding(encoding)]) yield ctx if block_given? ctx.parse_with(self) end ``` Parse given `io` parse\_memory(data) { |ctx| ... } Show source ``` # File lib/nokogiri/xml/sax/parser.rb, line 109 def parse_memory(data) ctx = ParserContext.memory(data) yield ctx if block_given? ctx.parse_with(self) end ``` nokogiri class Nokogiri::XML::SAX::Document class Nokogiri::XML::SAX::Document =================================== Parent: [Object](https://nokogiri.org/rdoc/Object.html) This class is used for registering types of events you are interested in handling. All of the methods on this class are available as possible events while parsing an [`XML`](../../xml) document. To register for any particular event, just subclass this class and implement the methods you are interested in knowing about. To only be notified about start and end element events, write a class like this: ``` class MyDocument < Nokogiri::XML::SAX::Document def start_element name, attrs = [] puts "#{name} started!" end def end_element name puts "#{name} ended" end end ``` You can use this event handler for any [`SAX`](../sax) style parser included with [`Nokogiri`](../../../nokogiri). See [`Nokogiri::XML::SAX`](../sax), and [`Nokogiri::HTML4::SAX`](../../html4/sax). cdata\_block(string) Show source ``` # File lib/nokogiri/xml/sax/document.rb, line 155 def cdata_block(string) end ``` Called when cdata blocks are found `string` contains the cdata content characters(string) Show source ``` # File lib/nokogiri/xml/sax/document.rb, line 131 def characters(string) end ``` Characters read between a tag. This method might be called multiple times given one contiguous string of characters. `string` contains the character data comment(string) Show source ``` # File lib/nokogiri/xml/sax/document.rb, line 137 def comment(string) end ``` Called when comments are encountered `string` contains the comment data end\_document() Show source ``` # File lib/nokogiri/xml/sax/document.rb, line 79 def end_document end ``` Called when document ends parsing end\_element(name) Show source ``` # File lib/nokogiri/xml/sax/document.rb, line 93 def end_element(name) end ``` Called at the end of an element `name` is the tag name end\_element\_namespace(name, prefix = nil, uri = nil) Show source ``` # File lib/nokogiri/xml/sax/document.rb, line 120 def end_element_namespace(name, prefix = nil, uri = nil) ### # Deal with SAX v1 interface end_element([prefix, name].compact.join(":")) end ``` Called at the end of an element `name` is the element’s name `prefix` is the namespace prefix associated with the element `uri` is the associated namespace URI error(string) Show source ``` # File lib/nokogiri/xml/sax/document.rb, line 149 def error(string) end ``` Called on document errors `string` contains the error processing\_instruction(name, content) Show source ``` # File lib/nokogiri/xml/sax/document.rb, line 162 def processing_instruction(name, content) end ``` Called when processing instructions are found `name` is the target of the instruction `content` is the value of the instruction start\_document() Show source ``` # File lib/nokogiri/xml/sax/document.rb, line 74 def start_document end ``` Called when document starts parsing start\_element(name, attrs = []) Show source ``` # File lib/nokogiri/xml/sax/document.rb, line 87 def start_element(name, attrs = []) end ``` Called at the beginning of an element * `name` is the name of the tag * `attrs` are an assoc list of namespaces and attributes, e.g.: ``` [ ["xmlns:foo", "http://sample.net"], ["size", "large"] ] ``` start\_element\_namespace(name, attrs = [], prefix = nil, uri = nil, ns = []) Show source ``` # File lib/nokogiri/xml/sax/document.rb, line 103 def start_element_namespace(name, attrs = [], prefix = nil, uri = nil, ns = []) ### # Deal with SAX v1 interface name = [prefix, name].compact.join(":") attributes = ns.map do |ns_prefix, ns_uri| [["xmlns", ns_prefix].compact.join(":"), ns_uri] end + attrs.map do |attr| [[attr.prefix, attr.localname].compact.join(":"), attr.value] end start_element(name, attributes) end ``` Called at the beginning of an element `name` is the element name `attrs` is a list of attributes `prefix` is the namespace prefix for the element `uri` is the associated namespace URI `ns` is a hash of namespace prefix:urls associated with the element warning(string) Show source ``` # File lib/nokogiri/xml/sax/document.rb, line 143 def warning(string) end ``` Called on document warnings `string` contains the warning xmldecl(version, encoding, standalone) Show source ``` # File lib/nokogiri/xml/sax/document.rb, line 69 def xmldecl(version, encoding, standalone) end ``` Called when an [`XML`](../../xml) declaration is parsed nokogiri class Nokogiri::XML::SAX::PushParser class Nokogiri::XML::SAX::PushParser ===================================== Parent: [Object](https://nokogiri.org/rdoc/Object.html) [`PushParser`](pushparser) can parse a document that is fed to it manually. It must be given a [`SAX::Document`](document) object which will be called with [`SAX`](../sax) events as the document is being parsed. Calling [`PushParser#<<`](pushparser#method-i-3C-3C) writes [`XML`](../../xml) to the parser, calling any [`SAX`](../sax) callbacks it can. [`PushParser#finish`](pushparser#method-i-finish) tells the parser that the document is finished and calls the end\_document [`SAX`](../sax) method. Example: ``` parser = PushParser.new(Class.new(XML::SAX::Document) { def start_document puts "start document called" end }.new) parser << "<div>hello<" parser << "/div>" parser.finish ``` document[RW] The [`Nokogiri::XML::SAX::Document`](document) on which the [`PushParser`](pushparser) will be operating new(doc = XML::SAX::Document.new, file\_name = nil, encoding = "UTF-8") Show source ``` # File lib/nokogiri/xml/sax/push_parser.rb, line 35 def initialize(doc = XML::SAX::Document.new, file_name = nil, encoding = "UTF-8") @document = doc @encoding = encoding @sax_parser = XML::SAX::Parser.new(doc) ## Create our push parser context initialize_native(@sax_parser, file_name) end ``` Create a new [`PushParser`](pushparser) with `doc` as the [`SAX`](../sax) [`Document`](document), providing an optional `file_name` and `encoding` <<(chunk, last\_chunk = false) Alias for: [write](pushparser#method-i-write) finish() Show source ``` # File lib/nokogiri/xml/sax/push_parser.rb, line 55 def finish write("", true) end ``` Finish the parsing. This method is only necessary for [`Nokogiri::XML::SAX::Document#end_document`](document#method-i-end_document) to be called. options() Show source ``` static VALUE get_options(VALUE self) { xmlParserCtxtPtr ctx; Data_Get_Struct(self, xmlParserCtxt, ctx); return INT2NUM(ctx->options); } ``` options=(p1) Show source ``` static VALUE set_options(VALUE self, VALUE options) { xmlParserCtxtPtr ctx; Data_Get_Struct(self, xmlParserCtxt, ctx); if (xmlCtxtUseOptions(ctx, (int)NUM2INT(options)) != 0) { rb_raise(rb_eRuntimeError, "Cannot set XML parser context options"); } return Qnil; } ``` replace\_entities Show source ``` static VALUE get_replace_entities(VALUE self) { xmlParserCtxtPtr ctx; Data_Get_Struct(self, xmlParserCtxt, ctx); if (0 == ctx->replaceEntities) { return Qfalse; } else { return Qtrue; } } ``` Should this parser replace entities? &amp; will get converted to β€˜&’ if set to true replace\_entities=(boolean) Show source ``` static VALUE set_replace_entities(VALUE self, VALUE value) { xmlParserCtxtPtr ctx; Data_Get_Struct(self, xmlParserCtxt, ctx); if (Qfalse == value) { ctx->replaceEntities = 0; } else { ctx->replaceEntities = 1; } return value; } ``` Should this parser replace entities? &amp; will get converted to β€˜&’ if set to true write(chunk, last\_chunk = false) Show source ``` # File lib/nokogiri/xml/sax/push_parser.rb, line 47 def write(chunk, last_chunk = false) native_write(chunk, last_chunk) end ``` Write a `chunk` of [`XML`](../../xml) to the [`PushParser`](pushparser). Any callback methods that can be called will be called immediately. Also aliased as: [<<](pushparser#method-i-3C-3C) nokogiri class Nokogiri::XML::SAX::Parser::Attribute class Nokogiri::XML::SAX::Parser::Attribute ============================================ Parent: Struct.new(:localname, :prefix, :uri, :value) nokogiri class Nokogiri::XML::Node::SaveOptions class Nokogiri::XML::Node::SaveOptions ======================================= Parent: [Object](https://nokogiri.org/rdoc/Object.html) Save options for serializing nodes. See the method group entitled [Serialization and Generating Output at `Node`](../node#class-Nokogiri::XML::Node-label-Serialization+and+Generating+Output) for usage. AS\_BUILDER Save builder created document AS\_HTML Save as [`HTML`](../../html4) AS\_XHTML Save as XHTML AS\_XML Save as [`XML`](../../xml) DEFAULT\_HTML the default for [`HTML`](../../html4) document DEFAULT\_XHTML the default for XHTML document DEFAULT\_XML the default for [`XML`](../../xml) documents FORMAT Format serialized xml NO\_DECLARATION Do not include declarations NO\_EMPTY\_TAGS Do not include empty tags NO\_XHTML Do not save XHTML options[R] Integer representation of the [`SaveOptions`](saveoptions) to\_i[R] Integer representation of the [`SaveOptions`](saveoptions) new(options = 0) Show source ``` # File lib/nokogiri/xml/node/save_options.rb, line 47 def initialize(options = 0) @options = options end ``` Create a new [`SaveOptions`](saveoptions) object with `options` nokogiri class Nokogiri::XSLT::Stylesheet class Nokogiri::XSLT::Stylesheet ================================= Parent: [Object](https://nokogiri.org/rdoc/Object.html) A [`Stylesheet`](stylesheet) represents an [`XSLT`](../xslt) [`Stylesheet`](stylesheet) object. [`Stylesheet`](stylesheet) creation is done through [`Nokogiri.XSLT`](../../nokogiri#method-c-XSLT). Here is an example of transforming an [`XML::Document`](../xml/document) with a Stylesheet: ``` doc = Nokogiri::XML(File.read('some_file.xml')) xslt = Nokogiri::XSLT(File.read('some_transformer.xslt')) puts xslt.transform(doc) ``` See [`Nokogiri::XSLT::Stylesheet#transform`](stylesheet#method-i-transform) for more transformation information. parse\_stylesheet\_doc(document) Show source ``` static VALUE parse_stylesheet_doc(VALUE klass, VALUE xmldocobj) { xmlDocPtr xml, xml_cpy; VALUE errstr, exception; xsltStylesheetPtr ss ; Data_Get_Struct(xmldocobj, xmlDoc, xml); errstr = rb_str_new(0, 0); xsltSetGenericErrorFunc((void *)errstr, xslt_generic_error_handler); xml_cpy = xmlCopyDoc(xml, 1); /* 1 => recursive */ ss = xsltParseStylesheetDoc(xml_cpy); xsltSetGenericErrorFunc(NULL, NULL); if (!ss) { xmlFreeDoc(xml_cpy); exception = rb_exc_new3(rb_eRuntimeError, errstr); rb_exc_raise(exception); } return Nokogiri_wrap_xslt_stylesheet(ss); } ``` Parse a stylesheet from `document`. apply\_to(document, params = []) Show source ``` # File lib/nokogiri/xslt/stylesheet.rb, line 22 def apply_to(document, params = []) serialize(transform(document, params)) end ``` Apply an [`XSLT`](../xslt) stylesheet to an [`XML::Document`](../xml/document). `params` is an array of strings used as [`XSLT`](../xslt) parameters. returns serialized document serialize(document) Show source ``` static VALUE serialize(VALUE self, VALUE xmlobj) { xmlDocPtr xml ; nokogiriXsltStylesheetTuple *wrapper; xmlChar *doc_ptr ; int doc_len ; VALUE rval ; Data_Get_Struct(xmlobj, xmlDoc, xml); Data_Get_Struct(self, nokogiriXsltStylesheetTuple, wrapper); xsltSaveResultToString(&doc_ptr, &doc_len, xml, wrapper->ss); rval = NOKOGIRI_STR_NEW(doc_ptr, doc_len); xmlFree(doc_ptr); return rval ; } ``` Serialize `document` to an xml string. transform(document) Show source transform(document, params = {}) ``` static VALUE transform(int argc, VALUE *argv, VALUE self) { VALUE xmldoc, paramobj, errstr, exception ; xmlDocPtr xml ; xmlDocPtr result ; nokogiriXsltStylesheetTuple *wrapper; const char **params ; long param_len, j ; int parse_error_occurred ; rb_scan_args(argc, argv, "11", &xmldoc, &paramobj); if (NIL_P(paramobj)) { paramobj = rb_ary_new2(0L) ; } if (!rb_obj_is_kind_of(xmldoc, cNokogiriXmlDocument)) { rb_raise(rb_eArgError, "argument must be a Nokogiri::XML::Document"); } /* handle hashes as arguments. */ if (T_HASH == TYPE(paramobj)) { paramobj = rb_funcall(paramobj, rb_intern("to_a"), 0); paramobj = rb_funcall(paramobj, rb_intern("flatten"), 0); } Check_Type(paramobj, T_ARRAY); Data_Get_Struct(xmldoc, xmlDoc, xml); Data_Get_Struct(self, nokogiriXsltStylesheetTuple, wrapper); param_len = RARRAY_LEN(paramobj); params = ruby_xcalloc((size_t)param_len + 1, sizeof(char *)); for (j = 0 ; j < param_len ; j++) { VALUE entry = rb_ary_entry(paramobj, j); const char *ptr = StringValueCStr(entry); params[j] = ptr; } params[param_len] = 0 ; errstr = rb_str_new(0, 0); xsltSetGenericErrorFunc((void *)errstr, xslt_generic_error_handler); xmlSetGenericErrorFunc((void *)errstr, xslt_generic_error_handler); result = xsltApplyStylesheet(wrapper->ss, xml, params); ruby_xfree(params); xsltSetGenericErrorFunc(NULL, NULL); xmlSetGenericErrorFunc(NULL, NULL); parse_error_occurred = (Qfalse == rb_funcall(errstr, rb_intern("empty?"), 0)); if (parse_error_occurred) { exception = rb_exc_new3(rb_eRuntimeError, errstr); rb_exc_raise(exception); } return noko_xml_document_wrap((VALUE)0, result) ; } ``` Apply an [`XSLT`](../xslt) stylesheet to an [`XML::Document`](../xml/document). Parameters * `document` ([`Nokogiri::XML::Document`](../xml/document)) the document to be transformed. * `params` (Hash, Array) strings used as [`XSLT`](../xslt) parameters. Returns [`Nokogiri::XML::Document`](../xml/document) **Example** of basic transformation: ``` xslt = <<~XSLT <xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform"> <xsl:param name="title"/> <xsl:template match="/"> <html> <body> <h1><xsl:value-of select="$title"/></h1> <ol> <xsl:for-each select="staff/employee"> <li><xsl:value-of select="employeeId"></li> </xsl:for-each> </ol> </body> </html> </xsl:stylesheet> XSLT xml = <<~XML <?xml version="1.0"?> <staff> <employee> <employeeId>EMP0001</employeeId> <position>Accountant</position> </employee> <employee> <employeeId>EMP0002</employeeId> <position>Developer</position> </employee> </staff> XML doc = Nokogiri::XML::Document.parse(xml) stylesheet = Nokogiri::XSLT.parse(xslt) ``` ⚠ Note that the `h1` element is empty because no param has been provided! ``` stylesheet.transform(doc).to_xml # => "<html><body>\n" + # "<h1></h1>\n" + # "<ol>\n" + # "<li>EMP0001</li>\n" + # "<li>EMP0002</li>\n" + # "</ol>\n" + # "</body></html>\n" ``` **Example** of using an input parameter hash: ⚠ The title is populated, but note how we need to quote-escape the value. ``` stylesheet.transform(doc, { "title" => "'Employee List'" }).to_xml # => "<html><body>\n" + # "<h1>Employee List</h1>\n" + # "<ol>\n" + # "<li>EMP0001</li>\n" + # "<li>EMP0002</li>\n" + # "</ol>\n" + # "</body></html>\n" ``` **Example** using the [`XSLT.quote_params`](../xslt#method-c-quote_params) helper method to safely quote-escape strings: ``` stylesheet.transform(doc, Nokogiri::XSLT.quote_params({ "title" => "Aaron's List" })).to_xml # => "<html><body>\n" + # "<h1>Aaron's List</h1>\n" + # "<ol>\n" + # "<li>EMP0001</li>\n" + # "<li>EMP0002</li>\n" + # "</ol>\n" + # "</body></html>\n" ``` **Example** using an array of [`XSLT`](../xslt) parameters You can also use an array if you want to. ``` stylesheet.transform(doc, ["title", "'Employee List'"]).to_xml # => "<html><body>\n" + # "<h1>Employee List</h1>\n" + # "<ol>\n" + # "<li>EMP0001</li>\n" + # "<li>EMP0002</li>\n" + # "</ol>\n" + # "</body></html>\n" ``` Or pass an array to [`XSLT.quote_params`](../xslt#method-c-quote_params): ``` stylesheet.transform(doc, Nokogiri::XSLT.quote_params(["title", "Aaron's List"])).to_xml # => "<html><body>\n" + # "<h1>Aaron's List</h1>\n" + # "<ol>\n" + # "<li>EMP0001</li>\n" + # "<li>EMP0002</li>\n" + # "</ol>\n" + # "</body></html>\n" ``` See: [`Nokogiri::XSLT.quote_params`](../xslt#method-c-quote_params)
programming_docs
werkzeug Werkzeug Werkzeug ======== *werkzeug* German noun: β€œtool”. Etymology: *werk* (β€œwork”), *zeug* (β€œstuff”) Werkzeug is a comprehensive [WSGI](https://wsgi.readthedocs.io/en/latest/) web application library. It began as a simple collection of various utilities for WSGI applications and has become one of the most advanced WSGI utility libraries. Werkzeug doesn’t enforce any dependencies. It is up to the developer to choose a template engine, database adapter, and even how to handle requests. Getting Started --------------- * [Installation](installation/index) + [Python Version](installation/index#python-version) + [Dependencies](installation/index#dependencies) + [Virtual environments](installation/index#virtual-environments) + [Install Werkzeug](installation/index#install-werkzeug) * [Werkzeug Tutorial](tutorial/index) + [Introducing Shortly](tutorial/index#introducing-shortly) + [Step 0: A Basic WSGI Introduction](tutorial/index#step-0-a-basic-wsgi-introduction) + [Step 1: Creating the Folders](tutorial/index#step-1-creating-the-folders) + [Step 2: The Base Structure](tutorial/index#step-2-the-base-structure) + [Intermezzo: Running the Application](tutorial/index#intermezzo-running-the-application) + [Step 3: The Environment](tutorial/index#step-3-the-environment) + [Step 4: The Routing](tutorial/index#step-4-the-routing) + [Step 5: The First View](tutorial/index#step-5-the-first-view) + [Step 6: Redirect View](tutorial/index#step-6-redirect-view) + [Step 7: Detail View](tutorial/index#step-7-detail-view) + [Step 8: Templates](tutorial/index#step-8-templates) + [Step 9: The Style](tutorial/index#step-9-the-style) + [Bonus: Refinements](tutorial/index#bonus-refinements) * [API Levels](levels/index) + [Example](levels/index#example) + [High or Low?](levels/index#high-or-low) * [Quickstart](quickstart/index) * [WSGI Environment](quickstart/index#wsgi-environment) * [Enter Request](quickstart/index#enter-request) * [Header Parsing](quickstart/index#header-parsing) * [Responses](quickstart/index#responses) Serving and Testing ------------------- * [Serving WSGI Applications](serving/index) + [Reloader](serving/index#reloader) + [Colored Logging](serving/index#colored-logging) + [Virtual Hosts](serving/index#virtual-hosts) + [Shutting Down The Server](serving/index#shutting-down-the-server) + [Troubleshooting](serving/index#troubleshooting) + [SSL](serving/index#ssl) + [Unix Sockets](serving/index#unix-sockets) * [Testing WSGI Applications](test/index) + [Test Client](test/index#test-client) + [Request Body](test/index#request-body) + [Environment Builder](test/index#environment-builder) + [API](test/index#api) * [Debugging Applications](debug/index) + [Enabling the Debugger](debug/index#enabling-the-debugger) + [Using the Debugger](debug/index#using-the-debugger) + [Debugger PIN](debug/index#debugger-pin) + [Pasting Errors](debug/index#pasting-errors) Reference --------- * [Request / Response Objects](wrappers/index) + [How they Work](wrappers/index#how-they-work) + [Mutability and Reusability of Wrappers](wrappers/index#mutability-and-reusability-of-wrappers) + [Wrapper Classes](wrappers/index#wrapper-classes) * [URL Routing](routing/index) + [Quickstart](routing/index#quickstart) + [Rule Format](routing/index#rule-format) + [Built-in Converters](routing/index#built-in-converters) + [Maps, Rules and Adapters](routing/index#maps-rules-and-adapters) + [Matchers](routing/index#matchers) + [Rule Factories](routing/index#rule-factories) + [Rule Templates](routing/index#rule-templates) + [Custom Converters](routing/index#custom-converters) + [Host Matching](routing/index#host-matching) + [WebSockets](routing/index#websockets) + [State Machine Matching](routing/index#state-machine-matching) * [WSGI Helpers](wsgi/index) + [Iterator / Stream Helpers](wsgi/index#iterator-stream-helpers) + [Environ Helpers](wsgi/index#environ-helpers) + [Convenience Helpers](wsgi/index#convenience-helpers) + [Bytes, Strings, and Encodings](wsgi/index#bytes-strings-and-encodings) + [Raw Request URI and Path Encoding](wsgi/index#raw-request-uri-and-path-encoding) * [HTTP Utilities](http/index) + [Datetime Functions](http/index#datetime-functions) + [Header Parsing](http/index#header-parsing) + [Header Utilities](http/index#header-utilities) + [Cookies](http/index#cookies) + [Conditional Response Helpers](http/index#conditional-response-helpers) + [Constants](http/index#constants) + [Form Data Parsing](http/index#module-werkzeug.formparser) * [Data Structures](datastructures/index) + [General Purpose](datastructures/index#general-purpose) + [HTTP Related](datastructures/index#http-related) + [Others](datastructures/index#others) * [Utilities](utils/index) + [General Helpers](utils/index#general-helpers) + [URL Helpers](utils/index#url-helpers) + [User Agent API](utils/index#module-werkzeug.user_agent) + [Security Helpers](utils/index#module-werkzeug.security) + [Logging](utils/index#logging) * [URL Helpers](urls/index) * [Context Locals](local/index) * [Proxy Objects](local/index#proxy-objects) * [Stacks and Namespaces](local/index#stacks-and-namespaces) * [Releasing Data](local/index#releasing-data) * [Middleware](middleware/index) + [X-Forwarded-For Proxy Fix](middleware/proxy_fix/index) + [Serve Shared Static Files](middleware/shared_data/index) + [Application Dispatcher](middleware/dispatcher/index) + [Basic HTTP Proxy](middleware/http_proxy/index) + [WSGI Protocol Linter](middleware/lint/index) + [Application Profiler](middleware/profiler/index) * [HTTP Exceptions](exceptions/index) + [Usage Example](exceptions/index#usage-example) + [Error Classes](exceptions/index#error-classes) + [Baseclass](exceptions/index#baseclass) + [Special HTTP Exceptions](exceptions/index#special-http-exceptions) + [Simple Aborting](exceptions/index#simple-aborting) + [Custom Errors](exceptions/index#custom-errors) Deployment ---------- * [Deploying to Production](deployment/index) + [Self-Hosted Options](deployment/index#self-hosted-options) - [Gunicorn](deployment/gunicorn/index) - [Waitress](deployment/waitress/index) - [mod\_wsgi](deployment/mod_wsgi/index) - [uWSGI](deployment/uwsgi/index) - [gevent](deployment/gevent/index) - [eventlet](deployment/eventlet/index) - [Tell Werkzeug it is Behind a Proxy](deployment/proxy_fix/index) - [nginx](deployment/nginx/index) - [Apache httpd](deployment/apache-httpd/index) + [Hosting Platforms](deployment/index#hosting-platforms) Additional Information ---------------------- * [Important Terms](terms/index) + [WSGI](terms/index#wsgi) + [Response Object](terms/index#response-object) + [View Function](terms/index#view-function) * [Unicode](unicode/index) + [Unicode in Python](unicode/index#unicode-in-python) + [Unicode in HTTP](unicode/index#unicode-in-http) + [Error Handling](unicode/index#error-handling) + [Request and Response Objects](unicode/index#request-and-response-objects) * [Dealing with Request Data](request_data/index) + [Missing EOF Marker on Input Stream](request_data/index#missing-eof-marker-on-input-stream) + [When does Werkzeug Parse?](request_data/index#when-does-werkzeug-parse) + [How does it Parse?](request_data/index#how-does-it-parse) + [Limiting Request Data](request_data/index#limiting-request-data) + [How to extend Parsing?](request_data/index#how-to-extend-parsing) * [BSD-3-Clause License](license/index) * [Changes](https://werkzeug.palletsprojects.com/en/2.2.x/changes/) + [Version 2.2.2](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-2-2-2) + [Version 2.2.1](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-2-2-1) + [Version 2.2.0](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-2-2-0) + [Version 2.1.2](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-2-1-2) + [Version 2.1.1](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-2-1-1) + [Version 2.1.0](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-2-1-0) + [Version 2.0.3](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-2-0-3) + [Version 2.0.2](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-2-0-2) + [Version 2.0.1](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-2-0-1) + [Version 2.0.0](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-2-0-0) + [Version 1.0.1](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-1-0-1) + [Version 1.0.0](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-1-0-0) + [Version 0.16.1](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-16-1) + [Version 0.16.0](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-16-0) + [Version 0.15.6](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-15-6) + [Version 0.15.5](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-15-5) + [Version 0.15.4](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-15-4) + [Version 0.15.3](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-15-3) + [Version 0.15.2](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-15-2) + [Version 0.15.1](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-15-1) + [Version 0.15.0](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-15-0) + [Version 0.14.1](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-14-1) + [Version 0.14](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-14) + [Version 0.13](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-13) + [Version 0.12.2](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-12-2) + [Version 0.12.1](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-12-1) + [Version 0.12](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-12) + [Version 0.11.16](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-11-16) + [Version 0.11.15](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-11-15) + [Version 0.11.14](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-11-14) + [Version 0.11.13](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-11-13) + [Version 0.11.12](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-11-12) + [Version 0.11.11](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-11-11) + [Version 0.11.10](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-11-10) + [Version 0.11.9](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-11-9) + [Version 0.11.8](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-11-8) + [Version 0.11.7](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-11-7) + [Version 0.11.6](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-11-6) + [Version 0.11.5](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-11-5) + [Version 0.11.4](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-11-4) + [Version 0.11.3](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-11-3) + [Version 0.11.2](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-11-2) + [Version 0.11.1](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-11-1) + [Version 0.11](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-11) + [Version 0.10.5](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-10-5) + [Version 0.10.4](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-10-4) + [Version 0.10.3](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-10-3) + [Version 0.10.2](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-10-2) + [Version 0.10.1](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-10-1) + [Version 0.10](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-10) + [Version 0.9.7](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-9-7) + [Version 0.9.6](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-9-6) + [Version 0.9.7](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#id1) + [Version 0.9.5](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-9-5) + [Version 0.9.4](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-9-4) + [Version 0.9.3](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-9-3) + [Version 0.9.2](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-9-2) + [Version 0.9.1](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-9-1) + [Version 0.9](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-9) + [Version 0.8.4](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-8-4) + [Version 0.8.3](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-8-3) + [Version 0.8.2](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-8-2) + [Version 0.8.1](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-8-1) + [Version 0.8](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-8) + [Version 0.7.2](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-7-2) + [Version 0.7.1](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-7-1) + [Version 0.7](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-7) + [Version 0.6.2](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-6-2) + [Version 0.6.1](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-6-1) + [Version 0.6](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-6) + [Version 0.5.1](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-5-1) + [Version 0.5](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-5) + [Version 0.4.1](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-4-1) + [Version 0.4](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-4) + [Version 0.3.1](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-3-1) + [Version 0.3](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-3) + [Version 0.2](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-2) + [Version 0.1](https://werkzeug.palletsprojects.com/en/2.2.x/changes/#version-0-1) werkzeug Middleware Middleware ========== A WSGI middleware is a WSGI application that wraps another application in order to observe or change its behavior. Werkzeug provides some middleware for common use cases. * [X-Forwarded-For Proxy Fix](proxy_fix/index) * [Serve Shared Static Files](shared_data/index) * [Application Dispatcher](dispatcher/index) * [Basic HTTP Proxy](http_proxy/index) * [WSGI Protocol Linter](lint/index) * [Application Profiler](profiler/index) The [interactive debugger](../debug/index) is also a middleware that can be applied manually, although it is typically used automatically with the [development server](../serving/index). werkzeug WSGI Protocol Linter WSGI Protocol Linter ==================== This module provides a middleware that performs sanity checks on the behavior of the WSGI server and application. It checks that the [**PEP 3333**](https://peps.python.org/pep-3333/) WSGI spec is properly implemented. It also warns on some common HTTP errors such as non-empty responses for 304 status codes. `class werkzeug.middleware.lint.LintMiddleware(app)` Warns about common errors in the WSGI and HTTP behavior of the server and wrapped application. Some of the issues it checks are: * invalid status codes * non-bytes sent to the WSGI server * strings returned from the WSGI application * non-empty conditional responses * unquoted etags * relative URLs in the Location header * unsafe calls to wsgi.input * unclosed iterators Error information is emitted using the [`warnings`](https://docs.python.org/3/library/warnings.html#module-warnings "(in Python v3.10)") module. Parameters: **app** (*WSGIApplication*) – The WSGI application to wrap. ``` from werkzeug.middleware.lint import LintMiddleware app = LintMiddleware(app) ``` werkzeug Serve Shared Static Files Serve Shared Static Files ========================= `class werkzeug.middleware.shared_data.SharedDataMiddleware(app, exports, disallow=None, cache=True, cache_timeout=43200, fallback_mimetype='application/octet-stream')` A WSGI middleware which provides static content for development environments or simple server setups. Its usage is quite simple: ``` import os from werkzeug.middleware.shared_data import SharedDataMiddleware app = SharedDataMiddleware(app, { '/shared': os.path.join(os.path.dirname(__file__), 'shared') }) ``` The contents of the folder `./shared` will now be available on `http://example.com/shared/`. This is pretty useful during development because a standalone media server is not required. Files can also be mounted on the root folder and still continue to use the application because the shared data middleware forwards all unhandled requests to the application, even if the requests are below one of the shared folders. If `pkg_resources` is available you can also tell the middleware to serve files from package data: ``` app = SharedDataMiddleware(app, { '/static': ('myapplication', 'static') }) ``` This will then serve the `static` folder in the `myapplication` Python package. The optional `disallow` parameter can be a list of [`fnmatch()`](https://docs.python.org/3/library/fnmatch.html#fnmatch.fnmatch "(in Python v3.10)") rules for files that are not accessible from the web. If `cache` is set to `False` no caching headers are sent. Currently the middleware does not support non-ASCII filenames. If the encoding on the file system happens to match the encoding of the URI it may work but this could also be by accident. We strongly suggest using ASCII only file names for static files. The middleware will guess the mimetype using the Python `mimetype` module. If it’s unable to figure out the charset it will fall back to `fallback_mimetype`. Parameters: * **app** (*WSGIApplication*) – the application to wrap. If you don’t want to wrap an application you can pass it `NotFound`. * **exports** ([Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[*[Dict](https://docs.python.org/3/library/typing.html#typing.Dict "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [Tuple](https://docs.python.org/3/library/typing.html#typing.Tuple "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]**]**]**,* [Iterable](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.10)")*[*[Tuple](https://docs.python.org/3/library/typing.html#typing.Tuple "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [Tuple](https://docs.python.org/3/library/typing.html#typing.Tuple "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]**]**]**]**]*) – a list or dict of exported files and folders. * **disallow** (*None*) – a list of [`fnmatch()`](https://docs.python.org/3/library/fnmatch.html#fnmatch.fnmatch "(in Python v3.10)") rules. * **cache** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – enable or disable caching headers. * **cache\_timeout** ([int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")) – the cache timeout in seconds for the headers. * **fallback\_mimetype** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – The fallback mimetype for unknown files. Changelog Changed in version 1.0: The default `fallback_mimetype` is `application/octet-stream`. If a filename looks like a text mimetype, the `utf-8` charset is added to it. New in version 0.6: Added `fallback_mimetype`. Changed in version 0.5: Added `cache_timeout`. `is_allowed(filename)` Subclasses can override this method to disallow the access to certain files. However by providing `disallow` in the constructor this method is overwritten. Parameters: **filename** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – Return type: [bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")
programming_docs
werkzeug Application Dispatcher Application Dispatcher ====================== This middleware creates a single WSGI application that dispatches to multiple other WSGI applications mounted at different URL paths. A common example is writing a Single Page Application, where you have a backend API and a frontend written in JavaScript that does the routing in the browser rather than requesting different pages from the server. The frontend is a single HTML and JS file that should be served for any path besides β€œ/api”. This example dispatches to an API app under β€œ/api”, an admin app under β€œ/admin”, and an app that serves frontend files for all other requests: ``` app = DispatcherMiddleware(serve_frontend, { '/api': api_app, '/admin': admin_app, }) ``` In production, you might instead handle this at the HTTP server level, serving files or proxying to application servers based on location. The API and admin apps would each be deployed with a separate WSGI server, and the static files would be served directly by the HTTP server. `class werkzeug.middleware.dispatcher.DispatcherMiddleware(app, mounts=None)` Combine multiple applications as a single WSGI application. Requests are dispatched to an application based on the path it is mounted under. Parameters: * **app** (*WSGIApplication*) – The WSGI application to dispatch to if the request doesn’t match a mounted path. * **mounts** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Dict](https://docs.python.org/3/library/typing.html#typing.Dict "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* *WSGIApplication**]**]*) – Maps path prefixes to applications for dispatching. werkzeug X-Forwarded-For Proxy Fix X-Forwarded-For Proxy Fix ========================= This module provides a middleware that adjusts the WSGI environ based on `X-Forwarded-` headers that proxies in front of an application may set. When an application is running behind a proxy server, WSGI may see the request as coming from that server rather than the real client. Proxies set various headers to track where the request actually came from. This middleware should only be used if the application is actually behind such a proxy, and should be configured with the number of proxies that are chained in front of it. Not all proxies set all the headers. Since incoming headers can be faked, you must set how many proxies are setting each header so the middleware knows what to trust. `class werkzeug.middleware.proxy_fix.ProxyFix(app, x_for=1, x_proto=1, x_host=0, x_port=0, x_prefix=0)` Adjust the WSGI environ based on `X-Forwarded-` that proxies in front of the application may set. * `X-Forwarded-For` sets `REMOTE_ADDR`. * `X-Forwarded-Proto` sets `wsgi.url_scheme`. * `X-Forwarded-Host` sets `HTTP_HOST`, `SERVER_NAME`, and `SERVER_PORT`. * `X-Forwarded-Port` sets `HTTP_HOST` and `SERVER_PORT`. * `X-Forwarded-Prefix` sets `SCRIPT_NAME`. You must tell the middleware how many proxies set each header so it knows what values to trust. It is a security issue to trust values that came from the client rather than a proxy. The original values of the headers are stored in the WSGI environ as `werkzeug.proxy_fix.orig`, a dict. Parameters: * **app** (*WSGIApplication*) – The WSGI application to wrap. * **x\_for** ([int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")) – Number of values to trust for `X-Forwarded-For`. * **x\_proto** ([int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")) – Number of values to trust for `X-Forwarded-Proto`. * **x\_host** ([int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")) – Number of values to trust for `X-Forwarded-Host`. * **x\_port** ([int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")) – Number of values to trust for `X-Forwarded-Port`. * **x\_prefix** ([int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")) – Number of values to trust for `X-Forwarded-Prefix`. ``` from werkzeug.middleware.proxy_fix import ProxyFix # App is behind one proxy that sets the -For and -Host headers. app = ProxyFix(app, x_for=1, x_host=1) ``` Changelog Changed in version 1.0: Deprecated code has been removed: * The `num_proxies` argument and attribute. * The `get_remote_addr` method. * The environ keys `orig_remote_addr`, `orig_wsgi_url_scheme`, and `orig_http_host`. Changed in version 0.15: All headers support multiple values. The `num_proxies` argument is deprecated. Each header is configured with a separate number of trusted proxies. Changed in version 0.15: Original WSGI environ values are stored in the `werkzeug.proxy_fix.orig` dict. `orig_remote_addr`, `orig_wsgi_url_scheme`, and `orig_http_host` are deprecated and will be removed in 1.0. Changed in version 0.15: Support `X-Forwarded-Port` and `X-Forwarded-Prefix`. Changed in version 0.15: `X-Forwarded-Host` and `X-Forwarded-Port` modify `SERVER_NAME` and `SERVER_PORT`. werkzeug Basic HTTP Proxy Basic HTTP Proxy ================ `class werkzeug.middleware.http_proxy.ProxyMiddleware(app, targets, chunk_size=16384, timeout=10)` Proxy requests under a path to an external server, routing other requests to the app. This middleware can only proxy HTTP requests, as HTTP is the only protocol handled by the WSGI server. Other protocols, such as WebSocket requests, cannot be proxied at this layer. This should only be used for development, in production a real proxy server should be used. The middleware takes a dict mapping a path prefix to a dict describing the host to be proxied to: ``` app = ProxyMiddleware(app, { "/static/": { "target": "http://127.0.0.1:5001/", } }) ``` Each host has the following options: `target:` The target URL to dispatch to. This is required. `remove_prefix:` Whether to remove the prefix from the URL before dispatching it to the target. The default is `False`. `host:` `"<auto>" (default):` The host header is automatically rewritten to the URL of the target. `None:` The host header is unmodified from the client request. Any other value: The host header is overwritten with the value. `headers:` A dictionary of headers to be sent with the request to the target. The default is `{}`. `ssl_context:` A [`ssl.SSLContext`](https://docs.python.org/3/library/ssl.html#ssl.SSLContext "(in Python v3.10)") defining how to verify requests if the target is HTTPS. The default is `None`. In the example above, everything under `"/static/"` is proxied to the server on port 5001. The host header is rewritten to the target, and the `"/static/"` prefix is removed from the URLs. Parameters: * **app** (*WSGIApplication*) – The WSGI application to wrap. * **targets** ([Mapping](https://docs.python.org/3/library/typing.html#typing.Mapping "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [Dict](https://docs.python.org/3/library/typing.html#typing.Dict "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")*]**]*) – Proxy target configurations. See description above. * **chunk\_size** ([int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")) – Size of chunks to read from input stream and write to target. * **timeout** ([int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")) – Seconds before an operation to a target fails. Changelog New in version 0.14. werkzeug Application Profiler Application Profiler ==================== This module provides a middleware that profiles each request with the [`cProfile`](https://docs.python.org/3/library/profile.html#module-cProfile "(in Python v3.10)") module. This can help identify bottlenecks in your code that may be slowing down your application. `class werkzeug.middleware.profiler.ProfilerMiddleware(app, stream=<_io.TextIOWrapper name='<stdout>' mode='w' encoding='utf-8'>, sort_by=('time', 'calls'), restrictions=(), profile_dir=None, filename_format='{method}.{path}.{elapsed:.0f}ms.{time:.0f}.prof')` Wrap a WSGI application and profile the execution of each request. Responses are buffered so that timings are more exact. If `stream` is given, [`pstats.Stats`](https://docs.python.org/3/library/profile.html#pstats.Stats "(in Python v3.10)") are written to it after each request. If `profile_dir` is given, [`cProfile`](https://docs.python.org/3/library/profile.html#module-cProfile "(in Python v3.10)") data files are saved to that directory, one file per request. The filename can be customized by passing `filename_format`. If it is a string, it will be formatted using [`str.format()`](https://docs.python.org/3/library/stdtypes.html#str.format "(in Python v3.10)") with the following fields available: * `{method}` - The request method; GET, POST, etc. * `{path}` - The request path or β€˜root’ should one not exist. * `{elapsed}` - The elapsed time of the request. * `{time}` - The time of the request. If it is a callable, it will be called with the WSGI `environ` dict and should return a filename. Parameters: * **app** (*WSGIApplication*) – The WSGI application to wrap. * **stream** ([IO](https://docs.python.org/3/library/typing.html#typing.IO "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – Write stats to this stream. Disable with `None`. * **sort\_by** ([Iterable](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – A tuple of columns to sort stats by. See [`pstats.Stats.sort_stats()`](https://docs.python.org/3/library/profile.html#pstats.Stats.sort_stats "(in Python v3.10)"). * **restrictions** ([Iterable](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.10)")*[*[Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")*,* [float](https://docs.python.org/3/library/functions.html#float "(in Python v3.10)")*]**]*) – A tuple of restrictions to filter stats by. See [`pstats.Stats.print_stats()`](https://docs.python.org/3/library/profile.html#pstats.Stats.print_stats "(in Python v3.10)"). * **profile\_dir** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – Save profile data files to this directory. * **filename\_format** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – Format string for profile data file names, or a callable returning a name. See explanation above. ``` from werkzeug.middleware.profiler import ProfilerMiddleware app = ProfilerMiddleware(app) ``` Changelog Changed in version 0.15: Stats are written even if `profile_dir` is given, and can be disable by passing `stream=None`. New in version 0.15: Added `filename_format`. New in version 0.9: Added `restrictions` and `profile_dir`. werkzeug Request / Response Objects Request / Response Objects ========================== The request and response objects wrap the WSGI environment or the return value from a WSGI application so that it is another WSGI application (wraps a whole application). How they Work ------------- Your WSGI application is always passed two arguments. The WSGI β€œenvironment” and the WSGI `start_response` function that is used to start the response phase. The [`Request`](#werkzeug.wrappers.Request "werkzeug.wrappers.Request") class wraps the `environ` for easier access to request variables (form data, request headers etc.). The [`Response`](#werkzeug.wrappers.Response "werkzeug.wrappers.Response") on the other hand is a standard WSGI application that you can create. The simple hello world in Werkzeug looks like this: ``` from werkzeug.wrappers import Response application = Response('Hello World!') ``` To make it more useful you can replace it with a function and do some processing: ``` from werkzeug.wrappers import Request, Response def application(environ, start_response): request = Request(environ) response = Response(f"Hello {request.args.get('name', 'World!')}!") return response(environ, start_response) ``` Because this is a very common task the [`Request`](#werkzeug.wrappers.Request "werkzeug.wrappers.Request") object provides a helper for that. The above code can be rewritten like this: ``` from werkzeug.wrappers import Request, Response @Request.application def application(request): return Response(f"Hello {request.args.get('name', 'World!')}!") ``` The `application` is still a valid WSGI application that accepts the environment and `start_response` callable. Mutability and Reusability of Wrappers -------------------------------------- The implementation of the Werkzeug request and response objects are trying to guard you from common pitfalls by disallowing certain things as much as possible. This serves two purposes: high performance and avoiding of pitfalls. For the request object the following rules apply: 1. The request object is immutable. Modifications are not supported by default, you may however replace the immutable attributes with mutable attributes if you need to modify it. 2. The request object may be shared in the same thread, but is not thread safe itself. If you need to access it from multiple threads, use locks around calls. 3. It’s not possible to pickle the request object. For the response object the following rules apply: 1. The response object is mutable 2. The response object can be pickled or copied after `freeze()` was called. 3. Since Werkzeug 0.6 it’s safe to use the same response object for multiple WSGI responses. 4. It’s possible to create copies using `copy.deepcopy`. Wrapper Classes --------------- `class werkzeug.wrappers.Request(environ, populate_request=True, shallow=False)` Represents an incoming WSGI HTTP request, with headers and body taken from the WSGI environment. Has properties and methods for using the functionality defined by various HTTP specs. The data in requests object is read-only. Text data is assumed to use UTF-8 encoding, which should be true for the vast majority of modern clients. Using an encoding set by the client is unsafe in Python due to extra encodings it provides, such as `zip`. To change the assumed encoding, subclass and replace [`charset`](#werkzeug.wrappers.Request.charset "werkzeug.wrappers.Request.charset"). Parameters: * **environ** (*WSGIEnvironment*) – The WSGI environ is generated by the WSGI server and contains information about the server configuration and client request. * **populate\_request** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – Add this request object to the WSGI environ as `environ['werkzeug.request']`. Can be useful when debugging. * **shallow** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – Makes reading from [`stream`](#werkzeug.wrappers.Request.stream "werkzeug.wrappers.Request.stream") (and any method that would read from it) raise a [`RuntimeError`](https://docs.python.org/3/library/exceptions.html#RuntimeError "(in Python v3.10)"). Useful to prevent consuming the form data in middleware, which would make it unavailable to the final application. Changelog Changed in version 2.1: Remove the `disable_data_descriptor` attribute. Changed in version 2.0: Combine `BaseRequest` and mixins into a single `Request` class. Using the old classes is deprecated and will be removed in Werkzeug 2.1. Changed in version 0.5: Read-only mode is enforced with immutable classes for all data. `_get_file_stream(total_content_length, content_type, filename=None, content_length=None)` Called to get a stream for the file upload. This must provide a file-like class with `read()`, `readline()` and `seek()` methods that is both writeable and readable. The default implementation returns a temporary file if the total content length is higher than 500KB. Because many browsers do not provide a content length for the files only the total content length matters. Parameters: * **total\_content\_length** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")*]*) – the total content length of all the data in the request combined. This value is guaranteed to be there. * **content\_type** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – the mimetype of the uploaded file. * **filename** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – the filename of the uploaded file. May be `None`. * **content\_length** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")*]*) – the length of this file. This value is usually not provided because webbrowsers do not provide this value. Return type: [IO](https://docs.python.org/3/library/typing.html#typing.IO "(in Python v3.10)")[[bytes](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.10)")] `property accept_charsets: CharsetAccept` List of charsets this client supports as [`CharsetAccept`](../datastructures/index#werkzeug.datastructures.CharsetAccept "werkzeug.datastructures.CharsetAccept") object. `property accept_encodings: Accept` List of encodings this client accepts. Encodings in a HTTP term are compression encodings such as gzip. For charsets have a look at `accept_charset`. `property accept_languages: LanguageAccept` List of languages this client accepts as [`LanguageAccept`](../datastructures/index#werkzeug.datastructures.LanguageAccept "werkzeug.datastructures.LanguageAccept") object. `property accept_mimetypes: MIMEAccept` List of mimetypes this client supports as [`MIMEAccept`](../datastructures/index#werkzeug.datastructures.MIMEAccept "werkzeug.datastructures.MIMEAccept") object. `access_control_request_headers` Sent with a preflight request to indicate which headers will be sent with the cross origin request. Set `access_control_allow_headers` on the response to indicate which headers are allowed. `access_control_request_method` Sent with a preflight request to indicate which method will be used for the cross origin request. Set `access_control_allow_methods` on the response to indicate which methods are allowed. `property access_route: List[str]` If a forwarded header exists this is a list of all ip addresses from the client ip to the last proxy server. `classmethod application(f)` Decorate a function as responder that accepts the request as the last argument. This works like the `responder()` decorator but the function is passed the request object as the last argument and the request object will be closed automatically: ``` @Request.application def my_wsgi_app(request): return Response('Hello World!') ``` As of Werkzeug 0.14 HTTP exceptions are automatically caught and converted to responses instead of failing. Parameters: **f** ([Callable](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.10)")*[**[*[Request](#werkzeug.wrappers.Request "werkzeug.wrappers.Request")*]**,* *WSGIApplication**]*) – the WSGI callable to decorate Returns: a new WSGI callable Return type: WSGIApplication `property args: MultiDict[str, str]` The parsed URL parameters (the part in the URL after the question mark). By default an [`ImmutableMultiDict`](../datastructures/index#werkzeug.datastructures.ImmutableMultiDict "werkzeug.datastructures.ImmutableMultiDict") is returned from this function. This can be changed by setting [`parameter_storage_class`](#werkzeug.wrappers.Request.parameter_storage_class "werkzeug.wrappers.Request.parameter_storage_class") to a different type. This might be necessary if the order of the form data is important. `property authorization: Optional[Authorization]` The `Authorization` object in parsed form. `property base_url: str` Like [`url`](#werkzeug.wrappers.Request.url "werkzeug.wrappers.Request.url") but without the query string. `property cache_control: RequestCacheControl` A [`RequestCacheControl`](../datastructures/index#werkzeug.datastructures.RequestCacheControl "werkzeug.datastructures.RequestCacheControl") object for the incoming cache control headers. `charset = 'utf-8'` The charset used to decode most data in the request. `close()` Closes associated resources of this request object. This closes all file handles explicitly. You can also use the request object in a with statement which will automatically close it. Changelog New in version 0.9. Return type: None `content_encoding` The Content-Encoding entity-header field is used as a modifier to the media-type. When present, its value indicates what additional content codings have been applied to the entity-body, and thus what decoding mechanisms must be applied in order to obtain the media-type referenced by the Content-Type header field. Changelog New in version 0.9. `property content_length: Optional[int]` The Content-Length entity-header field indicates the size of the entity-body in bytes or, in the case of the HEAD method, the size of the entity-body that would have been sent had the request been a GET. `content_md5` The Content-MD5 entity-header field, as defined in RFC 1864, is an MD5 digest of the entity-body for the purpose of providing an end-to-end message integrity check (MIC) of the entity-body. (Note: a MIC is good for detecting accidental modification of the entity-body in transit, but is not proof against malicious attacks.) Changelog New in version 0.9. `content_type` The Content-Type entity-header field indicates the media type of the entity-body sent to the recipient or, in the case of the HEAD method, the media type that would have been sent had the request been a GET. `property cookies: ImmutableMultiDict[str, str]` A [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.10)") with the contents of all cookies transmitted with the request. `property data: bytes` Contains the incoming request data as string in case it came with a mimetype Werkzeug does not handle. `date` The Date general-header field represents the date and time at which the message was originated, having the same semantics as orig-date in RFC 822. Changelog Changed in version 2.0: The datetime object is timezone-aware. `dict_storage_class` alias of [`ImmutableMultiDict`](../datastructures/index#werkzeug.datastructures.ImmutableMultiDict "werkzeug.datastructures.ImmutableMultiDict") `encoding_errors = 'replace'` the error handling procedure for errors, defaults to β€˜replace’ `environ: WSGIEnvironment` The WSGI environment containing HTTP headers and information from the WSGI server. `property files: ImmutableMultiDict[str, FileStorage]` [`MultiDict`](../datastructures/index#werkzeug.datastructures.MultiDict "werkzeug.datastructures.MultiDict") object containing all uploaded files. Each key in [`files`](#werkzeug.wrappers.Request.files "werkzeug.wrappers.Request.files") is the name from the `<input type="file" name="">`. Each value in [`files`](#werkzeug.wrappers.Request.files "werkzeug.wrappers.Request.files") is a Werkzeug [`FileStorage`](../datastructures/index#werkzeug.datastructures.FileStorage "werkzeug.datastructures.FileStorage") object. It basically behaves like a standard file object you know from Python, with the difference that it also has a [`save()`](../datastructures/index#werkzeug.datastructures.FileStorage.save "werkzeug.datastructures.FileStorage.save") function that can store the file on the filesystem. Note that [`files`](#werkzeug.wrappers.Request.files "werkzeug.wrappers.Request.files") will only contain data if the request method was POST, PUT or PATCH and the `<form>` that posted to the request had `enctype="multipart/form-data"`. It will be empty otherwise. See the [`MultiDict`](../datastructures/index#werkzeug.datastructures.MultiDict "werkzeug.datastructures.MultiDict") / [`FileStorage`](../datastructures/index#werkzeug.datastructures.FileStorage "werkzeug.datastructures.FileStorage") documentation for more details about the used data structure. `property form: ImmutableMultiDict[str, str]` The form parameters. By default an [`ImmutableMultiDict`](../datastructures/index#werkzeug.datastructures.ImmutableMultiDict "werkzeug.datastructures.ImmutableMultiDict") is returned from this function. This can be changed by setting [`parameter_storage_class`](#werkzeug.wrappers.Request.parameter_storage_class "werkzeug.wrappers.Request.parameter_storage_class") to a different type. This might be necessary if the order of the form data is important. Please keep in mind that file uploads will not end up here, but instead in the [`files`](#werkzeug.wrappers.Request.files "werkzeug.wrappers.Request.files") attribute. Changelog Changed in version 0.9: Previous to Werkzeug 0.9 this would only contain form data for POST and PUT requests. `form_data_parser_class` alias of [`FormDataParser`](../http/index#werkzeug.formparser.FormDataParser "werkzeug.formparser.FormDataParser") `classmethod from_values(*args, **kwargs)` Create a new request object based on the values provided. If environ is given missing values are filled from there. This method is useful for small scripts when you need to simulate a request from an URL. Do not use this method for unittesting, there is a full featured client object (`Client`) that allows to create multipart requests, support for cookies etc. This accepts the same options as the [`EnvironBuilder`](../test/index#werkzeug.test.EnvironBuilder "werkzeug.test.EnvironBuilder"). Changelog Changed in version 0.5: This method now accepts the same arguments as [`EnvironBuilder`](../test/index#werkzeug.test.EnvironBuilder "werkzeug.test.EnvironBuilder"). Because of this the `environ` parameter is now called `environ_overrides`. Returns: request object Parameters: * **args** ([Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")) – * **kwargs** ([Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")) – Return type: [Request](#werkzeug.wrappers.Request "werkzeug.wrappers.request.Request") `property full_path: str` Requested path, including the query string. `get_data(cache=True, as_text=False, parse_form_data=False)` This reads the buffered incoming data from the client into one bytes object. By default this is cached but that behavior can be changed by setting `cache` to `False`. Usually it’s a bad idea to call this method without checking the content length first as a client could send dozens of megabytes or more to cause memory problems on the server. Note that if the form data was already parsed this method will not return anything as form data parsing does not cache the data like this method does. To implicitly invoke form data parsing function set `parse_form_data` to `True`. When this is done the return value of this method will be an empty string if the form parser handles the data. This generally is not necessary as if the whole data is cached (which is the default) the form parser will used the cached data to parse the form data. Please be generally aware of checking the content length first in any case before calling this method to avoid exhausting server memory. If `as_text` is set to `True` the return value will be a decoded string. Changelog New in version 0.9. Parameters: * **cache** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – * **as\_text** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – * **parse\_form\_data** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – Return type: [Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")[[bytes](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.10)"), [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")] `get_json(force=False, silent=False, cache=True)` Parse [`data`](#werkzeug.wrappers.Request.data "werkzeug.wrappers.Request.data") as JSON. If the mimetype does not indicate JSON (*application/json*, see [`is_json`](#werkzeug.wrappers.Request.is_json "werkzeug.wrappers.Request.is_json")), or parsing fails, [`on_json_loading_failed()`](#werkzeug.wrappers.Request.on_json_loading_failed "werkzeug.wrappers.Request.on_json_loading_failed") is called and its return value is used as the return value. By default this raises a 400 Bad Request error. Parameters: * **force** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – Ignore the mimetype and always try to parse JSON. * **silent** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – Silence mimetype and parsing errors, and return `None` instead. * **cache** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – Store the parsed JSON to return for subsequent calls. Return type: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")[[Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")] Changelog Changed in version 2.1: Raise a 400 error if the content type is incorrect. `headers` The headers received with the request. `property host: str` The host name the request was made to, including the port if it’s non-standard. Validated with [`trusted_hosts`](#werkzeug.wrappers.Request.trusted_hosts "werkzeug.wrappers.Request.trusted_hosts"). `property host_url: str` The request URL scheme and host only. `property if_match: ETags` An object containing all the etags in the `If-Match` header. Return type: [`ETags`](../datastructures/index#werkzeug.datastructures.ETags "werkzeug.datastructures.ETags") `property if_modified_since: Optional[datetime]` The parsed `If-Modified-Since` header as a datetime object. Changelog Changed in version 2.0: The datetime object is timezone-aware. `property if_none_match: ETags` An object containing all the etags in the `If-None-Match` header. Return type: [`ETags`](../datastructures/index#werkzeug.datastructures.ETags "werkzeug.datastructures.ETags") `property if_range: IfRange` The parsed `If-Range` header. Changelog Changed in version 2.0: `IfRange.date` is timezone-aware. New in version 0.7. `property if_unmodified_since: Optional[datetime]` The parsed `If-Unmodified-Since` header as a datetime object. Changelog Changed in version 2.0: The datetime object is timezone-aware. `input_stream` The WSGI input stream. In general it’s a bad idea to use this one because you can easily read past the boundary. Use the [`stream`](#werkzeug.wrappers.Request.stream "werkzeug.wrappers.Request.stream") instead. `property is_json: bool` Check if the mimetype indicates JSON data, either *application/json* or *application/\*+json*. `is_multiprocess` boolean that is `True` if the application is served by a WSGI server that spawns multiple processes. `is_multithread` boolean that is `True` if the application is served by a multithreaded WSGI server. `is_run_once` boolean that is `True` if the application will be executed only once in a process lifetime. This is the case for CGI for example, but it’s not guaranteed that the execution only happens one time. `property is_secure: bool` `True` if the request was made with a secure protocol (HTTPS or WSS). `property json: Optional[Any]` The parsed JSON data if [`mimetype`](#werkzeug.wrappers.Request.mimetype "werkzeug.wrappers.Request.mimetype") indicates JSON (*application/json*, see [`is_json`](#werkzeug.wrappers.Request.is_json "werkzeug.wrappers.Request.is_json")). Calls [`get_json()`](#werkzeug.wrappers.Request.get_json "werkzeug.wrappers.Request.get_json") with default arguments. If the request content type is not `application/json`, this will raise a 400 Bad Request error. Changelog Changed in version 2.1: Raise a 400 error if the content type is incorrect. `json_module = <module 'json' from '/home/docs/.asdf/installs/python/3.10.4/lib/python3.10/json/__init__.py'>` A module or other object that has `dumps` and `loads` functions that match the API of the built-in [`json`](https://docs.python.org/3/library/json.html#module-json "(in Python v3.10)") module. `list_storage_class` alias of [`ImmutableList`](../datastructures/index#werkzeug.datastructures.ImmutableList "werkzeug.datastructures.ImmutableList") `make_form_data_parser()` Creates the form data parser. Instantiates the [`form_data_parser_class`](#werkzeug.wrappers.Request.form_data_parser_class "werkzeug.wrappers.Request.form_data_parser_class") with some parameters. Changelog New in version 0.8. Return type: [FormDataParser](../http/index#werkzeug.formparser.FormDataParser "werkzeug.formparser.FormDataParser") `max_content_length: Optional[int] = None` the maximum content length. This is forwarded to the form data parsing function (`parse_form_data()`). When set and the [`form`](#werkzeug.wrappers.Request.form "werkzeug.wrappers.Request.form") or [`files`](#werkzeug.wrappers.Request.files "werkzeug.wrappers.Request.files") attribute is accessed and the parsing fails because more than the specified value is transmitted a [`RequestEntityTooLarge`](../exceptions/index#werkzeug.exceptions.RequestEntityTooLarge "werkzeug.exceptions.RequestEntityTooLarge") exception is raised. Have a look at [Dealing with Request Data](../request_data/index) for more details. Changelog New in version 0.5. `max_form_memory_size: Optional[int] = None` the maximum form field size. This is forwarded to the form data parsing function (`parse_form_data()`). When set and the [`form`](#werkzeug.wrappers.Request.form "werkzeug.wrappers.Request.form") or [`files`](#werkzeug.wrappers.Request.files "werkzeug.wrappers.Request.files") attribute is accessed and the data in memory for post data is longer than the specified value a [`RequestEntityTooLarge`](../exceptions/index#werkzeug.exceptions.RequestEntityTooLarge "werkzeug.exceptions.RequestEntityTooLarge") exception is raised. Have a look at [Dealing with Request Data](../request_data/index) for more details. Changelog New in version 0.5. `max_forwards` The Max-Forwards request-header field provides a mechanism with the TRACE and OPTIONS methods to limit the number of proxies or gateways that can forward the request to the next inbound server. `method` The method the request was made with, such as `GET`. `property mimetype: str` Like [`content_type`](#werkzeug.wrappers.Request.content_type "werkzeug.wrappers.Request.content_type"), but without parameters (eg, without charset, type etc.) and always lowercase. For example if the content type is `text/HTML; charset=utf-8` the mimetype would be `'text/html'`. `property mimetype_params: Dict[str, str]` The mimetype parameters as dict. For example if the content type is `text/html; charset=utf-8` the params would be `{'charset': 'utf-8'}`. `on_json_loading_failed(e)` Called if [`get_json()`](#werkzeug.wrappers.Request.get_json "werkzeug.wrappers.Request.get_json") fails and isn’t silenced. If this method returns a value, it is used as the return value for [`get_json()`](#werkzeug.wrappers.Request.get_json "werkzeug.wrappers.Request.get_json"). The default implementation raises [`BadRequest`](../exceptions/index#werkzeug.exceptions.BadRequest "werkzeug.exceptions.BadRequest"). Parameters: **e** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[ValueError](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.10)")*]*) – If parsing failed, this is the exception. It will be `None` if the content type wasn’t `application/json`. Return type: [Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)") `origin` The host that the request originated from. Set `access_control_allow_origin` on the response to indicate which origins are allowed. `parameter_storage_class` alias of [`ImmutableMultiDict`](../datastructures/index#werkzeug.datastructures.ImmutableMultiDict "werkzeug.datastructures.ImmutableMultiDict") `path` The path part of the URL after [`root_path`](#werkzeug.wrappers.Request.root_path "werkzeug.wrappers.Request.root_path"). This is the path used for routing within the application. `property pragma: HeaderSet` The Pragma general-header field is used to include implementation-specific directives that might apply to any recipient along the request/response chain. All pragma directives specify optional behavior from the viewpoint of the protocol; however, some systems MAY require that behavior be consistent with the directives. `query_string` The part of the URL after the β€œ?”. This is the raw value, use [`args`](#werkzeug.wrappers.Request.args "werkzeug.wrappers.Request.args") for the parsed values. `property range: Optional[Range]` The parsed `Range` header. Changelog New in version 0.7. Return type: [`Range`](../datastructures/index#werkzeug.datastructures.Range "werkzeug.datastructures.Range") `referrer` The Referer[sic] request-header field allows the client to specify, for the server’s benefit, the address (URI) of the resource from which the Request-URI was obtained (the β€œreferrer”, although the header field is misspelled). `remote_addr` The address of the client sending the request. `remote_user` If the server supports user authentication, and the script is protected, this attribute contains the username the user has authenticated as. `root_path` The prefix that the application is mounted under, without a trailing slash. [`path`](#werkzeug.wrappers.Request.path "werkzeug.wrappers.Request.path") comes after this. `property root_url: str` The request URL scheme, host, and root path. This is the root that the application is accessed from. `scheme` The URL scheme of the protocol the request used, such as `https` or `wss`. `property script_root: str` Alias for `self.root_path`. `environ["SCRIPT_ROOT"]` without a trailing slash. `server` The address of the server. `(host, port)`, `(path, None)` for unix sockets, or `None` if not known. `shallow: bool` Set when creating the request object. If `True`, reading from the request body will cause a `RuntimeException`. Useful to prevent modifying the stream from middleware. `property stream: IO[bytes]` If the incoming form data was not encoded with a known mimetype the data is stored unmodified in this stream for consumption. Most of the time it is a better idea to use [`data`](#werkzeug.wrappers.Request.data "werkzeug.wrappers.Request.data") which will give you that data as a string. The stream only returns the data once. Unlike [`input_stream`](#werkzeug.wrappers.Request.input_stream "werkzeug.wrappers.Request.input_stream") this stream is properly guarded that you can’t accidentally read past the length of the input. Werkzeug will internally always refer to this stream to read data which makes it possible to wrap this object with a stream that does filtering. Changelog Changed in version 0.9: This stream is now always available but might be consumed by the form parser later on. Previously the stream was only set if no parsing happened. `trusted_hosts: t.Optional[t.List[str]] = None` Valid host names when handling requests. By default all hosts are trusted, which means that whatever the client says the host is will be accepted. Because `Host` and `X-Forwarded-Host` headers can be set to any value by a malicious client, it is recommended to either set this property or implement similar validation in the proxy (if the application is being run behind one). Changelog New in version 0.9. `property url: str` The full request URL with the scheme, host, root path, path, and query string. `property url_charset: str` The charset that is assumed for URLs. Defaults to the value of [`charset`](#werkzeug.wrappers.Request.charset "werkzeug.wrappers.Request.charset"). Changelog New in version 0.6. `property url_root: str` Alias for [`root_url`](#werkzeug.wrappers.Request.root_url "werkzeug.wrappers.Request.root_url"). The URL with scheme, host, and root path. For example, `https://example.com/app/`. `property user_agent: UserAgent` The user agent. Use `user_agent.string` to get the header value. Set [`user_agent_class`](#werkzeug.wrappers.Request.user_agent_class "werkzeug.wrappers.Request.user_agent_class") to a subclass of [`UserAgent`](../utils/index#werkzeug.user_agent.UserAgent "werkzeug.user_agent.UserAgent") to provide parsing for the other properties or other extended data. Changelog Changed in version 2.0: The built in parser is deprecated and will be removed in Werkzeug 2.1. A `UserAgent` subclass must be set to parse data from the string. `user_agent_class` alias of [`UserAgent`](../utils/index#werkzeug.user_agent.UserAgent "werkzeug.user_agent.UserAgent") `property values: CombinedMultiDict[str, str]` A [`werkzeug.datastructures.CombinedMultiDict`](../datastructures/index#werkzeug.datastructures.CombinedMultiDict "werkzeug.datastructures.CombinedMultiDict") that combines [`args`](#werkzeug.wrappers.Request.args "werkzeug.wrappers.Request.args") and [`form`](#werkzeug.wrappers.Request.form "werkzeug.wrappers.Request.form"). For GET requests, only `args` are present, not `form`. Changelog Changed in version 2.0: For GET requests, only `args` are present, not `form`. `property want_form_data_parsed: bool` `True` if the request method carries content. By default this is true if a `Content-Type` is sent. Changelog New in version 0.8. `class werkzeug.wrappers.Response(response=None, status=None, headers=None, mimetype=None, content_type=None, direct_passthrough=False)` Represents an outgoing WSGI HTTP response with body, status, and headers. Has properties and methods for using the functionality defined by various HTTP specs. The response body is flexible to support different use cases. The simple form is passing bytes, or a string which will be encoded as UTF-8. Passing an iterable of bytes or strings makes this a streaming response. A generator is particularly useful for building a CSV file in memory or using SSE (Server Sent Events). A file-like object is also iterable, although the [`send_file()`](../utils/index#werkzeug.utils.send_file "werkzeug.utils.send_file") helper should be used in that case. The response object is itself a WSGI application callable. When called ([`__call__()`](#werkzeug.wrappers.Response.__call__ "werkzeug.wrappers.Response.__call__")) with `environ` and `start_response`, it will pass its status and headers to `start_response` then return its body as an iterable. ``` from werkzeug.wrappers.response import Response def index(): return Response("Hello, World!") def application(environ, start_response): path = environ.get("PATH_INFO") or "/" if path == "/": response = index() else: response = Response("Not Found", status=404) return response(environ, start_response) ``` Parameters: * **response** ([Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[*[Iterable](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]**,* [Iterable](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.10)")*[*[bytes](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.10)")*]**]*) – The data for the body of the response. A string or bytes, or tuple or list of strings or bytes, for a fixed-length response, or any other iterable of strings or bytes for a streaming response. Defaults to an empty body. * **status** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[*[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")*,* [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [HTTPStatus](https://docs.python.org/3/library/http.html#http.HTTPStatus "(in Python v3.10)")*]**]*) – The status code for the response. Either an int, in which case the default status message is added, or a string in the form `{code} {message}`, like `404 Not Found`. Defaults to 200. * **headers** ([Headers](../datastructures/index#werkzeug.datastructures.Headers "werkzeug.datastructures.Headers")) – A [`Headers`](../datastructures/index#werkzeug.datastructures.Headers "werkzeug.datastructures.Headers") object, or a list of `(key, value)` tuples that will be converted to a `Headers` object. * **mimetype** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – The mime type (content type without charset or other parameters) of the response. If the value starts with `text/` (or matches some other special cases), the charset will be added to create the `content_type`. * **content\_type** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – The full content type of the response. Overrides building the value from `mimetype`. * **direct\_passthrough** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – Pass the response body directly through as the WSGI iterable. This can be used when the body is a binary file or other iterator of bytes, to skip some unnecessary checks. Use [`send_file()`](../utils/index#werkzeug.utils.send_file "werkzeug.utils.send_file") instead of setting this manually. Changelog Changed in version 2.0: Combine `BaseResponse` and mixins into a single `Response` class. Using the old classes is deprecated and will be removed in Werkzeug 2.1. Changed in version 0.5: The `direct_passthrough` parameter was added. `__call__(environ, start_response)` Process this response as WSGI application. Parameters: * **environ** (*WSGIEnvironment*) – the WSGI environment. * **start\_response** (*StartResponse*) – the response callable provided by the WSGI server. Returns: an application iterator Return type: [Iterable](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.10)")[[bytes](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.10)")] `_ensure_sequence(mutable=False)` This method can be called by methods that need a sequence. If `mutable` is true, it will also ensure that the response sequence is a standard Python list. Changelog New in version 0.6. Parameters: **mutable** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – Return type: None `accept_ranges` The `Accept-Ranges` header. Even though the name would indicate that multiple values are supported, it must be one string token only. The values `'bytes'` and `'none'` are common. Changelog New in version 0.7. `property access_control_allow_credentials: bool` Whether credentials can be shared by the browser to JavaScript code. As part of the preflight request it indicates whether credentials can be used on the cross origin request. `access_control_allow_headers` Which headers can be sent with the cross origin request. `access_control_allow_methods` Which methods can be used for the cross origin request. `access_control_allow_origin` The origin or β€˜\*’ for any origin that may make cross origin requests. `access_control_expose_headers` Which headers can be shared by the browser to JavaScript code. `access_control_max_age` The maximum age in seconds the access control settings can be cached for. `add_etag(overwrite=False, weak=False)` Add an etag for the current response if there is none yet. Changelog Changed in version 2.0: SHA-1 is used to generate the value. MD5 may not be available in some environments. Parameters: * **overwrite** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – * **weak** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – Return type: None `age` The Age response-header field conveys the sender’s estimate of the amount of time since the response (or its revalidation) was generated at the origin server. Age values are non-negative decimal integers, representing time in seconds. `property allow: HeaderSet` The Allow entity-header field lists the set of methods supported by the resource identified by the Request-URI. The purpose of this field is strictly to inform the recipient of valid methods associated with the resource. An Allow header field MUST be present in a 405 (Method Not Allowed) response. `autocorrect_location_header = False` If a redirect `Location` header is a relative URL, make it an absolute URL, including scheme and domain. Changelog Changed in version 2.1: This is disabled by default, so responses will send relative redirects. New in version 0.8. `automatically_set_content_length = True` Should this response object automatically set the content-length header if possible? This is true by default. Changelog New in version 0.8. `property cache_control: ResponseCacheControl` The Cache-Control general-header field is used to specify directives that MUST be obeyed by all caching mechanisms along the request/response chain. `calculate_content_length()` Returns the content length if available or `None` otherwise. Return type: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")[[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")] `call_on_close(func)` Adds a function to the internal list of functions that should be called as part of closing down the response. Since 0.7 this function also returns the function that was passed so that this can be used as a decorator. Changelog New in version 0.6. Parameters: **func** ([Callable](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.10)")*[**[**]**,* [Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")*]*) – Return type: [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.10)")[[], [Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")] `charset = 'utf-8'` the charset of the response. `close()` Close the wrapped response if possible. You can also use the object in a with statement which will automatically close it. Changelog New in version 0.9: Can now be used in a with statement. Return type: None `content_encoding` The Content-Encoding entity-header field is used as a modifier to the media-type. When present, its value indicates what additional content codings have been applied to the entity-body, and thus what decoding mechanisms must be applied in order to obtain the media-type referenced by the Content-Type header field. `property content_language: HeaderSet` The Content-Language entity-header field describes the natural language(s) of the intended audience for the enclosed entity. Note that this might not be equivalent to all the languages used within the entity-body. `content_length` The Content-Length entity-header field indicates the size of the entity-body, in decimal number of OCTETs, sent to the recipient or, in the case of the HEAD method, the size of the entity-body that would have been sent had the request been a GET. `content_location` The Content-Location entity-header field MAY be used to supply the resource location for the entity enclosed in the message when that entity is accessible from a location separate from the requested resource’s URI. `content_md5` The Content-MD5 entity-header field, as defined in RFC 1864, is an MD5 digest of the entity-body for the purpose of providing an end-to-end message integrity check (MIC) of the entity-body. (Note: a MIC is good for detecting accidental modification of the entity-body in transit, but is not proof against malicious attacks.) `property content_range: ContentRange` The `Content-Range` header as a [`ContentRange`](../datastructures/index#werkzeug.datastructures.ContentRange "werkzeug.datastructures.ContentRange") object. Available even if the header is not set. Changelog New in version 0.7. `property content_security_policy: ContentSecurityPolicy` The `Content-Security-Policy` header as a `ContentSecurityPolicy` object. Available even if the header is not set. The Content-Security-Policy header adds an additional layer of security to help detect and mitigate certain types of attacks. `property content_security_policy_report_only: ContentSecurityPolicy` The `Content-Security-policy-report-only` header as a `ContentSecurityPolicy` object. Available even if the header is not set. The Content-Security-Policy-Report-Only header adds a csp policy that is not enforced but is reported thereby helping detect certain types of attacks. `content_type` The Content-Type entity-header field indicates the media type of the entity-body sent to the recipient or, in the case of the HEAD method, the media type that would have been sent had the request been a GET. `cross_origin_embedder_policy` Prevents a document from loading any cross-origin resources that do not explicitly grant the document permission. Values must be a member of the `werkzeug.http.COEP` enum. `cross_origin_opener_policy` Allows control over sharing of browsing context group with cross-origin documents. Values must be a member of the `werkzeug.http.COOP` enum. `property data: Union[bytes, str]` A descriptor that calls [`get_data()`](#werkzeug.wrappers.Response.get_data "werkzeug.wrappers.Response.get_data") and [`set_data()`](#werkzeug.wrappers.Response.set_data "werkzeug.wrappers.Response.set_data"). `date` The Date general-header field represents the date and time at which the message was originated, having the same semantics as orig-date in RFC 822. Changelog Changed in version 2.0: The datetime object is timezone-aware. `default_mimetype: Optional[str] = 'text/plain'` the default mimetype if none is provided. `default_status = 200` the default status if none is provided. `delete_cookie(key, path='/', domain=None, secure=False, httponly=False, samesite=None)` Delete a cookie. Fails silently if key doesn’t exist. Parameters: * **key** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – the key (name) of the cookie to be deleted. * **path** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – if the cookie that should be deleted was limited to a path, the path has to be defined here. * **domain** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – if the cookie that should be deleted was limited to a domain, that domain has to be defined here. * **secure** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – If `True`, the cookie will only be available via HTTPS. * **httponly** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – Disallow JavaScript access to the cookie. * **samesite** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – Limit the scope of the cookie to only be attached to requests that are β€œsame-site”. Return type: None `direct_passthrough` Pass the response body directly through as the WSGI iterable. This can be used when the body is a binary file or other iterator of bytes, to skip some unnecessary checks. Use [`send_file()`](../utils/index#werkzeug.utils.send_file "werkzeug.utils.send_file") instead of setting this manually. `expires` The Expires entity-header field gives the date/time after which the response is considered stale. A stale cache entry may not normally be returned by a cache. Changelog Changed in version 2.0: The datetime object is timezone-aware. `classmethod force_type(response, environ=None)` Enforce that the WSGI response is a response object of the current type. Werkzeug will use the [`Response`](#werkzeug.wrappers.Response "werkzeug.wrappers.Response") internally in many situations like the exceptions. If you call `get_response()` on an exception you will get back a regular [`Response`](#werkzeug.wrappers.Response "werkzeug.wrappers.Response") object, even if you are using a custom subclass. This method can enforce a given response type, and it will also convert arbitrary WSGI callables into response objects if an environ is provided: ``` # convert a Werkzeug response object into an instance of the # MyResponseClass subclass. response = MyResponseClass.force_type(response) # convert any WSGI application into a response object response = MyResponseClass.force_type(response, environ) ``` This is especially useful if you want to post-process responses in the main dispatcher and use functionality provided by your subclass. Keep in mind that this will modify response objects in place if possible! Parameters: * **response** ([Response](#werkzeug.wrappers.Response "werkzeug.wrappers.Response")) – a response object or wsgi application. * **environ** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[**WSGIEnvironment**]*) – a WSGI environment object. Returns: a response object. Return type: [Response](#werkzeug.wrappers.Response "werkzeug.wrappers.Response") `freeze()` Make the response object ready to be pickled. Does the following: * Buffer the response into a list, ignoring `implicity_sequence_conversion` and [`direct_passthrough`](#werkzeug.wrappers.Response.direct_passthrough "werkzeug.wrappers.Response.direct_passthrough"). * Set the `Content-Length` header. * Generate an `ETag` header if one is not already set. Changelog Changed in version 2.1: Removed the `no_etag` parameter. Changed in version 2.0: An `ETag` header is added, the `no_etag` parameter is deprecated and will be removed in Werkzeug 2.1. Changed in version 0.6: The `Content-Length` header is set. Return type: None `classmethod from_app(app, environ, buffered=False)` Create a new response object from an application output. This works best if you pass it an application that returns a generator all the time. Sometimes applications may use the `write()` callable returned by the `start_response` function. This tries to resolve such edge cases automatically. But if you don’t get the expected output you should set `buffered` to `True` which enforces buffering. Parameters: * **app** (*WSGIApplication*) – the WSGI application to execute. * **environ** (*WSGIEnvironment*) – the WSGI environment to execute against. * **buffered** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – set to `True` to enforce buffering. Returns: a response object. Return type: [Response](#werkzeug.wrappers.Response "werkzeug.wrappers.Response") `get_app_iter(environ)` Returns the application iterator for the given environ. Depending on the request method and the current status code the return value might be an empty response rather than the one from the response. If the request method is `HEAD` or the status code is in a range where the HTTP specification requires an empty response, an empty iterable is returned. Changelog New in version 0.6. Parameters: **environ** (*WSGIEnvironment*) – the WSGI environment of the request. Returns: a response iterable. Return type: [Iterable](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.10)")[[bytes](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.10)")] `get_data(as_text=False)` The string representation of the response body. Whenever you call this property the response iterable is encoded and flattened. This can lead to unwanted behavior if you stream big data. This behavior can be disabled by setting [`implicit_sequence_conversion`](#werkzeug.wrappers.Response.implicit_sequence_conversion "werkzeug.wrappers.Response.implicit_sequence_conversion") to `False`. If `as_text` is set to `True` the return value will be a decoded string. Changelog New in version 0.9. Parameters: **as\_text** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – Return type: [Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")[[bytes](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.10)"), [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")] `get_etag()` Return a tuple in the form `(etag, is_weak)`. If there is no ETag the return value is `(None, None)`. Return type: [Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")[[Tuple](https://docs.python.org/3/library/typing.html#typing.Tuple "(in Python v3.10)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)"), [bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")], [Tuple](https://docs.python.org/3/library/typing.html#typing.Tuple "(in Python v3.10)")[None, None]] `get_json(force=False, silent=False)` Parse [`data`](#werkzeug.wrappers.Response.data "werkzeug.wrappers.Response.data") as JSON. Useful during testing. If the mimetype does not indicate JSON (*application/json*, see [`is_json`](#werkzeug.wrappers.Response.is_json "werkzeug.wrappers.Response.is_json")), this returns `None`. Unlike [`Request.get_json()`](#werkzeug.wrappers.Request.get_json "werkzeug.wrappers.Request.get_json"), the result is not cached. Parameters: * **force** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – Ignore the mimetype and always try to parse JSON. * **silent** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – Silence parsing errors and return `None` instead. Return type: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")[[Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")] `get_wsgi_headers(environ)` This is automatically called right before the response is started and returns headers modified for the given environment. It returns a copy of the headers from the response with some modifications applied if necessary. For example the location header (if present) is joined with the root URL of the environment. Also the content length is automatically set to zero here for certain status codes. Changelog Changed in version 0.6: Previously that function was called `fix_headers` and modified the response object in place. Also since 0.6, IRIs in location and content-location headers are handled properly. Also starting with 0.6, Werkzeug will attempt to set the content length if it is able to figure it out on its own. This is the case if all the strings in the response iterable are already encoded and the iterable is buffered. Parameters: **environ** (*WSGIEnvironment*) – the WSGI environment of the request. Returns: returns a new [`Headers`](../datastructures/index#werkzeug.datastructures.Headers "werkzeug.datastructures.Headers") object. Return type: [Headers](../datastructures/index#werkzeug.datastructures.Headers "werkzeug.datastructures.Headers") `get_wsgi_response(environ)` Returns the final WSGI response as tuple. The first item in the tuple is the application iterator, the second the status and the third the list of headers. The response returned is created specially for the given environment. For example if the request method in the WSGI environment is `'HEAD'` the response will be empty and only the headers and status code will be present. Changelog New in version 0.6. Parameters: **environ** (*WSGIEnvironment*) – the WSGI environment of the request. Returns: an `(app_iter, status, headers)` tuple. Return type: [Tuple](https://docs.python.org/3/library/typing.html#typing.Tuple "(in Python v3.10)")[[Iterable](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.10)")[[bytes](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.10)")], [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)"), [List](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.10)")[[Tuple](https://docs.python.org/3/library/typing.html#typing.Tuple "(in Python v3.10)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)"), [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")]]] `implicit_sequence_conversion = True` if set to `False` accessing properties on the response object will not try to consume the response iterator and convert it into a list. Changelog New in version 0.6.2: That attribute was previously called `implicit_seqence_conversion`. (Notice the typo). If you did use this feature, you have to adapt your code to the name change. `property is_json: bool` Check if the mimetype indicates JSON data, either *application/json* or *application/\*+json*. `property is_sequence: bool` If the iterator is buffered, this property will be `True`. A response object will consider an iterator to be buffered if the response attribute is a list or tuple. Changelog New in version 0.6. `property is_streamed: bool` If the response is streamed (the response is not an iterable with a length information) this property is `True`. In this case streamed means that there is no information about the number of iterations. This is usually `True` if a generator is passed to the response object. This is useful for checking before applying some sort of post filtering that should not take place for streamed responses. `iter_encoded()` Iter the response encoded with the encoding of the response. If the response object is invoked as WSGI application the return value of this method is used as application iterator unless [`direct_passthrough`](#werkzeug.wrappers.Response.direct_passthrough "werkzeug.wrappers.Response.direct_passthrough") was activated. Return type: [Iterator](https://docs.python.org/3/library/typing.html#typing.Iterator "(in Python v3.10)")[[bytes](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.10)")] `property json: Optional[Any]` The parsed JSON data if [`mimetype`](#werkzeug.wrappers.Response.mimetype "werkzeug.wrappers.Response.mimetype") indicates JSON (*application/json*, see [`is_json`](#werkzeug.wrappers.Response.is_json "werkzeug.wrappers.Response.is_json")). Calls [`get_json()`](#werkzeug.wrappers.Response.get_json "werkzeug.wrappers.Response.get_json") with default arguments. `json_module = <module 'json' from '/home/docs/.asdf/installs/python/3.10.4/lib/python3.10/json/__init__.py'>` A module or other object that has `dumps` and `loads` functions that match the API of the built-in [`json`](https://docs.python.org/3/library/json.html#module-json "(in Python v3.10)") module. `last_modified` The Last-Modified entity-header field indicates the date and time at which the origin server believes the variant was last modified. Changelog Changed in version 2.0: The datetime object is timezone-aware. `location` The Location response-header field is used to redirect the recipient to a location other than the Request-URI for completion of the request or identification of a new resource. `make_conditional(request_or_environ, accept_ranges=False, complete_length=None)` Make the response conditional to the request. This method works best if an etag was defined for the response already. The `add_etag` method can be used to do that. If called without etag just the date header is set. This does nothing if the request method in the request or environ is anything but GET or HEAD. For optimal performance when handling range requests, it’s recommended that your response data object implements `seekable`, `seek` and `tell` methods as described by [`io.IOBase`](https://docs.python.org/3/library/io.html#io.IOBase "(in Python v3.10)"). Objects returned by [`wrap_file()`](../wsgi/index#werkzeug.wsgi.wrap_file "werkzeug.wsgi.wrap_file") automatically implement those methods. It does not remove the body of the response because that’s something the [`__call__()`](#werkzeug.wrappers.Response.__call__ "werkzeug.wrappers.Response.__call__") function does for us automatically. Returns self so that you can do `return resp.make_conditional(req)` but modifies the object in-place. Parameters: * **request\_or\_environ** ([Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[**WSGIEnvironment**,* [Request](#werkzeug.wrappers.Request "werkzeug.wrappers.Request")*]*) – a request object or WSGI environment to be used to make the response conditional against. * **accept\_ranges** ([Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[*[bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")*,* [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – This parameter dictates the value of `Accept-Ranges` header. If `False` (default), the header is not set. If `True`, it will be set to `"bytes"`. If `None`, it will be set to `"none"`. If it’s a string, it will use this value. * **complete\_length** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")*]*) – Will be used only in valid Range Requests. It will set `Content-Range` complete length value and compute `Content-Length` real value. This parameter is mandatory for successful Range Requests completion. Raises: [`RequestedRangeNotSatisfiable`](../exceptions/index#werkzeug.exceptions.RequestedRangeNotSatisfiable "werkzeug.exceptions.RequestedRangeNotSatisfiable") if `Range` header could not be parsed or satisfied. Return type: [Response](#werkzeug.wrappers.Response "werkzeug.wrappers.Response") Changelog Changed in version 2.0: Range processing is skipped if length is 0 instead of raising a 416 Range Not Satisfiable error. `make_sequence()` Converts the response iterator in a list. By default this happens automatically if required. If `implicit_sequence_conversion` is disabled, this method is not automatically called and some properties might raise exceptions. This also encodes all the items. Changelog New in version 0.6. Return type: None `max_cookie_size = 4093` Warn if a cookie header exceeds this size. The default, 4093, should be safely [supported by most browsers](http://browsercookielimits.squawky.net/). A cookie larger than this size will still be sent, but it may be ignored or handled incorrectly by some browsers. Set to 0 to disable this check. Changelog New in version 0.13. `property mimetype: Optional[str]` The mimetype (content type without charset etc.) `property mimetype_params: Dict[str, str]` The mimetype parameters as dict. For example if the content type is `text/html; charset=utf-8` the params would be `{'charset': 'utf-8'}`. Changelog New in version 0.5. `response: Union[Iterable[str], Iterable[bytes]]` The response body to send as the WSGI iterable. A list of strings or bytes represents a fixed-length response, any other iterable is a streaming response. Strings are encoded to bytes as UTF-8. Do not set to a plain string or bytes, that will cause sending the response to be very inefficient as it will iterate one byte at a time. `property retry_after: Optional[datetime]` The Retry-After response-header field can be used with a 503 (Service Unavailable) response to indicate how long the service is expected to be unavailable to the requesting client. Time in seconds until expiration or date. Changelog Changed in version 2.0: The datetime object is timezone-aware. `set_cookie(key, value='', max_age=None, expires=None, path='/', domain=None, secure=False, httponly=False, samesite=None)` Sets a cookie. A warning is raised if the size of the cookie header exceeds [`max_cookie_size`](#werkzeug.wrappers.Response.max_cookie_size "werkzeug.wrappers.Response.max_cookie_size"), but the header will still be set. Parameters: * **key** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – the key (name) of the cookie to be set. * **value** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – the value of the cookie. * **max\_age** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[*[timedelta](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.10)")*,* [int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")*]**]*) – should be a number of seconds, or `None` (default) if the cookie should last only as long as the client’s browser session. * **expires** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [datetime](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.10)")*,* [int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")*,* [float](https://docs.python.org/3/library/functions.html#float "(in Python v3.10)")*]**]*) – should be a `datetime` object or UNIX timestamp. * **path** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – limits the cookie to a given path, per default it will span the whole domain. * **domain** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – if you want to set a cross-domain cookie. For example, `domain=".example.com"` will set a cookie that is readable by the domain `www.example.com`, `foo.example.com` etc. Otherwise, a cookie will only be readable by the domain that set it. * **secure** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – If `True`, the cookie will only be available via HTTPS. * **httponly** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – Disallow JavaScript access to the cookie. * **samesite** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – Limit the scope of the cookie to only be attached to requests that are β€œsame-site”. Return type: None `set_data(value)` Sets a new string as response. The value must be a string or bytes. If a string is set it’s encoded to the charset of the response (utf-8 by default). Changelog New in version 0.9. Parameters: **value** ([Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[*[bytes](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.10)")*,* [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – Return type: None `set_etag(etag, weak=False)` Set the etag, and override the old one if there was one. Parameters: * **etag** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – * **weak** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – Return type: None `property status: str` The HTTP status code as a string. `property status_code: int` The HTTP status code as a number. `property stream: ResponseStream` The response iterable as write-only stream. `property vary: HeaderSet` The Vary field value indicates the set of request-header fields that fully determines, while the response is fresh, whether a cache is permitted to use the response to reply to a subsequent request without revalidation. `property www_authenticate: WWWAuthenticate` The `WWW-Authenticate` header in a parsed form.
programming_docs
werkzeug Werkzeug Tutorial Werkzeug Tutorial ================= Welcome to the Werkzeug tutorial in which we will create a [TinyURL](https://tinyurl.com/) clone that stores URLs in a redis instance. The libraries we will use for this applications are [Jinja](http://jinja.pocoo.org/) 2 for the templates, [redis](https://redis.io/) for the database layer and, of course, Werkzeug for the WSGI layer. You can use `pip` to install the required libraries: ``` pip install Jinja2 redis Werkzeug ``` Also make sure to have a redis server running on your local machine. If you are on OS X, you can use `brew` to install it: ``` brew install redis ``` If you are on Ubuntu or Debian, you can use apt-get: ``` sudo apt-get install redis-server ``` Redis was developed for UNIX systems and was never really designed to work on Windows. For development purposes, the unofficial ports however work well enough. You can get them from [github](https://github.com/dmajkic/redis/downloads). Introducing Shortly ------------------- In this tutorial, we will together create a simple URL shortener service with Werkzeug. Please keep in mind that Werkzeug is not a framework, it’s a library with utilities to create your own framework or application and as such is very flexible. The approach we use here is just one of many you can use. As data store, we will use [redis](https://redis.io/) here instead of a relational database to keep this simple and because that’s the kind of job that [redis](https://redis.io/) excels at. The final result will look something like this: Step 0: A Basic WSGI Introduction --------------------------------- Werkzeug is a utility library for WSGI. WSGI itself is a protocol or convention that ensures that your web application can speak with the webserver and more importantly that web applications work nicely together. A basic β€œHello World” application in WSGI without the help of Werkzeug looks like this: ``` def application(environ, start_response): start_response('200 OK', [('Content-Type', 'text/plain')]) return ['Hello World!'.encode('utf-8')] ``` A WSGI application is something you can call and pass an environ dict and a `start_response` callable. The environ contains all incoming information, the `start_response` function can be used to indicate the start of the response. With Werkzeug you don’t have to deal directly with either as request and response objects are provided to work with them. The request data takes the environ object and allows you to access the data from that environ in a nice manner. The response object is a WSGI application in itself and provides a much nicer way to create responses. Here is how you would write that application with response objects: ``` from werkzeug.wrappers import Response def application(environ, start_response): response = Response('Hello World!', mimetype='text/plain') return response(environ, start_response) ``` And here an expanded version that looks at the query string in the URL (more importantly at the `name` parameter in the URL to substitute β€œWorld” against another word): ``` from werkzeug.wrappers import Request, Response def application(environ, start_response): request = Request(environ) text = f"Hello {request.args.get('name', 'World')}!" response = Response(text, mimetype='text/plain') return response(environ, start_response) ``` And that’s all you need to know about WSGI. Step 1: Creating the Folders ---------------------------- Before we get started, let’s create the folders needed for this application: ``` /shortly /static /templates ``` The shortly folder is not a python package, but just something where we drop our files. Directly into this folder we will then put our main module in the following steps. The files inside the static folder are available to users of the application via HTTP. This is the place where CSS and JavaScript files go. Inside the templates folder we will make Jinja2 look for templates. The templates you create later in the tutorial will go in this directory. Step 2: The Base Structure -------------------------- Now let’s get right into it and create a module for our application. Let’s create a file called `shortly.py` in the `shortly` folder. At first we will need a bunch of imports. I will pull in all the imports here, even if they are not used right away, to keep it from being confusing: ``` import os import redis from werkzeug.urls import url_parse from werkzeug.wrappers import Request, Response from werkzeug.routing import Map, Rule from werkzeug.exceptions import HTTPException, NotFound from werkzeug.middleware.shared_data import SharedDataMiddleware from werkzeug.utils import redirect from jinja2 import Environment, FileSystemLoader ``` Then we can create the basic structure for our application and a function to create a new instance of it, optionally with a piece of WSGI middleware that exports all the files on the `static` folder on the web: ``` class Shortly(object): def __init__(self, config): self.redis = redis.Redis( config['redis_host'], config['redis_port'], decode_responses=True ) def dispatch_request(self, request): return Response('Hello World!') def wsgi_app(self, environ, start_response): request = Request(environ) response = self.dispatch_request(request) return response(environ, start_response) def __call__(self, environ, start_response): return self.wsgi_app(environ, start_response) def create_app(redis_host='localhost', redis_port=6379, with_static=True): app = Shortly({ 'redis_host': redis_host, 'redis_port': redis_port }) if with_static: app.wsgi_app = SharedDataMiddleware(app.wsgi_app, { '/static': os.path.join(os.path.dirname(__file__), 'static') }) return app ``` Lastly we can add a piece of code that will start a local development server with automatic code reloading and a debugger: ``` if __name__ == '__main__': from werkzeug.serving import run_simple app = create_app() run_simple('127.0.0.1', 5000, app, use_debugger=True, use_reloader=True) ``` The basic idea here is that our `Shortly` class is an actual WSGI application. The `__call__` method directly dispatches to `wsgi_app`. This is done so that we can wrap `wsgi_app` to apply middlewares like we do in the `create_app` function. The actual `wsgi_app` method then creates a `Request` object and calls the `dispatch_request` method which then has to return a `Response` object which is then evaluated as WSGI application again. As you can see: turtles all the way down. Both the `Shortly` class we create, as well as any request object in Werkzeug implements the WSGI interface. As a result of that you could even return another WSGI application from the `dispatch_request` method. The `create_app` factory function can be used to create a new instance of our application. Not only will it pass some parameters as configuration to the application but also optionally add a WSGI middleware that exports static files. This way we have access to the files from the static folder even when we are not configuring our server to provide them which is very helpful for development. Intermezzo: Running the Application ----------------------------------- Now you should be able to execute the file with `python` and see a server on your local machine: ``` $ python shortly.py * Running on http://127.0.0.1:5000/ * Restarting with reloader: stat() polling ``` It also tells you that the reloader is active. It will use various techniques to figure out if any file changed on the disk and then automatically restart. Just go to the URL and you should see β€œHello World!”. Step 3: The Environment ----------------------- Now that we have the basic application class, we can make the constructor do something useful and provide a few helpers on there that can come in handy. We will need to be able to render templates and connect to redis, so let’s extend the class a bit: ``` def __init__(self, config): self.redis = redis.Redis(config['redis_host'], config['redis_port']) template_path = os.path.join(os.path.dirname(__file__), 'templates') self.jinja_env = Environment(loader=FileSystemLoader(template_path), autoescape=True) def render_template(self, template_name, **context): t = self.jinja_env.get_template(template_name) return Response(t.render(context), mimetype='text/html') ``` Step 4: The Routing ------------------- Next up is routing. Routing is the process of matching and parsing the URL to something we can use. Werkzeug provides a flexible integrated routing system which we can use for that. The way it works is that you create a [`Map`](../routing/index#werkzeug.routing.Map "werkzeug.routing.Map") instance and add a bunch of [`Rule`](../routing/index#werkzeug.routing.Rule "werkzeug.routing.Rule") objects. Each rule has a pattern it will try to match the URL against and an β€œendpoint”. The endpoint is typically a string and can be used to uniquely identify the URL. We could also use this to automatically reverse the URL, but that’s not what we will do in this tutorial. Just put this into the constructor: ``` self.url_map = Map([ Rule('/', endpoint='new_url'), Rule('/<short_id>', endpoint='follow_short_link'), Rule('/<short_id>+', endpoint='short_link_details') ]) ``` Here we create a URL map with three rules. `/` for the root of the URL space where we will just dispatch to a function that implements the logic to create a new URL. And then one that follows the short link to the target URL and another one with the same rule but a plus (`+`) at the end to show the link details. So how do we find our way from the endpoint to a function? That’s up to you. The way we will do it in this tutorial is by calling the method `on_` + endpoint on the class itself. Here is how this works: ``` def dispatch_request(self, request): adapter = self.url_map.bind_to_environ(request.environ) try: endpoint, values = adapter.match() return getattr(self, f'on_{endpoint}')(request, **values) except HTTPException as e: return e ``` We bind the URL map to the current environment and get back a `URLAdapter`. The adapter can be used to match the request but also to reverse URLs. The match method will return the endpoint and a dictionary of values in the URL. For instance the rule for `follow_short_link` has a variable part called `short_id`. When we go to `http://localhost:5000/foo` we will get the following values back: ``` endpoint = 'follow_short_link' values = {'short_id': 'foo'} ``` If it does not match anything, it will raise a [`NotFound`](../exceptions/index#werkzeug.exceptions.NotFound "werkzeug.exceptions.NotFound") exception, which is an [`HTTPException`](../exceptions/index#werkzeug.exceptions.HTTPException "werkzeug.exceptions.HTTPException"). All HTTP exceptions are also WSGI applications by themselves which render a default error page. So we just catch all of them down and return the error itself. If all works well, we call the function `on_` + endpoint and pass it the request as argument as well as all the URL arguments as keyword arguments and return the response object that method returns. Step 5: The First View ---------------------- Let’s start with the first view: the one for new URLs: ``` def on_new_url(self, request): error = None url = '' if request.method == 'POST': url = request.form['url'] if not is_valid_url(url): error = 'Please enter a valid URL' else: short_id = self.insert_url(url) return redirect(f"/{short_id}+") return self.render_template('new_url.html', error=error, url=url) ``` This logic should be easy to understand. Basically we are checking that the request method is POST, in which case we validate the URL and add a new entry to the database, then redirect to the detail page. This means we need to write a function and a helper method. For URL validation this is good enough: ``` def is_valid_url(url): parts = url_parse(url) return parts.scheme in ('http', 'https') ``` For inserting the URL, all we need is this little method on our class: ``` def insert_url(self, url): short_id = self.redis.get(f'reverse-url:{url}') if short_id is not None: return short_id url_num = self.redis.incr('last-url-id') short_id = base36_encode(url_num) self.redis.set(f'url-target:{short_id}', url) self.redis.set(f'reverse-url:{url}', short_id) return short_id ``` `reverse-url:` + the URL will store the short id. If the URL was already submitted this won’t be None and we can just return that value which will be the short ID. Otherwise we increment the `last-url-id` key and convert it to base36. Then we store the link and the reverse entry in redis. And here the function to convert to base 36: ``` def base36_encode(number): assert number >= 0, 'positive integer required' if number == 0: return '0' base36 = [] while number != 0: number, i = divmod(number, 36) base36.append('0123456789abcdefghijklmnopqrstuvwxyz'[i]) return ''.join(reversed(base36)) ``` So what is missing for this view to work is the template. We will create this later, let’s first also write the other views and then do the templates in one go. Step 6: Redirect View --------------------- The redirect view is easy. All it has to do is to look for the link in redis and redirect to it. Additionally we will also increment a counter so that we know how often a link was clicked: ``` def on_follow_short_link(self, request, short_id): link_target = self.redis.get(f'url-target:{short_id}') if link_target is None: raise NotFound() self.redis.incr(f'click-count:{short_id}') return redirect(link_target) ``` In this case we will raise a [`NotFound`](../exceptions/index#werkzeug.exceptions.NotFound "werkzeug.exceptions.NotFound") exception by hand if the URL does not exist, which will bubble up to the `dispatch_request` function and be converted into a default 404 response. Step 7: Detail View ------------------- The link detail view is very similar, we just render a template again. In addition to looking up the target, we also ask redis for the number of times the link was clicked and let it default to zero if such a key does not yet exist: ``` def on_short_link_details(self, request, short_id): link_target = self.redis.get(f'url-target:{short_id}') if link_target is None: raise NotFound() click_count = int(self.redis.get(f'click-count:{short_id}') or 0) return self.render_template('short_link_details.html', link_target=link_target, short_id=short_id, click_count=click_count ) ``` Please be aware that redis always works with strings, so you have to convert the click count to [`int`](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)") by hand. Step 8: Templates ----------------- And here are all the templates. Just drop them into the `templates` folder. Jinja2 supports template inheritance, so the first thing we will do is create a layout template with blocks that act as placeholders. We also set up Jinja2 so that it automatically escapes strings with HTML rules, so we don’t have to spend time on that ourselves. This prevents XSS attacks and rendering errors. *layout.html*: ``` <!doctype html> <title>{% block title %}{% endblock %} | shortly</title> <link rel=stylesheet href=/static/style.css type=text/css> <div class=box> <h1><a href=/>shortly</a></h1> <p class=tagline>Shortly is a URL shortener written with Werkzeug {% block body %}{% endblock %} </div> ``` *new\_url.html*: ``` {% extends "layout.html" %} {% block title %}Create New Short URL{% endblock %} {% block body %} <h2>Submit URL</h2> <form action="" method=post> {% if error %} <p class=error><strong>Error:</strong> {{ error }} {% endif %} <p>URL: <input type=text name=url value="{{ url }}" class=urlinput> <input type=submit value="Shorten"> </form> {% endblock %} ``` *short\_link\_details.html*: ``` {% extends "layout.html" %} {% block title %}Details about /{{ short_id }}{% endblock %} {% block body %} <h2><a href="/{{ short_id }}">/{{ short_id }}</a></h2> <dl> <dt>Full link <dd class=link><div>{{ link_target }}</div> <dt>Click count: <dd>{{ click_count }} </dl> {% endblock %} ``` Step 9: The Style ----------------- For this to look better than ugly black and white, here a simple stylesheet that goes along: *static/style.css*: ``` body { background: #E8EFF0; margin: 0; padding: 0; } body, input { font-family: 'Helvetica Neue', Arial, sans-serif; font-weight: 300; font-size: 18px; } .box { width: 500px; margin: 60px auto; padding: 20px; background: white; box-shadow: 0 1px 4px #BED1D4; border-radius: 2px; } a { color: #11557C; } h1, h2 { margin: 0; color: #11557C; } h1 a { text-decoration: none; } h2 { font-weight: normal; font-size: 24px; } .tagline { color: #888; font-style: italic; margin: 0 0 20px 0; } .link div { overflow: auto; font-size: 0.8em; white-space: pre; padding: 4px 10px; margin: 5px 0; background: #E5EAF1; } dt { font-weight: normal; } .error { background: #E8EFF0; padding: 3px 8px; color: #11557C; font-size: 0.9em; border-radius: 2px; } .urlinput { width: 300px; } ``` Bonus: Refinements ------------------ Look at the implementation in the example dictionary in the Werkzeug repository to see a version of this tutorial with some small refinements such as a custom 404 page. * [shortly in the example folder](https://github.com/pallets/werkzeug/tree/main/examples/shortly) werkzeug Serving WSGI Applications Serving WSGI Applications ========================= There are many ways to serve a WSGI application. While you’re developing it, you usually don’t want to have a full-blown webserver like Apache up and running, but instead a simple standalone one. Because of that Werkzeug comes with a builtin development server. The easiest way is creating a small `start-myproject.py` file that runs the application using the builtin server: ``` from werkzeug.serving import run_simple from myproject import make_app app = make_app(...) run_simple('localhost', 8080, app, use_reloader=True) ``` You can also pass it the `extra_files` keyword argument with a list of additional files (like configuration files) you want to observe. `werkzeug.serving.run_simple(hostname, port, application, use_reloader=False, use_debugger=False, use_evalex=True, extra_files=None, exclude_patterns=None, reloader_interval=1, reloader_type='auto', threaded=False, processes=1, request_handler=None, static_files=None, passthrough_errors=False, ssl_context=None)` Start a development server for a WSGI application. Various optional features can be enabled. Warning Do not use the development server when deploying to production. It is intended for use only during local development. It is not designed to be particularly efficient, stable, or secure. Parameters: * **hostname** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – The host to bind to, for example `'localhost'`. Can be a domain, IPv4 or IPv6 address, or file path starting with `unix://` for a Unix socket. * **port** ([int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")) – The port to bind to, for example `8080`. Using `0` tells the OS to pick a random free port. * **application** (*WSGIApplication*) – The WSGI application to run. * **use\_reloader** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – Use a reloader process to restart the server process when files are changed. * **use\_debugger** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – Use Werkzeug’s debugger, which will show formatted tracebacks on unhandled exceptions. * **use\_evalex** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – Make the debugger interactive. A Python terminal can be opened for any frame in the traceback. Some protection is provided by requiring a PIN, but this should never be enabled on a publicly visible server. * **extra\_files** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Iterable](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]**]*) – The reloader will watch these files for changes in addition to Python modules. For example, watch a configuration file. * **exclude\_patterns** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Iterable](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]**]*) – The reloader will ignore changes to any files matching these [`fnmatch`](https://docs.python.org/3/library/fnmatch.html#module-fnmatch "(in Python v3.10)") patterns. For example, ignore cache files. * **reloader\_interval** ([int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")) – How often the reloader tries to check for changes. * **reloader\_type** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – The reloader to use. The `'stat'` reloader is built in, but may require significant CPU to watch files. The `'watchdog'` reloader is much more efficient but requires installing the `watchdog` package first. * **threaded** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – Handle concurrent requests using threads. Cannot be used with `processes`. * **processes** ([int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")) – Handle concurrent requests using up to this number of processes. Cannot be used with `threaded`. * **request\_handler** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Type](https://docs.python.org/3/library/typing.html#typing.Type "(in Python v3.10)")*[**WSGIRequestHandler**]**]*) – Use a different `BaseHTTPRequestHandler` subclass to handle requests. * **static\_files** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Dict](https://docs.python.org/3/library/typing.html#typing.Dict "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [Tuple](https://docs.python.org/3/library/typing.html#typing.Tuple "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]**]**]**]*) – A dict mapping URL prefixes to directories to serve static files from using `SharedDataMiddleware`. * **passthrough\_errors** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – Don’t catch unhandled exceptions at the server level, let the serve crash instead. If `use_debugger` is enabled, the debugger will still catch such errors. * **ssl\_context** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[*[ssl.SSLContext](https://docs.python.org/3/library/ssl.html#ssl.SSLContext "(in Python v3.10)")*,* [Tuple](https://docs.python.org/3/library/typing.html#typing.Tuple "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]**]**,* *te.Literal**[**'adhoc'**]**]**]*) – Configure TLS to serve over HTTPS. Can be an [`ssl.SSLContext`](https://docs.python.org/3/library/ssl.html#ssl.SSLContext "(in Python v3.10)") object, a `(cert_file, key_file)` tuple to create a typical context, or the string `'adhoc'` to generate a temporary self-signed certificate. Return type: None Changelog Changed in version 2.1: Instructions are shown for dealing with an β€œaddress already in use” error. Changed in version 2.1: Running on `0.0.0.0` or `::` shows the loopback IP in addition to a real IP. Changed in version 2.1: The command-line interface was removed. Changed in version 2.0: Running on `0.0.0.0` or `::` shows a real IP address that was bound as well as a warning not to run the development server in production. Changed in version 2.0: The `exclude_patterns` parameter was added. Changed in version 0.15: Bind to a Unix socket by passing a `hostname` that starts with `unix://`. Changed in version 0.10: Improved the reloader and added support for changing the backend through the `reloader_type` parameter. Changed in version 0.9: A command-line interface was added. Changed in version 0.8: `ssl_context` can be a tuple of paths to the certificate and private key files. Changed in version 0.6: The `ssl_context` parameter was added. Changed in version 0.5: The `static_files` and `passthrough_errors` parameters were added. `werkzeug.serving.is_running_from_reloader()` Check if the server is running as a subprocess within the Werkzeug reloader. Changelog New in version 0.10. Return type: [bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)") `werkzeug.serving.make_ssl_devcert(base_path, host=None, cn=None)` Creates an SSL key for development. This should be used instead of the `'adhoc'` key which generates a new cert on each server start. It accepts a path for where it should store the key and cert and either a host or CN. If a host is given it will use the CN `*.host/CN=host`. For more information see [`run_simple()`](#werkzeug.serving.run_simple "werkzeug.serving.run_simple"). Changelog New in version 0.9. Parameters: * **base\_path** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – the path to the certificate and key. The extension `.crt` is added for the certificate, `.key` is added for the key. * **host** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – the name of the host. This can be used as an alternative for the `cn`. * **cn** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – the `CN` to use. Return type: [Tuple](https://docs.python.org/3/library/typing.html#typing.Tuple "(in Python v3.10)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)"), [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")] Information The development server is not intended to be used on production systems. It was designed especially for development purposes and performs poorly under high load. For deployment setups have a look at the [Deploying to Production](../deployment/index) pages. Reloader -------- Changelog Changed in version 0.10. The Werkzeug reloader constantly monitors modules and paths of your web application, and restarts the server if any of the observed files change. Since version 0.10, there are two backends the reloader supports: `stat` and `watchdog`. * The default `stat` backend simply checks the `mtime` of all files in a regular interval. This is sufficient for most cases, however, it is known to drain a laptop’s battery. * The `watchdog` backend uses filesystem events, and is much faster than `stat`. It requires the [watchdog](https://pypi.org/project/watchdog/) module to be installed. The recommended way to achieve this is to add `Werkzeug[watchdog]` to your requirements file. If `watchdog` is installed and available it will automatically be used instead of the builtin `stat` reloader. To switch between the backends you can use the `reloader_type` parameter of the [`run_simple()`](#werkzeug.serving.run_simple "werkzeug.serving.run_simple") function. `'stat'` sets it to the default stat based polling and `'watchdog'` forces it to the watchdog backend. Note Some edge cases, like modules that failed to import correctly, are not handled by the stat reloader for performance reasons. The watchdog reloader monitors such files too. Colored Logging --------------- The development server highlights the request logs in different colors based on the status code. On Windows, [Colorama](https://pypi.org/project/colorama/) must be installed as well to enable this. Virtual Hosts ------------- Many web applications utilize multiple subdomains. This can be a bit tricky to simulate locally. Fortunately there is the [hosts file](https://en.wikipedia.org/wiki/Hosts_file) that can be used to assign the local computer multiple names. This allows you to call your local computer `yourapplication.local` and `api.yourapplication.local` (or anything else) in addition to `localhost`. You can find the hosts file on the following location: | | | | --- | --- | | Windows | `%SystemRoot%\system32\drivers\etc\hosts` | | Linux / OS X | `/etc/hosts` | You can open the file with your favorite text editor and add a new name after `localhost`: ``` 127.0.0.1 localhost yourapplication.local api.yourapplication.local ``` Save the changes and after a while you should be able to access the development server on these host names as well. You can use the [URL Routing](../routing/index) system to dispatch between different hosts or parse `request.host` yourself. Shutting Down The Server ------------------------ In some cases it can be useful to shut down a server after handling a request. For example, a local command line tool that needs OAuth authentication could temporarily start a server to listen for a response, record the user’s token, then stop the server. One method to do this could be to start a server in a [`multiprocessing`](https://docs.python.org/3/library/multiprocessing.html#module-multiprocessing "(in Python v3.10)") process, then terminate the process after a value is passed back to the parent. ``` import multiprocessing from werkzeug import Request, Response, run_simple def get_token(q: multiprocessing.Queue) -> None: @Request.application def app(request: Request) -> Response: q.put(request.args["token"]) return Response("", 204) run_simple("localhost", 5000, app) if __name__ == "__main__": q = multiprocessing.Queue() p = multiprocessing.Process(target=get_token, args=(q,)) p.start() print("waiting") token = q.get(block=True) p.terminate() print(token) ``` That example uses Werkzeug’s development server, but any production server that can be started as a Python process could use the same technique and should be preferred for security. Another method could be to start a [`subprocess`](https://docs.python.org/3/library/subprocess.html#module-subprocess "(in Python v3.10)") process and send the value back over `stdout`. Troubleshooting --------------- On operating systems that support ipv6 and have it configured such as modern Linux systems, OS X 10.4 or higher as well as Windows Vista some browsers can be painfully slow if accessing your local server. The reason for this is that sometimes β€œlocalhost” is configured to be available on both ipv4 and ipv6 sockets and some browsers will try to access ipv6 first and then ipv4. At the current time the integrated webserver does not support ipv6 and ipv4 at the same time and for better portability ipv4 is the default. If you notice that the web browser takes ages to load the page there are two ways around this issue. If you don’t need ipv6 support you can disable the ipv6 entry in the [hosts file](https://en.wikipedia.org/wiki/Hosts_file) by removing this line: ``` ::1 localhost ``` Alternatively you can also disable ipv6 support in your browser. For example if Firefox shows this behavior you can disable it by going to `about:config` and disabling the `network.dns.disableIPv6` key. This however is not recommended as of Werkzeug 0.6.1! Starting with Werkzeug 0.6.1, the server will now switch between ipv4 and ipv6 based on your operating system’s configuration. This means if that you disabled ipv6 support in your browser but your operating system is preferring ipv6, you will be unable to connect to your server. In that situation, you can either remove the localhost entry for `::1` or explicitly bind the hostname to an ipv4 address (`127.0.0.1`) SSL --- Changelog New in version 0.6. The builtin server supports SSL for testing purposes. If an SSL context is provided it will be used. That means a server can either run in HTTP or HTTPS mode, but not both. ### Quickstart The easiest way to do SSL based development with Werkzeug is by using it to generate an SSL certificate and private key and storing that somewhere and to then put it there. For the certificate you need to provide the name of your server on generation or a `CN`. 1. Generate an SSL key and store it somewhere: ``` >>> from werkzeug.serving import make_ssl_devcert >>> make_ssl_devcert('/path/to/the/key', host='localhost') ('/path/to/the/key.crt', '/path/to/the/key.key') ``` 2. Now this tuple can be passed as `ssl_context` to the [`run_simple()`](#werkzeug.serving.run_simple "werkzeug.serving.run_simple") method: ``` run_simple('localhost', 4000, application, ssl_context=('/path/to/the/key.crt', '/path/to/the/key.key')) ``` You will have to acknowledge the certificate in your browser once then. ### Loading Contexts by Hand You can use a `ssl.SSLContext` object instead of a tuple for full control over the TLS configuration. ``` import ssl ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) ctx.load_cert_chain('ssl.cert', 'ssl.key') run_simple('localhost', 4000, application, ssl_context=ctx) ``` ### Generating Certificates A key and certificate can be created in advance using the openssl tool instead of the [`make_ssl_devcert()`](#werkzeug.serving.make_ssl_devcert "werkzeug.serving.make_ssl_devcert"). This requires that you have the `openssl` command installed on your system: ``` $ openssl genrsa 1024 > ssl.key $ openssl req -new -x509 -nodes -sha1 -days 365 -key ssl.key > ssl.cert ``` ### Adhoc Certificates The easiest way to enable SSL is to start the server in adhoc-mode. In that case Werkzeug will generate an SSL certificate for you: ``` run_simple('localhost', 4000, application, ssl_context='adhoc') ``` The downside of this of course is that you will have to acknowledge the certificate each time the server is reloaded. Adhoc certificates are discouraged because modern browsers do a bad job at supporting them for security reasons. This feature requires the cryptography library to be installed. Unix Sockets ------------ The dev server can bind to a Unix socket instead of a TCP socket. [`run_simple()`](#werkzeug.serving.run_simple "werkzeug.serving.run_simple") will bind to a Unix socket if the `hostname` parameter starts with `'unix://'`. ``` from werkzeug.serving import run_simple run_simple('unix://example.sock', 0, app) ```
programming_docs
werkzeug BSD-3-Clause License BSD-3-Clause License ==================== Copyright 2007 Pallets Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS β€œAS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. werkzeug Testing WSGI Applications Testing WSGI Applications ========================= Test Client ----------- Werkzeug provides a [`Client`](#werkzeug.test.Client "werkzeug.test.Client") to simulate requests to a WSGI application without starting a server. The client has methods for making different types of requests, as well as managing cookies across requests. ``` >>> from werkzeug.test import Client >>> from werkzeug.testapp import test_app >>> c = Client(test_app) >>> response = c.get("/") >>> response.status_code 200 >>> resp.headers Headers([('Content-Type', 'text/html; charset=utf-8'), ('Content-Length', '6658')]) >>> response.get_data(as_text=True) '<!doctype html>...' ``` The client’s request methods return instances of [`TestResponse`](#werkzeug.test.TestResponse "werkzeug.test.TestResponse"). This provides extra attributes and methods on top of [`Response`](../wrappers/index#werkzeug.wrappers.Response "werkzeug.wrappers.Response") that are useful for testing. Request Body ------------ By passing a dict to `data`, the client will construct a request body with file and form data. It will set the content type to `application/x-www-form-urlencoded` if there are no files, or `multipart/form-data` there are. ``` import io response = client.post(data={ "name": "test", "file": (BytesIO("file contents".encode("utf8")), "test.txt") }) ``` Pass a string, bytes, or file-like object to `data` to use that as the raw request body. In that case, you should set the content type appropriately. For example, to post YAML: ``` response = client.post( data="a: value\nb: 1\n", content_type="application/yaml" ) ``` A shortcut when testing JSON APIs is to pass a dict to `json` instead of using `data`. This will automatically call `json.dumps()` and set the content type to `application/json`. Additionally, if the app returns JSON, `response.json` will automatically call `json.loads()`. ``` response = client.post("/api", json={"a": "value", "b": 1}) obj = response.json() ``` Environment Builder ------------------- [`EnvironBuilder`](#werkzeug.test.EnvironBuilder "werkzeug.test.EnvironBuilder") is used to construct a WSGI environ dict. The test client uses this internally to prepare its requests. The arguments passed to the client request methods are the same as the builder. Sometimes, it can be useful to construct a WSGI environment manually. An environ builder or dict can be passed to the test client request methods in place of other arguments to use a custom environ. ``` from werkzeug.test import EnvironBuilder builder = EnvironBuilder(...) # build an environ dict environ = builder.get_environ() # build an environ dict wrapped in a request request = builder.get_request() ``` The test client responses make this available through [`TestResponse.request`](#werkzeug.test.TestResponse.request "werkzeug.test.TestResponse.request") and `response.request.environ`. API --- `class werkzeug.test.Client(application, response_wrapper=None, use_cookies=True, allow_subdomain_redirects=False)` This class allows you to send requests to a wrapped application. The use\_cookies parameter indicates whether cookies should be stored and sent for subsequent requests. This is True by default, but passing False will disable this behaviour. If you want to request some subdomain of your application you may set `allow_subdomain_redirects` to `True` as if not no external redirects are allowed. Changelog Changed in version 2.1: Removed deprecated behavior of treating the response as a tuple. All data is available as properties on the returned response object. Changed in version 2.0: `response_wrapper` is always a subclass of :class:`TestResponse`. Changed in version 0.5: Added the `use_cookies` parameter. Parameters: * **application** (*WSGIApplication*) – * **response\_wrapper** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Type](https://docs.python.org/3/library/typing.html#typing.Type "(in Python v3.10)")*[*[Response](../wrappers/index#werkzeug.wrappers.Response "werkzeug.wrappers.Response")*]**]*) – * **use\_cookies** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – * **allow\_subdomain\_redirects** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – `set_cookie(server_name, key, value='', max_age=None, expires=None, path='/', domain=None, secure=False, httponly=False, samesite=None, charset='utf-8')` Sets a cookie in the client’s cookie jar. The server name is required and has to match the one that is also passed to the open call. Parameters: * **server\_name** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – * **key** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – * **value** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – * **max\_age** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[*[timedelta](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.10)")*,* [int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")*]**]*) – * **expires** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [datetime](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.10)")*,* [int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")*,* [float](https://docs.python.org/3/library/functions.html#float "(in Python v3.10)")*]**]*) – * **path** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – * **domain** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – * **secure** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – * **httponly** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – * **samesite** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – * **charset** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – Return type: None `delete_cookie(server_name, key, path='/', domain=None, secure=False, httponly=False, samesite=None)` Deletes a cookie in the test client. Parameters: * **server\_name** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – * **key** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – * **path** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – * **domain** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – * **secure** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – * **httponly** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – * **samesite** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – Return type: None `open(*args, buffered=False, follow_redirects=False, **kwargs)` Generate an environ dict from the given arguments, make a request to the application using it, and return the response. Parameters: * **args** ([Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")) – Passed to [`EnvironBuilder`](#werkzeug.test.EnvironBuilder "werkzeug.test.EnvironBuilder") to create the environ for the request. If a single arg is passed, it can be an existing [`EnvironBuilder`](#werkzeug.test.EnvironBuilder "werkzeug.test.EnvironBuilder") or an environ dict. * **buffered** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – Convert the iterator returned by the app into a list. If the iterator has a `close()` method, it is called automatically. * **follow\_redirects** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – Make additional requests to follow HTTP redirects until a non-redirect status is returned. [`TestResponse.history`](#werkzeug.test.TestResponse.history "werkzeug.test.TestResponse.history") lists the intermediate responses. * **kwargs** ([Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")) – Return type: [TestResponse](#werkzeug.test.TestResponse "werkzeug.test.TestResponse") Changelog Changed in version 2.1: Removed the `as_tuple` parameter. Changed in version 2.0: `as_tuple` is deprecated and will be removed in Werkzeug 2.1. Use [`TestResponse.request`](#werkzeug.test.TestResponse.request "werkzeug.test.TestResponse.request") and `request.environ` instead. Changed in version 2.0: The request input stream is closed when calling `response.close()`. Input streams for redirects are automatically closed. Changed in version 0.5: If a dict is provided as file in the dict for the `data` parameter the content type has to be called `content_type` instead of `mimetype`. This change was made for consistency with `werkzeug.FileWrapper`. Changed in version 0.5: Added the `follow_redirects` parameter. `get(*args, **kw)` Call [`open()`](#werkzeug.test.Client.open "werkzeug.test.Client.open") with `method` set to `GET`. Parameters: * **args** ([Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")) – * **kw** ([Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")) – Return type: [TestResponse](#werkzeug.test.TestResponse "werkzeug.test.TestResponse") `post(*args, **kw)` Call [`open()`](#werkzeug.test.Client.open "werkzeug.test.Client.open") with `method` set to `POST`. Parameters: * **args** ([Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")) – * **kw** ([Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")) – Return type: [TestResponse](#werkzeug.test.TestResponse "werkzeug.test.TestResponse") `put(*args, **kw)` Call [`open()`](#werkzeug.test.Client.open "werkzeug.test.Client.open") with `method` set to `PUT`. Parameters: * **args** ([Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")) – * **kw** ([Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")) – Return type: [TestResponse](#werkzeug.test.TestResponse "werkzeug.test.TestResponse") `delete(*args, **kw)` Call [`open()`](#werkzeug.test.Client.open "werkzeug.test.Client.open") with `method` set to `DELETE`. Parameters: * **args** ([Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")) – * **kw** ([Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")) – Return type: [TestResponse](#werkzeug.test.TestResponse "werkzeug.test.TestResponse") `patch(*args, **kw)` Call [`open()`](#werkzeug.test.Client.open "werkzeug.test.Client.open") with `method` set to `PATCH`. Parameters: * **args** ([Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")) – * **kw** ([Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")) – Return type: [TestResponse](#werkzeug.test.TestResponse "werkzeug.test.TestResponse") `options(*args, **kw)` Call [`open()`](#werkzeug.test.Client.open "werkzeug.test.Client.open") with `method` set to `OPTIONS`. Parameters: * **args** ([Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")) – * **kw** ([Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")) – Return type: [TestResponse](#werkzeug.test.TestResponse "werkzeug.test.TestResponse") `head(*args, **kw)` Call [`open()`](#werkzeug.test.Client.open "werkzeug.test.Client.open") with `method` set to `HEAD`. Parameters: * **args** ([Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")) – * **kw** ([Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")) – Return type: [TestResponse](#werkzeug.test.TestResponse "werkzeug.test.TestResponse") `trace(*args, **kw)` Call [`open()`](#werkzeug.test.Client.open "werkzeug.test.Client.open") with `method` set to `TRACE`. Parameters: * **args** ([Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")) – * **kw** ([Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")) – Return type: [TestResponse](#werkzeug.test.TestResponse "werkzeug.test.TestResponse") `class werkzeug.test.TestResponse(response, status, headers, request, history=(), **kwargs)` [`Response`](../wrappers/index#werkzeug.wrappers.Response "werkzeug.wrappers.Response") subclass that provides extra information about requests made with the test [`Client`](#werkzeug.test.Client "werkzeug.test.Client"). Test client requests will always return an instance of this class. If a custom response class is passed to the client, it is subclassed along with this to support test information. If the test request included large files, or if the application is serving a file, call `close()` to close any open files and prevent Python showing a `ResourceWarning`. Changed in version 2.2: Set the `default_mimetype` to None to prevent a mimetype being assumed if missing. Changelog Changed in version 2.1: Removed deprecated behavior for treating the response instance as a tuple. New in version 2.0: Test client methods always return instances of this class. Parameters: * **response** ([Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[*[Iterable](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]**,* [Iterable](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.10)")*[*[bytes](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.10)")*]**]*) – * **status** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – * **headers** ([Headers](../datastructures/index#werkzeug.datastructures.Headers "werkzeug.datastructures.Headers")) – * **request** ([Request](../wrappers/index#werkzeug.wrappers.Request "werkzeug.wrappers.request.Request")) – * **history** ([Tuple](https://docs.python.org/3/library/typing.html#typing.Tuple "(in Python v3.10)")*[*[TestResponse](#werkzeug.test.TestResponse "werkzeug.test.TestResponse")*,* *...**]*) – * **kwargs** ([Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")) – `default_mimetype: Optional[str] = None` the default mimetype if none is provided. `request: Request` A request object with the environ used to make the request that resulted in this response. `history: Tuple[TestResponse, ...]` A list of intermediate responses. Populated when the test request is made with `follow_redirects` enabled. `property text: str` The response data as text. A shortcut for `response.get_data(as_text=True)`. Changelog New in version 2.1. `class werkzeug.test.EnvironBuilder(path='/', base_url=None, query_string=None, method='GET', input_stream=None, content_type=None, content_length=None, errors_stream=None, multithread=False, multiprocess=False, run_once=False, headers=None, data=None, environ_base=None, environ_overrides=None, charset='utf-8', mimetype=None, json=None, auth=None)` This class can be used to conveniently create a WSGI environment for testing purposes. It can be used to quickly create WSGI environments or request objects from arbitrary data. The signature of this class is also used in some other places as of Werkzeug 0.5 ([`create_environ()`](#werkzeug.test.create_environ "werkzeug.test.create_environ"), `Response.from_values()`, [`Client.open()`](#werkzeug.test.Client.open "werkzeug.test.Client.open")). Because of this most of the functionality is available through the constructor alone. Files and regular form data can be manipulated independently of each other with the [`form`](#werkzeug.test.EnvironBuilder.form "werkzeug.test.EnvironBuilder.form") and [`files`](#werkzeug.test.EnvironBuilder.files "werkzeug.test.EnvironBuilder.files") attributes, but are passed with the same argument to the constructor: `data`. `data` can be any of these values: * a `str` or `bytes` object: The object is converted into an [`input_stream`](#werkzeug.test.EnvironBuilder.input_stream "werkzeug.test.EnvironBuilder.input_stream"), the [`content_length`](#werkzeug.test.EnvironBuilder.content_length "werkzeug.test.EnvironBuilder.content_length") is set and you have to provide a [`content_type`](#werkzeug.test.EnvironBuilder.content_type "werkzeug.test.EnvironBuilder.content_type"). * a `dict` or `MultiDict`: The keys have to be strings. The values have to be either any of the following objects, or a list of any of the following objects: + a `file`-like object: These are converted into `FileStorage` objects automatically. + a `tuple`: The `add_file()` method is called with the key and the unpacked `tuple` items as positional arguments. + a `str`: The string is set as form data for the associated key. * a file-like object: The object content is loaded in memory and then handled like a regular `str` or a `bytes`. Parameters: * **path** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – the path of the request. In the WSGI environment this will end up as `PATH_INFO`. If the `query_string` is not defined and there is a question mark in the `path` everything after it is used as query string. * **base\_url** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – the base URL is a URL that is used to extract the WSGI URL scheme, host (server name + server port) and the script root (`SCRIPT_NAME`). * **query\_string** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[*[Mapping](https://docs.python.org/3/library/typing.html#typing.Mapping "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]**,* [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]**]*) – an optional string or dict with URL parameters. * **method** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – the HTTP method to use, defaults to `GET`. * **input\_stream** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[IO](https://docs.python.org/3/library/typing.html#typing.IO "(in Python v3.10)")*[*[bytes](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.10)")*]**]*) – an optional input stream. Do not specify this and `data`. As soon as an input stream is set you can’t modify [`args`](#werkzeug.test.EnvironBuilder.args "werkzeug.test.EnvironBuilder.args") and [`files`](#werkzeug.test.EnvironBuilder.files "werkzeug.test.EnvironBuilder.files") unless you set the [`input_stream`](#werkzeug.test.EnvironBuilder.input_stream "werkzeug.test.EnvironBuilder.input_stream") to `None` again. * **content\_type** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – The content type for the request. As of 0.5 you don’t have to provide this when specifying files and form data via `data`. * **content\_length** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")*]*) – The content length for the request. You don’t have to specify this when providing data via `data`. * **errors\_stream** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[IO](https://docs.python.org/3/library/typing.html#typing.IO "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]**]*) – an optional error stream that is used for `wsgi.errors`. Defaults to `stderr`. * **multithread** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – controls `wsgi.multithread`. Defaults to `False`. * **multiprocess** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – controls `wsgi.multiprocess`. Defaults to `False`. * **run\_once** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – controls `wsgi.run_once`. Defaults to `False`. * **headers** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[*[Headers](../datastructures/index#werkzeug.datastructures.Headers "werkzeug.datastructures.Headers")*,* [Iterable](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.10)")*[*[Tuple](https://docs.python.org/3/library/typing.html#typing.Tuple "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]**]**]**]*) – an optional list or `Headers` object of headers. * **data** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[*[IO](https://docs.python.org/3/library/typing.html#typing.IO "(in Python v3.10)")*[*[bytes](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.10)")*]**,* [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [bytes](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.10)")*,* [Mapping](https://docs.python.org/3/library/typing.html#typing.Mapping "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")*]**]**]*) – a string or dict of form data or a file-object. See explanation above. * **json** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Mapping](https://docs.python.org/3/library/typing.html#typing.Mapping "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")*]**]*) – An object to be serialized and assigned to `data`. Defaults the content type to `"application/json"`. Serialized with the function assigned to [`json_dumps`](#werkzeug.test.EnvironBuilder.json_dumps "werkzeug.test.EnvironBuilder.json_dumps"). * **environ\_base** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Mapping](https://docs.python.org/3/library/typing.html#typing.Mapping "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")*]**]*) – an optional dict of environment defaults. * **environ\_overrides** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Mapping](https://docs.python.org/3/library/typing.html#typing.Mapping "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")*]**]*) – an optional dict of environment overrides. * **charset** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – the charset used to encode string data. * **auth** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[*[Authorization](../datastructures/index#werkzeug.datastructures.Authorization "werkzeug.datastructures.Authorization")*,* [Tuple](https://docs.python.org/3/library/typing.html#typing.Tuple "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]**]**]*) – An authorization object to use for the `Authorization` header value. A `(username, password)` tuple is a shortcut for `Basic` authorization. * **mimetype** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – Changelog Changed in version 2.1: `CONTENT_TYPE` and `CONTENT_LENGTH` are not duplicated as header keys in the environ. Changed in version 2.0: `REQUEST_URI` and `RAW_URI` is the full raw URI including the query string, not only the path. Changed in version 2.0: The default [`request_class`](#werkzeug.test.EnvironBuilder.request_class "werkzeug.test.EnvironBuilder.request_class") is `Request` instead of `BaseRequest`. New in version 2.0: Added the `auth` parameter. New in version 0.15: The `json` param and [`json_dumps()`](#werkzeug.test.EnvironBuilder.json_dumps "werkzeug.test.EnvironBuilder.json_dumps") method. New in version 0.15: The environ has keys `REQUEST_URI` and `RAW_URI` containing the path before percent-decoding. This is not part of the WSGI PEP, but many WSGI servers include it. Changed in version 0.6: `path` and `base_url` can now be unicode strings that are encoded with `iri_to_uri()`. `server_protocol = 'HTTP/1.1'` the server protocol to use. defaults to HTTP/1.1 `wsgi_version = (1, 0)` the wsgi version to use. defaults to (1, 0) `request_class` The default request class used by [`get_request()`](#werkzeug.test.EnvironBuilder.get_request "werkzeug.test.EnvironBuilder.get_request"). alias of [`Request`](../wrappers/index#werkzeug.wrappers.Request "werkzeug.wrappers.request.Request") `static json_dumps(obj, *, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, cls=None, indent=None, separators=None, default=None, sort_keys=False, **kw)` The serialization function used when `json` is passed. `classmethod from_environ(environ, **kwargs)` Turn an environ dict back into a builder. Any extra kwargs override the args extracted from the environ. Changelog Changed in version 2.0: Path and query values are passed through the WSGI decoding dance to avoid double encoding. New in version 0.15. Parameters: * **environ** (*WSGIEnvironment*) – * **kwargs** ([Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")) – Return type: [EnvironBuilder](#werkzeug.test.EnvironBuilder "werkzeug.test.EnvironBuilder") `property base_url: str` The base URL is used to extract the URL scheme, host name, port, and root path. `property content_type: Optional[str]` The content type for the request. Reflected from and to the `headers`. Do not set if you set [`files`](#werkzeug.test.EnvironBuilder.files "werkzeug.test.EnvironBuilder.files") or [`form`](#werkzeug.test.EnvironBuilder.form "werkzeug.test.EnvironBuilder.form") for auto detection. `property mimetype: Optional[str]` The mimetype (content type without charset etc.) Changelog New in version 0.14. `property mimetype_params: Mapping[str, str]` The mimetype parameters as dict. For example if the content type is `text/html; charset=utf-8` the params would be `{'charset': 'utf-8'}`. Changelog New in version 0.14. `property content_length: Optional[int]` The content length as integer. Reflected from and to the `headers`. Do not set if you set [`files`](#werkzeug.test.EnvironBuilder.files "werkzeug.test.EnvironBuilder.files") or [`form`](#werkzeug.test.EnvironBuilder.form "werkzeug.test.EnvironBuilder.form") for auto detection. `property form: MultiDict` A `MultiDict` of form values. `property files: FileMultiDict` A `FileMultiDict` of uploaded files. Use `add_file()` to add new files. `property input_stream: Optional[IO[bytes]]` An optional input stream. This is mutually exclusive with setting [`form`](#werkzeug.test.EnvironBuilder.form "werkzeug.test.EnvironBuilder.form") and [`files`](#werkzeug.test.EnvironBuilder.files "werkzeug.test.EnvironBuilder.files"), setting it will clear those. Do not provide this if the method is not `POST` or another method that has a body. `property query_string: str` The query string. If you set this to a string [`args`](#werkzeug.test.EnvironBuilder.args "werkzeug.test.EnvironBuilder.args") will no longer be available. `property args: MultiDict` The URL arguments as `MultiDict`. `property server_name: str` The server name (read-only, use `host` to set) `property server_port: int` The server port as integer (read-only, use `host` to set) `close()` Closes all files. If you put real `file` objects into the [`files`](#werkzeug.test.EnvironBuilder.files "werkzeug.test.EnvironBuilder.files") dict you can call this method to automatically close them all in one go. Return type: None `get_environ()` Return the built environ. Changelog Changed in version 0.15: The content type and length headers are set based on input stream detection. Previously this only set the WSGI keys. Return type: WSGIEnvironment `get_request(cls=None)` Returns a request with the data. If the request class is not specified [`request_class`](#werkzeug.test.EnvironBuilder.request_class "werkzeug.test.EnvironBuilder.request_class") is used. Parameters: **cls** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Type](https://docs.python.org/3/library/typing.html#typing.Type "(in Python v3.10)")*[*[Request](../wrappers/index#werkzeug.wrappers.Request "werkzeug.wrappers.request.Request")*]**]*) – The request wrapper to use. Return type: [Request](../wrappers/index#werkzeug.wrappers.Request "werkzeug.wrappers.request.Request") `werkzeug.test.create_environ(*args, **kwargs)` Create a new WSGI environ dict based on the values passed. The first parameter should be the path of the request which defaults to β€˜/’. The second one can either be an absolute path (in that case the host is localhost:80) or a full path to the request with scheme, netloc port and the path to the script. This accepts the same arguments as the [`EnvironBuilder`](#werkzeug.test.EnvironBuilder "werkzeug.test.EnvironBuilder") constructor. Changelog Changed in version 0.5: This function is now a thin wrapper over [`EnvironBuilder`](#werkzeug.test.EnvironBuilder "werkzeug.test.EnvironBuilder") which was added in 0.5. The `headers`, `environ_base`, `environ_overrides` and `charset` parameters were added. Parameters: * **args** ([Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")) – * **kwargs** ([Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")) – Return type: WSGIEnvironment `werkzeug.test.run_wsgi_app(app, environ, buffered=False)` Return a tuple in the form (app\_iter, status, headers) of the application output. This works best if you pass it an application that returns an iterator all the time. Sometimes applications may use the `write()` callable returned by the `start_response` function. This tries to resolve such edge cases automatically. But if you don’t get the expected output you should set `buffered` to `True` which enforces buffering. If passed an invalid WSGI application the behavior of this function is undefined. Never pass non-conforming WSGI applications to this function. Parameters: * **app** (*WSGIApplication*) – the application to execute. * **buffered** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – set to `True` to enforce buffering. * **environ** (*WSGIEnvironment*) – Returns: tuple in the form `(app_iter, status, headers)` Return type: [Tuple](https://docs.python.org/3/library/typing.html#typing.Tuple "(in Python v3.10)")[[Iterable](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.10)")[[bytes](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.10)")], [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)"), [Headers](../datastructures/index#werkzeug.datastructures.Headers "werkzeug.datastructures.Headers")]
programming_docs
werkzeug Unicode Unicode ======= Werkzeug uses strings internally everwhere text data is assumed, even if the HTTP standard is not Unicode aware. Basically all incoming data is decoded from the charset (UTF-8 by default) so that you don’t work with bytes directly. Outgoing data is encoded into the target charset. Unicode in Python ----------------- Imagine you have the German Umlaut `ΓΆ`. In ASCII you cannot represent that character, but in the `latin-1` and `utf-8` character sets you can represent it, but they look different when encoded: ``` >>> "ΓΆ".encode("latin1") b'\xf6' >>> "ΓΆ".encode("utf-8") b'\xc3\xb6' ``` An `ΓΆ` looks different depending on the encoding which makes it hard to work with it as bytes. Instead, Python treats strings as Unicode text and stores the information `LATIN SMALL LETTER O WITH DIAERESIS` instead of the bytes for `ΓΆ` in a specific encoding. The length of a string with 1 character will be 1, where the length of the bytes might be some other value. Unicode in HTTP --------------- However, the HTTP spec was written in a time where ASCII bytes were the common way data was represented. To work around this for the modern web, Werkzeug decodes and encodes incoming and outgoing data automatically. Data sent from the browser to the web application is decoded from UTF-8 bytes into a string. Data sent from the application back to the browser is encoded back to UTF-8. Error Handling -------------- Functions that do internal encoding or decoding accept an `errors` keyword argument that is passed to `str.decode()` and [`str.encode()`](https://docs.python.org/3/library/stdtypes.html#str.encode "(in Python v3.10)"). The default is `'replace'` so that errors are easy to spot. It might be useful to set it to `'strict'` in order to catch the error and report the bad data to the client. Request and Response Objects ---------------------------- In most cases, you should stick with Werkzeug’s default encoding of UTF-8. If you have a specific reason to, you can subclass [`wrappers.Request`](../wrappers/index#werkzeug.wrappers.Request "werkzeug.wrappers.Request") and [`wrappers.Response`](../wrappers/index#werkzeug.wrappers.Response "werkzeug.wrappers.Response") to change the encoding and error handling. ``` from werkzeug.wrappers.request import Request from werkzeug.wrappers.response import Response class Latin1Request(Request): charset = "latin1" encoding_errors = "strict" class Latin1Response(Response): charset = "latin1" ``` The error handling can only be changed for the request. Werkzeug will always raise errors when encoding to bytes in the response. It’s your responsibility to not create data that is not present in the target charset. This is not an issue for UTF-8. werkzeug Data Structures Data Structures =============== Werkzeug provides some subclasses of common Python objects to extend them with additional features. Some of them are used to make them immutable, others are used to change some semantics to better work with HTTP. General Purpose --------------- Changelog Changed in version 0.6: The general purpose classes are now pickleable in each protocol as long as the contained objects are pickleable. This means that the [`FileMultiDict`](#werkzeug.datastructures.FileMultiDict "werkzeug.datastructures.FileMultiDict") won’t be pickleable as soon as it contains a file. `class werkzeug.datastructures.TypeConversionDict` Works like a regular dict but the [`get()`](#werkzeug.datastructures.TypeConversionDict.get "werkzeug.datastructures.TypeConversionDict.get") method can perform type conversions. [`MultiDict`](#werkzeug.datastructures.MultiDict "werkzeug.datastructures.MultiDict") and [`CombinedMultiDict`](#werkzeug.datastructures.CombinedMultiDict "werkzeug.datastructures.CombinedMultiDict") are subclasses of this class and provide the same feature. Changelog New in version 0.5. `get(key, default=None, type=None)` Return the default value if the requested data doesn’t exist. If `type` is provided and is a callable it should convert the value, return it or raise a [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.10)") if that is not possible. In this case the function will return the default as if the value was not found: ``` >>> d = TypeConversionDict(foo='42', bar='blub') >>> d.get('foo', type=int) 42 >>> d.get('bar', -1, type=int) -1 ``` Parameters: * **key** – The key to be looked up. * **default** – The default value to be returned if the key can’t be looked up. If not further specified `None` is returned. * **type** – A callable that is used to cast the value in the [`MultiDict`](#werkzeug.datastructures.MultiDict "werkzeug.datastructures.MultiDict"). If a [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.10)") is raised by this callable the default value is returned. `class werkzeug.datastructures.ImmutableTypeConversionDict` Works like a [`TypeConversionDict`](#werkzeug.datastructures.TypeConversionDict "werkzeug.datastructures.TypeConversionDict") but does not support modifications. Changelog New in version 0.5. `copy()` Return a shallow mutable copy of this object. Keep in mind that the standard library’s [`copy()`](#werkzeug.datastructures.ImmutableTypeConversionDict.copy "werkzeug.datastructures.ImmutableTypeConversionDict.copy") function is a no-op for this class like for any other python immutable type (eg: [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)")). `class werkzeug.datastructures.MultiDict(mapping=None)` A [`MultiDict`](#werkzeug.datastructures.MultiDict "werkzeug.datastructures.MultiDict") is a dictionary subclass customized to deal with multiple values for the same key which is for example used by the parsing functions in the wrappers. This is necessary because some HTML form elements pass multiple values for the same key. [`MultiDict`](#werkzeug.datastructures.MultiDict "werkzeug.datastructures.MultiDict") implements all standard dictionary methods. Internally, it saves all values for a key as a list, but the standard dict access methods will only return the first value for a key. If you want to gain access to the other values, too, you have to use the `list` methods as explained below. Basic Usage: ``` >>> d = MultiDict([('a', 'b'), ('a', 'c')]) >>> d MultiDict([('a', 'b'), ('a', 'c')]) >>> d['a'] 'b' >>> d.getlist('a') ['b', 'c'] >>> 'a' in d True ``` It behaves like a normal dict thus all dict functions will only return the first value when multiple values for one key are found. From Werkzeug 0.3 onwards, the `KeyError` raised by this class is also a subclass of the `BadRequest` HTTP exception and will render a page for a `400 BAD REQUEST` if caught in a catch-all for HTTP exceptions. A [`MultiDict`](#werkzeug.datastructures.MultiDict "werkzeug.datastructures.MultiDict") can be constructed from an iterable of `(key, value)` tuples, a dict, a [`MultiDict`](#werkzeug.datastructures.MultiDict "werkzeug.datastructures.MultiDict") or from Werkzeug 0.2 onwards some keyword parameters. Parameters: **mapping** – the initial value for the [`MultiDict`](#werkzeug.datastructures.MultiDict "werkzeug.datastructures.MultiDict"). Either a regular dict, an iterable of `(key, value)` tuples or `None`. `add(key, value)` Adds a new value for the key. Changelog New in version 0.6. Parameters: * **key** – the key for the value. * **value** – the value to add. `clear() β†’ None. Remove all items from D.` `copy()` Return a shallow copy of this object. `deepcopy(memo=None)` Return a deep copy of this object. `fromkeys(value=None, /)` Create a new dictionary with keys from iterable and values set to value. `get(key, default=None, type=None)` Return the default value if the requested data doesn’t exist. If `type` is provided and is a callable it should convert the value, return it or raise a [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.10)") if that is not possible. In this case the function will return the default as if the value was not found: ``` >>> d = TypeConversionDict(foo='42', bar='blub') >>> d.get('foo', type=int) 42 >>> d.get('bar', -1, type=int) -1 ``` Parameters: * **key** – The key to be looked up. * **default** – The default value to be returned if the key can’t be looked up. If not further specified `None` is returned. * **type** – A callable that is used to cast the value in the [`MultiDict`](#werkzeug.datastructures.MultiDict "werkzeug.datastructures.MultiDict"). If a [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.10)") is raised by this callable the default value is returned. `getlist(key, type=None)` Return the list of items for a given key. If that key is not in the `MultiDict`, the return value will be an empty list. Just like `get`, `getlist` accepts a `type` parameter. All items will be converted with the callable defined there. Parameters: * **key** – The key to be looked up. * **type** – A callable that is used to cast the value in the [`MultiDict`](#werkzeug.datastructures.MultiDict "werkzeug.datastructures.MultiDict"). If a [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.10)") is raised by this callable the value will be removed from the list. Returns: a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of all the values for the key. `items(multi=False)` Return an iterator of `(key, value)` pairs. Parameters: **multi** – If set to `True` the iterator returned will have a pair for each value of each key. Otherwise it will only contain pairs for the first value of each key. `keys() β†’ a set-like object providing a view on D's keys` `lists()` Return a iterator of `(key, values)` pairs, where values is the list of all values associated with the key. `listvalues()` Return an iterator of all values associated with a key. Zipping [`keys()`](#werkzeug.datastructures.MultiDict.keys "werkzeug.datastructures.MultiDict.keys") and this is the same as calling [`lists()`](#werkzeug.datastructures.MultiDict.lists "werkzeug.datastructures.MultiDict.lists"): ``` >>> d = MultiDict({"foo": [1, 2, 3]}) >>> zip(d.keys(), d.listvalues()) == d.lists() True ``` `pop(key, default=no value)` Pop the first item for a list on the dict. Afterwards the key is removed from the dict, so additional values are discarded: ``` >>> d = MultiDict({"foo": [1, 2, 3]}) >>> d.pop("foo") 1 >>> "foo" in d False ``` Parameters: * **key** – the key to pop. * **default** – if provided the value to return if the key was not in the dictionary. `popitem()` Pop an item from the dict. `popitemlist()` Pop a `(key, list)` tuple from the dict. `poplist(key)` Pop the list for a key from the dict. If the key is not in the dict an empty list is returned. Changelog Changed in version 0.5: If the key does no longer exist a list is returned instead of raising an error. `setdefault(key, default=None)` Returns the value for the key if it is in the dict, otherwise it returns `default` and sets that value for `key`. Parameters: * **key** – The key to be looked up. * **default** – The default value to be returned if the key is not in the dict. If not further specified it’s `None`. `setlist(key, new_list)` Remove the old values for a key and add new ones. Note that the list you pass the values in will be shallow-copied before it is inserted in the dictionary. ``` >>> d = MultiDict() >>> d.setlist('foo', ['1', '2']) >>> d['foo'] '1' >>> d.getlist('foo') ['1', '2'] ``` Parameters: * **key** – The key for which the values are set. * **new\_list** – An iterable with the new values for the key. Old values are removed first. `setlistdefault(key, default_list=None)` Like `setdefault` but sets multiple values. The list returned is not a copy, but the list that is actually used internally. This means that you can put new values into the dict by appending items to the list: ``` >>> d = MultiDict({"foo": 1}) >>> d.setlistdefault("foo").extend([2, 3]) >>> d.getlist("foo") [1, 2, 3] ``` Parameters: * **key** – The key to be looked up. * **default\_list** – An iterable of default values. It is either copied (in case it was a list) or converted into a list before returned. Returns: a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") `to_dict(flat=True)` Return the contents as regular dict. If `flat` is `True` the returned dict will only have the first item present, if `flat` is `False` all values will be returned as lists. Parameters: **flat** – If set to `False` the dict returned will have lists with all the values in it. Otherwise it will only contain the first value for each key. Returns: a [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.10)") `update(mapping)` update() extends rather than replaces existing key lists: ``` >>> a = MultiDict({'x': 1}) >>> b = MultiDict({'x': 2, 'y': 3}) >>> a.update(b) >>> a MultiDict([('y', 3), ('x', 1), ('x', 2)]) ``` If the value list for a key in `other_dict` is empty, no new values will be added to the dict and the key will not be created: ``` >>> x = {'empty_list': []} >>> y = MultiDict() >>> y.update(x) >>> y MultiDict([]) ``` `values()` Returns an iterator of the first value on every key’s value list. `class werkzeug.datastructures.OrderedMultiDict(mapping=None)` Works like a regular [`MultiDict`](#werkzeug.datastructures.MultiDict "werkzeug.datastructures.MultiDict") but preserves the order of the fields. To convert the ordered multi dict into a list you can use the `items()` method and pass it `multi=True`. In general an [`OrderedMultiDict`](#werkzeug.datastructures.OrderedMultiDict "werkzeug.datastructures.OrderedMultiDict") is an order of magnitude slower than a [`MultiDict`](#werkzeug.datastructures.MultiDict "werkzeug.datastructures.MultiDict"). note Due to a limitation in Python you cannot convert an ordered multi dict into a regular dict by using `dict(multidict)`. Instead you have to use the `to_dict()` method, otherwise the internal bucket objects are exposed. `class werkzeug.datastructures.ImmutableMultiDict(mapping=None)` An immutable [`MultiDict`](#werkzeug.datastructures.MultiDict "werkzeug.datastructures.MultiDict"). Changelog New in version 0.5. `copy()` Return a shallow mutable copy of this object. Keep in mind that the standard library’s [`copy()`](#werkzeug.datastructures.ImmutableMultiDict.copy "werkzeug.datastructures.ImmutableMultiDict.copy") function is a no-op for this class like for any other python immutable type (eg: [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)")). `class werkzeug.datastructures.ImmutableOrderedMultiDict(mapping=None)` An immutable [`OrderedMultiDict`](#werkzeug.datastructures.OrderedMultiDict "werkzeug.datastructures.OrderedMultiDict"). Changelog New in version 0.6. `copy()` Return a shallow mutable copy of this object. Keep in mind that the standard library’s [`copy()`](#werkzeug.datastructures.ImmutableOrderedMultiDict.copy "werkzeug.datastructures.ImmutableOrderedMultiDict.copy") function is a no-op for this class like for any other python immutable type (eg: [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)")). `class werkzeug.datastructures.CombinedMultiDict(dicts=None)` A read only [`MultiDict`](#werkzeug.datastructures.MultiDict "werkzeug.datastructures.MultiDict") that you can pass multiple [`MultiDict`](#werkzeug.datastructures.MultiDict "werkzeug.datastructures.MultiDict") instances as sequence and it will combine the return values of all wrapped dicts: ``` >>> from werkzeug.datastructures import CombinedMultiDict, MultiDict >>> post = MultiDict([('foo', 'bar')]) >>> get = MultiDict([('blub', 'blah')]) >>> combined = CombinedMultiDict([get, post]) >>> combined['foo'] 'bar' >>> combined['blub'] 'blah' ``` This works for all read operations and will raise a `TypeError` for methods that usually change data which isn’t possible. From Werkzeug 0.3 onwards, the `KeyError` raised by this class is also a subclass of the `BadRequest` HTTP exception and will render a page for a `400 BAD REQUEST` if caught in a catch-all for HTTP exceptions. `class werkzeug.datastructures.ImmutableDict` An immutable [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.10)"). Changelog New in version 0.5. `copy()` Return a shallow mutable copy of this object. Keep in mind that the standard library’s [`copy()`](#werkzeug.datastructures.ImmutableDict.copy "werkzeug.datastructures.ImmutableDict.copy") function is a no-op for this class like for any other python immutable type (eg: [`tuple`](https://docs.python.org/3/library/stdtypes.html#tuple "(in Python v3.10)")). `class werkzeug.datastructures.ImmutableList(iterable=(), /)` An immutable [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)"). Changelog New in version 0.5. Private: `class werkzeug.datastructures.FileMultiDict(mapping=None)` A special [`MultiDict`](#werkzeug.datastructures.MultiDict "werkzeug.datastructures.MultiDict") that has convenience methods to add files to it. This is used for `EnvironBuilder` and generally useful for unittesting. Changelog New in version 0.5. `add_file(name, file, filename=None, content_type=None)` Adds a new file to the dict. `file` can be a file name or a `file`-like or a [`FileStorage`](#werkzeug.datastructures.FileStorage "werkzeug.datastructures.FileStorage") object. Parameters: * **name** – the name of the field. * **file** – a filename or `file`-like object * **filename** – an optional filename * **content\_type** – an optional content type HTTP Related ------------ `class werkzeug.datastructures.Headers([defaults])` An object that stores some headers. It has a dict-like interface, but is ordered, can store the same key multiple times, and iterating yields `(key, value)` pairs instead of only keys. This data structure is useful if you want a nicer way to handle WSGI headers which are stored as tuples in a list. From Werkzeug 0.3 onwards, the [`KeyError`](https://docs.python.org/3/library/exceptions.html#KeyError "(in Python v3.10)") raised by this class is also a subclass of the `BadRequest` HTTP exception and will render a page for a `400 BAD REQUEST` if caught in a catch-all for HTTP exceptions. Headers is mostly compatible with the Python [`wsgiref.headers.Headers`](https://docs.python.org/3/library/wsgiref.html#wsgiref.headers.Headers "(in Python v3.10)") class, with the exception of `__getitem__`. [`wsgiref`](https://docs.python.org/3/library/wsgiref.html#module-wsgiref "(in Python v3.10)") will return `None` for `headers['missing']`, whereas [`Headers`](#werkzeug.datastructures.Headers "werkzeug.datastructures.Headers") will raise a [`KeyError`](https://docs.python.org/3/library/exceptions.html#KeyError "(in Python v3.10)"). To create a new `Headers` object, pass it a list, dict, or other `Headers` object with default values. These values are validated the same way values added later are. Parameters: **defaults** – The list of default values for the [`Headers`](#werkzeug.datastructures.Headers "werkzeug.datastructures.Headers"). Changelog Changed in version 2.1.0: Default values are validated the same as values added later. Changed in version 0.9: This data structure now stores unicode values similar to how the multi dicts do it. The main difference is that bytes can be set as well which will automatically be latin1 decoded. Changed in version 0.9: The `linked()` function was removed without replacement as it was an API that does not support the changes to the encoding model. `add(_key, _value, **kw)` Add a new header tuple to the list. Keyword arguments can specify additional parameters for the header value, with underscores converted to dashes: ``` >>> d = Headers() >>> d.add('Content-Type', 'text/plain') >>> d.add('Content-Disposition', 'attachment', filename='foo.png') ``` The keyword argument dumping uses `dump_options_header()` behind the scenes. Changelog New in version 0.4.1: keyword arguments were added for [`wsgiref`](https://docs.python.org/3/library/wsgiref.html#module-wsgiref "(in Python v3.10)") compatibility. `add_header(_key, _value, **_kw)` Add a new header tuple to the list. An alias for [`add()`](#werkzeug.datastructures.Headers.add "werkzeug.datastructures.Headers.add") for compatibility with the [`wsgiref`](https://docs.python.org/3/library/wsgiref.html#module-wsgiref "(in Python v3.10)") [`add_header()`](https://docs.python.org/3/library/wsgiref.html#wsgiref.headers.Headers.add_header "(in Python v3.10)") method. `clear()` Clears all headers. `extend(*args, **kwargs)` Extend headers in this object with items from another object containing header items as well as keyword arguments. To replace existing keys instead of extending, use [`update()`](#werkzeug.datastructures.Headers.update "werkzeug.datastructures.Headers.update") instead. If provided, the first argument can be another [`Headers`](#werkzeug.datastructures.Headers "werkzeug.datastructures.Headers") object, a [`MultiDict`](#werkzeug.datastructures.MultiDict "werkzeug.datastructures.MultiDict"), [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.10)"), or iterable of pairs. Changelog Changed in version 1.0: Support [`MultiDict`](#werkzeug.datastructures.MultiDict "werkzeug.datastructures.MultiDict"). Allow passing `kwargs`. `get(key, default=None, type=None, as_bytes=False)` Return the default value if the requested data doesn’t exist. If `type` is provided and is a callable it should convert the value, return it or raise a [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.10)") if that is not possible. In this case the function will return the default as if the value was not found: ``` >>> d = Headers([('Content-Length', '42')]) >>> d.get('Content-Length', type=int) 42 ``` Changelog New in version 0.9: Added support for `as_bytes`. Parameters: * **key** – The key to be looked up. * **default** – The default value to be returned if the key can’t be looked up. If not further specified `None` is returned. * **type** – A callable that is used to cast the value in the [`Headers`](#werkzeug.datastructures.Headers "werkzeug.datastructures.Headers"). If a [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.10)") is raised by this callable the default value is returned. * **as\_bytes** – return bytes instead of strings. `get_all(name)` Return a list of all the values for the named field. This method is compatible with the [`wsgiref`](https://docs.python.org/3/library/wsgiref.html#module-wsgiref "(in Python v3.10)") [`get_all()`](https://docs.python.org/3/library/wsgiref.html#wsgiref.headers.Headers.get_all "(in Python v3.10)") method. `getlist(key, type=None, as_bytes=False)` Return the list of items for a given key. If that key is not in the [`Headers`](#werkzeug.datastructures.Headers "werkzeug.datastructures.Headers"), the return value will be an empty list. Just like [`get()`](#werkzeug.datastructures.Headers.get "werkzeug.datastructures.Headers.get"), [`getlist()`](#werkzeug.datastructures.Headers.getlist "werkzeug.datastructures.Headers.getlist") accepts a `type` parameter. All items will be converted with the callable defined there. Changelog New in version 0.9: Added support for `as_bytes`. Parameters: * **key** – The key to be looked up. * **type** – A callable that is used to cast the value in the [`Headers`](#werkzeug.datastructures.Headers "werkzeug.datastructures.Headers"). If a [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.10)") is raised by this callable the value will be removed from the list. * **as\_bytes** – return bytes instead of strings. Returns: a [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") of all the values for the key. `pop(key=None, default=no value)` Removes and returns a key or index. Parameters: **key** – The key to be popped. If this is an integer the item at that position is removed, if it’s a string the value for that key is. If the key is omitted or `None` the last item is removed. Returns: an item. `popitem()` Removes a key or index and returns a (key, value) item. `remove(key)` Remove a key. Parameters: **key** – The key to be removed. `set(_key, _value, **kw)` Remove all header tuples for `key` and add a new one. The newly added key either appears at the end of the list if there was no entry or replaces the first one. Keyword arguments can specify additional parameters for the header value, with underscores converted to dashes. See [`add()`](#werkzeug.datastructures.Headers.add "werkzeug.datastructures.Headers.add") for more information. Changelog Changed in version 0.6.1: [`set()`](#werkzeug.datastructures.Headers.set "werkzeug.datastructures.Headers.set") now accepts the same arguments as [`add()`](#werkzeug.datastructures.Headers.add "werkzeug.datastructures.Headers.add"). Parameters: * **key** – The key to be inserted. * **value** – The value to be inserted. `setdefault(key, default)` Return the first value for the key if it is in the headers, otherwise set the header to the value given by `default` and return that. Parameters: * **key** – The header key to get. * **default** – The value to set for the key if it is not in the headers. `setlist(key, values)` Remove any existing values for a header and add new ones. Parameters: * **key** – The header key to set. * **values** – An iterable of values to set for the key. Changelog New in version 1.0. `setlistdefault(key, default)` Return the list of values for the key if it is in the headers, otherwise set the header to the list of values given by `default` and return that. Unlike [`MultiDict.setlistdefault()`](#werkzeug.datastructures.MultiDict.setlistdefault "werkzeug.datastructures.MultiDict.setlistdefault"), modifying the returned list will not affect the headers. Parameters: * **key** – The header key to get. * **default** – An iterable of values to set for the key if it is not in the headers. Changelog New in version 1.0. `to_wsgi_list()` Convert the headers into a list suitable for WSGI. Returns: list `update(*args, **kwargs)` Replace headers in this object with items from another headers object and keyword arguments. To extend existing keys instead of replacing, use [`extend()`](#werkzeug.datastructures.Headers.extend "werkzeug.datastructures.Headers.extend") instead. If provided, the first argument can be another [`Headers`](#werkzeug.datastructures.Headers "werkzeug.datastructures.Headers") object, a [`MultiDict`](#werkzeug.datastructures.MultiDict "werkzeug.datastructures.MultiDict"), [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.10)"), or iterable of pairs. Changelog New in version 1.0. `class werkzeug.datastructures.EnvironHeaders(environ)` Read only version of the headers from a WSGI environment. This provides the same interface as `Headers` and is constructed from a WSGI environment. From Werkzeug 0.3 onwards, the `KeyError` raised by this class is also a subclass of the `BadRequest` HTTP exception and will render a page for a `400 BAD REQUEST` if caught in a catch-all for HTTP exceptions. `class werkzeug.datastructures.HeaderSet(headers=None, on_update=None)` Similar to the [`ETags`](#werkzeug.datastructures.ETags "werkzeug.datastructures.ETags") class this implements a set-like structure. Unlike [`ETags`](#werkzeug.datastructures.ETags "werkzeug.datastructures.ETags") this is case insensitive and used for vary, allow, and content-language headers. If not constructed using the `parse_set_header()` function the instantiation works like this: ``` >>> hs = HeaderSet(['foo', 'bar', 'baz']) >>> hs HeaderSet(['foo', 'bar', 'baz']) ``` `add(header)` Add a new header to the set. `as_set(preserve_casing=False)` Return the set as real python set type. When calling this, all the items are converted to lowercase and the ordering is lost. Parameters: **preserve\_casing** – if set to `True` the items in the set returned will have the original case like in the [`HeaderSet`](#werkzeug.datastructures.HeaderSet "werkzeug.datastructures.HeaderSet"), otherwise they will be lowercase. `clear()` Clear the set. `discard(header)` Like [`remove()`](#werkzeug.datastructures.HeaderSet.remove "werkzeug.datastructures.HeaderSet.remove") but ignores errors. Parameters: **header** – the header to be discarded. `find(header)` Return the index of the header in the set or return -1 if not found. Parameters: **header** – the header to be looked up. `index(header)` Return the index of the header in the set or raise an [`IndexError`](https://docs.python.org/3/library/exceptions.html#IndexError "(in Python v3.10)"). Parameters: **header** – the header to be looked up. `remove(header)` Remove a header from the set. This raises an [`KeyError`](https://docs.python.org/3/library/exceptions.html#KeyError "(in Python v3.10)") if the header is not in the set. Changelog Changed in version 0.5: In older versions a [`IndexError`](https://docs.python.org/3/library/exceptions.html#IndexError "(in Python v3.10)") was raised instead of a [`KeyError`](https://docs.python.org/3/library/exceptions.html#KeyError "(in Python v3.10)") if the object was missing. Parameters: **header** – the header to be removed. `to_header()` Convert the header set into an HTTP header string. `update(iterable)` Add all the headers from the iterable to the set. Parameters: **iterable** – updates the set with the items from the iterable. `class werkzeug.datastructures.Accept(values=())` An [`Accept`](#werkzeug.datastructures.Accept "werkzeug.datastructures.Accept") object is just a list subclass for lists of `(value, quality)` tuples. It is automatically sorted by specificity and quality. All [`Accept`](#werkzeug.datastructures.Accept "werkzeug.datastructures.Accept") objects work similar to a list but provide extra functionality for working with the data. Containment checks are normalized to the rules of that header: ``` >>> a = CharsetAccept([('ISO-8859-1', 1), ('utf-8', 0.7)]) >>> a.best 'ISO-8859-1' >>> 'iso-8859-1' in a True >>> 'UTF8' in a True >>> 'utf7' in a False ``` To get the quality for an item you can use normal item lookup: ``` >>> print a['utf-8'] 0.7 >>> a['utf7'] 0 ``` Changelog Changed in version 1.0.0: [`Accept`](#werkzeug.datastructures.Accept "werkzeug.datastructures.Accept") internal values are no longer ordered alphabetically for equal quality tags. Instead the initial order is preserved. Changed in version 0.5: [`Accept`](#werkzeug.datastructures.Accept "werkzeug.datastructures.Accept") objects are forced immutable now. `property best` The best match as value. `best_match(matches, default=None)` Returns the best match from a list of possible matches based on the specificity and quality of the client. If two items have the same quality and specificity, the one is returned that comes first. Parameters: * **matches** – a list of matches to check for * **default** – the value that is returned if none match `find(key)` Get the position of an entry or return -1. Parameters: **key** – The key to be looked up. `index(key)` Get the position of an entry or raise [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.10)"). Parameters: **key** – The key to be looked up. Changelog Changed in version 0.5: This used to raise [`IndexError`](https://docs.python.org/3/library/exceptions.html#IndexError "(in Python v3.10)"), which was inconsistent with the list API. `quality(key)` Returns the quality of the key. Changelog New in version 0.6: In previous versions you had to use the item-lookup syntax (eg: `obj[key]` instead of `obj.quality(key)`) `to_header()` Convert the header set into an HTTP header string. `values()` Iterate over all values. `class werkzeug.datastructures.MIMEAccept(values=())` Like [`Accept`](#werkzeug.datastructures.Accept "werkzeug.datastructures.Accept") but with special methods and behavior for mimetypes. `property accept_html` True if this object accepts HTML. `property accept_json` True if this object accepts JSON. `property accept_xhtml` True if this object accepts XHTML. `class werkzeug.datastructures.CharsetAccept(values=())` Like [`Accept`](#werkzeug.datastructures.Accept "werkzeug.datastructures.Accept") but with normalization for charsets. `class werkzeug.datastructures.LanguageAccept(values=())` Like [`Accept`](#werkzeug.datastructures.Accept "werkzeug.datastructures.Accept") but with normalization for language tags. `class werkzeug.datastructures.RequestCacheControl(values=(), on_update=None)` A cache control for requests. This is immutable and gives access to all the request-relevant cache control headers. To get a header of the [`RequestCacheControl`](#werkzeug.datastructures.RequestCacheControl "werkzeug.datastructures.RequestCacheControl") object again you can convert the object into a string or call the `to_header()` method. If you plan to subclass it and add your own items have a look at the sourcecode for that class. Changelog Changed in version 2.1.0: Setting int properties such as `max_age` will convert the value to an int. New in version 0.5: In previous versions a `CacheControl` class existed that was used both for request and response. `no_cache` accessor for β€˜no-cache’ `no_store` accessor for β€˜no-store’ `max_age` accessor for β€˜max-age’ `no_transform` accessor for β€˜no-transform’ `property max_stale` accessor for β€˜max-stale’ `property min_fresh` accessor for β€˜min-fresh’ `property only_if_cached` accessor for β€˜only-if-cached’ `class werkzeug.datastructures.ResponseCacheControl(values=(), on_update=None)` A cache control for responses. Unlike [`RequestCacheControl`](#werkzeug.datastructures.RequestCacheControl "werkzeug.datastructures.RequestCacheControl") this is mutable and gives access to response-relevant cache control headers. To get a header of the [`ResponseCacheControl`](#werkzeug.datastructures.ResponseCacheControl "werkzeug.datastructures.ResponseCacheControl") object again you can convert the object into a string or call the `to_header()` method. If you plan to subclass it and add your own items have a look at the sourcecode for that class. Changelog Changed in version 2.1.1: `s_maxage` converts the value to an int. Changed in version 2.1.0: Setting int properties such as `max_age` will convert the value to an int. New in version 0.5: In previous versions a `CacheControl` class existed that was used both for request and response. `no_cache` accessor for β€˜no-cache’ `no_store` accessor for β€˜no-store’ `max_age` accessor for β€˜max-age’ `no_transform` accessor for β€˜no-transform’ `property immutable` accessor for β€˜immutable’ `property must_revalidate` accessor for β€˜must-revalidate’ `property private` accessor for β€˜private’ `property proxy_revalidate` accessor for β€˜proxy-revalidate’ `property public` accessor for β€˜public’ `property s_maxage` accessor for β€˜s-maxage’ `class werkzeug.datastructures.ETags(strong_etags=None, weak_etags=None, star_tag=False)` A set that can be used to check if one etag is present in a collection of etags. `as_set(include_weak=False)` Convert the `ETags` object into a python set. Per default all the weak etags are not part of this set. `contains(etag)` Check if an etag is part of the set ignoring weak tags. It is also possible to use the `in` operator. `contains_raw(etag)` When passed a quoted tag it will check if this tag is part of the set. If the tag is weak it is checked against weak and strong tags, otherwise strong only. `contains_weak(etag)` Check if an etag is part of the set including weak and strong tags. `is_strong(etag)` Check if an etag is strong. `is_weak(etag)` Check if an etag is weak. `to_header()` Convert the etags set into a HTTP header string. `class werkzeug.datastructures.Authorization(auth_type, data=None)` Represents an `Authorization` header sent by the client. This is returned by [`parse_authorization_header()`](../http/index#werkzeug.http.parse_authorization_header "werkzeug.http.parse_authorization_header"). It can be useful to create the object manually to pass to the test [`Client`](../test/index#werkzeug.test.Client "werkzeug.test.Client"). Changelog Changed in version 0.5: This object became immutable. `property cnonce` If the server sent a qop-header in the `WWW-Authenticate` header, the client has to provide this value for HTTP digest auth. See the RFC for more details. `property nc` The nonce count value transmitted by clients if a qop-header is also transmitted. HTTP digest auth only. `property nonce` The nonce the server sent for digest auth, sent back by the client. A nonce should be unique for every 401 response for HTTP digest auth. `property opaque` The opaque header from the server returned unchanged by the client. It is recommended that this string be base64 or hexadecimal data. Digest auth only. `property password` When the authentication type is basic this is the password transmitted by the client, else `None`. `property qop` Indicates what β€œquality of protection” the client has applied to the message for HTTP digest auth. Note that this is a single token, not a quoted list of alternatives as in WWW-Authenticate. `property realm` This is the server realm sent back for HTTP digest auth. `property response` A string of 32 hex digits computed as defined in RFC 2617, which proves that the user knows a password. Digest auth only. `to_header()` Convert to a string value for an `Authorization` header. Changelog New in version 2.0: Added to support passing authorization to the test client. `property uri` The URI from Request-URI of the Request-Line; duplicated because proxies are allowed to change the Request-Line in transit. HTTP digest auth only. `property username` The username transmitted. This is set for both basic and digest auth all the time. `class werkzeug.datastructures.WWWAuthenticate(auth_type=None, values=None, on_update=None)` Provides simple access to `WWW-Authenticate` headers. `property algorithm` A string indicating a pair of algorithms used to produce the digest and a checksum. If this is not present it is assumed to be β€œMD5”. If the algorithm is not understood, the challenge should be ignored (and a different one used, if there is more than one). `static auth_property(name, doc=None)` A static helper function for Authentication subclasses to add extra authentication system properties onto a class: ``` class FooAuthenticate(WWWAuthenticate): special_realm = auth_property('special_realm') ``` For more information have a look at the sourcecode to see how the regular properties ([`realm`](#werkzeug.datastructures.WWWAuthenticate.realm "werkzeug.datastructures.WWWAuthenticate.realm") etc.) are implemented. `property domain` A list of URIs that define the protection space. If a URI is an absolute path, it is relative to the canonical root URL of the server being accessed. `property nonce` A server-specified data string which should be uniquely generated each time a 401 response is made. It is recommended that this string be base64 or hexadecimal data. `property opaque` A string of data, specified by the server, which should be returned by the client unchanged in the Authorization header of subsequent requests with URIs in the same protection space. It is recommended that this string be base64 or hexadecimal data. `property qop` A set of quality-of-privacy directives such as auth and auth-int. `property realm` A string to be displayed to users so they know which username and password to use. This string should contain at least the name of the host performing the authentication and might additionally indicate the collection of users who might have access. `set_basic(realm='authentication required')` Clear the auth info and enable basic auth. `set_digest(realm, nonce, qop=('auth',), opaque=None, algorithm=None, stale=False)` Clear the auth info and enable digest auth. `property stale` A flag, indicating that the previous request from the client was rejected because the nonce value was stale. `to_header()` Convert the stored values into a WWW-Authenticate header. `property type` The type of the auth mechanism. HTTP currently specifies `Basic` and `Digest`. `class werkzeug.datastructures.IfRange(etag=None, date=None)` Very simple object that represents the `If-Range` header in parsed form. It will either have neither a etag or date or one of either but never both. Changelog New in version 0.7. `date` The date in parsed format or `None`. `etag` The etag parsed and unquoted. Ranges always operate on strong etags so the weakness information is not necessary. `to_header()` Converts the object back into an HTTP header. `class werkzeug.datastructures.Range(units, ranges)` Represents a `Range` header. All methods only support only bytes as the unit. Stores a list of ranges if given, but the methods only work if only one range is provided. Raises: [**ValueError**](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.10)") – If the ranges provided are invalid. Changelog Changed in version 0.15: The ranges passed in are validated. New in version 0.7. `make_content_range(length)` Creates a [`ContentRange`](#werkzeug.datastructures.ContentRange "werkzeug.datastructures.ContentRange") object from the current range and given content length. `range_for_length(length)` If the range is for bytes, the length is not None and there is exactly one range and it is satisfiable it returns a `(start, stop)` tuple, otherwise `None`. `ranges` A list of `(begin, end)` tuples for the range header provided. The ranges are non-inclusive. `to_content_range_header(length)` Converts the object into `Content-Range` HTTP header, based on given length `to_header()` Converts the object back into an HTTP header. `units` The units of this range. Usually β€œbytes”. `class werkzeug.datastructures.ContentRange(units, start, stop, length=None, on_update=None)` Represents the content range header. Changelog New in version 0.7. `property length` The length of the range or `None`. `set(start, stop, length=None, units='bytes')` Simple method to update the ranges. `property start` The start point of the range or `None`. `property stop` The stop point of the range (non-inclusive) or `None`. Can only be `None` if also start is `None`. `property units` The units to use, usually β€œbytes” `unset()` Sets the units to `None` which indicates that the header should no longer be used. Others ------ `class werkzeug.datastructures.FileStorage(stream=None, filename=None, name=None, content_type=None, content_length=None, headers=None)` The [`FileStorage`](#werkzeug.datastructures.FileStorage "werkzeug.datastructures.FileStorage") class is a thin wrapper over incoming files. It is used by the request object to represent uploaded files. All the attributes of the wrapper stream are proxied by the file storage so it’s possible to do `storage.read()` instead of the long form `storage.stream.read()`. `stream` The input stream for the uploaded file. This usually points to an open temporary file. `filename` The filename of the file on the client. Can be a `str`, or an instance of `os.PathLike`. `name` The name of the form field. `headers` The multipart headers as [`Headers`](#werkzeug.datastructures.Headers "werkzeug.datastructures.Headers") object. This usually contains irrelevant information but in combination with custom multipart requests the raw headers might be interesting. Changelog New in version 0.6. `close()` Close the underlying file if possible. `property content_length` The content-length sent in the header. Usually not available `property content_type` The content-type sent in the header. Usually not available `property mimetype` Like [`content_type`](#werkzeug.datastructures.FileStorage.content_type "werkzeug.datastructures.FileStorage.content_type"), but without parameters (eg, without charset, type etc.) and always lowercase. For example if the content type is `text/HTML; charset=utf-8` the mimetype would be `'text/html'`. Changelog New in version 0.7. `property mimetype_params` The mimetype parameters as dict. For example if the content type is `text/html; charset=utf-8` the params would be `{'charset': 'utf-8'}`. Changelog New in version 0.7. `save(dst, buffer_size=16384)` Save the file to a destination path or file object. If the destination is a file object you have to close it yourself after the call. The buffer size is the number of bytes held in memory during the copy process. It defaults to 16KB. For secure file saving also have a look at `secure_filename()`. Parameters: * **dst** – a filename, [`os.PathLike`](https://docs.python.org/3/library/os.html#os.PathLike "(in Python v3.10)"), or open file object to write to. * **buffer\_size** – Passed as the `length` parameter of [`shutil.copyfileobj()`](https://docs.python.org/3/library/shutil.html#shutil.copyfileobj "(in Python v3.10)"). Changelog Changed in version 1.0: Supports [`pathlib`](https://docs.python.org/3/library/pathlib.html#module-pathlib "(in Python v3.10)").
programming_docs
werkzeug Dealing with Request Data Dealing with Request Data ========================= The most important rule about web development is β€œDo not trust the user”. This is especially true for incoming request data on the input stream. With WSGI this is actually a bit harder than you would expect. Because of that Werkzeug wraps the request stream for you to save you from the most prominent problems with it. Missing EOF Marker on Input Stream ---------------------------------- The input stream has no end-of-file marker. If you would call the `read()` method on the `wsgi.input` stream you would cause your application to hang on conforming servers. This is actually intentional however painful. Werkzeug solves that problem by wrapping the input stream in a special `LimitedStream`. The input stream is exposed on the request objects as `stream`. This one is either an empty stream (if the form data was parsed) or a limited stream with the contents of the input stream. When does Werkzeug Parse? ------------------------- Werkzeug parses the incoming data under the following situations: * you access either `form`, `files`, or `stream` and the request method was `POST` or `PUT`. * if you call `parse_form_data()`. These calls are not interchangeable. If you invoke `parse_form_data()` you must not use the request object or at least not the attributes that trigger the parsing process. This is also true if you read from the `wsgi.input` stream before the parsing. **General rule:** Leave the WSGI input stream alone. Especially in WSGI middlewares. Use either the parsing functions or the request object. Do not mix multiple WSGI utility libraries for form data parsing or anything else that works on the input stream. How does it Parse? ------------------ The standard Werkzeug parsing behavior handles three cases: * input content type was `multipart/form-data`. In this situation the `stream` will be empty and `form` will contain the regular `POST` / `PUT` data, `files` will contain the uploaded files as `FileStorage` objects. * input content type was `application/x-www-form-urlencoded`. Then the `stream` will be empty and `form` will contain the regular `POST` / `PUT` data and `files` will be empty. * the input content type was neither of them, `stream` points to a `LimitedStream` with the input data for further processing. Special note on the `get_data` method: Calling this loads the full request data into memory. This is only safe to do if the `max_content_length` is set. Also you can *either* read the stream *or* call `get_data()`. Limiting Request Data --------------------- To avoid being the victim of a DDOS attack you can set the maximum accepted content length and request field sizes. The `Request` class has two attributes for that: `max_content_length` and `max_form_memory_size`. The first one can be used to limit the total content length. For example by setting it to `1024 * 1024 * 16` the request won’t accept more than 16MB of transmitted data. Because certain data can’t be moved to the hard disk (regular post data) whereas temporary files can, there is a second limit you can set. The `max_form_memory_size` limits the size of `POST` transmitted form data. By setting it to `1024 * 1024 * 2` you can make sure that all in memory-stored fields are not more than 2MB in size. This however does *not* affect in-memory stored files if the `stream_factory` used returns a in-memory file. How to extend Parsing? ---------------------- Modern web applications transmit a lot more than multipart form data or url encoded data. To extend the capabilities, subclass `Request` or `Request` and add or extend methods. werkzeug WSGI Helpers WSGI Helpers ============ The following classes and functions are designed to make working with the WSGI specification easier or operate on the WSGI layer. All the functionality from this module is available on the high-level [Request / Response Objects](../wrappers/index). Iterator / Stream Helpers ------------------------- These classes and functions simplify working with the WSGI application iterator and the input stream. `class werkzeug.wsgi.ClosingIterator(iterable, callbacks=None)` The WSGI specification requires that all middlewares and gateways respect the `close` callback of the iterable returned by the application. Because it is useful to add another close action to a returned iterable and adding a custom iterable is a boring task this class can be used for that: ``` return ClosingIterator(app(environ, start_response), [cleanup_session, cleanup_locals]) ``` If there is just one close function it can be passed instead of the list. A closing iterator is not needed if the application uses response objects and finishes the processing if the response is started: ``` try: return response(environ, start_response) finally: cleanup_session() cleanup_locals() ``` Parameters: * **iterable** ([Iterable](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.10)")*[*[bytes](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.10)")*]*) – * **callbacks** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[*[Callable](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.10)")*[**[**]**,* *None**]**,* [Iterable](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.10)")*[*[Callable](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.10)")*[**[**]**,* *None**]**]**]**]*) – `class werkzeug.wsgi.FileWrapper(file, buffer_size=8192)` This class can be used to convert a `file`-like object into an iterable. It yields `buffer_size` blocks until the file is fully read. You should not use this class directly but rather use the [`wrap_file()`](#werkzeug.wsgi.wrap_file "werkzeug.wsgi.wrap_file") function that uses the WSGI server’s file wrapper support if it’s available. Changelog New in version 0.5. If you’re using this object together with a `Response` you have to use the `direct_passthrough` mode. Parameters: * **file** ([IO](https://docs.python.org/3/library/typing.html#typing.IO "(in Python v3.10)")*[*[bytes](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.10)")*]*) – a `file`-like object with a `read()` method. * **buffer\_size** ([int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")) – number of bytes for one iteration. `class werkzeug.wsgi.LimitedStream(stream, limit)` Wraps a stream so that it doesn’t read more than n bytes. If the stream is exhausted and the caller tries to get more bytes from it [`on_exhausted()`](#werkzeug.wsgi.LimitedStream.on_exhausted "werkzeug.wsgi.LimitedStream.on_exhausted") is called which by default returns an empty string. The return value of that function is forwarded to the reader function. So if it returns an empty string [`read()`](#werkzeug.wsgi.LimitedStream.read "werkzeug.wsgi.LimitedStream.read") will return an empty string as well. The limit however must never be higher than what the stream can output. Otherwise [`readlines()`](#werkzeug.wsgi.LimitedStream.readlines "werkzeug.wsgi.LimitedStream.readlines") will try to read past the limit. Note on WSGI compliance calls to [`readline()`](#werkzeug.wsgi.LimitedStream.readline "werkzeug.wsgi.LimitedStream.readline") and [`readlines()`](#werkzeug.wsgi.LimitedStream.readlines "werkzeug.wsgi.LimitedStream.readlines") are not WSGI compliant because it passes a size argument to the readline methods. Unfortunately the WSGI PEP is not safely implementable without a size argument to [`readline()`](#werkzeug.wsgi.LimitedStream.readline "werkzeug.wsgi.LimitedStream.readline") because there is no EOF marker in the stream. As a result of that the use of [`readline()`](#werkzeug.wsgi.LimitedStream.readline "werkzeug.wsgi.LimitedStream.readline") is discouraged. For the same reason iterating over the [`LimitedStream`](#werkzeug.wsgi.LimitedStream "werkzeug.wsgi.LimitedStream") is not portable. It internally calls [`readline()`](#werkzeug.wsgi.LimitedStream.readline "werkzeug.wsgi.LimitedStream.readline"). We strongly suggest using [`read()`](#werkzeug.wsgi.LimitedStream.read "werkzeug.wsgi.LimitedStream.read") only or using the [`make_line_iter()`](#werkzeug.wsgi.make_line_iter "werkzeug.wsgi.make_line_iter") which safely iterates line-based over a WSGI input stream. Parameters: * **stream** ([IO](https://docs.python.org/3/library/typing.html#typing.IO "(in Python v3.10)")*[*[bytes](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.10)")*]*) – the stream to wrap. * **limit** ([int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")) – the limit for the stream, must not be longer than what the string can provide if the stream does not end with `EOF` (like `wsgi.input`) `exhaust(chunk_size=65536)` Exhaust the stream. This consumes all the data left until the limit is reached. Parameters: **chunk\_size** ([int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")) – the size for a chunk. It will read the chunk until the stream is exhausted and throw away the results. Return type: None `property is_exhausted: bool` If the stream is exhausted this attribute is `True`. `on_disconnect()` What should happen if a disconnect is detected? The return value of this function is returned from read functions in case the client went away. By default a [`ClientDisconnected`](../exceptions/index#werkzeug.exceptions.ClientDisconnected "werkzeug.exceptions.ClientDisconnected") exception is raised. Return type: [bytes](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.10)") `on_exhausted()` This is called when the stream tries to read past the limit. The return value of this function is returned from the reading function. Return type: [bytes](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.10)") `read(size=None)` Read `size` bytes or if size is not provided everything is read. Parameters: **size** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")*]*) – the number of bytes read. Return type: [bytes](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.10)") `readable()` Return whether object was opened for reading. If False, read() will raise OSError. Return type: [bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)") `readline(size=None)` Reads one line from the stream. Parameters: **size** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")*]*) – Return type: [bytes](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.10)") `readlines(size=None)` Reads a file into a list of strings. It calls [`readline()`](#werkzeug.wsgi.LimitedStream.readline "werkzeug.wsgi.LimitedStream.readline") until the file is read to the end. It does support the optional `size` argument if the underlying stream supports it for `readline`. Parameters: **size** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")*]*) – Return type: [List](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.10)")[[bytes](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.10)")] `tell()` Returns the position of the stream. Changelog New in version 0.9. Return type: [int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)") `werkzeug.wsgi.make_line_iter(stream, limit=None, buffer_size=10240, cap_at_buffer=False)` Safely iterates line-based over an input stream. If the input stream is not a [`LimitedStream`](#werkzeug.wsgi.LimitedStream "werkzeug.wsgi.LimitedStream") the `limit` parameter is mandatory. This uses the stream’s `read()` method internally as opposite to the `readline()` method that is unsafe and can only be used in violation of the WSGI specification. The same problem applies to the `__iter__` function of the input stream which calls `readline()` without arguments. If you need line-by-line processing it’s strongly recommended to iterate over the input stream using this helper function. Changelog New in version 0.11.10: added support for the `cap_at_buffer` parameter. New in version 0.9: added support for iterators as input stream. Changed in version 0.8: This function now ensures that the limit was reached. Parameters: * **stream** ([Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[*[Iterable](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.10)")*[*[bytes](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.10)")*]**,* [IO](https://docs.python.org/3/library/typing.html#typing.IO "(in Python v3.10)")*[*[bytes](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.10)")*]**]*) – the stream or iterate to iterate over. * **limit** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")*]*) – the limit in bytes for the stream. (Usually content length. Not necessary if the `stream` is a [`LimitedStream`](#werkzeug.wsgi.LimitedStream "werkzeug.wsgi.LimitedStream"). * **buffer\_size** ([int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")) – The optional buffer size. * **cap\_at\_buffer** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – if this is set chunks are split if they are longer than the buffer size. Internally this is implemented that the buffer size might be exhausted by a factor of two however. Return type: [Iterator](https://docs.python.org/3/library/typing.html#typing.Iterator "(in Python v3.10)")[[bytes](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.10)")] `werkzeug.wsgi.make_chunk_iter(stream, separator, limit=None, buffer_size=10240, cap_at_buffer=False)` Works like [`make_line_iter()`](#werkzeug.wsgi.make_line_iter "werkzeug.wsgi.make_line_iter") but accepts a separator which divides chunks. If you want newline based processing you should use [`make_line_iter()`](#werkzeug.wsgi.make_line_iter "werkzeug.wsgi.make_line_iter") instead as it supports arbitrary newline markers. Changelog New in version 0.11.10: added support for the `cap_at_buffer` parameter. New in version 0.9: added support for iterators as input stream. New in version 0.8. Parameters: * **stream** ([Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[*[Iterable](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.10)")*[*[bytes](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.10)")*]**,* [IO](https://docs.python.org/3/library/typing.html#typing.IO "(in Python v3.10)")*[*[bytes](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.10)")*]**]*) – the stream or iterate to iterate over. * **separator** ([bytes](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.10)")) – the separator that divides chunks. * **limit** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")*]*) – the limit in bytes for the stream. (Usually content length. Not necessary if the `stream` is otherwise already limited). * **buffer\_size** ([int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")) – The optional buffer size. * **cap\_at\_buffer** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – if this is set chunks are split if they are longer than the buffer size. Internally this is implemented that the buffer size might be exhausted by a factor of two however. Return type: [Iterator](https://docs.python.org/3/library/typing.html#typing.Iterator "(in Python v3.10)")[[bytes](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.10)")] `werkzeug.wsgi.wrap_file(environ, file, buffer_size=8192)` Wraps a file. This uses the WSGI server’s file wrapper if available or otherwise the generic [`FileWrapper`](#werkzeug.wsgi.FileWrapper "werkzeug.wsgi.FileWrapper"). Changelog New in version 0.5. If the file wrapper from the WSGI server is used it’s important to not iterate over it from inside the application but to pass it through unchanged. If you want to pass out a file wrapper inside a response object you have to set `Response.direct_passthrough` to `True`. More information about file wrappers are available in [**PEP 333**](https://peps.python.org/pep-0333/). Parameters: * **file** ([IO](https://docs.python.org/3/library/typing.html#typing.IO "(in Python v3.10)")*[*[bytes](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.10)")*]*) – a `file`-like object with a `read()` method. * **buffer\_size** ([int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")) – number of bytes for one iteration. * **environ** (*WSGIEnvironment*) – Return type: [Iterable](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.10)")[[bytes](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.10)")] Environ Helpers --------------- These functions operate on the WSGI environment. They extract useful information or perform common manipulations: `werkzeug.wsgi.get_host(environ, trusted_hosts=None)` Return the host for the given WSGI environment. The `Host` header is preferred, then `SERVER_NAME` if it’s not set. The returned host will only contain the port if it is different than the standard port for the protocol. Optionally, verify that the host is trusted using [`host_is_trusted()`](#werkzeug.wsgi.host_is_trusted "werkzeug.wsgi.host_is_trusted") and raise a [`SecurityError`](../exceptions/index#werkzeug.exceptions.SecurityError "werkzeug.exceptions.SecurityError") if it is not. Parameters: * **environ** (*WSGIEnvironment*) – A WSGI environment dict. * **trusted\_hosts** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Iterable](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]**]*) – A list of trusted host names. Returns: Host, with port if necessary. Raises: [**SecurityError**](../exceptions/index#werkzeug.exceptions.SecurityError "werkzeug.exceptions.SecurityError") – If the host is not trusted. Return type: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") `werkzeug.wsgi.get_content_length(environ)` Returns the content length from the WSGI environment as integer. If it’s not available or chunked transfer encoding is used, `None` is returned. Changelog New in version 0.9. Parameters: **environ** (*WSGIEnvironment*) – the WSGI environ to fetch the content length from. Return type: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")[[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")] `werkzeug.wsgi.get_input_stream(environ, safe_fallback=True)` Returns the input stream from the WSGI environment and wraps it in the most sensible way possible. The stream returned is not the raw WSGI stream in most cases but one that is safe to read from without taking into account the content length. If content length is not set, the stream will be empty for safety reasons. If the WSGI server supports chunked or infinite streams, it should set the `wsgi.input_terminated` value in the WSGI environ to indicate that. Changelog New in version 0.9. Parameters: * **environ** (*WSGIEnvironment*) – the WSGI environ to fetch the stream from. * **safe\_fallback** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – use an empty stream as a safe fallback when the content length is not set. Disabling this allows infinite streams, which can be a denial-of-service risk. Return type: [IO](https://docs.python.org/3/library/typing.html#typing.IO "(in Python v3.10)")[[bytes](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.10)")] `werkzeug.wsgi.get_current_url(environ, root_only=False, strip_querystring=False, host_only=False, trusted_hosts=None)` Recreate the URL for a request from the parts in a WSGI environment. The URL is an IRI, not a URI, so it may contain Unicode characters. Use [`iri_to_uri()`](../urls/index#werkzeug.urls.iri_to_uri "werkzeug.urls.iri_to_uri") to convert it to ASCII. Parameters: * **environ** (*WSGIEnvironment*) – The WSGI environment to get the URL parts from. * **root\_only** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – Only build the root path, don’t include the remaining path or query string. * **strip\_querystring** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – Don’t include the query string. * **host\_only** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – Only build the scheme and host. * **trusted\_hosts** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Iterable](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]**]*) – A list of trusted host names to validate the host against. Return type: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") `werkzeug.wsgi.get_query_string(environ)` Returns the `QUERY_STRING` from the WSGI environment. This also takes care of the WSGI decoding dance. The string returned will be restricted to ASCII characters. Parameters: **environ** (*WSGIEnvironment*) – WSGI environment to get the query string from. Return type: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") Deprecated since version 2.2: Will be removed in Werkzeug 2.3. Changelog New in version 0.9. `werkzeug.wsgi.get_script_name(environ, charset='utf-8', errors='replace')` Return the `SCRIPT_NAME` from the WSGI environment and decode it unless `charset` is set to `None`. Parameters: * **environ** (*WSGIEnvironment*) – WSGI environment to get the path from. * **charset** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – The charset for the path, or `None` if no decoding should be performed. * **errors** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – The decoding error handling. Return type: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") Deprecated since version 2.2: Will be removed in Werkzeug 2.3. Changelog New in version 0.9. `werkzeug.wsgi.get_path_info(environ, charset='utf-8', errors='replace')` Return the `PATH_INFO` from the WSGI environment and decode it unless `charset` is `None`. Parameters: * **environ** (*WSGIEnvironment*) – WSGI environment to get the path from. * **charset** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – The charset for the path info, or `None` if no decoding should be performed. * **errors** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – The decoding error handling. Return type: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") Changelog New in version 0.9. `werkzeug.wsgi.pop_path_info(environ, charset='utf-8', errors='replace')` Removes and returns the next segment of `PATH_INFO`, pushing it onto `SCRIPT_NAME`. Returns `None` if there is nothing left on `PATH_INFO`. If the `charset` is set to `None` bytes are returned. If there are empty segments (`'/foo//bar`) these are ignored but properly pushed to the `SCRIPT_NAME`: ``` >>> env = {'SCRIPT_NAME': '/foo', 'PATH_INFO': '/a/b'} >>> pop_path_info(env) 'a' >>> env['SCRIPT_NAME'] '/foo/a' >>> pop_path_info(env) 'b' >>> env['SCRIPT_NAME'] '/foo/a/b' ``` Deprecated since version 2.2: Will be removed in Werkzeug 2.3. Changelog Changed in version 0.9: The path is now decoded and a charset and encoding parameter can be provided. New in version 0.5. Parameters: * **environ** (*WSGIEnvironment*) – the WSGI environment that is modified. * **charset** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – The `encoding` parameter passed to `bytes.decode()`. * **errors** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – The `errors` paramater passed to `bytes.decode()`. Return type: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")] `werkzeug.wsgi.peek_path_info(environ, charset='utf-8', errors='replace')` Returns the next segment on the `PATH_INFO` or `None` if there is none. Works like [`pop_path_info()`](#werkzeug.wsgi.pop_path_info "werkzeug.wsgi.pop_path_info") without modifying the environment: ``` >>> env = {'SCRIPT_NAME': '/foo', 'PATH_INFO': '/a/b'} >>> peek_path_info(env) 'a' >>> peek_path_info(env) 'a' ``` If the `charset` is set to `None` bytes are returned. Deprecated since version 2.2: Will be removed in Werkzeug 2.3. Changelog Changed in version 0.9: The path is now decoded and a charset and encoding parameter can be provided. New in version 0.5. Parameters: * **environ** (*WSGIEnvironment*) – the WSGI environment that is checked. * **charset** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – * **errors** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – Return type: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")] `werkzeug.wsgi.extract_path_info(environ_or_baseurl, path_or_url, charset='utf-8', errors='werkzeug.url_quote', collapse_http_schemes=True)` Extracts the path info from the given URL (or WSGI environment) and path. The path info returned is a string. The URLs might also be IRIs. If the path info could not be determined, `None` is returned. Some examples: ``` >>> extract_path_info('http://example.com/app', '/app/hello') '/hello' >>> extract_path_info('http://example.com/app', ... 'https://example.com/app/hello') '/hello' >>> extract_path_info('http://example.com/app', ... 'https://example.com/app/hello', ... collapse_http_schemes=False) is None True ``` Instead of providing a base URL you can also pass a WSGI environment. Parameters: * **environ\_or\_baseurl** ([Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* *WSGIEnvironment**]*) – a WSGI environment dict, a base URL or base IRI. This is the root of the application. * **path\_or\_url** ([Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* *\_URLTuple**]*) – an absolute path from the server root, a relative path (in which case it’s the path info) or a full URL. * **charset** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – the charset for byte data in URLs * **errors** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – the error handling on decode * **collapse\_http\_schemes** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – if set to `False` the algorithm does not assume that http and https on the same server point to the same resource. Return type: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")] Deprecated since version 2.2: Will be removed in Werkzeug 2.3. Changelog Changed in version 0.15: The `errors` parameter defaults to leaving invalid bytes quoted instead of replacing them. New in version 0.6. `werkzeug.wsgi.host_is_trusted(hostname, trusted_list)` Check if a host matches a list of trusted names. Parameters: * **hostname** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – The name to check. * **trusted\_list** ([Iterable](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – A list of valid names to match. If a name starts with a dot it will match all subdomains. Return type: [bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)") Changelog New in version 0.9. Convenience Helpers ------------------- `werkzeug.wsgi.responder(f)` Marks a function as responder. Decorate a function with it and it will automatically call the return value as WSGI application. Example: ``` @responder def application(environ, start_response): return Response('Hello World!') ``` Parameters: **f** ([Callable](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.10)")*[**[**...**]**,* *WSGIApplication**]*) – Return type: WSGIApplication `werkzeug.testapp.test_app(environ, start_response)` Simple test application that dumps the environment. You can use it to check if Werkzeug is working properly: ``` >>> from werkzeug.serving import run_simple >>> from werkzeug.testapp import test_app >>> run_simple('localhost', 3000, test_app) * Running on http://localhost:3000/ ``` The application displays important information from the WSGI environment, the Python interpreter and the installed libraries. Parameters: * **environ** (*WSGIEnvironment*) – * **start\_response** (*StartResponse*) – Return type: [Iterable](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.10)")[[bytes](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.10)")] Bytes, Strings, and Encodings ----------------------------- The values in HTTP requests come in as bytes representing (or encoded to) ASCII. The WSGI specification ([**PEP 3333**](https://peps.python.org/pep-3333/)) decided to always use the `str` type to represent values. To accomplish this, the raw bytes are decoded using the ISO-8859-1 charset to produce a string. Strings in the WSGI environment are restricted to ISO-8859-1 code points. If a string read from the environment might contain characters outside that charset, it must first be decoded to bytes as ISO-8859-1, then encoded to a string using the proper charset (typically UTF-8). The reverse is done when writing to the environ. This is known as the β€œWSGI encoding dance”. Werkzeug provides functions to deal with this automatically so that you don’t need to be aware of the inner workings. Use the functions on this page as well as [`EnvironHeaders()`](../datastructures/index#werkzeug.datastructures.EnvironHeaders "werkzeug.datastructures.EnvironHeaders") to read data out of the WSGI environment. Applications should avoid manually creating or modifying a WSGI environment unless they take care of the proper encoding or decoding step. All high level interfaces in Werkzeug will apply the encoding and decoding as necessary. Raw Request URI and Path Encoding --------------------------------- The `PATH_INFO` in the environ is the path value after percent-decoding. For example, the raw path `/hello%2fworld` would show up from the WSGI server to Werkzeug as `/hello/world`. This loses the information that the slash was a raw character as opposed to a path separator. The WSGI specification ([**PEP 3333**](https://peps.python.org/pep-3333/)) does not provide a way to get the original value, so it is impossible to route some types of data in the path. The most compatible way to work around this is to send problematic data in the query string instead of the path. However, many WSGI servers add a non-standard environ key with the raw path. To match this behavior, Werkzeug’s test client and development server will add the raw value to both the `REQUEST_URI` and `RAW_URI` keys. If you want to route based on this value, you can use middleware to replace `PATH_INFO` in the environ before it reaches the application. However, keep in mind that these keys are non-standard and not guaranteed to be present.
programming_docs
werkzeug Important Terms Important Terms =============== This page covers important terms used in the documentation and Werkzeug itself. WSGI ---- WSGI a specification for Python web applications Werkzeug follows. It was specified in the [**PEP 3333**](https://peps.python.org/pep-3333/) and is widely supported. Unlike previous solutions it guarantees that web applications, servers and utilities can work together. Response Object --------------- For Werkzeug, a response object is an object that works like a WSGI application but does not do any request processing. Usually you have a view function or controller method that processes the request and assembles a response object. A response object is *not* necessarily the `Response` class or a subclass thereof. For example Pylons/webob provide a very similar response class that can be used as well (`webob.Response`). View Function ------------- Often people speak of MVC (Model, View, Controller) when developing web applications. However, the Django framework coined MTV (Model, Template, View) which basically means the same but reduces the concept to the data model, a function that processes data from the request and the database and renders a template. Werkzeug itself does not tell you how you should develop applications, but the documentation often speaks of view functions that work roughly the same. The idea of a view function is that it’s called with a request object (and optionally some parameters from an URL rule) and returns a response object. werkzeug Utilities Utilities ========= Various utility functions shipped with Werkzeug. General Helpers --------------- `class werkzeug.utils.cached_property(fget, name=None, doc=None)` A `property()` that is only evaluated once. Subsequent access returns the cached value. Setting the property sets the cached value. Deleting the property clears the cached value, accessing it again will evaluate it again. ``` class Example: @cached_property def value(self): # calculate something important here return 42 e = Example() e.value # evaluates e.value # uses cache e.value = 16 # sets cache del e.value # clears cache ``` If the class defines `__slots__`, it must add `_cache_{name}` as a slot. Alternatively, it can add `__dict__`, but that’s usually not desirable. Changelog Changed in version 2.1: Works with `__slots__`. Changed in version 2.0: `del obj.name` clears the cached value. Parameters: * **fget** ([Callable](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.10)")*[**[*[Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")*]**,* *\_T**]*) – * **name** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – * **doc** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – `class werkzeug.utils.environ_property(name, default=None, load_func=None, dump_func=None, read_only=None, doc=None)` Maps request attributes to environment variables. This works not only for the Werkzeug request object, but also any other class with an environ attribute: ``` >>> class Test(object): ... environ = {'key': 'value'} ... test = environ_property('key') >>> var = Test() >>> var.test 'value' ``` If you pass it a second value it’s used as default if the key does not exist, the third one can be a converter that takes a value and converts it. If it raises [`ValueError`](https://docs.python.org/3/library/exceptions.html#ValueError "(in Python v3.10)") or [`TypeError`](https://docs.python.org/3/library/exceptions.html#TypeError "(in Python v3.10)") the default value is used. If no default value is provided `None` is used. Per default the property is read only. You have to explicitly enable it by passing `read_only=False` to the constructor. Parameters: * **name** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – * **default** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[**\_TAccessorValue**]*) – * **load\_func** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Callable](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.10)")*[**[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]**,* *\_TAccessorValue**]**]*) – * **dump\_func** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Callable](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.10)")*[**[**\_TAccessorValue**]**,* [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]**]*) – * **read\_only** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")*]*) – * **doc** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – `class werkzeug.utils.header_property(name, default=None, load_func=None, dump_func=None, read_only=None, doc=None)` Like `environ_property` but for headers. Parameters: * **name** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – * **default** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[**\_TAccessorValue**]*) – * **load\_func** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Callable](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.10)")*[**[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]**,* *\_TAccessorValue**]**]*) – * **dump\_func** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Callable](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.10)")*[**[**\_TAccessorValue**]**,* [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]**]*) – * **read\_only** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")*]*) – * **doc** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – `werkzeug.utils.redirect(location, code=302, Response=None)` Returns a response object (a WSGI application) that, if called, redirects the client to the target location. Supported codes are 301, 302, 303, 305, 307, and 308. 300 is not supported because it’s not a real redirect and 304 because it’s the answer for a request with a request with defined If-Modified-Since headers. Changelog New in version 0.10: The class used for the Response object can now be passed in. New in version 0.6: The location can now be a unicode string that is encoded using the `iri_to_uri()` function. Parameters: * **location** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – the location the response should redirect to. * **code** ([int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")) – the redirect status code. defaults to 302. * **Response** (*class*) – a Response class to use when instantiating a response. The default is [`werkzeug.wrappers.Response`](../wrappers/index#werkzeug.wrappers.Response "werkzeug.wrappers.Response") if unspecified. Return type: [Response](../wrappers/index#werkzeug.wrappers.Response "werkzeug.wrappers.Response") `werkzeug.utils.append_slash_redirect(environ, code=308)` Redirect to the current URL with a slash appended. If the current URL is `/user/42`, the redirect URL will be `42/`. When joined to the current URL during response processing or by the browser, this will produce `/user/42/`. The behavior is undefined if the path ends with a slash already. If called unconditionally on a URL, it may produce a redirect loop. Parameters: * **environ** (*WSGIEnvironment*) – Use the path and query from this WSGI environment to produce the redirect URL. * **code** ([int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")) – the status code for the redirect. Return type: [Response](../wrappers/index#werkzeug.wrappers.Response "werkzeug.wrappers.Response") Changelog Changed in version 2.1: Produce a relative URL that only modifies the last segment. Relevant when the current path has multiple segments. Changed in version 2.1: The default status code is 308 instead of 301. This preserves the request method and body. `werkzeug.utils.send_file(path_or_file, environ, mimetype=None, as_attachment=False, download_name=None, conditional=True, etag=True, last_modified=None, max_age=None, use_x_sendfile=False, response_class=None, _root_path=None)` Send the contents of a file to the client. The first argument can be a file path or a file-like object. Paths are preferred in most cases because Werkzeug can manage the file and get extra information from the path. Passing a file-like object requires that the file is opened in binary mode, and is mostly useful when building a file in memory with [`io.BytesIO`](https://docs.python.org/3/library/io.html#io.BytesIO "(in Python v3.10)"). Never pass file paths provided by a user. The path is assumed to be trusted, so a user could craft a path to access a file you didn’t intend. If the WSGI server sets a `file_wrapper` in `environ`, it is used, otherwise Werkzeug’s built-in wrapper is used. Alternatively, if the HTTP server supports `X-Sendfile`, `use_x_sendfile=True` will tell the server to send the given path, which is much more efficient than reading it in Python. Parameters: * **path\_or\_file** ([Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[*[PathLike](https://docs.python.org/3/library/os.html#os.PathLike "(in Python v3.10)")*,* [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [IO](https://docs.python.org/3/library/typing.html#typing.IO "(in Python v3.10)")*[*[bytes](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.10)")*]**]*) – The path to the file to send, relative to the current working directory if a relative path is given. Alternatively, a file-like object opened in binary mode. Make sure the file pointer is seeked to the start of the data. * **environ** (*WSGIEnvironment*) – The WSGI environ for the current request. * **mimetype** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – The MIME type to send for the file. If not provided, it will try to detect it from the file name. * **as\_attachment** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – Indicate to a browser that it should offer to save the file instead of displaying it. * **download\_name** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – The default name browsers will use when saving the file. Defaults to the passed file name. * **conditional** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – Enable conditional and range responses based on request headers. Requires passing a file path and `environ`. * **etag** ([Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[*[bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")*,* [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – Calculate an ETag for the file, which requires passing a file path. Can also be a string to use instead. * **last\_modified** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[*[datetime](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.10)")*,* [int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")*,* [float](https://docs.python.org/3/library/functions.html#float "(in Python v3.10)")*]**]*) – The last modified time to send for the file, in seconds. If not provided, it will try to detect it from the file path. * **max\_age** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[*[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")*,* [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.10)")*[**[*[Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]**]**,* [Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")*]**]**]**]*) – How long the client should cache the file, in seconds. If set, `Cache-Control` will be `public`, otherwise it will be `no-cache` to prefer conditional caching. * **use\_x\_sendfile** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – Set the `X-Sendfile` header to let the server to efficiently send the file. Requires support from the HTTP server. Requires passing a file path. * **response\_class** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Type](https://docs.python.org/3/library/typing.html#typing.Type "(in Python v3.10)")*[*[Response](../wrappers/index#werkzeug.wrappers.Response "werkzeug.wrappers.Response")*]**]*) – Build the response using this class. Defaults to [`Response`](../wrappers/index#werkzeug.wrappers.Response "werkzeug.wrappers.Response"). * **\_root\_path** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[*[PathLike](https://docs.python.org/3/library/os.html#os.PathLike "(in Python v3.10)")*,* [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]**]*) – Do not use. For internal use only. Use `send_from_directory()` to safely send files under a path. Return type: [Response](../wrappers/index#werkzeug.wrappers.Response "werkzeug.wrappers.Response") Changelog Changed in version 2.0.2: `send_file` only sets a detected `Content-Encoding` if `as_attachment` is disabled. New in version 2.0: Adapted from Flask’s implementation. Changed in version 2.0: `download_name` replaces Flask’s `attachment_filename` parameter. If `as_attachment=False`, it is passed with `Content-Disposition: inline` instead. Changed in version 2.0: `max_age` replaces Flask’s `cache_timeout` parameter. `conditional` is enabled and `max_age` is not set by default. Changed in version 2.0: `etag` replaces Flask’s `add_etags` parameter. It can be a string to use instead of generating one. Changed in version 2.0: If an encoding is returned when guessing `mimetype` from `download_name`, set the `Content-Encoding` header. `werkzeug.utils.import_string(import_name, silent=False)` Imports an object based on a string. This is useful if you want to use import paths as endpoints or something similar. An import path can be specified either in dotted notation (`xml.sax.saxutils.escape`) or with a colon as object delimiter (`xml.sax.saxutils:escape`). If `silent` is True the return value will be `None` if the import fails. Parameters: * **import\_name** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – the dotted name for the object to import. * **silent** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – if set to `True` import errors are ignored and `None` is returned instead. Returns: imported object Return type: [Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)") `werkzeug.utils.find_modules(import_path, include_packages=False, recursive=False)` Finds all the modules below a package. This can be useful to automatically import all views / controllers so that their metaclasses / function decorators have a chance to register themselves on the application. Packages are not returned unless `include_packages` is `True`. This can also recursively list modules but in that case it will import all the packages to get the correct load path of that module. Parameters: * **import\_path** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – the dotted name for the package to find child modules. * **include\_packages** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – set to `True` if packages should be returned, too. * **recursive** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – set to `True` if recursion should happen. Returns: generator Return type: [Iterator](https://docs.python.org/3/library/typing.html#typing.Iterator "(in Python v3.10)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")] `werkzeug.utils.secure_filename(filename)` Pass it a filename and it will return a secure version of it. This filename can then safely be stored on a regular file system and passed to [`os.path.join()`](https://docs.python.org/3/library/os.path.html#os.path.join "(in Python v3.10)"). The filename returned is an ASCII only string for maximum portability. On windows systems the function also makes sure that the file is not named after one of the special device files. ``` >>> secure_filename("My cool movie.mov") 'My_cool_movie.mov' >>> secure_filename("../../../etc/passwd") 'etc_passwd' >>> secure_filename('i contain cool \xfcml\xe4uts.txt') 'i_contain_cool_umlauts.txt' ``` The function might return an empty filename. It’s your responsibility to ensure that the filename is unique and that you abort or generate a random filename if the function returned an empty one. Changelog New in version 0.5. Parameters: **filename** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – the filename to secure Return type: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") URL Helpers ----------- Please refer to [URL Helpers](../urls/index). User Agent API -------------- `class werkzeug.user_agent.UserAgent(string)` Represents a parsed user agent header value. The default implementation does no parsing, only the [`string`](#werkzeug.user_agent.UserAgent.string "werkzeug.user_agent.UserAgent.string") attribute is set. A subclass may parse the string to set the common attributes or expose other information. Set [`werkzeug.wrappers.Request.user_agent_class`](../wrappers/index#werkzeug.wrappers.Request.user_agent_class "werkzeug.wrappers.Request.user_agent_class") to use a subclass. Parameters: **string** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – The header value to parse. Changelog New in version 2.0: This replaces the previous `useragents` module, but does not provide a built-in parser. `platform: Optional[str] = None` The OS name, if it could be parsed from the string. `browser: Optional[str] = None` The browser name, if it could be parsed from the string. `version: Optional[str] = None` The browser version, if it could be parsed from the string. `language: Optional[str] = None` The browser language, if it could be parsed from the string. `string: str` The original header value. `to_header()` Convert to a header value. Return type: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") Security Helpers ---------------- `werkzeug.security.generate_password_hash(password, method='pbkdf2:sha256', salt_length=16)` Hash a password with the given method and salt with a string of the given length. The format of the string returned includes the method that was used so that [`check_password_hash()`](#werkzeug.security.check_password_hash "werkzeug.security.check_password_hash") can check the hash. The format for the hashed string looks like this: ``` method$salt$hash ``` This method can **not** generate unsalted passwords but it is possible to set param method=’plain’ in order to enforce plaintext passwords. If a salt is used, hmac is used internally to salt the password. If PBKDF2 is wanted it can be enabled by setting the method to `pbkdf2:method:iterations` where iterations is optional: ``` pbkdf2:sha256:80000$salt$hash pbkdf2:sha256$salt$hash ``` Parameters: * **password** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – the password to hash. * **method** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – the hash method to use (one that hashlib supports). Can optionally be in the format `pbkdf2:method:iterations` to enable PBKDF2. * **salt\_length** ([int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")) – the length of the salt in letters. Return type: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") `werkzeug.security.check_password_hash(pwhash, password)` Check a password against a given salted and hashed password value. In order to support unsalted legacy passwords this method supports plain text passwords, md5 and sha1 hashes (both salted and unsalted). Returns `True` if the password matched, `False` otherwise. Parameters: * **pwhash** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – a hashed string like returned by [`generate_password_hash()`](#werkzeug.security.generate_password_hash "werkzeug.security.generate_password_hash"). * **password** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – the plaintext password to compare against the hash. Return type: [bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)") `werkzeug.security.safe_join(directory, *pathnames)` Safely join zero or more untrusted path components to a base directory to avoid escaping the base directory. Parameters: * **directory** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – The trusted base directory. * **pathnames** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – The untrusted path components relative to the base directory. Returns: A safe path, otherwise `None`. Return type: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")] Logging ------- Werkzeug uses standard Python [`logging`](https://docs.python.org/3/library/logging.html#module-logging "(in Python v3.10)"). The logger is named `"werkzeug"`. ``` import logging logger = logging.getLogger("werkzeug") ``` If the logger level is not set, it will be set to `INFO` on first use. If there is no handler for that level, a [`StreamHandler`](https://docs.python.org/3/library/logging.handlers.html#logging.StreamHandler "(in Python v3.10)") is added.
programming_docs
werkzeug Installation Installation ============ Python Version -------------- We recommend using the latest version of Python. Werkzeug supports Python 3.7 and newer. Dependencies ------------ Werkzeug does not have any direct dependencies. ### Optional dependencies These distributions will not be installed automatically. Werkzeug will detect and use them if you install them. * [Colorama](https://pypi.org/project/colorama/) provides request log highlighting when using the development server on Windows. This works automatically on other systems. * [Watchdog](https://pypi.org/project/watchdog/) provides a faster, more efficient reloader for the development server. ### greenlet You may choose to use gevent or eventlet with your application. In this case, greenlet>=1.0 is required. When using PyPy, PyPy>=7.3.7 is required. These are not minimum supported versions, they only indicate the first versions that added necessary features. You should use the latest versions of each. Virtual environments -------------------- Use a virtual environment to manage the dependencies for your project, both in development and in production. What problem does a virtual environment solve? The more Python projects you have, the more likely it is that you need to work with different versions of Python libraries, or even Python itself. Newer versions of libraries for one project can break compatibility in another project. Virtual environments are independent groups of Python libraries, one for each project. Packages installed for one project will not affect other projects or the operating system’s packages. Python comes bundled with the [`venv`](https://docs.python.org/3/library/venv.html#module-venv "(in Python v3.10)") module to create virtual environments. ### Create an environment Create a project folder and a `venv` folder within: ``` mkdir myproject cd myproject python3 -m venv venv ``` On Windows: ``` py -3 -m venv venv ``` ### Activate the environment Before you work on your project, activate the corresponding environment: ``` . venv/bin/activate ``` On Windows: ``` venv\Scripts\activate ``` Your shell prompt will change to show the name of the activated environment. Install Werkzeug ---------------- Within the activated environment, use the following command to install Werkzeug: ``` pip install Werkzeug ``` werkzeug HTTP Exceptions HTTP Exceptions =============== Implements a number of Python exceptions which can be raised from within a view to trigger a standard HTTP non-200 response. Usage Example ------------- ``` from werkzeug.wrappers.request import Request from werkzeug.exceptions import HTTPException, NotFound def view(request): raise NotFound() @Request.application def application(request): try: return view(request) except HTTPException as e: return e ``` As you can see from this example those exceptions are callable WSGI applications. However, they are not Werkzeug response objects. You can get a response object by calling `get_response()` on a HTTP exception. Keep in mind that you may have to pass an environ (WSGI) or scope (ASGI) to `get_response()` because some errors fetch additional information relating to the request. If you want to hook in a different exception page to say, a 404 status code, you can add a second except for a specific subclass of an error: ``` @Request.application def application(request): try: return view(request) except NotFound as e: return not_found(request) except HTTPException as e: return e ``` Error Classes ------------- The following error classes exist in Werkzeug: `exception werkzeug.exceptions.BadRequest(description=None, response=None)` *400* `Bad Request` Raise if the browser sends something to the application the application or server cannot handle. Parameters: * **description** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – * **response** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Response](../wrappers/index#werkzeug.wrappers.Response "werkzeug.wrappers.Response")*]*) – Return type: None `exception werkzeug.exceptions.Unauthorized(description=None, response=None, www_authenticate=None)` *401* `Unauthorized` Raise if the user is not authorized to access a resource. The `www_authenticate` argument should be used to set the `WWW-Authenticate` header. This is used for HTTP basic auth and other schemes. Use [`WWWAuthenticate`](../datastructures/index#werkzeug.datastructures.WWWAuthenticate "werkzeug.datastructures.WWWAuthenticate") to create correctly formatted values. Strictly speaking a 401 response is invalid if it doesn’t provide at least one value for this header, although real clients typically don’t care. Parameters: * **description** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – Override the default message used for the body of the response. * **www-authenticate** – A single value, or list of values, for the WWW-Authenticate header(s). * **response** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Response](../wrappers/index#werkzeug.wrappers.Response "werkzeug.wrappers.Response")*]*) – * **www\_authenticate** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[*[WWWAuthenticate](../datastructures/index#werkzeug.datastructures.WWWAuthenticate "werkzeug.datastructures.WWWAuthenticate")*,* [Iterable](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.10)")*[*[WWWAuthenticate](../datastructures/index#werkzeug.datastructures.WWWAuthenticate "werkzeug.datastructures.WWWAuthenticate")*]**]**]*) – Return type: None Changelog Changed in version 2.0: Serialize multiple `www_authenticate` items into multiple `WWW-Authenticate` headers, rather than joining them into a single value, for better interoperability. Changed in version 0.15.3: If the `www_authenticate` argument is not set, the `WWW-Authenticate` header is not set. Changed in version 0.15.3: The `response` argument was restored. Changed in version 0.15.1: `description` was moved back as the first argument, restoring its previous position. Changed in version 0.15.0: `www_authenticate` was added as the first argument, ahead of `description`. `exception werkzeug.exceptions.Forbidden(description=None, response=None)` *403* `Forbidden` Raise if the user doesn’t have the permission for the requested resource but was authenticated. Parameters: * **description** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – * **response** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Response](../wrappers/index#werkzeug.wrappers.Response "werkzeug.wrappers.Response")*]*) – Return type: None `exception werkzeug.exceptions.NotFound(description=None, response=None)` *404* `Not Found` Raise if a resource does not exist and never existed. Parameters: * **description** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – * **response** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Response](../wrappers/index#werkzeug.wrappers.Response "werkzeug.wrappers.Response")*]*) – Return type: None `exception werkzeug.exceptions.MethodNotAllowed(valid_methods=None, description=None, response=None)` *405* `Method Not Allowed` Raise if the server used a method the resource does not handle. For example `POST` if the resource is view only. Especially useful for REST. The first argument for this exception should be a list of allowed methods. Strictly speaking the response would be invalid if you don’t provide valid methods in the header which you can do with that list. Takes an optional list of valid http methods starting with werkzeug 0.3 the list will be mandatory. Parameters: * **valid\_methods** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Iterable](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]**]*) – * **description** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – * **response** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Response](../wrappers/index#werkzeug.wrappers.Response "werkzeug.wrappers.Response")*]*) – Return type: None `exception werkzeug.exceptions.NotAcceptable(description=None, response=None)` *406* `Not Acceptable` Raise if the server can’t return any content conforming to the `Accept` headers of the client. Parameters: * **description** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – * **response** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Response](../wrappers/index#werkzeug.wrappers.Response "werkzeug.wrappers.Response")*]*) – Return type: None `exception werkzeug.exceptions.RequestTimeout(description=None, response=None)` *408* `Request Timeout` Raise to signalize a timeout. Parameters: * **description** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – * **response** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Response](../wrappers/index#werkzeug.wrappers.Response "werkzeug.wrappers.Response")*]*) – Return type: None `exception werkzeug.exceptions.Conflict(description=None, response=None)` *409* `Conflict` Raise to signal that a request cannot be completed because it conflicts with the current state on the server. Changelog New in version 0.7. Parameters: * **description** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – * **response** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Response](../wrappers/index#werkzeug.wrappers.Response "werkzeug.wrappers.Response")*]*) – Return type: None `exception werkzeug.exceptions.Gone(description=None, response=None)` *410* `Gone` Raise if a resource existed previously and went away without new location. Parameters: * **description** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – * **response** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Response](../wrappers/index#werkzeug.wrappers.Response "werkzeug.wrappers.Response")*]*) – Return type: None `exception werkzeug.exceptions.LengthRequired(description=None, response=None)` *411* `Length Required` Raise if the browser submitted data but no `Content-Length` header which is required for the kind of processing the server does. Parameters: * **description** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – * **response** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Response](../wrappers/index#werkzeug.wrappers.Response "werkzeug.wrappers.Response")*]*) – Return type: None `exception werkzeug.exceptions.PreconditionFailed(description=None, response=None)` *412* `Precondition Failed` Status code used in combination with `If-Match`, `If-None-Match`, or `If-Unmodified-Since`. Parameters: * **description** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – * **response** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Response](../wrappers/index#werkzeug.wrappers.Response "werkzeug.wrappers.Response")*]*) – Return type: None `exception werkzeug.exceptions.RequestEntityTooLarge(description=None, response=None)` *413* `Request Entity Too Large` The status code one should return if the data submitted exceeded a given limit. Parameters: * **description** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – * **response** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Response](../wrappers/index#werkzeug.wrappers.Response "werkzeug.wrappers.Response")*]*) – Return type: None `exception werkzeug.exceptions.RequestURITooLarge(description=None, response=None)` *414* `Request URI Too Large` Like *413* but for too long URLs. Parameters: * **description** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – * **response** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Response](../wrappers/index#werkzeug.wrappers.Response "werkzeug.wrappers.Response")*]*) – Return type: None `exception werkzeug.exceptions.UnsupportedMediaType(description=None, response=None)` *415* `Unsupported Media Type` The status code returned if the server is unable to handle the media type the client transmitted. Parameters: * **description** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – * **response** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Response](../wrappers/index#werkzeug.wrappers.Response "werkzeug.wrappers.Response")*]*) – Return type: None `exception werkzeug.exceptions.RequestedRangeNotSatisfiable(length=None, units='bytes', description=None, response=None)` *416* `Requested Range Not Satisfiable` The client asked for an invalid part of the file. Changelog New in version 0.7. Takes an optional `Content-Range` header value based on `length` parameter. Parameters: * **length** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")*]*) – * **units** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – * **description** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – * **response** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Response](../wrappers/index#werkzeug.wrappers.Response "werkzeug.wrappers.Response")*]*) – Return type: None `exception werkzeug.exceptions.ExpectationFailed(description=None, response=None)` *417* `Expectation Failed` The server cannot meet the requirements of the Expect request-header. Changelog New in version 0.7. Parameters: * **description** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – * **response** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Response](../wrappers/index#werkzeug.wrappers.Response "werkzeug.wrappers.Response")*]*) – Return type: None `exception werkzeug.exceptions.ImATeapot(description=None, response=None)` *418* `I’m a teapot` The server should return this if it is a teapot and someone attempted to brew coffee with it. Changelog New in version 0.7. Parameters: * **description** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – * **response** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Response](../wrappers/index#werkzeug.wrappers.Response "werkzeug.wrappers.Response")*]*) – Return type: None `exception werkzeug.exceptions.UnprocessableEntity(description=None, response=None)` *422* `Unprocessable Entity` Used if the request is well formed, but the instructions are otherwise incorrect. Parameters: * **description** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – * **response** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Response](../wrappers/index#werkzeug.wrappers.Response "werkzeug.wrappers.Response")*]*) – Return type: None `exception werkzeug.exceptions.Locked(description=None, response=None)` *423* `Locked` Used if the resource that is being accessed is locked. Parameters: * **description** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – * **response** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Response](../wrappers/index#werkzeug.wrappers.Response "werkzeug.wrappers.Response")*]*) – Return type: None `exception werkzeug.exceptions.FailedDependency(description=None, response=None)` *424* `Failed Dependency` Used if the method could not be performed on the resource because the requested action depended on another action and that action failed. Parameters: * **description** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – * **response** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Response](../wrappers/index#werkzeug.wrappers.Response "werkzeug.wrappers.Response")*]*) – Return type: None `exception werkzeug.exceptions.PreconditionRequired(description=None, response=None)` *428* `Precondition Required` The server requires this request to be conditional, typically to prevent the lost update problem, which is a race condition between two or more clients attempting to update a resource through PUT or DELETE. By requiring each client to include a conditional header (β€œIf-Match” or β€œIf-Unmodified- Since”) with the proper value retained from a recent GET request, the server ensures that each client has at least seen the previous revision of the resource. Parameters: * **description** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – * **response** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Response](../wrappers/index#werkzeug.wrappers.Response "werkzeug.wrappers.Response")*]*) – Return type: None `exception werkzeug.exceptions.TooManyRequests(description=None, response=None, retry_after=None)` *429* `Too Many Requests` The server is limiting the rate at which this user receives responses, and this request exceeds that rate. (The server may use any convenient method to identify users and their request rates). The server may include a β€œRetry-After” header to indicate how long the user should wait before retrying. Parameters: * **retry\_after** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[*[datetime](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.10)")*,* [int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")*]**]*) – If given, set the `Retry-After` header to this value. May be an [`int`](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)") number of seconds or a [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.10)"). * **description** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – * **response** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Response](../wrappers/index#werkzeug.wrappers.Response "werkzeug.wrappers.Response")*]*) – Return type: None Changelog Changed in version 1.0: Added `retry_after` parameter. `exception werkzeug.exceptions.RequestHeaderFieldsTooLarge(description=None, response=None)` *431* `Request Header Fields Too Large` The server refuses to process the request because the header fields are too large. One or more individual fields may be too large, or the set of all headers is too large. Parameters: * **description** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – * **response** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Response](../wrappers/index#werkzeug.wrappers.Response "werkzeug.wrappers.Response")*]*) – Return type: None `exception werkzeug.exceptions.UnavailableForLegalReasons(description=None, response=None)` *451* `Unavailable For Legal Reasons` This status code indicates that the server is denying access to the resource as a consequence of a legal demand. Parameters: * **description** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – * **response** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Response](../wrappers/index#werkzeug.wrappers.Response "werkzeug.wrappers.Response")*]*) – Return type: None `exception werkzeug.exceptions.InternalServerError(description=None, response=None, original_exception=None)` *500* `Internal Server Error` Raise if an internal server error occurred. This is a good fallback if an unknown error occurred in the dispatcher. Changelog Changed in version 1.0.0: Added the [`original_exception`](#werkzeug.exceptions.InternalServerError.original_exception "werkzeug.exceptions.InternalServerError.original_exception") attribute. Parameters: * **description** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – * **response** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Response](../wrappers/index#werkzeug.wrappers.Response "werkzeug.wrappers.Response")*]*) – * **original\_exception** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[BaseException](https://docs.python.org/3/library/exceptions.html#BaseException "(in Python v3.10)")*]*) – Return type: None `original_exception` The original exception that caused this 500 error. Can be used by frameworks to provide context when handling unexpected errors. `exception werkzeug.exceptions.NotImplemented(description=None, response=None)` *501* `Not Implemented` Raise if the application does not support the action requested by the browser. Parameters: * **description** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – * **response** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Response](../wrappers/index#werkzeug.wrappers.Response "werkzeug.wrappers.Response")*]*) – Return type: None `exception werkzeug.exceptions.BadGateway(description=None, response=None)` *502* `Bad Gateway` If you do proxying in your application you should return this status code if you received an invalid response from the upstream server it accessed in attempting to fulfill the request. Parameters: * **description** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – * **response** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Response](../wrappers/index#werkzeug.wrappers.Response "werkzeug.wrappers.Response")*]*) – Return type: None `exception werkzeug.exceptions.ServiceUnavailable(description=None, response=None, retry_after=None)` *503* `Service Unavailable` Status code you should return if a service is temporarily unavailable. Parameters: * **retry\_after** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[*[datetime](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.10)")*,* [int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")*]**]*) – If given, set the `Retry-After` header to this value. May be an [`int`](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)") number of seconds or a [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.10)"). * **description** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – * **response** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Response](../wrappers/index#werkzeug.wrappers.Response "werkzeug.wrappers.Response")*]*) – Return type: None Changelog Changed in version 1.0: Added `retry_after` parameter. `exception werkzeug.exceptions.GatewayTimeout(description=None, response=None)` *504* `Gateway Timeout` Status code you should return if a connection to an upstream server times out. Parameters: * **description** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – * **response** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Response](../wrappers/index#werkzeug.wrappers.Response "werkzeug.wrappers.Response")*]*) – Return type: None `exception werkzeug.exceptions.HTTPVersionNotSupported(description=None, response=None)` *505* `HTTP Version Not Supported` The server does not support the HTTP protocol version used in the request. Parameters: * **description** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – * **response** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Response](../wrappers/index#werkzeug.wrappers.Response "werkzeug.wrappers.Response")*]*) – Return type: None `exception werkzeug.exceptions.ClientDisconnected(description=None, response=None)` Internal exception that is raised if Werkzeug detects a disconnected client. Since the client is already gone at that point attempting to send the error message to the client might not work and might ultimately result in another exception in the server. Mainly this is here so that it is silenced by default as far as Werkzeug is concerned. Since disconnections cannot be reliably detected and are unspecified by WSGI to a large extent this might or might not be raised if a client is gone. Changelog New in version 0.8. Parameters: * **description** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – * **response** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Response](../wrappers/index#werkzeug.wrappers.Response "werkzeug.wrappers.Response")*]*) – Return type: None `exception werkzeug.exceptions.SecurityError(description=None, response=None)` Raised if something triggers a security error. This is otherwise exactly like a bad request error. Changelog New in version 0.9. Parameters: * **description** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – * **response** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Response](../wrappers/index#werkzeug.wrappers.Response "werkzeug.wrappers.Response")*]*) – Return type: None Baseclass --------- All the exceptions implement this common interface: `exception werkzeug.exceptions.HTTPException(description=None, response=None)` The base class for all HTTP exceptions. This exception can be called as a WSGI application to render a default error page or you can catch the subclasses of it independently and render nicer error messages. Changelog Changed in version 2.1: Removed the `wrap` class method. Parameters: * **description** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – * **response** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Response](../wrappers/index#werkzeug.wrappers.Response "werkzeug.wrappers.Response")*]*) – Return type: None `__call__(environ, start_response)` Call the exception as WSGI application. Parameters: * **environ** (*WSGIEnvironment*) – the WSGI environment. * **start\_response** (*StartResponse*) – the response callable provided by the WSGI server. Return type: [Iterable](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.10)")[[bytes](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.10)")] `get_response(environ=None, scope=None)` Get a response object. If one was passed to the exception it’s returned directly. Parameters: * **environ** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[**WSGIEnvironment**,* *WSGIRequest**]**]*) – the optional environ for the request. This can be used to modify the response depending on how the request looked like. * **scope** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.10)")*]*) – Returns: a `Response` object or a subclass thereof. Return type: [Response](../wrappers/index#werkzeug.wrappers.Response "werkzeug.wrappers.Response") Special HTTP Exceptions ----------------------- Starting with Werkzeug 0.3 some of the builtin classes raise exceptions that look like regular python exceptions (eg [`KeyError`](https://docs.python.org/3/library/exceptions.html#KeyError "(in Python v3.10)")) but are [`BadRequest`](#werkzeug.exceptions.BadRequest "werkzeug.exceptions.BadRequest") HTTP exceptions at the same time. This decision was made to simplify a common pattern where you want to abort if the client tampered with the submitted form data in a way that the application can’t recover properly and should abort with `400 BAD REQUEST`. Assuming the application catches all HTTP exceptions and reacts to them properly a view function could do the following safely and doesn’t have to check if the keys exist: ``` def new_post(request): post = Post(title=request.form['title'], body=request.form['body']) post.save() return redirect(post.url) ``` If `title` or `body` are missing in the form, a special key error will be raised which behaves like a [`KeyError`](https://docs.python.org/3/library/exceptions.html#KeyError "(in Python v3.10)") but also a [`BadRequest`](#werkzeug.exceptions.BadRequest "werkzeug.exceptions.BadRequest") exception. `exception werkzeug.exceptions.BadRequestKeyError(arg=None, *args, **kwargs)` An exception that is used to signal both a [`KeyError`](https://docs.python.org/3/library/exceptions.html#KeyError "(in Python v3.10)") and a [`BadRequest`](#werkzeug.exceptions.BadRequest "werkzeug.exceptions.BadRequest"). Used by many of the datastructures. Parameters: * **arg** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – * **args** ([Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")) – * **kwargs** ([Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")) – Simple Aborting --------------- Sometimes it’s convenient to just raise an exception by the error code, without importing the exception and looking up the name etc. For this purpose there is the [`abort()`](#werkzeug.exceptions.abort "werkzeug.exceptions.abort") function. `werkzeug.exceptions.abort(status, *args, **kwargs)` Raises an [`HTTPException`](#werkzeug.exceptions.HTTPException "werkzeug.exceptions.HTTPException") for the given status code or WSGI application. If a status code is given, it will be looked up in the list of exceptions and will raise that exception. If passed a WSGI application, it will wrap it in a proxy WSGI exception and raise that: ``` abort(404) # 404 Not Found abort(Response('Hello World')) ``` Parameters: * **status** ([Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[*[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")*,* [Response](../wrappers/index#werkzeug.wrappers.Response "werkzeug.wrappers.Response")*]*) – * **args** ([Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")) – * **kwargs** ([Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")) – Return type: te.NoReturn If you want to use this functionality with custom exceptions you can create an instance of the aborter class: `class werkzeug.exceptions.Aborter(mapping=None, extra=None)` When passed a dict of code -> exception items it can be used as callable that raises exceptions. If the first argument to the callable is an integer it will be looked up in the mapping, if it’s a WSGI application it will be raised in a proxy exception. The rest of the arguments are forwarded to the exception constructor. Parameters: * **mapping** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Dict](https://docs.python.org/3/library/typing.html#typing.Dict "(in Python v3.10)")*[*[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")*,* [Type](https://docs.python.org/3/library/typing.html#typing.Type "(in Python v3.10)")*[*[HTTPException](#werkzeug.exceptions.HTTPException "werkzeug.exceptions.HTTPException")*]**]**]*) – * **extra** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Dict](https://docs.python.org/3/library/typing.html#typing.Dict "(in Python v3.10)")*[*[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")*,* [Type](https://docs.python.org/3/library/typing.html#typing.Type "(in Python v3.10)")*[*[HTTPException](#werkzeug.exceptions.HTTPException "werkzeug.exceptions.HTTPException")*]**]**]*) – Custom Errors ------------- As you can see from the list above not all status codes are available as errors. Especially redirects and other non 200 status codes that do not represent errors are missing. For redirects you can use the `redirect()` function from the utilities. If you want to add an error yourself you can subclass [`HTTPException`](#werkzeug.exceptions.HTTPException "werkzeug.exceptions.HTTPException"): ``` from werkzeug.exceptions import HTTPException class PaymentRequired(HTTPException): code = 402 description = '<p>Payment required.</p>' ``` This is the minimal code you need for your own exception. If you want to add more logic to the errors you can override the `get_description()`, `get_body()`, `get_headers()` and [`get_response()`](#werkzeug.exceptions.HTTPException.get_response "werkzeug.exceptions.HTTPException.get_response") methods. In any case you should have a look at the sourcecode of the exceptions module. You can override the default description in the constructor with the `description` parameter: ``` raise BadRequest(description='Request failed because X was not present') ```
programming_docs
werkzeug Quickstart Quickstart ========== This part of the documentation shows how to use the most important parts of Werkzeug. It’s intended as a starting point for developers with basic understanding of [**PEP 3333**](https://peps.python.org/pep-3333/) (WSGI) and [**RFC 2616**](https://datatracker.ietf.org/doc/html/rfc2616.html) (HTTP). werkzeug Context Locals Context Locals ============== You may find that you have some data during each request that you want to use across functions. Instead of passing these as arguments between every function, you may want to access them as global data. However, using global variables in Python web applications is not thread safe; different workers might interfere with each others’ data. Instead of storing common data during a request using global variables, you must use context-local variables instead. A context local is defined/imported globally, but the data it contains is specific to the current thread, asyncio task, or greenlet. You won’t accidentally get or overwrite another worker’s data. The current approach for storing per-context data in Python is the `contextvars` module. Context vars store data per thread, async task, or greenlet. This replaces the older [`threading.local`](https://docs.python.org/3/library/threading.html#threading.local "(in Python v3.10)") which only handled threads. Werkzeug provides wrappers around [`ContextVar`](https://docs.python.org/3/library/contextvars.html#contextvars.ContextVar "(in Python v3.10)") to make it easier to work with. werkzeug HTTP Utilities HTTP Utilities ============== Werkzeug provides a couple of functions to parse and generate HTTP headers that are useful when implementing WSGI middlewares or whenever you are operating on a lower level layer. All this functionality is also exposed from request and response objects. Datetime Functions ------------------ These functions simplify working with times in an HTTP context. Werkzeug produces timezone-aware [`datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.10)") objects in UTC. When passing datetime objects to Werkzeug, it assumes any naive datetime is in UTC. When comparing datetime values from Werkzeug, your own datetime objects must also be timezone-aware, or you must make the values from Werkzeug naive. * `dt = datetime.now(timezone.utc)` gets the current time in UTC. * `dt = datetime(..., tzinfo=timezone.utc)` creates a time in UTC. * `dt = dt.replace(tzinfo=timezone.utc)` makes a naive object aware by assuming it’s in UTC. * `dt = dt.replace(tzinfo=None)` makes an aware object naive. `werkzeug.http.parse_date(value)` Parse an [**RFC 2822**](https://datatracker.ietf.org/doc/html/rfc2822.html) date into a timezone-aware [`datetime.datetime`](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.10)") object, or `None` if parsing fails. This is a wrapper for [`email.utils.parsedate_to_datetime()`](https://docs.python.org/3/library/email.utils.html#email.utils.parsedate_to_datetime "(in Python v3.10)"). It returns `None` if parsing fails instead of raising an exception, and always returns a timezone-aware datetime object. If the string doesn’t have timezone information, it is assumed to be UTC. Parameters: **value** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – A string with a supported date format. Return type: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")[[datetime](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.10)")] Changelog Changed in version 2.0: Return a timezone-aware datetime object. Use `email.utils.parsedate_to_datetime`. `werkzeug.http.http_date(timestamp=None)` Format a datetime object or timestamp into an [**RFC 2822**](https://datatracker.ietf.org/doc/html/rfc2822.html) date string. This is a wrapper for [`email.utils.format_datetime()`](https://docs.python.org/3/library/email.utils.html#email.utils.format_datetime "(in Python v3.10)"). It assumes naive datetime objects are in UTC instead of raising an exception. Parameters: **timestamp** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[*[datetime](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.10)")*,* [date](https://docs.python.org/3/library/datetime.html#datetime.date "(in Python v3.10)")*,* [int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")*,* [float](https://docs.python.org/3/library/functions.html#float "(in Python v3.10)")*,* [struct\_time](https://docs.python.org/3/library/time.html#time.struct_time "(in Python v3.10)")*]**]*) – The datetime or timestamp to format. Defaults to the current time. Return type: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") Changelog Changed in version 2.0: Use `email.utils.format_datetime`. Accept `date` objects. Header Parsing -------------- The following functions can be used to parse incoming HTTP headers. Because Python does not provide data structures with the semantics required by [**RFC 2616**](https://datatracker.ietf.org/doc/html/rfc2616.html), Werkzeug implements some custom data structures that are [documented separately](../datastructures/index#http-datastructures). `werkzeug.http.parse_options_header(value)` Parse a `Content-Type`-like header into a tuple with the value and any options: ``` >>> parse_options_header('text/html; charset=utf8') ('text/html', {'charset': 'utf8'}) ``` This should is not for `Cache-Control`-like headers, which use a different format. For those, use [`parse_dict_header()`](#werkzeug.http.parse_dict_header "werkzeug.http.parse_dict_header"). Parameters: **value** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – The header value to parse. Return type: [Tuple](https://docs.python.org/3/library/typing.html#typing.Tuple "(in Python v3.10)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)"), [Dict](https://docs.python.org/3/library/typing.html#typing.Dict "(in Python v3.10)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)"), [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")]] Changed in version 2.2: Option names are always converted to lowercase. Changelog Changed in version 2.1: The `multiple` parameter is deprecated and will be removed in Werkzeug 2.2. Changed in version 0.15: [**RFC 2231**](https://datatracker.ietf.org/doc/html/rfc2231.html) parameter continuations are handled. New in version 0.5. `werkzeug.http.parse_set_header(value, on_update=None)` Parse a set-like header and return a [`HeaderSet`](../datastructures/index#werkzeug.datastructures.HeaderSet "werkzeug.datastructures.HeaderSet") object: ``` >>> hs = parse_set_header('token, "quoted value"') ``` The return value is an object that treats the items case-insensitively and keeps the order of the items: ``` >>> 'TOKEN' in hs True >>> hs.index('quoted value') 1 >>> hs HeaderSet(['token', 'quoted value']) ``` To create a header from the `HeaderSet` again, use the [`dump_header()`](#werkzeug.http.dump_header "werkzeug.http.dump_header") function. Parameters: * **value** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – a set header to be parsed. * **on\_update** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Callable](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.10)")*[**[*[HeaderSet](../datastructures/index#werkzeug.datastructures.HeaderSet "werkzeug.datastructures.HeaderSet")*]**,* *None**]**]*) – an optional callable that is called every time a value on the [`HeaderSet`](../datastructures/index#werkzeug.datastructures.HeaderSet "werkzeug.datastructures.HeaderSet") object is changed. Returns: a [`HeaderSet`](../datastructures/index#werkzeug.datastructures.HeaderSet "werkzeug.datastructures.HeaderSet") Return type: [HeaderSet](../datastructures/index#werkzeug.datastructures.HeaderSet "werkzeug.datastructures.HeaderSet") `werkzeug.http.parse_list_header(value)` Parse lists as described by RFC 2068 Section 2. In particular, parse comma-separated lists where the elements of the list may include quoted-strings. A quoted-string could contain a comma. A non-quoted string could have quotes in the middle. Quotes are removed automatically after parsing. It basically works like [`parse_set_header()`](#werkzeug.http.parse_set_header "werkzeug.http.parse_set_header") just that items may appear multiple times and case sensitivity is preserved. The return value is a standard [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)"): ``` >>> parse_list_header('token, "quoted value"') ['token', 'quoted value'] ``` To create a header from the [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") again, use the [`dump_header()`](#werkzeug.http.dump_header "werkzeug.http.dump_header") function. Parameters: **value** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – a string with a list header. Returns: [`list`](https://docs.python.org/3/library/stdtypes.html#list "(in Python v3.10)") Return type: [List](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.10)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")] `werkzeug.http.parse_dict_header(value, cls=<class 'dict'>)` Parse lists of key, value pairs as described by RFC 2068 Section 2 and convert them into a python dict (or any other mapping object created from the type with a dict like interface provided by the `cls` argument): ``` >>> d = parse_dict_header('foo="is a fish", bar="as well"') >>> type(d) is dict True >>> sorted(d.items()) [('bar', 'as well'), ('foo', 'is a fish')] ``` If there is no value for a key it will be `None`: ``` >>> parse_dict_header('key_without_value') {'key_without_value': None} ``` To create a header from the [`dict`](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.10)") again, use the [`dump_header()`](#werkzeug.http.dump_header "werkzeug.http.dump_header") function. Changelog Changed in version 0.9: Added support for `cls` argument. Parameters: * **value** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – a string with a dict header. * **cls** ([Type](https://docs.python.org/3/library/typing.html#typing.Type "(in Python v3.10)")*[*[dict](https://docs.python.org/3/library/stdtypes.html#dict "(in Python v3.10)")*]*) – callable to use for storage of parsed results. Returns: an instance of `cls` Return type: [Dict](https://docs.python.org/3/library/typing.html#typing.Dict "(in Python v3.10)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)"), [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")] `werkzeug.http.parse_accept_header(value[, class])` Parses an HTTP Accept-\* header. This does not implement a complete valid algorithm but one that supports at least value and quality extraction. Returns a new `Accept` object (basically a list of `(value, quality)` tuples sorted by the quality with some additional accessor methods). The second parameter can be a subclass of `Accept` that is created with the parsed values and returned. Parameters: * **value** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – the accept header string to be parsed. * **cls** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Type](https://docs.python.org/3/library/typing.html#typing.Type "(in Python v3.10)")*[**\_TAnyAccept**]**]*) – the wrapper class for the return value (can be `Accept` or a subclass thereof) Returns: an instance of `cls`. Return type: *\_TAnyAccept* `werkzeug.http.parse_cache_control_header(value, on_update=None, cls=None)` Parse a cache control header. The RFC differs between response and request cache control, this method does not. It’s your responsibility to not use the wrong control statements. Changelog New in version 0.5: The `cls` was added. If not specified an immutable [`RequestCacheControl`](../datastructures/index#werkzeug.datastructures.RequestCacheControl "werkzeug.datastructures.RequestCacheControl") is returned. Parameters: * **value** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – a cache control header to be parsed. * **on\_update** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Callable](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.10)")*[**[**\_TAnyCC**]**,* *None**]**]*) – an optional callable that is called every time a value on the `CacheControl` object is changed. * **cls** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Type](https://docs.python.org/3/library/typing.html#typing.Type "(in Python v3.10)")*[**\_TAnyCC**]**]*) – the class for the returned object. By default [`RequestCacheControl`](../datastructures/index#werkzeug.datastructures.RequestCacheControl "werkzeug.datastructures.RequestCacheControl") is used. Returns: a `cls` object. Return type: *\_TAnyCC* `werkzeug.http.parse_authorization_header(value)` Parse an HTTP basic/digest authorization header transmitted by the web browser. The return value is either `None` if the header was invalid or not given, otherwise an [`Authorization`](../datastructures/index#werkzeug.datastructures.Authorization "werkzeug.datastructures.Authorization") object. Parameters: **value** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – the authorization header to parse. Returns: a [`Authorization`](../datastructures/index#werkzeug.datastructures.Authorization "werkzeug.datastructures.Authorization") object or `None`. Return type: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")[[Authorization](../datastructures/index#werkzeug.datastructures.Authorization "werkzeug.datastructures.Authorization")] `werkzeug.http.parse_www_authenticate_header(value, on_update=None)` Parse an HTTP WWW-Authenticate header into a [`WWWAuthenticate`](../datastructures/index#werkzeug.datastructures.WWWAuthenticate "werkzeug.datastructures.WWWAuthenticate") object. Parameters: * **value** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – a WWW-Authenticate header to parse. * **on\_update** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Callable](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.10)")*[**[*[WWWAuthenticate](../datastructures/index#werkzeug.datastructures.WWWAuthenticate "werkzeug.datastructures.WWWAuthenticate")*]**,* *None**]**]*) – an optional callable that is called every time a value on the [`WWWAuthenticate`](../datastructures/index#werkzeug.datastructures.WWWAuthenticate "werkzeug.datastructures.WWWAuthenticate") object is changed. Returns: a [`WWWAuthenticate`](../datastructures/index#werkzeug.datastructures.WWWAuthenticate "werkzeug.datastructures.WWWAuthenticate") object. Return type: [WWWAuthenticate](../datastructures/index#werkzeug.datastructures.WWWAuthenticate "werkzeug.datastructures.WWWAuthenticate") `werkzeug.http.parse_if_range_header(value)` Parses an if-range header which can be an etag or a date. Returns a [`IfRange`](../datastructures/index#werkzeug.datastructures.IfRange "werkzeug.datastructures.IfRange") object. Changelog Changed in version 2.0: If the value represents a datetime, it is timezone-aware. New in version 0.7. Parameters: **value** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – Return type: [IfRange](../datastructures/index#werkzeug.datastructures.IfRange "werkzeug.datastructures.IfRange") `werkzeug.http.parse_range_header(value, make_inclusive=True)` Parses a range header into a [`Range`](../datastructures/index#werkzeug.datastructures.Range "werkzeug.datastructures.Range") object. If the header is missing or malformed `None` is returned. `ranges` is a list of `(start, stop)` tuples where the ranges are non-inclusive. Changelog New in version 0.7. Parameters: * **value** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – * **make\_inclusive** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – Return type: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")[[Range](../datastructures/index#werkzeug.datastructures.Range "werkzeug.datastructures.Range")] `werkzeug.http.parse_content_range_header(value, on_update=None)` Parses a range header into a [`ContentRange`](../datastructures/index#werkzeug.datastructures.ContentRange "werkzeug.datastructures.ContentRange") object or `None` if parsing is not possible. Changelog New in version 0.7. Parameters: * **value** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – a content range header to be parsed. * **on\_update** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Callable](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.10)")*[**[*[ContentRange](../datastructures/index#werkzeug.datastructures.ContentRange "werkzeug.datastructures.ContentRange")*]**,* *None**]**]*) – an optional callable that is called every time a value on the [`ContentRange`](../datastructures/index#werkzeug.datastructures.ContentRange "werkzeug.datastructures.ContentRange") object is changed. Return type: [Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")[[ContentRange](../datastructures/index#werkzeug.datastructures.ContentRange "werkzeug.datastructures.ContentRange")] Header Utilities ---------------- The following utilities operate on HTTP headers well but do not parse them. They are useful if you’re dealing with conditional responses or if you want to proxy arbitrary requests but want to remove WSGI-unsupported hop-by-hop headers. Also there is a function to create HTTP header strings from the parsed data. `werkzeug.http.is_entity_header(header)` Check if a header is an entity header. Changelog New in version 0.5. Parameters: **header** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – the header to test. Returns: `True` if it’s an entity header, `False` otherwise. Return type: [bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)") `werkzeug.http.is_hop_by_hop_header(header)` Check if a header is an HTTP/1.1 β€œHop-by-Hop” header. Changelog New in version 0.5. Parameters: **header** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – the header to test. Returns: `True` if it’s an HTTP/1.1 β€œHop-by-Hop” header, `False` otherwise. Return type: [bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)") `werkzeug.http.remove_entity_headers(headers, allowed=('expires', 'content-location'))` Remove all entity headers from a list or `Headers` object. This operation works in-place. `Expires` and `Content-Location` headers are by default not removed. The reason for this is [**RFC 2616**](https://datatracker.ietf.org/doc/html/rfc2616.html) section 10.3.5 which specifies some entity headers that should be sent. Changelog Changed in version 0.5: added `allowed` parameter. Parameters: * **headers** ([Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[*[Headers](../datastructures/index#werkzeug.datastructures.Headers "werkzeug.datastructures.Headers")*,* [List](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.10)")*[*[Tuple](https://docs.python.org/3/library/typing.html#typing.Tuple "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]**]**]*) – a list or `Headers` object. * **allowed** ([Iterable](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – a list of headers that should still be allowed even though they are entity headers. Return type: None `werkzeug.http.remove_hop_by_hop_headers(headers)` Remove all HTTP/1.1 β€œHop-by-Hop” headers from a list or `Headers` object. This operation works in-place. Changelog New in version 0.5. Parameters: **headers** ([Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[*[Headers](../datastructures/index#werkzeug.datastructures.Headers "werkzeug.datastructures.Headers")*,* [List](https://docs.python.org/3/library/typing.html#typing.List "(in Python v3.10)")*[*[Tuple](https://docs.python.org/3/library/typing.html#typing.Tuple "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]**]**]*) – a list or `Headers` object. Return type: None `werkzeug.http.is_byte_range_valid(start, stop, length)` Checks if a given byte content range is valid for the given length. Changelog New in version 0.7. Parameters: * **start** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")*]*) – * **stop** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")*]*) – * **length** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")*]*) – Return type: [bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)") `werkzeug.http.quote_header_value(value, extra_chars='', allow_token=True)` Quote a header value if necessary. Changelog New in version 0.5. Parameters: * **value** ([Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")*]*) – the value to quote. * **extra\_chars** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – a list of extra characters to skip quoting. * **allow\_token** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – if this is enabled token values are returned unchanged. Return type: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") `werkzeug.http.unquote_header_value(value, is_filename=False)` Unquotes a header value. (Reversal of [`quote_header_value()`](#werkzeug.http.quote_header_value "werkzeug.http.quote_header_value")). This does not use the real unquoting but what browsers are actually using for quoting. Changelog New in version 0.5. Parameters: * **value** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – the header value to unquote. * **is\_filename** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – The value represents a filename or path. Return type: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") `werkzeug.http.dump_header(iterable, allow_token=True)` Dump an HTTP header again. This is the reversal of [`parse_list_header()`](#werkzeug.http.parse_list_header "werkzeug.http.parse_list_header"), [`parse_set_header()`](#werkzeug.http.parse_set_header "werkzeug.http.parse_set_header") and [`parse_dict_header()`](#werkzeug.http.parse_dict_header "werkzeug.http.parse_dict_header"). This also quotes strings that include an equals sign unless you pass it as dict of key, value pairs. ``` >>> dump_header({'foo': 'bar baz'}) 'foo="bar baz"' >>> dump_header(('foo', 'bar baz')) 'foo, "bar baz"' ``` Parameters: * **iterable** ([Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[*[Dict](https://docs.python.org/3/library/typing.html#typing.Dict "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")*]**]**,* [Iterable](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]**]*) – the iterable or dict of values to quote. * **allow\_token** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – if set to `False` tokens as values are disallowed. See [`quote_header_value()`](#werkzeug.http.quote_header_value "werkzeug.http.quote_header_value") for more details. Return type: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") Cookies ------- `werkzeug.http.parse_cookie(header, charset='utf-8', errors='replace', cls=None)` Parse a cookie from a string or WSGI environ. The same key can be provided multiple times, the values are stored in-order. The default `MultiDict` will have the first value first, and all values can be retrieved with `MultiDict.getlist()`. Parameters: * **header** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[**WSGIEnvironment**,* [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [bytes](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.10)")*]**]*) – The cookie header as a string, or a WSGI environ dict with a `HTTP_COOKIE` key. * **charset** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – The charset for the cookie values. * **errors** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – The error behavior for the charset decoding. * **cls** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Type](https://docs.python.org/3/library/typing.html#typing.Type "(in Python v3.10)")*[**ds.MultiDict**]**]*) – A dict-like class to store the parsed cookies in. Defaults to `MultiDict`. Return type: ds.MultiDict[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)"), [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")] Changelog Changed in version 1.0.0: Returns a `MultiDict` instead of a `TypeConversionDict`. Changed in version 0.5: Returns a `TypeConversionDict` instead of a regular dict. The `cls` parameter was added. `werkzeug.http.dump_cookie(key, value='', max_age=None, expires=None, path='/', domain=None, secure=False, httponly=False, charset='utf-8', sync_expires=True, max_size=4093, samesite=None)` Create a Set-Cookie header without the `Set-Cookie` prefix. The return value is usually restricted to ascii as the vast majority of values are properly escaped, but that is no guarantee. It’s tunneled through latin1 as required by [**PEP 3333**](https://peps.python.org/pep-3333/). The return value is not ASCII safe if the key contains unicode characters. This is technically against the specification but happens in the wild. It’s strongly recommended to not use non-ASCII values for the keys. Parameters: * **max\_age** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[*[timedelta](https://docs.python.org/3/library/datetime.html#datetime.timedelta "(in Python v3.10)")*,* [int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")*]**]*) – should be a number of seconds, or `None` (default) if the cookie should last only as long as the client’s browser session. Additionally `timedelta` objects are accepted, too. * **expires** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [datetime](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.10)")*,* [int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")*,* [float](https://docs.python.org/3/library/functions.html#float "(in Python v3.10)")*]**]*) – should be a `datetime` object or unix timestamp. * **path** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – limits the cookie to a given path, per default it will span the whole domain. * **domain** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – Use this if you want to set a cross-domain cookie. For example, `domain=".example.com"` will set a cookie that is readable by the domain `www.example.com`, `foo.example.com` etc. Otherwise, a cookie will only be readable by the domain that set it. * **secure** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – The cookie will only be available via HTTPS * **httponly** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – disallow JavaScript to access the cookie. This is an extension to the cookie standard and probably not supported by all browsers. * **charset** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – the encoding for string values. * **sync\_expires** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – automatically set expires if max\_age is defined but expires not. * **max\_size** ([int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")) – Warn if the final header value exceeds this size. The default, 4093, should be safely [supported by most browsers](http://browsercookielimits.squawky.net/). Set to 0 to disable this check. * **samesite** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – Limits the scope of the cookie such that it will only be attached to requests if those requests are same-site. * **key** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – * **value** ([Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[*[bytes](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.10)")*,* [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – Return type: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") Changelog Changed in version 1.0.0: The string `'None'` is accepted for `samesite`. Conditional Response Helpers ---------------------------- For conditional responses the following functions might be useful: `werkzeug.http.parse_etags(value)` Parse an etag header. Parameters: **value** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – the tag header to parse Returns: an [`ETags`](../datastructures/index#werkzeug.datastructures.ETags "werkzeug.datastructures.ETags") object. Return type: [ETags](../datastructures/index#werkzeug.datastructures.ETags "werkzeug.datastructures.ETags") `werkzeug.http.quote_etag(etag, weak=False)` Quote an etag. Parameters: * **etag** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – the etag to quote. * **weak** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – set to `True` to tag it β€œweak”. Return type: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") `werkzeug.http.unquote_etag(etag)` Unquote a single etag: ``` >>> unquote_etag('W/"bar"') ('bar', True) >>> unquote_etag('"bar"') ('bar', False) ``` Parameters: **etag** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – the etag identifier to unquote. Returns: a `(etag, weak)` tuple. Return type: [Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")[[Tuple](https://docs.python.org/3/library/typing.html#typing.Tuple "(in Python v3.10)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)"), [bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")], [Tuple](https://docs.python.org/3/library/typing.html#typing.Tuple "(in Python v3.10)")[None, None]] `werkzeug.http.generate_etag(data)` Generate an etag for some data. Changelog Changed in version 2.0: Use SHA-1. MD5 may not be available in some environments. Parameters: **data** ([bytes](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.10)")) – Return type: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") `werkzeug.http.is_resource_modified(environ, etag=None, data=None, last_modified=None, ignore_if_range=True)` Convenience method for conditional requests. Parameters: * **environ** (*WSGIEnvironment*) – the WSGI environment of the request to be checked. * **etag** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – the etag for the response for comparison. * **data** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[bytes](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.10)")*]*) – or alternatively the data of the response to automatically generate an etag using [`generate_etag()`](#werkzeug.http.generate_etag "werkzeug.http.generate_etag"). * **last\_modified** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[*[datetime](https://docs.python.org/3/library/datetime.html#datetime.datetime "(in Python v3.10)")*,* [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]**]*) – an optional date of the last modification. * **ignore\_if\_range** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – If `False`, `If-Range` header will be taken into account. Returns: `True` if the resource was modified, otherwise `False`. Return type: [bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)") Changelog Changed in version 2.0: SHA-1 is used to generate an etag value for the data. MD5 may not be available in some environments. Changed in version 1.0.0: The check is run for methods other than `GET` and `HEAD`. Constants --------- `werkzeug.http.HTTP_STATUS_CODES` A dict of status code -> default status message pairs. This is used by the wrappers and other places where an integer status code is expanded to a string throughout Werkzeug. Form Data Parsing ----------------- Werkzeug provides the form parsing functions separately from the request object so that you can access form data from a plain WSGI environment. The following formats are currently supported by the form data parser: * `application/x-www-form-urlencoded` * `multipart/form-data` Nested multipart is not currently supported (Werkzeug 0.9), but it isn’t used by any of the modern web browsers. Usage example: ``` >>> from io import BytesIO >>> from werkzeug.formparser import parse_form_data >>> data = ( ... b'--foo\r\nContent-Disposition: form-data; name="test"\r\n' ... b"\r\nHello World!\r\n--foo--" ... ) >>> environ = { ... "wsgi.input": BytesIO(data), ... "CONTENT_LENGTH": str(len(data)), ... "CONTENT_TYPE": "multipart/form-data; boundary=foo", ... "REQUEST_METHOD": "POST", ... } >>> stream, form, files = parse_form_data(environ) >>> stream.read() b'' >>> form['test'] 'Hello World!' >>> not files True ``` Normally the WSGI environment is provided by the WSGI gateway with the incoming data as part of it. If you want to generate such fake-WSGI environments for unittesting you might want to use the `create_environ()` function or the `EnvironBuilder` instead. `class werkzeug.formparser.FormDataParser(stream_factory=None, charset='utf-8', errors='replace', max_form_memory_size=None, max_content_length=None, cls=None, silent=True)` This class implements parsing of form data for Werkzeug. By itself it can parse multipart and url encoded form data. It can be subclassed and extended but for most mimetypes it is a better idea to use the untouched stream and expose it as separate attributes on a request object. Changelog New in version 0.8. Parameters: * **stream\_factory** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[**TStreamFactory**]*) – An optional callable that returns a new read and writeable file descriptor. This callable works the same as `Response._get_file_stream()`. * **charset** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – The character set for URL and url encoded form data. * **errors** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – The encoding error behavior. * **max\_form\_memory\_size** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")*]*) – the maximum number of bytes to be accepted for in-memory stored form data. If the data exceeds the value specified an `RequestEntityTooLarge` exception is raised. * **max\_content\_length** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")*]*) – If this is provided and the transmitted data is longer than this value an `RequestEntityTooLarge` exception is raised. * **cls** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Type](https://docs.python.org/3/library/typing.html#typing.Type "(in Python v3.10)")*[*[MultiDict](../datastructures/index#werkzeug.datastructures.MultiDict "werkzeug.datastructures.MultiDict")*]**]*) – an optional dict class to use. If this is not specified or `None` the default `MultiDict` is used. * **silent** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – If set to False parsing errors will not be caught. `werkzeug.formparser.parse_form_data(environ, stream_factory=None, charset='utf-8', errors='replace', max_form_memory_size=None, max_content_length=None, cls=None, silent=True)` Parse the form data in the environ and return it as tuple in the form `(stream, form, files)`. You should only call this method if the transport method is `POST`, `PUT`, or `PATCH`. If the mimetype of the data transmitted is `multipart/form-data` the files multidict will be filled with `FileStorage` objects. If the mimetype is unknown the input stream is wrapped and returned as first argument, else the stream is empty. This is a shortcut for the common usage of [`FormDataParser`](#werkzeug.formparser.FormDataParser "werkzeug.formparser.FormDataParser"). Have a look at [Dealing with Request Data](../request_data/index) for more details. Changelog New in version 0.5.1: The optional `silent` flag was added. New in version 0.5: The `max_form_memory_size`, `max_content_length` and `cls` parameters were added. Parameters: * **environ** (*WSGIEnvironment*) – the WSGI environment to be used for parsing. * **stream\_factory** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[**TStreamFactory**]*) – An optional callable that returns a new read and writeable file descriptor. This callable works the same as `Response._get_file_stream()`. * **charset** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – The character set for URL and url encoded form data. * **errors** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – The encoding error behavior. * **max\_form\_memory\_size** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")*]*) – the maximum number of bytes to be accepted for in-memory stored form data. If the data exceeds the value specified an `RequestEntityTooLarge` exception is raised. * **max\_content\_length** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")*]*) – If this is provided and the transmitted data is longer than this value an `RequestEntityTooLarge` exception is raised. * **cls** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Type](https://docs.python.org/3/library/typing.html#typing.Type "(in Python v3.10)")*[*[MultiDict](../datastructures/index#werkzeug.datastructures.MultiDict "werkzeug.datastructures.MultiDict")*]**]*) – an optional dict class to use. If this is not specified or `None` the default `MultiDict` is used. * **silent** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – If set to False parsing errors will not be caught. Returns: A tuple in the form `(stream, form, files)`. Return type: t\_parse\_result
programming_docs
werkzeug URL Helpers URL Helpers =========== Functions for working with URLs. Contains implementations of functions from [`urllib.parse`](https://docs.python.org/3/library/urllib.parse.html#module-urllib.parse "(in Python v3.10)") that handle bytes and strings. `class werkzeug.urls.BaseURL(scheme, netloc, path, query, fragment)` Superclass of [`URL`](#werkzeug.urls.URL "werkzeug.urls.URL") and [`BytesURL`](#werkzeug.urls.BytesURL "werkzeug.urls.BytesURL"). Create new instance of \_URLTuple(scheme, netloc, path, query, fragment) Parameters: * **scheme** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – * **netloc** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – * **path** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – * **query** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – * **fragment** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – `property ascii_host: Optional[str]` Works exactly like [`host`](#werkzeug.urls.BaseURL.host "werkzeug.urls.BaseURL.host") but will return a result that is restricted to ASCII. If it finds a netloc that is not ASCII it will attempt to idna decode it. This is useful for socket operations when the URL might include internationalized characters. `property auth: Optional[str]` The authentication part in the URL if available, `None` otherwise. `decode_netloc()` Decodes the netloc part into a string. Return type: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") `decode_query(*args, **kwargs)` Decodes the query part of the URL. Ths is a shortcut for calling [`url_decode()`](#werkzeug.urls.url_decode "werkzeug.urls.url_decode") on the query argument. The arguments and keyword arguments are forwarded to [`url_decode()`](#werkzeug.urls.url_decode "werkzeug.urls.url_decode") unchanged. Parameters: * **args** ([Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")) – * **kwargs** ([Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")) – Return type: ds.MultiDict[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)"), [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")] `encode_netloc()` Encodes the netloc part to an ASCII safe URL as bytes. Return type: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") `get_file_location(pathformat=None)` Returns a tuple with the location of the file in the form `(server, location)`. If the netloc is empty in the URL or points to localhost, it’s represented as `None`. The `pathformat` by default is autodetection but needs to be set when working with URLs of a specific system. The supported values are `'windows'` when working with Windows or DOS paths and `'posix'` when working with posix paths. If the URL does not point to a local file, the server and location are both represented as `None`. Parameters: **pathformat** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – The expected format of the path component. Currently `'windows'` and `'posix'` are supported. Defaults to `None` which is autodetect. Return type: [Tuple](https://docs.python.org/3/library/typing.html#typing.Tuple "(in Python v3.10)")[[Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")], [Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")]] `property host: Optional[str]` The host part of the URL if available, otherwise `None`. The host is either the hostname or the IP address mentioned in the URL. It will not contain the port. `join(*args, **kwargs)` Joins this URL with another one. This is just a convenience function for calling into [`url_join()`](#werkzeug.urls.url_join "werkzeug.urls.url_join") and then parsing the return value again. Parameters: * **args** ([Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")) – * **kwargs** ([Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")) – Return type: [BaseURL](#werkzeug.urls.BaseURL "werkzeug.urls.BaseURL") `property password: Optional[str]` The password if it was part of the URL, `None` otherwise. This undergoes URL decoding and will always be a string. `property port: Optional[int]` The port in the URL as an integer if it was present, `None` otherwise. This does not fill in default ports. `property raw_password: Optional[str]` The password if it was part of the URL, `None` otherwise. Unlike [`password`](#werkzeug.urls.BaseURL.password "werkzeug.urls.BaseURL.password") this one is not being decoded. `property raw_username: Optional[str]` The username if it was part of the URL, `None` otherwise. Unlike [`username`](#werkzeug.urls.BaseURL.username "werkzeug.urls.BaseURL.username") this one is not being decoded. `replace(**kwargs)` Return an URL with the same values, except for those parameters given new values by whichever keyword arguments are specified. Parameters: **kwargs** ([Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")) – Return type: [BaseURL](#werkzeug.urls.BaseURL "werkzeug.urls.BaseURL") `to_iri_tuple()` Returns a [`URL`](#werkzeug.urls.URL "werkzeug.urls.URL") tuple that holds a IRI. This will try to decode as much information as possible in the URL without losing information similar to how a web browser does it for the URL bar. It’s usually more interesting to directly call [`uri_to_iri()`](#werkzeug.urls.uri_to_iri "werkzeug.urls.uri_to_iri") which will return a string. Return type: [BaseURL](#werkzeug.urls.BaseURL "werkzeug.urls.BaseURL") `to_uri_tuple()` Returns a [`BytesURL`](#werkzeug.urls.BytesURL "werkzeug.urls.BytesURL") tuple that holds a URI. This will encode all the information in the URL properly to ASCII using the rules a web browser would follow. It’s usually more interesting to directly call [`iri_to_uri()`](#werkzeug.urls.iri_to_uri "werkzeug.urls.iri_to_uri") which will return a string. Return type: [BaseURL](#werkzeug.urls.BaseURL "werkzeug.urls.BaseURL") `to_url()` Returns a URL string or bytes depending on the type of the information stored. This is just a convenience function for calling [`url_unparse()`](#werkzeug.urls.url_unparse "werkzeug.urls.url_unparse") for this URL. Return type: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") `property username: Optional[str]` The username if it was part of the URL, `None` otherwise. This undergoes URL decoding and will always be a string. `class werkzeug.urls.BytesURL(scheme, netloc, path, query, fragment)` Represents a parsed URL in bytes. Create new instance of \_URLTuple(scheme, netloc, path, query, fragment) Parameters: * **scheme** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – * **netloc** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – * **path** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – * **query** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – * **fragment** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – `decode(charset='utf-8', errors='replace')` Decodes the URL to a tuple made out of strings. The charset is only being used for the path, query and fragment. Parameters: * **charset** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – * **errors** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – Return type: [URL](#werkzeug.urls.URL "werkzeug.urls.URL") `encode_netloc()` Returns the netloc unchanged as bytes. Return type: [bytes](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.10)") `class werkzeug.urls.URL(scheme, netloc, path, query, fragment)` Represents a parsed URL. This behaves like a regular tuple but also has some extra attributes that give further insight into the URL. Create new instance of \_URLTuple(scheme, netloc, path, query, fragment) Parameters: * **scheme** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – * **netloc** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – * **path** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – * **query** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – * **fragment** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – `encode(charset='utf-8', errors='replace')` Encodes the URL to a tuple made out of bytes. The charset is only being used for the path, query and fragment. Parameters: * **charset** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – * **errors** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – Return type: [BytesURL](#werkzeug.urls.BytesURL "werkzeug.urls.BytesURL") `werkzeug.urls.iri_to_uri(iri, charset='utf-8', errors='strict', safe_conversion=False)` Convert an IRI to a URI. All non-ASCII and unsafe characters are quoted. If the URL has a domain, it is encoded to Punycode. ``` >>> iri_to_uri('http://\u2603.net/p\xe5th?q=\xe8ry%DF') 'http://xn--n3h.net/p%C3%A5th?q=%C3%A8ry%DF' ``` Parameters: * **iri** ([Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [Tuple](https://docs.python.org/3/library/typing.html#typing.Tuple "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]**]*) – The IRI to convert. * **charset** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – The encoding of the IRI. * **errors** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – Error handler to use during `bytes.encode`. * **safe\_conversion** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – Return the URL unchanged if it only contains ASCII characters and no whitespace. See the explanation below. Return type: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") There is a general problem with IRI conversion with some protocols that are in violation of the URI specification. Consider the following two IRIs: ``` magnet:?xt=uri:whatever itms-services://?action=download-manifest ``` After parsing, we don’t know if the scheme requires the `//`, which is dropped if empty, but conveys different meanings in the final URL if it’s present or not. In this case, you can use `safe_conversion`, which will return the URL unchanged if it only contains ASCII characters and no whitespace. This can result in a URI with unquoted characters if it was not already quoted correctly, but preserves the URL’s semantics. Werkzeug uses this for the `Location` header for redirects. Changelog Changed in version 0.15: All reserved characters remain unquoted. Previously, only some reserved characters were left unquoted. Changed in version 0.9.6: The `safe_conversion` parameter was added. New in version 0.6. `werkzeug.urls.uri_to_iri(uri, charset='utf-8', errors='werkzeug.url_quote')` Convert a URI to an IRI. All valid UTF-8 characters are unquoted, leaving all reserved and invalid characters quoted. If the URL has a domain, it is decoded from Punycode. ``` >>> uri_to_iri("http://xn--n3h.net/p%C3%A5th?q=%C3%A8ry%DF") 'http://\u2603.net/p\xe5th?q=\xe8ry%DF' ``` Parameters: * **uri** ([Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [Tuple](https://docs.python.org/3/library/typing.html#typing.Tuple "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]**]*) – The URI to convert. * **charset** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – The encoding to encode unquoted bytes with. * **errors** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – Error handler to use during `bytes.encode`. By default, invalid bytes are left quoted. Return type: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") Changelog Changed in version 0.15: All reserved and invalid characters remain quoted. Previously, only some reserved characters were preserved, and invalid bytes were replaced instead of left quoted. New in version 0.6. `werkzeug.urls.url_decode(s, charset='utf-8', include_empty=True, errors='replace', separator='&', cls=None)` Parse a query string and return it as a `MultiDict`. Parameters: * **s** (*AnyStr*) – The query string to parse. * **charset** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – Decode bytes to string with this charset. If not given, bytes are returned as-is. * **include\_empty** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – Include keys with empty values in the dict. * **errors** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – Error handling behavior when decoding bytes. * **separator** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – Separator character between pairs. * **cls** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Type](https://docs.python.org/3/library/typing.html#typing.Type "(in Python v3.10)")*[**ds.MultiDict**]**]*) – Container to hold result instead of `MultiDict`. Return type: ds.MultiDict[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)"), [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")] Changelog Changed in version 2.0: The `decode_keys` parameter is deprecated and will be removed in Werkzeug 2.1. Changed in version 0.5: In previous versions β€œ;” and β€œ&” could be used for url decoding. Now only β€œ&” is supported. If you want to use β€œ;”, a different `separator` can be provided. Changed in version 0.5: The `cls` parameter was added. `werkzeug.urls.url_decode_stream(stream, charset='utf-8', include_empty=True, errors='replace', separator=b'&', cls=None, limit=None)` Works like [`url_decode()`](#werkzeug.urls.url_decode "werkzeug.urls.url_decode") but decodes a stream. The behavior of stream and limit follows functions like [`make_line_iter()`](../wsgi/index#werkzeug.wsgi.make_line_iter "werkzeug.wsgi.make_line_iter"). The generator of pairs is directly fed to the `cls` so you can consume the data while it’s parsed. Parameters: * **stream** ([IO](https://docs.python.org/3/library/typing.html#typing.IO "(in Python v3.10)")*[*[bytes](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.10)")*]*) – a stream with the encoded querystring * **charset** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – the charset of the query string. If set to `None` no decoding will take place. * **include\_empty** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – Set to `False` if you don’t want empty values to appear in the dict. * **errors** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – the decoding error behavior. * **separator** ([bytes](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.10)")) – the pair separator to be used, defaults to `&` * **cls** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Type](https://docs.python.org/3/library/typing.html#typing.Type "(in Python v3.10)")*[**ds.MultiDict**]**]*) – an optional dict class to use. If this is not specified or `None` the default `MultiDict` is used. * **limit** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")*]*) – the content length of the URL data. Not necessary if a limited stream is provided. Return type: ds.MultiDict[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)"), [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")] Changelog Changed in version 2.0: The `decode_keys` and `return_iterator` parameters are deprecated and will be removed in Werkzeug 2.1. New in version 0.8. `werkzeug.urls.url_encode(obj, charset='utf-8', sort=False, key=None, separator='&')` URL encode a dict/`MultiDict`. If a value is `None` it will not appear in the result string. Per default only values are encoded into the target charset strings. Parameters: * **obj** ([Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[*[Mapping](https://docs.python.org/3/library/typing.html#typing.Mapping "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]**,* [Iterable](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.10)")*[*[Tuple](https://docs.python.org/3/library/typing.html#typing.Tuple "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]**]**]*) – the object to encode into a query string. * **charset** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – the charset of the query string. * **sort** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – set to `True` if you want parameters to be sorted by `key`. * **separator** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – the separator to be used for the pairs. * **key** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Callable](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.10)")*[**[*[Tuple](https://docs.python.org/3/library/typing.html#typing.Tuple "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]**]**,* [Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")*]**]*) – an optional function to be used for sorting. For more details check out the [`sorted()`](https://docs.python.org/3/library/functions.html#sorted "(in Python v3.10)") documentation. Return type: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") Changelog Changed in version 2.0: The `encode_keys` parameter is deprecated and will be removed in Werkzeug 2.1. Changed in version 0.5: Added the `sort`, `key`, and `separator` parameters. `werkzeug.urls.url_encode_stream(obj, stream=None, charset='utf-8', sort=False, key=None, separator='&')` Like [`url_encode()`](#werkzeug.urls.url_encode "werkzeug.urls.url_encode") but writes the results to a stream object. If the stream is `None` a generator over all encoded pairs is returned. Parameters: * **obj** ([Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[*[Mapping](https://docs.python.org/3/library/typing.html#typing.Mapping "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]**,* [Iterable](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.10)")*[*[Tuple](https://docs.python.org/3/library/typing.html#typing.Tuple "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]**]**]*) – the object to encode into a query string. * **stream** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[IO](https://docs.python.org/3/library/typing.html#typing.IO "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]**]*) – a stream to write the encoded object into or `None` if an iterator over the encoded pairs should be returned. In that case the separator argument is ignored. * **charset** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – the charset of the query string. * **sort** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – set to `True` if you want parameters to be sorted by `key`. * **separator** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – the separator to be used for the pairs. * **key** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Callable](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.10)")*[**[*[Tuple](https://docs.python.org/3/library/typing.html#typing.Tuple "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]**]**,* [Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")*]**]*) – an optional function to be used for sorting. For more details check out the [`sorted()`](https://docs.python.org/3/library/functions.html#sorted "(in Python v3.10)") documentation. Return type: None Changelog Changed in version 2.0: The `encode_keys` parameter is deprecated and will be removed in Werkzeug 2.1. New in version 0.8. `werkzeug.urls.url_fix(s, charset='utf-8')` Sometimes you get an URL by a user that just isn’t a real URL because it contains unsafe characters like β€˜ β€˜ and so on. This function can fix some of the problems in a similar way browsers handle data entered by the user: ``` >>> url_fix('http://de.wikipedia.org/wiki/Elf (Begriffskl\xe4rung)') 'http://de.wikipedia.org/wiki/Elf%20(Begriffskl%C3%A4rung)' ``` Parameters: * **s** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – the string with the URL to fix. * **charset** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – The target charset for the URL if the url was given as a string. Return type: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") `werkzeug.urls.url_join(base, url, allow_fragments=True)` Join a base URL and a possibly relative URL to form an absolute interpretation of the latter. Parameters: * **base** ([Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [Tuple](https://docs.python.org/3/library/typing.html#typing.Tuple "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]**]*) – the base URL for the join operation. * **url** ([Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [Tuple](https://docs.python.org/3/library/typing.html#typing.Tuple "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]**]*) – the URL to join. * **allow\_fragments** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – indicates whether fragments should be allowed. Return type: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") `werkzeug.urls.url_parse(url, scheme=None, allow_fragments=True)` Parses a URL from a string into a [`URL`](#werkzeug.urls.URL "werkzeug.urls.URL") tuple. If the URL is lacking a scheme it can be provided as second argument. Otherwise, it is ignored. Optionally fragments can be stripped from the URL by setting `allow_fragments` to `False`. The inverse of this function is [`url_unparse()`](#werkzeug.urls.url_unparse "werkzeug.urls.url_unparse"). Parameters: * **url** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – the URL to parse. * **scheme** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – the default schema to use if the URL is schemaless. * **allow\_fragments** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – if set to `False` a fragment will be removed from the URL. Return type: [BaseURL](#werkzeug.urls.BaseURL "werkzeug.urls.BaseURL") `werkzeug.urls.url_quote(string, charset='utf-8', errors='strict', safe='/:', unsafe='')` URL encode a single string with a given encoding. Parameters: * **s** – the string to quote. * **charset** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – the charset to be used. * **safe** ([Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [bytes](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.10)")*]*) – an optional sequence of safe characters. * **unsafe** ([Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [bytes](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.10)")*]*) – an optional sequence of unsafe characters. * **string** ([Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [bytes](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.10)")*]*) – * **errors** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – Return type: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") Changelog New in version 0.9.2: The `unsafe` parameter was added. `werkzeug.urls.url_quote_plus(string, charset='utf-8', errors='strict', safe='')` URL encode a single string with the given encoding and convert whitespace to β€œ+”. Parameters: * **s** – The string to quote. * **charset** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – The charset to be used. * **safe** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – An optional sequence of safe characters. * **string** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – * **errors** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – Return type: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") `werkzeug.urls.url_unparse(components)` The reverse operation to [`url_parse()`](#werkzeug.urls.url_parse "werkzeug.urls.url_parse"). This accepts arbitrary as well as [`URL`](#werkzeug.urls.URL "werkzeug.urls.URL") tuples and returns a URL as a string. Parameters: **components** ([Tuple](https://docs.python.org/3/library/typing.html#typing.Tuple "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – the parsed URL as tuple which should be converted into a URL string. Return type: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") `werkzeug.urls.url_unquote(s, charset='utf-8', errors='replace', unsafe='')` URL decode a single string with a given encoding. If the charset is set to `None` no decoding is performed and raw bytes are returned. Parameters: * **s** ([Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [bytes](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.10)")*]*) – the string to unquote. * **charset** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – the charset of the query string. If set to `None` no decoding will take place. * **errors** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – the error handling for the charset decoding. * **unsafe** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – Return type: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") `werkzeug.urls.url_unquote_plus(s, charset='utf-8', errors='replace')` URL decode a single string with the given `charset` and decode β€œ+” to whitespace. Per default encoding errors are ignored. If you want a different behavior you can set `errors` to `'replace'` or `'strict'`. Parameters: * **s** ([Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [bytes](https://docs.python.org/3/library/stdtypes.html#bytes "(in Python v3.10)")*]*) – The string to unquote. * **charset** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – the charset of the query string. If set to `None` no decoding will take place. * **errors** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – The error handling for the `charset` decoding. Return type: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")
programming_docs
werkzeug Deploying to Production Deploying to Production ======================= After developing your application, you’ll want to make it available publicly to other users. When you’re developing locally, you’re probably using the built-in development server, debugger, and reloader. These should not be used in production. Instead, you should use a dedicated WSGI server or hosting platform, some of which will be described here. β€œProduction” means β€œnot development”, which applies whether you’re serving your application publicly to millions of users or privately / locally to a single user. **Do not use the development server when deploying to production. It is intended for use only during local development. It is not designed to be particularly secure, stable, or efficient.** Self-Hosted Options ------------------- Werkzeug is a WSGI *application*. A WSGI *server* is used to run the application, converting incoming HTTP requests to the standard WSGI environ, and converting outgoing WSGI responses to HTTP responses. The primary goal of these docs is to familiarize you with the concepts involved in running a WSGI application using a production WSGI server and HTTP server. There are many WSGI servers and HTTP servers, with many configuration possibilities. The pages below discuss the most common servers, and show the basics of running each one. The next section discusses platforms that can manage this for you. * [Gunicorn](gunicorn/index) * [Waitress](waitress/index) * [mod\_wsgi](mod_wsgi/index) * [uWSGI](uwsgi/index) * [gevent](gevent/index) * [eventlet](eventlet/index) WSGI servers have HTTP servers built-in. However, a dedicated HTTP server may be safer, more efficient, or more capable. Putting an HTTP server in front of the WSGI server is called a β€œreverse proxy.” * [Tell Werkzeug it is Behind a Proxy](proxy_fix/index) * [nginx](nginx/index) * [Apache httpd](apache-httpd/index) This list is not exhaustive, and you should evaluate these and other servers based on your application’s needs. Different servers will have different capabilities, configuration, and support. Hosting Platforms ----------------- There are many services available for hosting web applications without needing to maintain your own server, networking, domain, etc. Some services may have a free tier up to a certain time or bandwidth. Many of these services use one of the WSGI servers described above, or a similar interface. You should evaluate services based on your application’s needs. Different services will have different capabilities, configuration, pricing, and support. You’ll probably need to [Tell Werkzeug it is Behind a Proxy](proxy_fix/index) when using most hosting platforms. werkzeug Apache httpd Apache httpd ============ [Apache httpd](https://httpd.apache.org/) is a fast, production level HTTP server. When serving your application with one of the WSGI servers listed in [Deploying to Production](../index), it is often good or necessary to put a dedicated HTTP server in front of it. This β€œreverse proxy” can handle incoming requests, TLS, and other security and performance concerns better than the WSGI server. httpd can be installed using your system package manager, or a pre-built executable for Windows. Installing and running httpd itself is outside the scope of this doc. This page outlines the basics of configuring httpd to proxy your application. Be sure to read its documentation to understand what features are available. Domain Name ----------- Acquiring and configuring a domain name is outside the scope of this doc. In general, you will buy a domain name from a registrar, pay for server space with a hosting provider, and then point your registrar at the hosting provider’s name servers. To simulate this, you can also edit your `hosts` file, located at `/etc/hosts` on Linux. Add a line that associates a name with the local IP. Modern Linux systems may be configured to treat any domain name that ends with `.localhost` like this without adding it to the `hosts` file. `/etc/hosts` ``` 127.0.0.1 hello.localhost ``` Configuration ------------- The httpd configuration is located at `/etc/httpd/conf/httpd.conf` on Linux. It may be different depending on your operating system. Check the docs and look for `httpd.conf`. Remove or comment out any existing `DocumentRoot` directive. Add the config lines below. We’ll assume the WSGI server is listening locally at `http://127.0.0.1:8000`. `/etc/httpd/conf/httpd.conf` ``` LoadModule proxy_module modules/mod_proxy.so LoadModule proxy_http_module modules/mod_proxy_http.so ProxyPass / http://127.0.0.1:8000/ RequestHeader set X-Forwarded-Proto http RequestHeader set X-Forwarded-Prefix / ``` The `LoadModule` lines might already exist. If so, make sure they are uncommented instead of adding them manually. Then [Tell Werkzeug it is Behind a Proxy](../proxy_fix/index) so that your application uses the `X-Forwarded` headers. `X-Forwarded-For` and `X-Forwarded-Host` are automatically set by `ProxyPass`. Static Files ------------ If your application has static files such as JavaScript, CSS, and images, it will be more efficient to let Nginx serve them directly rather than going through the Python application. Assuming the static files are expected to be available under the `/static/` URL, and are stored at `/home/project/static/`, add the following to the config above. ``` Alias /static/ /home/project/static/ ``` werkzeug gevent gevent ====== Prefer using [Gunicorn](../gunicorn/index) or [uWSGI](../uwsgi/index) with gevent workers rather than using [gevent](https://www.gevent.org/) directly. Gunicorn and uWSGI provide much more configurable and production-tested servers. [gevent](https://www.gevent.org/) allows writing asynchronous, coroutine-based code that looks like standard synchronous Python. It uses [greenlet](https://greenlet.readthedocs.io/en/latest/) to enable task switching without writing `async/await` or using `asyncio`. [eventlet](../eventlet/index) is another library that does the same thing. Certain dependencies you have, or other considerations, may affect which of the two you choose to use. gevent provides a WSGI server that can handle many connections at once instead of one per worker process. You must actually use gevent in your own code to see any benefit to using the server. Installing ---------- When using gevent, greenlet>=1.0 is required, otherwise context locals such as `request` will not work as expected. When using PyPy, PyPy>=7.3.7 is required. Create a virtualenv, install your application, then install `gevent`. ``` $ cd hello-app $ python -m venv venv $ . venv/bin/activate $ pip install . # install your application $ pip install gevent ``` Running ------- To use gevent to serve your application, write a script that imports its `WSGIServer`, as well as your app or app factory. `wsgi.py` ``` from gevent.pywsgi import WSGIServer from hello import create_app app = create_app() http_server = WSGIServer(("127.0.0.1", 8000), app) http_server.serve_forever() ``` ``` $ python wsgi.py ``` No output is shown when the server starts. Binding Externally ------------------ gevent should not be run as root because it would cause your application code to run as root, which is not secure. However, this means it will not be possible to bind to port 80 or 443. Instead, a reverse proxy such as [nginx](../nginx/index) or [Apache httpd](../apache-httpd/index) should be used in front of gevent. You can bind to all external IPs on a non-privileged port by using `0.0.0.0` in the server arguments shown in the previous section. Don’t do this when using a reverse proxy setup, otherwise it will be possible to bypass the proxy. `0.0.0.0` is not a valid address to navigate to, you’d use a specific IP address in your browser. werkzeug Waitress Waitress ======== [Waitress](https://docs.pylonsproject.org/projects/waitress/) is a pure Python WSGI server. * It is easy to configure. * It supports Windows directly. * It is easy to install as it does not require additional dependencies or compilation. * It does not support streaming requests, full request data is always buffered. * It uses a single process with multiple thread workers. This page outlines the basics of running Waitress. Be sure to read its documentation and `waitress-serve --help` to understand what features are available. Installing ---------- Create a virtualenv, install your application, then install `waitress`. ``` $ cd hello-app $ python -m venv venv $ . venv/bin/activate $ pip install . # install your application $ pip install waitress ``` Running ------- The only required argument to `waitress-serve` tells it how to load your application. The syntax is `{module}:{app}`. `module` is the dotted import name to the module with your application. `app` is the variable with the application. If you’re using the app factory pattern, use `--call {module}:{factory}` instead. ``` # equivalent to 'from hello import app' $ waitress-serve hello:app --host 127.0.0.1 # equivalent to 'from hello import create_app; create_app()' $ waitress-serve --call hello:create_app --host 127.0.0.1 Serving on http://127.0.0.1:8080 ``` The `--host` option binds the server to local `127.0.0.1` only. Logs for each request aren’t shown, only errors are shown. Logging can be configured through the Python interface instead of the command line. Binding Externally ------------------ Waitress should not be run as root because it would cause your application code to run as root, which is not secure. However, this means it will not be possible to bind to port 80 or 443. Instead, a reverse proxy such as [nginx](../nginx/index) or [Apache httpd](../apache-httpd/index) should be used in front of Waitress. You can bind to all external IPs on a non-privileged port by not specifying the `--host` option. Don’t do this when using a revers proxy setup, otherwise it will be possible to bypass the proxy. `0.0.0.0` is not a valid address to navigate to, you’d use a specific IP address in your browser. werkzeug Gunicorn Gunicorn ======== [Gunicorn](https://gunicorn.org/) is a pure Python WSGI server with simple configuration and multiple worker implementations for performance tuning. * It tends to integrate easily with hosting platforms. * It does not support Windows (but does run on WSL). * It is easy to install as it does not require additional dependencies or compilation. * It has built-in async worker support using gevent or eventlet. This page outlines the basics of running Gunicorn. Be sure to read its [documentation](https://docs.gunicorn.org/) and use `gunicorn --help` to understand what features are available. Installing ---------- Gunicorn is easy to install, as it does not require external dependencies or compilation. It runs on Windows only under WSL. Create a virtualenv, install your application, then install `gunicorn`. ``` $ cd hello-app $ python -m venv venv $ . venv/bin/activate $ pip install . # install your application $ pip install gunicorn ``` Running ------- The only required argument to Gunicorn tells it how to load your application. The syntax is `{module_import}:{app_variable}`. `module_import` is the dotted import name to the module with your application. `app_variable` is the variable with the application. It can also be a function call (with any arguments) if you’re using the app factory pattern. ``` # equivalent to 'from hello import app' $ gunicorn -w 4 'hello:app' # equivalent to 'from hello import create_app; create_app()' $ gunicorn -w 4 'hello:create_app()' Starting gunicorn 20.1.0 Listening at: http://127.0.0.1:8000 (x) Using worker: sync Booting worker with pid: x Booting worker with pid: x Booting worker with pid: x Booting worker with pid: x ``` The `-w` option specifies the number of processes to run; a starting value could be `CPU * 2`. The default is only 1 worker, which is probably not what you want for the default worker type. Logs for each request aren’t shown by default, only worker info and errors are shown. To show access logs on stdout, use the `--access-logfile=-` option. Binding Externally ------------------ Gunicorn should not be run as root because it would cause your application code to run as root, which is not secure. However, this means it will not be possible to bind to port 80 or 443. Instead, a reverse proxy such as [nginx](../nginx/index) or [Apache httpd](../apache-httpd/index) should be used in front of Gunicorn. You can bind to all external IPs on a non-privileged port using the `-b 0.0.0.0` option. Don’t do this when using a reverse proxy setup, otherwise it will be possible to bypass the proxy. ``` $ gunicorn -w 4 -b 0.0.0.0 'hello:create_app()' Listening at: http://0.0.0.0:8000 (x) ``` `0.0.0.0` is not a valid address to navigate to, you’d use a specific IP address in your browser. Async with gevent or eventlet ----------------------------- The default sync worker is appropriate for many use cases. If you need asynchronous support, Gunicorn provides workers using either [gevent](https://www.gevent.org/) or [eventlet](https://eventlet.net/). This is not the same as Python’s `async/await`, or the ASGI server spec. You must actually use gevent/eventlet in your own code to see any benefit to using the workers. When using either gevent or eventlet, greenlet>=1.0 is required, otherwise context locals such as `request` will not work as expected. When using PyPy, PyPy>=7.3.7 is required. To use gevent: ``` $ gunicorn -k gevent 'hello:create_app()' Starting gunicorn 20.1.0 Listening at: http://127.0.0.1:8000 (x) Using worker: gevent Booting worker with pid: x ``` To use eventlet: ``` $ gunicorn -k eventlet 'hello:create_app()' Starting gunicorn 20.1.0 Listening at: http://127.0.0.1:8000 (x) Using worker: eventlet Booting worker with pid: x ``` werkzeug mod_wsgi mod\_wsgi ========= [mod\_wsgi](https://modwsgi.readthedocs.io/) is a WSGI server integrated with the [Apache httpd](https://httpd.apache.org/) server. The modern [mod\_wsgi-express](https://pypi.org/project/mod-wsgi/) command makes it easy to configure and start the server without needing to write Apache httpd configuration. * Tightly integrated with Apache httpd. * Supports Windows directly. * Requires a compiler and the Apache development headers to install. * Does not require a reverse proxy setup. This page outlines the basics of running mod\_wsgi-express, not the more complex installation and configuration with httpd. Be sure to read the [mod\_wsgi-express](https://pypi.org/project/mod-wsgi/), [mod\_wsgi](https://modwsgi.readthedocs.io/), and [Apache httpd](https://httpd.apache.org/) documentation to understand what features are available. Installing ---------- Installing mod\_wsgi requires a compiler and the Apache server and development headers installed. You will get an error if they are not. How to install them depends on the OS and package manager that you use. Create a virtualenv, install your application, then install `mod_wsgi`. ``` $ cd hello-app $ python -m venv venv $ . venv/bin/activate $ pip install . # install your application $ pip install mod_wsgi ``` Running ------- The only argument to `mod_wsgi-express` specifies a script containing your application, which must be called `application`. You can write a small script to import your app with this name, or to create it if using the app factory pattern. `wsgi.py` ``` from hello import app application = app ``` `wsgi.py` ``` from hello import create_app application = create_app() ``` Now run the `mod_wsgi-express start-server` command. ``` $ mod_wsgi-express start-server wsgi.py --processes 4 ``` The `--processes` option specifies the number of worker processes to run; a starting value could be `CPU * 2`. Logs for each request aren’t show in the terminal. If an error occurs, its information is written to the error log file shown when starting the server. Binding Externally ------------------ Unlike the other WSGI servers in these docs, mod\_wsgi can be run as root to bind to privileged ports like 80 and 443. However, it must be configured to drop permissions to a different user and group for the worker processes. For example, if you created a `hello` user and group, you should install your virtualenv and application as that user, then tell mod\_wsgi to drop to that user after starting. ``` $ sudo /home/hello/venv/bin/mod_wsgi-express start-server \ /home/hello/wsgi.py \ --user hello --group hello --port 80 --processes 4 ``` werkzeug Tell Werkzeug it is Behind a Proxy Tell Werkzeug it is Behind a Proxy ================================== When using a reverse proxy, or many Python hosting platforms, the proxy will intercept and forward all external requests to the local WSGI server. From the WSGI server and application’s perspectives, requests are now coming from the HTTP server to the local address, rather than from the remote address to the external server address. HTTP servers should set `X-Forwarded-` headers to pass on the real values to the application. The application can then be told to trust and use those values by wrapping it with the [X-Forwarded-For Proxy Fix](../../middleware/proxy_fix/index) middleware provided by Werkzeug. This middleware should only be used if the application is actually behind a proxy, and should be configured with the number of proxies that are chained in front of it. Not all proxies set all the headers. Since incoming headers can be faked, you must set how many proxies are setting each header so the middleware knows what to trust. ``` from werkzeug.middleware.proxy_fix import ProxyFix app.wsgi_app = ProxyFix( app.wsgi_app, x_for=1, x_proto=1, x_host=1, x_prefix=1 ) ``` Remember, only apply this middleware if you are behind a proxy, and set the correct number of proxies that set each header. It can be a security issue if you get this configuration wrong. werkzeug nginx nginx ===== [nginx](https://nginx.org/) is a fast, production level HTTP server. When serving your application with one of the WSGI servers listed in [Deploying to Production](../index), it is often good or necessary to put a dedicated HTTP server in front of it. This β€œreverse proxy” can handle incoming requests, TLS, and other security and performance concerns better than the WSGI server. Nginx can be installed using your system package manager, or a pre-built executable for Windows. Installing and running Nginx itself is outside the scope of this doc. This page outlines the basics of configuring Nginx to proxy your application. Be sure to read its documentation to understand what features are available. Domain Name ----------- Acquiring and configuring a domain name is outside the scope of this doc. In general, you will buy a domain name from a registrar, pay for server space with a hosting provider, and then point your registrar at the hosting provider’s name servers. To simulate this, you can also edit your `hosts` file, located at `/etc/hosts` on Linux. Add a line that associates a name with the local IP. Modern Linux systems may be configured to treat any domain name that ends with `.localhost` like this without adding it to the `hosts` file. `/etc/hosts` ``` 127.0.0.1 hello.localhost ``` Configuration ------------- The nginx configuration is located at `/etc/nginx/nginx.conf` on Linux. It may be different depending on your operating system. Check the docs and look for `nginx.conf`. Remove or comment out any existing `server` section. Add a `server` section and use the `proxy_pass` directive to point to the address the WSGI server is listening on. We’ll assume the WSGI server is listening locally at `http://127.0.0.1:8000`. `/etc/nginx.conf` ``` server { listen 80; server_name _; location / { proxy_pass http://127.0.0.1:8000/; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header X-Forwarded-Host $host; proxy_set_header X-Forwarded-Prefix /; } } ``` Then [Tell Werkzeug it is Behind a Proxy](../proxy_fix/index) so that your application uses these headers. Static Files ------------ If your application has static files such as JavaScript, CSS, and images, it will be more efficient to let Nginx serve them directly rather than going through the Python application. Assuming the static files are expected to be available under the `/static/` URL, and are stored at `/home/project/static/`, add the following to the `server` block above. ``` location /static { alias /home/project/static; } ```
programming_docs
werkzeug uWSGI uWSGI ===== [uWSGI](https://uwsgi-docs.readthedocs.io/en/latest/) is a fast, compiled server suite with extensive configuration and capabilities beyond a basic server. * It can be very performant due to being a compiled program. * It is complex to configure beyond the basic application, and has so many options that it can be difficult for beginners to understand. * It does not support Windows (but does run on WSL). * It requires a compiler to install in some cases. This page outlines the basics of running uWSGI. Be sure to read its documentation to understand what features are available. Installing ---------- uWSGI has multiple ways to install it. The most straightforward is to install the `pyuwsgi` package, which provides precompiled wheels for common platforms. However, it does not provide SSL support, which can be provided with a reverse proxy instead. Create a virtualenv, install your application, then install `pyuwsgi`. ``` $ cd hello-app $ python -m venv venv $ . venv/bin/activate $ pip install . # install your application $ pip install pyuwsgi ``` If you have a compiler available, you can install the `uwsgi` package instead. Or install the `pyuwsgi` package from sdist instead of wheel. Either method will include SSL support. ``` $ pip install uwsgi # or $ pip install --no-binary pyuwsgi pyuwsgi ``` Running ------- The most basic way to run uWSGI is to tell it to start an HTTP server and import your application. ``` $ uwsgi --http 127.0.0.1:8000 --master -p 4 -w hello:app *** Starting uWSGI 2.0.20 (64bit) on [x] *** *** Operational MODE: preforking *** mounting hello:app on / spawned uWSGI master process (pid: x) spawned uWSGI worker 1 (pid: x, cores: 1) spawned uWSGI worker 2 (pid: x, cores: 1) spawned uWSGI worker 3 (pid: x, cores: 1) spawned uWSGI worker 4 (pid: x, cores: 1) spawned uWSGI http 1 (pid: x) ``` If you’re using the app factory pattern, you’ll need to create a small Python file to create the app, then point uWSGI at that. `wsgi.py` ``` from hello import create_app app = create_app() ``` ``` $ uwsgi --http 127.0.0.1:8000 --master -p 4 -w wsgi:app ``` The `--http` option starts an HTTP server at 127.0.0.1 port 8000. The `--master` option specifies the standard worker manager. The `-p` option starts 4 worker processes; a starting value could be `CPU * 2`. The `-w` option tells uWSGI how to import your application Binding Externally ------------------ uWSGI should not be run as root with the configuration shown in this doc because it would cause your application code to run as root, which is not secure. However, this means it will not be possible to bind to port 80 or 443. Instead, a reverse proxy such as [nginx](../nginx/index) or [Apache httpd](../apache-httpd/index) should be used in front of uWSGI. It is possible to run uWSGI as root securely, but that is beyond the scope of this doc. uWSGI has optimized integration with [Nginx uWSGI](https://uwsgi-docs.readthedocs.io/en/latest/Nginx.html) and [Apache mod\_proxy\_uwsgi](https://uwsgi-docs.readthedocs.io/en/latest/Apache.html#mod-proxy-uwsgi), and possibly other servers, instead of using a standard HTTP proxy. That configuration is beyond the scope of this doc, see the links for more information. You can bind to all external IPs on a non-privileged port using the `--http 0.0.0.0:8000` option. Don’t do this when using a reverse proxy setup, otherwise it will be possible to bypass the proxy. ``` $ uwsgi --http 0.0.0.0:8000 --master -p 4 -w wsgi:app ``` `0.0.0.0` is not a valid address to navigate to, you’d use a specific IP address in your browser. Async with gevent ----------------- The default sync worker is appropriate for many use cases. If you need asynchronous support, uWSGI provides a [gevent](https://www.gevent.org/) worker. This is not the same as Python’s `async/await`, or the ASGI server spec. You must actually use gevent in your own code to see any benefit to using the worker. When using gevent, greenlet>=1.0 is required, otherwise context locals such as `request` will not work as expected. When using PyPy, PyPy>=7.3.7 is required. ``` $ uwsgi --http 127.0.0.1:8000 --master --gevent 100 -w wsgi:app *** Starting uWSGI 2.0.20 (64bit) on [x] *** *** Operational MODE: async *** mounting hello:app on / spawned uWSGI master process (pid: x) spawned uWSGI worker 1 (pid: x, cores: 100) spawned uWSGI http 1 (pid: x) *** running gevent loop engine [addr:x] *** ``` werkzeug eventlet eventlet ======== Prefer using [Gunicorn](../gunicorn/index) with eventlet workers rather than using [eventlet](https://eventlet.net/) directly. Gunicorn provides a much more configurable and production-tested server. [eventlet](https://eventlet.net/) allows writing asynchronous, coroutine-based code that looks like standard synchronous Python. It uses [greenlet](https://greenlet.readthedocs.io/en/latest/) to enable task switching without writing `async/await` or using `asyncio`. [gevent](../gevent/index) is another library that does the same thing. Certain dependencies you have, or other considerations, may affect which of the two you choose to use. eventlet provides a WSGI server that can handle many connections at once instead of one per worker process. You must actually use eventlet in your own code to see any benefit to using the server. Installing ---------- When using eventlet, greenlet>=1.0 is required, otherwise context locals such as `request` will not work as expected. When using PyPy, PyPy>=7.3.7 is required. Create a virtualenv, install your application, then install `eventlet`. ``` $ cd hello-app $ python -m venv venv $ . venv/bin/activate $ pip install . # install your application $ pip install eventlet ``` Running ------- To use eventlet to serve your application, write a script that imports its `wsgi.server`, as well as your app or app factory. `wsgi.py` ``` import eventlet from eventlet import wsgi from hello import create_app app = create_app() wsgi.server(eventlet.listen(("127.0.0.1", 8000), app) ``` ``` $ python wsgi.py (x) wsgi starting up on http://127.0.0.1:8000 ``` Binding Externally ------------------ eventlet should not be run as root because it would cause your application code to run as root, which is not secure. However, this means it will not be possible to bind to port 80 or 443. Instead, a reverse proxy such as [nginx](../nginx/index) or [Apache httpd](../apache-httpd/index) should be used in front of eventlet. You can bind to all external IPs on a non-privileged port by using `0.0.0.0` in the server arguments shown in the previous section. Don’t do this when using a reverse proxy setup, otherwise it will be possible to bypass the proxy. `0.0.0.0` is not a valid address to navigate to, you’d use a specific IP address in your browser. werkzeug URL Routing URL Routing =========== When it comes to combining multiple controller or view functions (however you want to call them), you need a dispatcher. A simple way would be applying regular expression tests on `PATH_INFO` and call registered callback functions that return the value. Werkzeug provides a much more powerful system, similar to [Routes](https://routes.readthedocs.io/en/latest/). All the objects mentioned on this page must be imported from [`werkzeug.routing`](#module-werkzeug.routing "werkzeug.routing"), not from `werkzeug`! Quickstart ---------- Here is a simple example which could be the URL definition for a blog: ``` from werkzeug.routing import Map, Rule, NotFound, RequestRedirect url_map = Map([ Rule('/', endpoint='blog/index'), Rule('/<int:year>/', endpoint='blog/archive'), Rule('/<int:year>/<int:month>/', endpoint='blog/archive'), Rule('/<int:year>/<int:month>/<int:day>/', endpoint='blog/archive'), Rule('/<int:year>/<int:month>/<int:day>/<slug>', endpoint='blog/show_post'), Rule('/about', endpoint='blog/about_me'), Rule('/feeds/', endpoint='blog/feeds'), Rule('/feeds/<feed_name>.rss', endpoint='blog/show_feed') ]) def application(environ, start_response): urls = url_map.bind_to_environ(environ) try: endpoint, args = urls.match() except HTTPException, e: return e(environ, start_response) start_response('200 OK', [('Content-Type', 'text/plain')]) return [f'Rule points to {endpoint!r} with arguments {args!r}'.encode()] ``` So what does that do? First of all we create a new [`Map`](#werkzeug.routing.Map "werkzeug.routing.Map") which stores a bunch of URL rules. Then we pass it a list of [`Rule`](#werkzeug.routing.Rule "werkzeug.routing.Rule") objects. Each [`Rule`](#werkzeug.routing.Rule "werkzeug.routing.Rule") object is instantiated with a string that represents a rule and an endpoint which will be the alias for what view the rule represents. Multiple rules can have the same endpoint, but should have different arguments to allow URL construction. The format for the URL rules is straightforward, but explained in detail below. Inside the WSGI application we bind the url\_map to the current request which will return a new [`MapAdapter`](#werkzeug.routing.MapAdapter "werkzeug.routing.MapAdapter"). This url\_map adapter can then be used to match or build domains for the current request. The [`MapAdapter.match()`](#werkzeug.routing.MapAdapter.match "werkzeug.routing.MapAdapter.match") method can then either return a tuple in the form `(endpoint, args)` or raise one of the three exceptions [`NotFound`](../exceptions/index#werkzeug.exceptions.NotFound "werkzeug.exceptions.NotFound"), [`MethodNotAllowed`](../exceptions/index#werkzeug.exceptions.MethodNotAllowed "werkzeug.exceptions.MethodNotAllowed"), or `RequestRedirect`. For more details about those exceptions have a look at the documentation of the [`MapAdapter.match()`](#werkzeug.routing.MapAdapter.match "werkzeug.routing.MapAdapter.match") method. Rule Format ----------- Rule strings are URL paths with placeholders for variable parts in the format `<converter(arguments):name>`. `converter` and `arguments` (with parentheses) are optional. If no converter is given, the `default` converter is used (`string` by default). The available converters are discussed below. Rules that end with a slash are β€œbranches”, others are β€œleaves”. If `strict_slashes` is enabled (the default), visiting a branch URL without a trailing slash will redirect to the URL with a slash appended. Many HTTP servers merge consecutive slashes into one when receiving requests. If `merge_slashes` is enabled (the default), rules will merge slashes in non-variable parts when matching and building. Visiting a URL with consecutive slashes will redirect to the URL with slashes merged. If you want to disable `merge_slashes` for a [`Rule`](#werkzeug.routing.Rule "werkzeug.routing.Rule") or [`Map`](#werkzeug.routing.Map "werkzeug.routing.Map"), you’ll also need to configure your web server appropriately. Built-in Converters ------------------- Converters for common types of URL variables are built-in. The available converters can be overridden or extended through [`Map.converters`](#werkzeug.routing.Map.converters "werkzeug.routing.Map.converters"). `class werkzeug.routing.UnicodeConverter(map, minlength=1, maxlength=None, length=None)` This converter is the default converter and accepts any string but only one path segment. Thus the string can not include a slash. This is the default validator. Example: ``` Rule('/pages/<page>'), Rule('/<string(length=2):lang_code>') ``` Parameters: * **map** ([Map](#werkzeug.routing.Map "werkzeug.routing.Map")) – the [`Map`](#werkzeug.routing.Map "werkzeug.routing.Map"). * **minlength** ([int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")) – the minimum length of the string. Must be greater or equal 1. * **maxlength** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")*]*) – the maximum length of the string. * **length** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")*]*) – the exact length of the string. `class werkzeug.routing.PathConverter(map, *args, **kwargs)` Like the default [`UnicodeConverter`](#werkzeug.routing.UnicodeConverter "werkzeug.routing.UnicodeConverter"), but it also matches slashes. This is useful for wikis and similar applications: ``` Rule('/<path:wikipage>') Rule('/<path:wikipage>/edit') ``` Parameters: * **map** ([Map](#werkzeug.routing.Map "werkzeug.routing.Map")) – the [`Map`](#werkzeug.routing.Map "werkzeug.routing.Map"). * **args** ([Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")) – * **kwargs** ([Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")) – `class werkzeug.routing.AnyConverter(map, *items)` Matches one of the items provided. Items can either be Python identifiers or strings: ``` Rule('/<any(about, help, imprint, class, "foo,bar"):page_name>') ``` Parameters: * **map** ([Map](#werkzeug.routing.Map "werkzeug.routing.Map")) – the [`Map`](#werkzeug.routing.Map "werkzeug.routing.Map"). * **items** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – this function accepts the possible items as positional arguments. Changed in version 2.2: Value is validated when building a URL. `class werkzeug.routing.IntegerConverter(map, fixed_digits=0, min=None, max=None, signed=False)` This converter only accepts integer values: ``` Rule("/page/<int:page>") ``` By default it only accepts unsigned, positive values. The `signed` parameter will enable signed, negative values. ``` Rule("/page/<int(signed=True):page>") ``` Parameters: * **map** ([Map](#werkzeug.routing.Map "werkzeug.routing.Map")) – The [`Map`](#werkzeug.routing.Map "werkzeug.routing.Map"). * **fixed\_digits** ([int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")) – The number of fixed digits in the URL. If you set this to `4` for example, the rule will only match if the URL looks like `/0001/`. The default is variable length. * **min** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")*]*) – The minimal value. * **max** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[int](https://docs.python.org/3/library/functions.html#int "(in Python v3.10)")*]*) – The maximal value. * **signed** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – Allow signed (negative) values. Changelog New in version 0.15: The `signed` parameter. `class werkzeug.routing.FloatConverter(map, min=None, max=None, signed=False)` This converter only accepts floating point values: ``` Rule("/probability/<float:probability>") ``` By default it only accepts unsigned, positive values. The `signed` parameter will enable signed, negative values. ``` Rule("/offset/<float(signed=True):offset>") ``` Parameters: * **map** ([Map](#werkzeug.routing.Map "werkzeug.routing.Map")) – The [`Map`](#werkzeug.routing.Map "werkzeug.routing.Map"). * **min** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.10)")*]*) – The minimal value. * **max** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[float](https://docs.python.org/3/library/functions.html#float "(in Python v3.10)")*]*) – The maximal value. * **signed** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – Allow signed (negative) values. Changelog New in version 0.15: The `signed` parameter. `class werkzeug.routing.UUIDConverter(map, *args, **kwargs)` This converter only accepts UUID strings: ``` Rule('/object/<uuid:identifier>') ``` Changelog New in version 0.10. Parameters: * **map** ([Map](#werkzeug.routing.Map "werkzeug.routing.Map")) – the [`Map`](#werkzeug.routing.Map "werkzeug.routing.Map"). * **args** ([Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")) – * **kwargs** ([Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")) – Maps, Rules and Adapters ------------------------ `class werkzeug.routing.Map(rules=None, default_subdomain='', charset='utf-8', strict_slashes=True, merge_slashes=True, redirect_defaults=True, converters=None, sort_parameters=False, sort_key=None, encoding_errors='replace', host_matching=False)` The map class stores all the URL rules and some configuration parameters. Some of the configuration values are only stored on the `Map` instance since those affect all rules, others are just defaults and can be overridden for each rule. Note that you have to specify all arguments besides the `rules` as keyword arguments! Parameters: * **rules** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Iterable](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.10)")*[*[RuleFactory](#werkzeug.routing.RuleFactory "werkzeug.routing.RuleFactory")*]**]*) – sequence of url rules for this map. * **default\_subdomain** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – The default subdomain for rules without a subdomain defined. * **charset** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – charset of the url. defaults to `"utf-8"` * **strict\_slashes** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – If a rule ends with a slash but the matched URL does not, redirect to the URL with a trailing slash. * **merge\_slashes** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – Merge consecutive slashes when matching or building URLs. Matches will redirect to the normalized URL. Slashes in variable parts are not merged. * **redirect\_defaults** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – This will redirect to the default rule if it wasn’t visited that way. This helps creating unique URLs. * **converters** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Mapping](https://docs.python.org/3/library/typing.html#typing.Mapping "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [Type](https://docs.python.org/3/library/typing.html#typing.Type "(in Python v3.10)")*[**BaseConverter**]**]**]*) – A dict of converters that adds additional converters to the list of converters. If you redefine one converter this will override the original one. * **sort\_parameters** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – If set to `True` the url parameters are sorted. See `url_encode` for more details. * **sort\_key** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Callable](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.10)")*[**[*[Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")*]**,* [Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")*]**]*) – The sort key function for `url_encode`. * **encoding\_errors** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – the error method to use for decoding * **host\_matching** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – if set to `True` it enables the host matching feature and disables the subdomain one. If enabled the `host` parameter to rules is used instead of the `subdomain` one. Changelog Changed in version 1.0: If `url_scheme` is `ws` or `wss`, only WebSocket rules will match. Changed in version 1.0: Added `merge_slashes`. Changed in version 0.7: Added `encoding_errors` and `host_matching`. Changed in version 0.5: Added `sort_parameters` and `sort_key`. `converters` The dictionary of converters. This can be modified after the class was created, but will only affect rules added after the modification. If the rules are defined with the list passed to the class, the `converters` parameter to the constructor has to be used instead. `add(rulefactory)` Add a new rule or factory to the map and bind it. Requires that the rule is not bound to another map. Parameters: **rulefactory** ([RuleFactory](#werkzeug.routing.RuleFactory "werkzeug.routing.RuleFactory")) – a [`Rule`](#werkzeug.routing.Rule "werkzeug.routing.Rule") or [`RuleFactory`](#werkzeug.routing.RuleFactory "werkzeug.routing.RuleFactory") Return type: None `bind(server_name, script_name=None, subdomain=None, url_scheme='http', default_method='GET', path_info=None, query_args=None)` Return a new [`MapAdapter`](#werkzeug.routing.MapAdapter "werkzeug.routing.MapAdapter") with the details specified to the call. Note that `script_name` will default to `'/'` if not further specified or `None`. The `server_name` at least is a requirement because the HTTP RFC requires absolute URLs for redirects and so all redirect exceptions raised by Werkzeug will contain the full canonical URL. If no path\_info is passed to `match()` it will use the default path info passed to bind. While this doesn’t really make sense for manual bind calls, it’s useful if you bind a map to a WSGI environment which already contains the path info. `subdomain` will default to the `default_subdomain` for this map if no defined. If there is no `default_subdomain` you cannot use the subdomain feature. Changelog Changed in version 1.0: If `url_scheme` is `ws` or `wss`, only WebSocket rules will match. Changed in version 0.15: `path_info` defaults to `'/'` if `None`. Changed in version 0.8: `query_args` can be a string. Changed in version 0.7: Added `query_args`. Parameters: * **server\_name** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – * **script\_name** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – * **subdomain** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – * **url\_scheme** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – * **default\_method** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – * **path\_info** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – * **query\_args** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[*[Mapping](https://docs.python.org/3/library/typing.html#typing.Mapping "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")*]**,* [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]**]*) – Return type: [MapAdapter](#werkzeug.routing.MapAdapter "werkzeug.routing.map.MapAdapter") `bind_to_environ(environ, server_name=None, subdomain=None)` Like [`bind()`](#werkzeug.routing.Map.bind "werkzeug.routing.Map.bind") but you can pass it an WSGI environment and it will fetch the information from that dictionary. Note that because of limitations in the protocol there is no way to get the current subdomain and real `server_name` from the environment. If you don’t provide it, Werkzeug will use `SERVER_NAME` and `SERVER_PORT` (or `HTTP_HOST` if provided) as used `server_name` with disabled subdomain feature. If `subdomain` is `None` but an environment and a server name is provided it will calculate the current subdomain automatically. Example: `server_name` is `'example.com'` and the `SERVER_NAME` in the wsgi `environ` is `'staging.dev.example.com'` the calculated subdomain will be `'staging.dev'`. If the object passed as environ has an environ attribute, the value of this attribute is used instead. This allows you to pass request objects. Additionally `PATH_INFO` added as a default of the [`MapAdapter`](#werkzeug.routing.MapAdapter "werkzeug.routing.MapAdapter") so that you don’t have to pass the path info to the match method. Changelog Changed in version 1.0.0: If the passed server name specifies port 443, it will match if the incoming scheme is `https` without a port. Changed in version 1.0.0: A warning is shown when the passed server name does not match the incoming WSGI server name. Changed in version 0.8: This will no longer raise a ValueError when an unexpected server name was passed. Changed in version 0.5: previously this method accepted a bogus `calculate_subdomain` parameter that did not have any effect. It was removed because of that. Parameters: * **environ** ([Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[**WSGIEnvironment**,* [Request](../wrappers/index#werkzeug.wrappers.Request "werkzeug.wrappers.Request")*]*) – a WSGI environment. * **server\_name** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – an optional server name hint (see above). * **subdomain** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – optionally the current subdomain (see above). Return type: [MapAdapter](#werkzeug.routing.MapAdapter "werkzeug.routing.MapAdapter") `default_converters = {'any': <class 'werkzeug.routing.converters.AnyConverter'>, 'default': <class 'werkzeug.routing.converters.UnicodeConverter'>, 'float': <class 'werkzeug.routing.converters.FloatConverter'>, 'int': <class 'werkzeug.routing.converters.IntegerConverter'>, 'path': <class 'werkzeug.routing.converters.PathConverter'>, 'string': <class 'werkzeug.routing.converters.UnicodeConverter'>, 'uuid': <class 'werkzeug.routing.converters.UUIDConverter'>}` A dict of default converters to be used. `is_endpoint_expecting(endpoint, *arguments)` Iterate over all rules and check if the endpoint expects the arguments provided. This is for example useful if you have some URLs that expect a language code and others that do not and you want to wrap the builder a bit so that the current language code is automatically added if not provided but endpoints expect it. Parameters: * **endpoint** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – the endpoint to check. * **arguments** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – this function accepts one or more arguments as positional arguments. Each one of them is checked. Return type: [bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)") `iter_rules(endpoint=None)` Iterate over all rules or the rules of an endpoint. Parameters: **endpoint** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – if provided only the rules for that endpoint are returned. Returns: an iterator Return type: [Iterator](https://docs.python.org/3/library/typing.html#typing.Iterator "(in Python v3.10)")[[Rule](#werkzeug.routing.Rule "werkzeug.routing.rules.Rule")] `lock_class()` The type of lock to use when updating. Changelog New in version 1.0. `update()` Called before matching and building to keep the compiled rules in the correct order after things changed. Return type: None `class werkzeug.routing.MapAdapter(map, server_name, script_name, subdomain, url_scheme, path_info, default_method, query_args=None)` Returned by [`Map.bind()`](#werkzeug.routing.Map.bind "werkzeug.routing.Map.bind") or [`Map.bind_to_environ()`](#werkzeug.routing.Map.bind_to_environ "werkzeug.routing.Map.bind_to_environ") and does the URL matching and building based on runtime information. Parameters: * **map** ([Map](#werkzeug.routing.Map "werkzeug.routing.map.Map")) – * **server\_name** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – * **script\_name** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – * **subdomain** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – * **url\_scheme** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – * **path\_info** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – * **default\_method** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – * **query\_args** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[*[Mapping](https://docs.python.org/3/library/typing.html#typing.Mapping "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")*]**,* [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]**]*) – `allowed_methods(path_info=None)` Returns the valid methods that match for a given path. Changelog New in version 0.7. Parameters: **path\_info** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – Return type: [Iterable](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.10)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")] `build(endpoint, values=None, method=None, force_external=False, append_unknown=True, url_scheme=None)` Building URLs works pretty much the other way round. Instead of `match` you call `build` and pass it the endpoint and a dict of arguments for the placeholders. The `build` function also accepts an argument called `force_external` which, if you set it to `True` will force external URLs. Per default external URLs (include the server name) will only be used if the target URL is on a different subdomain. ``` >>> m = Map([ ... Rule('/', endpoint='index'), ... Rule('/downloads/', endpoint='downloads/index'), ... Rule('/downloads/<int:id>', endpoint='downloads/show') ... ]) >>> urls = m.bind("example.com", "/") >>> urls.build("index", {}) '/' >>> urls.build("downloads/show", {'id': 42}) '/downloads/42' >>> urls.build("downloads/show", {'id': 42}, force_external=True) 'http://example.com/downloads/42' ``` Because URLs cannot contain non ASCII data you will always get bytes back. Non ASCII characters are urlencoded with the charset defined on the map instance. Additional values are converted to strings and appended to the URL as URL querystring parameters: ``` >>> urls.build("index", {'q': 'My Searchstring'}) '/?q=My+Searchstring' ``` When processing those additional values, lists are furthermore interpreted as multiple values (as per [`werkzeug.datastructures.MultiDict`](../datastructures/index#werkzeug.datastructures.MultiDict "werkzeug.datastructures.MultiDict")): ``` >>> urls.build("index", {'q': ['a', 'b', 'c']}) '/?q=a&q=b&q=c' ``` Passing a `MultiDict` will also add multiple values: ``` >>> urls.build("index", MultiDict((('p', 'z'), ('q', 'a'), ('q', 'b')))) '/?p=z&q=a&q=b' ``` If a rule does not exist when building a `BuildError` exception is raised. The build method accepts an argument called `method` which allows you to specify the method you want to have an URL built for if you have different methods for the same endpoint specified. Parameters: * **endpoint** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – the endpoint of the URL to build. * **values** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Mapping](https://docs.python.org/3/library/typing.html#typing.Mapping "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")*]**]*) – the values for the URL to build. Unhandled values are appended to the URL as query parameters. * **method** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – the HTTP method for the rule if there are different URLs for different methods on the same endpoint. * **force\_external** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – enforce full canonical external URLs. If the URL scheme is not provided, this will generate a protocol-relative URL. * **append\_unknown** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – unknown parameters are appended to the generated URL as query string argument. Disable this if you want the builder to ignore those. * **url\_scheme** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – Scheme to use in place of the bound `url_scheme`. Return type: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") Changelog Changed in version 2.0: Added the `url_scheme` parameter. New in version 0.6: Added the `append_unknown` parameter. `dispatch(view_func, path_info=None, method=None, catch_http_exceptions=False)` Does the complete dispatching process. `view_func` is called with the endpoint and a dict with the values for the view. It should look up the view function, call it, and return a response object or WSGI application. http exceptions are not caught by default so that applications can display nicer error messages by just catching them by hand. If you want to stick with the default error messages you can pass it `catch_http_exceptions=True` and it will catch the http exceptions. Here a small example for the dispatch usage: ``` from werkzeug.wrappers import Request, Response from werkzeug.wsgi import responder from werkzeug.routing import Map, Rule def on_index(request): return Response('Hello from the index') url_map = Map([Rule('/', endpoint='index')]) views = {'index': on_index} @responder def application(environ, start_response): request = Request(environ) urls = url_map.bind_to_environ(environ) return urls.dispatch(lambda e, v: views[e](request, **v), catch_http_exceptions=True) ``` Keep in mind that this method might return exception objects, too, so use `Response.force_type` to get a response object. Parameters: * **view\_func** ([Callable](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.10)")*[**[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [Mapping](https://docs.python.org/3/library/typing.html#typing.Mapping "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")*]**]**,* *WSGIApplication**]*) – a function that is called with the endpoint as first argument and the value dict as second. Has to dispatch to the actual view function with this information. (see above) * **path\_info** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – the path info to use for matching. Overrides the path info specified on binding. * **method** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – the HTTP method used for matching. Overrides the method specified on binding. * **catch\_http\_exceptions** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – set to `True` to catch any of the werkzeug `HTTPException`s. Return type: WSGIApplication `get_host(domain_part)` Figures out the full host name for the given domain part. The domain part is a subdomain in case host matching is disabled or a full host name. Parameters: **domain\_part** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – Return type: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") `make_alias_redirect_url(path, endpoint, values, method, query_args)` Internally called to make an alias redirect URL. Parameters: * **path** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – * **endpoint** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – * **values** ([Mapping](https://docs.python.org/3/library/typing.html#typing.Mapping "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")*]*) – * **method** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – * **query\_args** ([Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[*[Mapping](https://docs.python.org/3/library/typing.html#typing.Mapping "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")*]**,* [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – Return type: [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)") `match(path_info: Optional[str] = None, method: Optional[str] = None, return_rule: te.Literal[False] = False, query_args: Optional[Union[Mapping[str, Any], str]] = None, websocket: Optional[bool] = None) β†’ Tuple[str, Mapping[str, Any]]` match(*path\_info:[Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")]=None*, *method:[Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")]=None*, *return\_rule:te.Literal[True]=True*, *query\_args:[Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")[[Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")[[Mapping](https://docs.python.org/3/library/typing.html#typing.Mapping "(in Python v3.10)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)"),[Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")],[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")]]=None*, *websocket:[Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")[[bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")]=None*) β†’ [Tuple](https://docs.python.org/3/library/typing.html#typing.Tuple "(in Python v3.10)")[[Rule](#werkzeug.routing.Rule "werkzeug.routing.rules.Rule"),[Mapping](https://docs.python.org/3/library/typing.html#typing.Mapping "(in Python v3.10)")[[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)"),[Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")]] The usage is simple: you just pass the match method the current path info as well as the method (which defaults to `GET`). The following things can then happen: * you receive a `NotFound` exception that indicates that no URL is matching. A `NotFound` exception is also a WSGI application you can call to get a default page not found page (happens to be the same object as `werkzeug.exceptions.NotFound`) * you receive a `MethodNotAllowed` exception that indicates that there is a match for this URL but not for the current request method. This is useful for RESTful applications. * you receive a `RequestRedirect` exception with a `new_url` attribute. This exception is used to notify you about a request Werkzeug requests from your WSGI application. This is for example the case if you request `/foo` although the correct URL is `/foo/` You can use the `RequestRedirect` instance as response-like object similar to all other subclasses of `HTTPException`. * you receive a `WebsocketMismatch` exception if the only match is a WebSocket rule but the bind is an HTTP request, or if the match is an HTTP rule but the bind is a WebSocket request. * you get a tuple in the form `(endpoint, arguments)` if there is a match (unless `return_rule` is True, in which case you get a tuple in the form `(rule, arguments)`) If the path info is not passed to the match method the default path info of the map is used (defaults to the root URL if not defined explicitly). All of the exceptions raised are subclasses of `HTTPException` so they can be used as WSGI responses. They will all render generic error or redirect pages. Here is a small example for matching: ``` >>> m = Map([ ... Rule('/', endpoint='index'), ... Rule('/downloads/', endpoint='downloads/index'), ... Rule('/downloads/<int:id>', endpoint='downloads/show') ... ]) >>> urls = m.bind("example.com", "/") >>> urls.match("/", "GET") ('index', {}) >>> urls.match("/downloads/42") ('downloads/show', {'id': 42}) ``` And here is what happens on redirect and missing URLs: ``` >>> urls.match("/downloads") Traceback (most recent call last): ... RequestRedirect: http://example.com/downloads/ >>> urls.match("/missing") Traceback (most recent call last): ... NotFound: 404 Not Found ``` Parameters: * **path\_info** – the path info to use for matching. Overrides the path info specified on binding. * **method** – the HTTP method used for matching. Overrides the method specified on binding. * **return\_rule** – return the rule that matched instead of just the endpoint (defaults to `False`). * **query\_args** – optional query arguments that are used for automatic redirects as string or dictionary. It’s currently not possible to use the query arguments for URL matching. * **websocket** – Match WebSocket instead of HTTP requests. A websocket request has a `ws` or `wss` `url_scheme`. This overrides that detection. Changelog New in version 1.0: Added `websocket`. Changed in version 0.8: `query_args` can be a string. New in version 0.7: Added `query_args`. New in version 0.6: Added `return_rule`. `test(path_info=None, method=None)` Test if a rule would match. Works like `match` but returns `True` if the URL matches, or `False` if it does not exist. Parameters: * **path\_info** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – the path info to use for matching. Overrides the path info specified on binding. * **method** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – the HTTP method used for matching. Overrides the method specified on binding. Return type: [bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)") `class werkzeug.routing.Rule(string, defaults=None, subdomain=None, methods=None, build_only=False, endpoint=None, strict_slashes=None, merge_slashes=None, redirect_to=None, alias=False, host=None, websocket=False)` A Rule represents one URL pattern. There are some options for `Rule` that change the way it behaves and are passed to the `Rule` constructor. Note that besides the rule-string all arguments *must* be keyword arguments in order to not break the application on Werkzeug upgrades. `string` Rule strings basically are just normal URL paths with placeholders in the format `<converter(arguments):name>` where the converter and the arguments are optional. If no converter is defined the `default` converter is used which means `string` in the normal configuration. URL rules that end with a slash are branch URLs, others are leaves. If you have `strict_slashes` enabled (which is the default), all branch URLs that are matched without a trailing slash will trigger a redirect to the same URL with the missing slash appended. The converters are defined on the `Map`. `endpoint` The endpoint for this rule. This can be anything. A reference to a function, a string, a number etc. The preferred way is using a string because the endpoint is used for URL generation. `defaults` An optional dict with defaults for other rules with the same endpoint. This is a bit tricky but useful if you want to have unique URLs: ``` url_map = Map([ Rule('/all/', defaults={'page': 1}, endpoint='all_entries'), Rule('/all/page/<int:page>', endpoint='all_entries') ]) ``` If a user now visits `http://example.com/all/page/1` they will be redirected to `http://example.com/all/`. If `redirect_defaults` is disabled on the `Map` instance this will only affect the URL generation. `subdomain` The subdomain rule string for this rule. If not specified the rule only matches for the `default_subdomain` of the map. If the map is not bound to a subdomain this feature is disabled. Can be useful if you want to have user profiles on different subdomains and all subdomains are forwarded to your application: ``` url_map = Map([ Rule('/', subdomain='<username>', endpoint='user/homepage'), Rule('/stats', subdomain='<username>', endpoint='user/stats') ]) ``` `methods` A sequence of http methods this rule applies to. If not specified, all methods are allowed. For example this can be useful if you want different endpoints for `POST` and `GET`. If methods are defined and the path matches but the method matched against is not in this list or in the list of another rule for that path the error raised is of the type `MethodNotAllowed` rather than `NotFound`. If `GET` is present in the list of methods and `HEAD` is not, `HEAD` is added automatically. `strict_slashes` Override the `Map` setting for `strict_slashes` only for this rule. If not specified the `Map` setting is used. `merge_slashes` Override `Map.merge_slashes` for this rule. `build_only` Set this to True and the rule will never match but will create a URL that can be build. This is useful if you have resources on a subdomain or folder that are not handled by the WSGI application (like static data) `redirect_to` If given this must be either a string or callable. In case of a callable it’s called with the url adapter that triggered the match and the values of the URL as keyword arguments and has to return the target for the redirect, otherwise it has to be a string with placeholders in rule syntax: ``` def foo_with_slug(adapter, id): # ask the database for the slug for the old id. this of # course has nothing to do with werkzeug. return f'foo/{Foo.get_slug_for_id(id)}' url_map = Map([ Rule('/foo/<slug>', endpoint='foo'), Rule('/some/old/url/<slug>', redirect_to='foo/<slug>'), Rule('/other/old/url/<int:id>', redirect_to=foo_with_slug) ]) ``` When the rule is matched the routing system will raise a `RequestRedirect` exception with the target for the redirect. Keep in mind that the URL will be joined against the URL root of the script so don’t use a leading slash on the target URL unless you really mean root of that domain. `alias` If enabled this rule serves as an alias for another rule with the same endpoint and arguments. `host` If provided and the URL map has host matching enabled this can be used to provide a match rule for the whole host. This also means that the subdomain feature is disabled. `websocket` If `True`, this rule is only matches for WebSocket (`ws://`, `wss://`) requests. By default, rules will only match for HTTP requests. Changelog Changed in version 2.1: Percent-encoded newlines (`%0a`), which are decoded by WSGI servers, are considered when routing instead of terminating the match early. New in version 1.0: Added `websocket`. New in version 1.0: Added `merge_slashes`. New in version 0.7: Added `alias` and `host`. Changed in version 0.6.1: `HEAD` is added to `methods` if `GET` is present. Parameters: * **string** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – * **defaults** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Mapping](https://docs.python.org/3/library/typing.html#typing.Mapping "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [Any](https://docs.python.org/3/library/typing.html#typing.Any "(in Python v3.10)")*]**]*) – * **subdomain** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – * **methods** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Iterable](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]**]*) – * **build\_only** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – * **endpoint** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – * **strict\_slashes** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")*]*) – * **merge\_slashes** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")*]*) – * **redirect\_to** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[Union](https://docs.python.org/3/library/typing.html#typing.Union "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*,* [Callable](https://docs.python.org/3/library/typing.html#typing.Callable "(in Python v3.10)")*[**[**...**]**,* [str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]**]**]*) – * **alias** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – * **host** ([Optional](https://docs.python.org/3/library/typing.html#typing.Optional "(in Python v3.10)")*[*[str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")*]*) – * **websocket** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – `empty()` Return an unbound copy of this rule. This can be useful if want to reuse an already bound URL for another map. See `get_empty_kwargs` to override what keyword arguments are provided to the new copy. Return type: [Rule](#werkzeug.routing.Rule "werkzeug.routing.rules.Rule") Matchers -------- `class werkzeug.routing.StateMachineMatcher(merge_slashes)` Parameters: **merge\_slashes** ([bool](https://docs.python.org/3/library/functions.html#bool "(in Python v3.10)")) – Rule Factories -------------- `class werkzeug.routing.RuleFactory` As soon as you have more complex URL setups it’s a good idea to use rule factories to avoid repetitive tasks. Some of them are builtin, others can be added by subclassing `RuleFactory` and overriding `get_rules`. `get_rules(map)` Subclasses of `RuleFactory` have to override this method and return an iterable of rules. Parameters: **map** ([Map](#werkzeug.routing.Map "werkzeug.routing.Map")) – Return type: [Iterable](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.10)")[[Rule](#werkzeug.routing.Rule "werkzeug.routing.Rule")] `class werkzeug.routing.Subdomain(subdomain, rules)` All URLs provided by this factory have the subdomain set to a specific domain. For example if you want to use the subdomain for the current language this can be a good setup: ``` url_map = Map([ Rule('/', endpoint='#select_language'), Subdomain('<string(length=2):lang_code>', [ Rule('/', endpoint='index'), Rule('/about', endpoint='about'), Rule('/help', endpoint='help') ]) ]) ``` All the rules except for the `'#select_language'` endpoint will now listen on a two letter long subdomain that holds the language code for the current request. Parameters: * **subdomain** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – * **rules** ([Iterable](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.10)")*[*[RuleFactory](#werkzeug.routing.RuleFactory "werkzeug.routing.rules.RuleFactory")*]*) – `class werkzeug.routing.Submount(path, rules)` Like `Subdomain` but prefixes the URL rule with a given string: ``` url_map = Map([ Rule('/', endpoint='index'), Submount('/blog', [ Rule('/', endpoint='blog/index'), Rule('/entry/<entry_slug>', endpoint='blog/show') ]) ]) ``` Now the rule `'blog/show'` matches `/blog/entry/<entry_slug>`. Parameters: * **path** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – * **rules** ([Iterable](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.10)")*[*[RuleFactory](#werkzeug.routing.RuleFactory "werkzeug.routing.rules.RuleFactory")*]*) – `class werkzeug.routing.EndpointPrefix(prefix, rules)` Prefixes all endpoints (which must be strings for this factory) with another string. This can be useful for sub applications: ``` url_map = Map([ Rule('/', endpoint='index'), EndpointPrefix('blog/', [Submount('/blog', [ Rule('/', endpoint='index'), Rule('/entry/<entry_slug>', endpoint='show') ])]) ]) ``` Parameters: * **prefix** ([str](https://docs.python.org/3/library/stdtypes.html#str "(in Python v3.10)")) – * **rules** ([Iterable](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.10)")*[*[RuleFactory](#werkzeug.routing.RuleFactory "werkzeug.routing.rules.RuleFactory")*]*) – Rule Templates -------------- `class werkzeug.routing.RuleTemplate(rules)` Returns copies of the rules wrapped and expands string templates in the endpoint, rule, defaults or subdomain sections. Here a small example for such a rule template: ``` from werkzeug.routing import Map, Rule, RuleTemplate resource = RuleTemplate([ Rule('/$name/', endpoint='$name.list'), Rule('/$name/<int:id>', endpoint='$name.show') ]) url_map = Map([resource(name='user'), resource(name='page')]) ``` When a rule template is called the keyword arguments are used to replace the placeholders in all the string parameters. Parameters: **rules** ([Iterable](https://docs.python.org/3/library/typing.html#typing.Iterable "(in Python v3.10)")*[*[Rule](#werkzeug.routing.Rule "werkzeug.routing.Rule")*]*) – Custom Converters ----------------- You can add custom converters that add behaviors not provided by the built-in converters. To make a custom converter, subclass `BaseConverter` then pass the new class to the [`Map`](#werkzeug.routing.Map "werkzeug.routing.Map") `converters` parameter, or add it to [`url_map.converters`](#werkzeug.routing.Map.converters "werkzeug.routing.Map.converters"). The converter should have a `regex` attribute with a regular expression to match with. If the converter can take arguments in a URL rule, it should accept them in its `__init__` method. The entire regex expression will be matched as a group and used as the value for conversion. If a custom converter can match a forward slash, `/`, it should have the attribute `part_isolating` set to `False`. This will ensure that rules using the custom converter are correctly matched. It can implement a `to_python` method to convert the matched string to some other object. This can also do extra validation that wasn’t possible with the `regex` attribute, and should raise a `werkzeug.routing.ValidationError` in that case. Raising any other errors will cause a 500 error. It can implement a `to_url` method to convert a Python object to a string when building a URL. Any error raised here will be converted to a `werkzeug.routing.BuildError` and eventually cause a 500 error. This example implements a `BooleanConverter` that will match the strings `"yes"`, `"no"`, and `"maybe"`, returning a random value for `"maybe"`. ``` from random import randrange from werkzeug.routing import BaseConverter, ValidationError class BooleanConverter(BaseConverter): regex = r"(?:yes|no|maybe)" def __init__(self, url_map, maybe=False): super().__init__(url_map) self.maybe = maybe def to_python(self, value): if value == "maybe": if self.maybe: return not randrange(2) raise ValidationError return value == 'yes' def to_url(self, value): return "yes" if value else "no" from werkzeug.routing import Map, Rule url_map = Map([ Rule("/vote/<bool:werkzeug_rocks>", endpoint="vote"), Rule("/guess/<bool(maybe=True):foo>", endpoint="guess") ], converters={'bool': BooleanConverter}) ``` If you want to change the default converter, assign a different converter to the `"default"` key. Host Matching ------------- Changelog New in version 0.7. Starting with Werkzeug 0.7 it’s also possible to do matching on the whole host names instead of just the subdomain. To enable this feature you need to pass `host_matching=True` to the [`Map`](#werkzeug.routing.Map "werkzeug.routing.Map") constructor and provide the `host` argument to all routes: ``` url_map = Map([ Rule('/', endpoint='www_index', host='www.example.com'), Rule('/', endpoint='help_index', host='help.example.com') ], host_matching=True) ``` Variable parts are of course also possible in the host section: ``` url_map = Map([ Rule('/', endpoint='www_index', host='www.example.com'), Rule('/', endpoint='user_index', host='<user>.example.com') ], host_matching=True) ``` WebSockets ---------- Changelog New in version 1.0. If a [`Rule`](#werkzeug.routing.Rule "werkzeug.routing.Rule") is created with `websocket=True`, it will only match if the [`Map`](#werkzeug.routing.Map "werkzeug.routing.Map") is bound to a request with a `url_scheme` of `ws` or `wss`. Note Werkzeug has no further WebSocket support beyond routing. This functionality is mostly of use to ASGI projects. ``` url_map = Map([ Rule("/ws", endpoint="comm", websocket=True), ]) adapter = map.bind("example.org", "/ws", url_scheme="ws") assert adapter.match() == ("comm", {}) ``` If the only match is a WebSocket rule and the bind is HTTP (or the only match is HTTP and the bind is WebSocket) a `WebsocketMismatch` (derives from [`BadRequest`](../exceptions/index#werkzeug.exceptions.BadRequest "werkzeug.exceptions.BadRequest")) exception is raised. As WebSocket URLs have a different scheme, rules are always built with a scheme and host, `force_external=True` is implied. ``` url = adapter.build("comm") assert url == "ws://example.org/ws" ``` State Machine Matching ---------------------- The default matching algorithm uses a state machine that transitions between parts of the request path to find a match. To understand how this works consider this rule: ``` /resource/<id> ``` Firstly this rule is decomposed into two `RulePart`. The first is a static part with a content equal to `resource`, the second is dynamic and requires a regex match to `[^/]+`. A state machine is then created with an initial state that represents the rule’s first `/`. This initial state has a single, static transition to the next state which represents the rule’s second `/`. This second state has a single dynamic transition to the final state which includes the rule. To match a path the matcher starts and the initial state and follows transitions that work. Clearly a trial path of `/resource/2` has the parts `""`, `resource`, and `2` which match the transitions and hence a rule will match. Whereas `/other/2` will not match as there is no transition for the `other` part from the initial state. The only diversion from this rule is if a `RulePart` is not part-isolating i.e. it will match `/`. In this case the `RulePart` is considered final and represents a transition that must include all the subsequent parts of the trial path.
programming_docs