In financial econometrics (the application of statistical methods to economic data), the Markov-switching multifractal (MSM) is a model of asset returns developed by Laurent E. Calvet and Adlai J. Fisher that incorporates stochastic volatility components of heterogeneous durations. MSM captures the outliers, log-memory-like volatility persistence and power variation of financial returns. In currency and equity series, MSM compares favorably with standard volatility models such as GARCH(1,1) and FIGARCH both in- and out-of-sample. MSM is used by practitioners in the financial industry for different types of forecasts. == MSM specification == The MSM model can be specified in both discrete time and continuous time. === Discrete time === Let P t {\displaystyle P_{t}} denote the price of a financial asset, and let r t = ln ( P t / P t − 1 ) {\displaystyle r_{t}=\ln(P_{t}/P_{t-1})} denote the return over two consecutive periods. In MSM, returns are specified as r t = μ + σ ¯ ( M 1 , t M 2 , t . . . M k ¯ , t ) 1 / 2 ϵ t , {\displaystyle r_{t}=\mu +{\bar {\sigma }}(M_{1,t}M_{2,t}...M_{{\bar {k}},t})^{1/2}\epsilon _{t},} where μ {\displaystyle \mu } and σ {\displaystyle \sigma } are constants and { ϵ t {\displaystyle \epsilon _{t}} } are independent standard Gaussians. Volatility is driven by the first-order latent Markov state vector: M t = ( M 1 , t M 2 , t … M k ¯ , t ) ∈ R + k ¯ . {\displaystyle M_{t}=(M_{1,t}M_{2,t}\dots M_{{\bar {k}},t})\in R_{+}^{\bar {k}}.} Given the volatility state M t {\displaystyle M_{t}} , the next-period multiplier M k , t + 1 {\displaystyle M_{k,t+1}} is drawn from a fixed distribution M with probability γ k {\displaystyle \gamma _{k}} , and is otherwise left unchanged. The transition probabilities are specified by γ k = 1 − ( 1 − γ 1 ) ( b k − 1 ) {\displaystyle \gamma _{k}=1-(1-\gamma _{1})^{(b^{k-1})}} . The sequence γ k {\displaystyle \gamma _{k}} is approximately geometric γ k ≈ γ 1 b k − 1 {\displaystyle \gamma _{k}\approx \gamma _{1}b^{k-1}} at low frequency. The marginal distribution M has a unit mean, has a positive support, and is independent of k. ==== Binomial MSM ==== In empirical applications, the distribution M is often a discrete distribution that can take the values m 0 {\displaystyle m_{0}} or 2 − m 0 {\displaystyle 2-m_{0}} with equal probability. The return process r t {\displaystyle r_{t}} is then specified by the parameters θ = ( m 0 , μ , σ ¯ , b , γ 1 ) {\displaystyle \theta =(m_{0},\mu ,{\bar {\sigma }},b,\gamma _{1})} . Note that the number of parameters is the same for all k ¯ > 1 {\displaystyle {\bar {k}}>1} . === Continuous time === MSM is similarly defined in continuous time. The price process follows the diffusion: d P t P t = μ d t + σ ( M t ) d W t , {\displaystyle {\frac {dP_{t}}{P_{t}}}=\mu dt+\sigma (M_{t})\,dW_{t},} where σ ( M t ) = σ ¯ ( M 1 , t … M k ¯ , t ) 1 / 2 {\displaystyle \sigma (M_{t})={\bar {\sigma }}(M_{1,t}\dots M_{{\bar {k}},t})^{1/2}} , W t {\displaystyle W_{t}} is a standard Brownian motion, and μ {\displaystyle \mu } and σ ¯ {\displaystyle {\bar {\sigma }}} are constants. Each component follows the dynamics: The intensities vary geometrically with k: γ k = γ 1 b k − 1 . {\displaystyle \gamma _{k}=\gamma _{1}b^{k-1}.} When the number of components k ¯ {\displaystyle {\bar {k}}} goes to infinity, continuous-time MSM converges to a multifractal diffusion, whose sample paths take a continuum of local Hölder exponents on any finite time interval. == Inference and closed-form likelihood == When M {\displaystyle M} has a discrete distribution, the Markov state vector M t {\displaystyle M_{t}} takes finitely many values m 1 , . . . , m d ∈ R + k ¯ {\displaystyle m^{1},...,m^{d}\in R_{+}^{\bar {k}}} . For instance, there are d = 2 k ¯ {\displaystyle d=2^{\bar {k}}} possible states in binomial MSM. The Markov dynamics are characterized by the transition matrix A = ( a i , j ) 1 ≤ i , j ≤ d {\displaystyle A=(a_{i,j})_{1\leq i,j\leq d}} with components a i , j = P ( M t + 1 = m j | M t = m i ) {\displaystyle a_{i,j}=P\left(M_{t+1}=m^{j}|M_{t}=m^{i}\right)} . Conditional on the volatility state, the return r t {\displaystyle r_{t}} has Gaussian density f ( r t | M t = m i ) = 1 2 π σ 2 ( m i ) exp [ − ( r t − μ ) 2 2 σ 2 ( m i ) ] . {\displaystyle f(r_{t}|M_{t}=m^{i})={\frac {1}{\sqrt {2\pi \sigma ^{2}(m^{i})}}}\exp \left[-{\frac {(r_{t}-\mu )^{2}}{2\sigma ^{2}(m^{i})}}\right].} === Conditional distribution === === Closed-form Likelihood === The log likelihood function has the following analytical expression: ln L ( r 1 , … , r T ; θ ) = ∑ t = 1 T ln [ ω ( r t ) . ( Π t − 1 A ) ] . {\displaystyle \ln L(r_{1},\dots ,r_{T};\theta )=\sum _{t=1}^{T}\ln[\omega (r_{t}).(\Pi _{t-1}A)].} Maximum likelihood provides reasonably precise estimates in finite samples. === Other estimation methods === When M {\displaystyle M} has a continuous distribution, estimation can proceed by simulated method of moments, or simulated likelihood via a particle filter. == Forecasting == Given r 1 , … , r t {\displaystyle r_{1},\dots ,r_{t}} , the conditional distribution of the latent state vector at date t + n {\displaystyle t+n} is given by: Π ^ t , n = Π t A n . {\displaystyle {\hat {\Pi }}_{t,n}=\Pi _{t}A^{n}.\,} MSM often provides better volatility forecasts than some of the best traditional models both in and out of sample. Calvet and Fisher report considerable gains in exchange rate volatility forecasts at horizons of 10 to 50 days as compared with GARCH(1,1), Markov-Switching GARCH, and Fractionally Integrated GARCH. Lux obtains similar results using linear predictions. == Applications == === Multiple assets and value-at-risk === Extensions of MSM to multiple assets provide reliable estimates of the value-at-risk in a portfolio of securities. === Asset pricing === In financial economics, MSM has been used to analyze the pricing implications of multifrequency risk. The models have had some success in explaining the excess volatility of stock returns compared to fundamentals and the negative skewness of equity returns. They have also been used to generate multifractal jump-diffusions. == Related approaches == MSM is a stochastic volatility model with arbitrarily many frequencies. MSM builds on the convenience of regime-switching models, which were advanced in economics and finance by James D. Hamilton. MSM is closely related to the Multifractal Model of Asset Returns. MSM improves on the MMAR's combinatorial construction by randomizing arrival times, guaranteeing a strictly stationary process. MSM provides a pure regime-switching formulation of multifractal measures, which were pioneered by Benoit Mandelbrot.
Overcast (app)
Overcast is a podcast app for iOS that was launched in 2014 by founder and operator Marco Arment. == Founder and operator == Arment was also the Chief Technology Officer of Tumblr and founder of Instapaper before founding Overcast, and he had created his own podcasts before launching the app. In March 2023, Arment told The Vergecast how he built and maintains Overcast by himself, and that he uses ad banners promoting podcasts to cover the costs of the free app. == Features and reception == In 2014, Overcast received positive reviews from MacWorld and iMore. In 2015, The Verge and The Sweet Setup each named it the best podcast app for iOS that year. In 2017, Discover Pods gave an endorsement citing the "smart speed" feature, which shortens quiet gaps in a podcast. In April 2019, Overcast introduced a feature that allowed users to share clips from podcasts to social media. In January 2020, Overcast was updated to allow users to skip the intros and outros of podcasts.
Uncertain data
In computer science, uncertain data is data that contains noise that makes it deviate from the correct, intended or original values. In the age of big data, uncertainty or data veracity is one of the defining characteristics of data. Data is constantly growing in volume, variety, velocity and uncertainty (1/veracity). Uncertain data is found in abundance today on the web, in sensor networks, within enterprises both in their structured and unstructured sources. For example, there may be uncertainty regarding the address of a customer in an enterprise dataset, or the temperature readings captured by a sensor due to aging of the sensor. In 2012 IBM called out managing uncertain data at scale in its global technology outlook report that presents a comprehensive analysis looking three to ten years into the future seeking to identify significant, disruptive technologies that will change the world. In order to make confident business decisions based on real-world data, analyses must necessarily account for many different kinds of uncertainty present in very large amounts of data. Analyses based on uncertain data will have an effect on the quality of subsequent decisions, so the degree and types of inaccuracies in this uncertain data cannot be ignored. Uncertain data is found in the area of sensor networks; text where noisy text is found in abundance on social media, web and within enterprises where the structured and unstructured data may be old, outdated, or plain incorrect; in modeling where the mathematical model may only be an approximation of the actual process. When representing such data in a database, an appropriate uncertain database model needs to be selected. == Example data model for uncertain data == One way to represent uncertain data is through probability distributions. Let us take the example of a relational database. There are three main ways to do represent uncertainty as probability distributions in such a database model. In attribute uncertainty, each uncertain attribute in a tuple is subject to its own independent probability distribution. For example, if readings are taken of temperature and wind speed, each would be described by its own probability distribution, as knowing the reading for one measurement would not provide any information about the other. In correlated uncertainty, multiple attributes may be described by a joint probability distribution. For example, if readings are taken of the position of an object, and the x- and y-coordinates stored, the probability of different values may depend on the distance from the recorded coordinates. As distance depends on both coordinates, it may be appropriate to use a joint distribution for these coordinates, as they are not independent. In tuple uncertainty, all the attributes of a tuple are subject to a joint probability distribution. This covers the case of correlated uncertainty, but also includes the case where there is a probability of a tuple not belonging in the relevant relation, which is indicated by all the probabilities not summing to one. For example, assume we have the following tuple from a probabilistic database: Then, the tuple has 10% chance of not existing in the database.
Boyfriend Maker
Boyfriend Maker was a dating sim, romance chatbot smartphone app for iOS (iPhone) and Android devices, developed by Japanese studio 36 You Games (styled as 36You) and distributed under the freemium business model. Boyfriend Maker incorporated advanced artificial intelligence chat technology a decade before products such as ChatGPT. According to the developer's website, Boyfriend Maker is an "app that lets you interact and chat with quirky virtual boyfriends". While each virtual boyfriend has certain unique characteristics, the various instances of the boyfriend are powered by a chat engine, that (at least within a language and market) can utilise vocabulary and knowledge acquired in a chat with one user in subsequent chats with other users. == Gameplay == Users gain experience points and in-game coins. Users can customize their virtual boyfriend's appearance by selecting items such as hair, clothing, face, and a necklace. == Apple delisting and reintroduction == In late November 2012, the original iOS Boyfriend Maker app was delisted from the Apple App Store due to "ribald" chat, according to the New York Times. Boyfriend Maker was removed by Apple due to "reports of references to violent sexual acts and pedophilia". Boyfriend Maker had an age rating of 4+, even though the chat bot "responds with often strange and explicit text unsuitable for young children". User-posted chat excerpts indicate that the virtual boyfriend would sometimes transition abruptly to sexual chat in response to a seemingly innocent question. In one user-posted example, in response to the question, "what kind of wedding cake will we have" the boyfriend responds, "a good sex ima be on top of u u gonna ride oon me bitin the pillow gurrl ima fuck da shit out of u". The developer's use of the SimSimi-created third-party chat engine may be responsible for the sexual text. As the virtual boyfriend converses with human users, the SimSimi chat engine acquires vocabulary from users of the game and applies this "learned" vocabulary in chats with other users. The chat engine might also employ lines harvested from human-human chat logs, song lyrics, movies or TV shows. In April 2013, a detuned and presumably tamer version of the app, titled Boyfriend Plus, was permitted on Apple's App Store.
Attensity
Attensity was an American company that provided social analytics and engagement applications for social customer relationship management (social CRM). Attensity's text analytics software applications extracted facts, relationships and sentiment from unstructured data. == History == Attensity was founded in 2000. An early investor in Attensity was In-Q-Tel, which funds technology to support the missions of the US Government and the broader DOD. InTTENSITY, an independent company that has combined Inxight with Attensity Software (the only joint development project that combines two InQTel funded software packages), was the exclusive distributor and outlet for Attensity in the Federal Market. In 2009, Attensity Corp., then based in Palo Alto, merged with Germany's Empolis and Living-e AG to form Attensity Group. In 2010, Attensity Group acquired Biz360, a provider of social media monitoring and market intelligence solutions. In early 2012, Attensity Group divested itself of the Empolis business unit via a management buyout; that unit currently conducts business under its pre-merger name. Attensity Group was a closely held private company. Its majority shareholder was Aeris Capital, a private Swiss investment office advising a high-net-worth individual and his charitable foundation. Foundation Capital, Granite Ventures, and Scale Venture Partners were among Biz360's investors and thus became shareholders in Attensity Group. In February 2016, Attensity's IP assets were acquired by InContact, and Attensity closed.
Concordancer
A concordancer is a computer program that automatically constructs a concordance—an alphabetised index of every occurrence of a word or phrase in a body of text, each entry displayed with its surrounding context. Concordancers are primary tools in corpus linguistics, lexicography, computer-assisted translation, and language teaching. The most common display format is the key word in context (KWIC) layout, in which each hit appears centred on a line with a fixed span of words to its left and right, enabling rapid scanning of usage patterns across many occurrences. == History == === Pre-computational concordances === The compilation of concordances predates computers by many centuries. Around 1230, the French Dominican cardinal Hugh of Saint-Cher directed a team of friars in assembling a concordance of the Latin Vulgate Bible, generally regarded as the first systematic concordance of any text. To help readers locate passages, Hugh divided each biblical chapter into lettered sections. Later milestones include a Hebrew Old Testament concordance compiled by Rabbi Mordecai Nathan (1448), Alexander Cruden's Complete Concordance to the Holy Scriptures (1737), and the manuscript Asaf ha-Mazkir, an unfinished concordance to the Babylonian Talmud compiled by Moses Rigotz around the turn of the 19th century. === First computer concordance === The first concordance produced with computing assistance was the Index Thomisticus, a comprehensive lexical index of the writings of and around Thomas Aquinas, totalling approximately 10.6 million Latin words. The Italian Jesuit priest Roberto Busa conceived the project in 1946 and secured the sponsorship of IBM in 1949 after a meeting with chairman Thomas J. Watson. Keypunch operators in Gallarate, Italy, encoded the texts onto punched cards from around 1950. IBM executive Paul Tasman developed the processing methods. The full 56-volume printed edition was completed around 1980, followed by a CD-ROM edition in 1989 and a web-accessible version in 2005. === The KWIC format === The key word in context (KWIC) display was formalised as a computational technique by Hans Peter Luhn, a researcher at IBM, in a 1960 paper in American Documentation. In KWIC output, each instance of the search term (the node word) is centred on a line with a fixed window of words to each side; sorting the resulting lines alphabetically by the immediately adjacent word reveals collocational and phraseological patterns at a glance. === COCOA === One of the first dedicated concordancing programs was COCOA (COunt and COncordance Generation on Atlas), created in 1965 by D. B. Russell at University College London and the Atlas Computer Laboratory in Harwell, Oxfordshire. Written in approximately 4,000 cards of FORTRAN, it processed text annotated with flat, non-hierarchical markup tags and could produce word counts and concordances in multiple languages. Within its first six months COCOA had been applied to texts in at least six languages. A second version designed for multiple mainframe platforms was distributed to British computing centres in the mid-1970s. Growing dissatisfaction with its interface and the eventual withdrawal of Atlas Laboratory support prompted British funding bodies to commission a successor program. === Oxford Concordance Program === The Oxford Concordance Program (OCP) was designed and written in FORTRAN by Susan Hockey and Ian Marriott at Oxford University Computing Services (OUCS) between 1979 and 1980 and first released in 1981. Hockey and Marriott acknowledged that OCP owed much to COCOA and the CLOC system at the University of Birmingham. OCP accepted COCOA-format markup to encode metadata such as author, act, scene, and line number, and was described by its authors as "a machine-independent text analysis program for producing word lists, indices and concordances in a variety of languages and alphabets." By the mid-1980s it had been licensed to approximately 240 institutions in 23 countries. A personal computer version, Micro-OCP, was developed for the IBM PC and sold by Oxford University Press from the late 1980s. Version 2 was rewritten in 1985–86 and documented in the same 1987 article by Hockey and co-author John Martin. === Personal computer era === The availability of affordable personal computers in the 1980s and 1990s enabled standalone concordancing applications that analysts could run locally without specialist computing facilities. MicroConcord, developed by Mike Scott and Tim Johns and published by Oxford University Press in 1993 for MS-DOS, was among the first concordancers designed specifically for classroom language teaching. WordSmith Tools, also developed by Mike Scott, was first released in 1996 and became one of the most widely used corpus analysis suites in academic linguistics research. Other tools from this era include TACT (University of Toronto, 1989), a suite of MS-DOS freeware programs for literary text analysis, and MonoConc, a Windows concordancer created by Michael Barlow. === Web-based concordancers === From the late 1990s onwards, web-based concordancers hosted on remote servers gave researchers browser access to large preloaded corpora without requiring local storage or processing. The Sketch Engine, developed by Adam Kilgarriff and Pavel Rychlý (Masaryk University), was launched commercially in July 2003 by Lexical Computing Limited and introduced word sketches—automatically generated one-page profiles of a word's typical grammatical relations and collocations. AntConc, created by Laurence Anthony at Waseda University, Tokyo, was first released in 2002 as freeware for Windows, macOS, and Linux. == Features == Modern concordancers typically offer a range of analytical functions beyond basic KWIC display. These commonly include: KWIC display with the node word centred and context words in aligned columns, sortable by the word one, two, or three positions to the left or right of the node (L1–L3 and R1–R3) Concordance plots, visualising the distribution of hits as marks along a scaled bar representing each text in the corpus Frequency and word lists, both alphabetical and ranked by frequency Collocation statistics, identifying words that co-occur with the search term more often than chance, quantified by measures such as mutual information, the t-score, or log-likelihood Keyword analysis, comparing word frequencies between a study corpus and a reference corpus to identify statistically distinctive items N-gram analysis, finding frequently recurring word sequences of a specified length Part-of-speech tagging integration, allowing searches filtered to particular grammatical categories Unicode support for multilingual text Bilingual and parallel concordancers additionally display aligned text in two or more languages side by side, enabling comparison of translation equivalents across language pairs. == Notable concordancers == === WordSmith Tools === Created by Mike Scott and first released in 1996, WordSmith Tools is a Windows corpus analysis suite that evolved from MicroConcord. Its three core modules are Concord (KWIC concordances), WordList (frequency and alphabetical word lists), and Keywords (statistical keyword identification relative to a reference corpus). Oxford University Press used WordSmith Tools for dictionary preparation work. Version 4.0 is freely available; later versions are sold by Lexical Analysis Software Limited. === AntConc === AntConc is a freeware, multiplatform concordancing toolkit created by Laurence Anthony, Professor of Applied Linguistics at Waseda University, Tokyo. First released in 2002 and formally described in a 2005 academic paper, it runs on Windows, macOS, and Linux. Its tools include a KWIC concordancer, a concordance plot for visualising distribution across texts, a collocates tool, a keyword list, and an n-gram analysis module. Because it is free and requires only plain text files, AntConc is widely used in linguistics courses and independent research worldwide. === Sketch Engine === The Sketch Engine is a corpus management and query system co-created by Adam Kilgarriff and Pavel Rychlý and launched in 2003 by Lexical Computing Limited. It provides browser-based access to over 800 corpora in more than 100 languages. Beyond concordance searching, it offers word sketches, collocation analysis, distributional thesaurus construction, keyword and terminology extraction, and diachronic analysis. It is used by major publishers including Macmillan and Oxford University Press for lexicographic research. A subset tool, SKELL (Sketch Engine for Language Learning), is freely accessible to individual learners. === Wmatrix === Wmatrix is a web-based corpus processing environment developed by Paul Rayson at the University Centre for Computer Corpus Research on Language (UCREL), Lancaster University. Alongside concordances and frequency lists, Wmatrix integrates CLAWS part-of-speech tagging and the USAS semantic tagger, enabling keyword analysis simultane
Connected-component labeling
Connected-component labeling (CCL), connected-component analysis (CCA), blob extraction, region labeling, blob discovery, or region extraction is an algorithmic application of graph theory, where subsets of connected components are uniquely labeled based on a given heuristic. Connected-component labeling is not to be confused with segmentation. Connected-component labeling is used in computer vision to detect connected regions in binary digital images, although color images and data with higher dimensionality can also be processed. When integrated into an image recognition system or human-computer interaction interface, connected component labeling can operate on a variety of information. Blob extraction is generally performed on the resulting binary image from a thresholding step, but it can be applicable to gray-scale and color images as well. Blobs may be counted, filtered, and tracked. Blob extraction is related to but distinct from blob detection. == Overview == A graph, containing vertices and connecting edges, is constructed from relevant input data. The vertices contain information required by the comparison heuristic, while the edges indicate connected 'neighbors'. An algorithm traverses the graph, labeling the vertices based on the connectivity and relative values of their neighbors. Connectivity is determined by the medium; image graphs, for example, can be 4-connected neighborhood or 8-connected neighborhood. Following the labeling stage, the graph may be partitioned into subsets, after which the original information can be recovered and processed . == Definition == The usage of the term connected-component labeling (CCL) and its definition is quite consistent in the academic literature, whereas connected-component analysis (CCA) varies both in terminology and in its definition of the problem. Rosenfeld et al. define connected components labeling as the “[c]reation of a labeled image in which the positions associated with the same connected component of the binary input image have a unique label.” Shapiro et al. define CCL as an operator whose “input is a binary image and [...] output is a symbolic image in which the label assigned to each pixel is an integer uniquely identifying the connected component to which that pixel belongs.” There is no consensus on the definition of CCA in the academic literature. It is often used interchangeably with CCL. A more extensive definition is given by Shapiro et al.: “Connected component analysis consists of connected component labeling of the black pixels followed by property measurement of the component regions and decision making.” The definition for connected-component analysis presented here is more general, taking the thoughts expressed in into account. == Algorithms == The algorithms discussed can be generalised to arbitrary dimensions, albeit with increased time and space complexity. === One component at a time === This is a fast and very simple method to implement and understand. It is based on graph traversal methods in graph theory. In short, once the first pixel of a connected component is found, all the connected pixels of that connected component are labelled before going onto the next pixel in the image. This algorithm is part of Vincent and Soille's watershed segmentation algorithm, other implementations also exist. In order to do that a linked list is formed that will keep the indexes of the pixels that are connected to each other, steps (2) and (3) below. The method of defining the linked list specifies the use of a depth or a breadth first search. For this particular application, there is no difference which strategy to use. The simplest kind of a last in first out queue implemented as a singly linked list will result in a depth first search strategy. It is assumed that the input image is a binary image, with pixels being either background or foreground and that the connected components in the foreground pixels are desired. The algorithm steps can be written as: Start from the first pixel in the image. Set current label to 1. Go to (2). If this pixel is a foreground pixel and it is not already labelled, give it the current label and add it as the first element in a queue, then go to (3). If it is a background pixel or it was already labelled, then repeat (2) for the next pixel in the image. Pop out an element from the queue, and look at its neighbours (based on any type of connectivity). If a neighbour is a foreground pixel and is not already labelled, give it the current label and add it to the queue. Repeat (3) until there are no more elements in the queue. Go to (2) for the next pixel in the image and increment current label by 1. Note that the pixels are labelled before being put into the queue. The queue will only keep a pixel to check its neighbours and add them to the queue if necessary. This algorithm only needs to check the neighbours of each foreground pixel once and doesn't check the neighbours of background pixels. The pseudocode is: algorithm OneComponentAtATime(data) input : imageData[xDim][yDim] initialization : label = 0, labelArray[xDim][yDim] = 0, statusArray[xDim][yDim] = false, queue1, queue2; for i = 0 to xDim do for j = 0 to yDim do if imageData[i][j] has not been processed do if imageData[i][j] is a foreground pixel do check its four neighbors(north, south, east, west) : if neighbor is not processed do if neighbor is a foreground pixel do add it to queue1 else update its status to processed end if labelArray[i][j] = label (give label) statusArray[i][j] = true (update status) while queue1 is not empty do For each pixel in the queue do : check its four neighbors if neighbor is not processed do if neighbor is a foreground pixel do add it to queue2 else update its status to processed end if give it the current label update its status to processed remove the current element from queue1 copy queue2 into queue1 end While increase the label end if else update its status to processed end if end if end if end for end for === Two-pass === Relatively simple to implement and understand, the two-pass algorithm, (also known as the Hoshen–Kopelman algorithm) iterates through 2-dimensional binary data. The algorithm makes two passes over the image: the first pass to assign temporary labels and record equivalences, and the second pass to replace each temporary label by the smallest label of its equivalence class. The input data can be modified in situ (which carries the risk of data corruption), or labeling information can be maintained in an additional data structure. Connectivity checks are carried out by checking neighbor pixels' labels (neighbor elements whose labels are not assigned yet are ignored), or say, the north-east, the north, the north-west and the west of the current pixel (assuming 8-connectivity). 4-connectivity uses only north and west neighbors of the current pixel. The following conditions are checked to determine the value of the label to be assigned to the current pixel (4-connectivity is assumed) Conditions to check: Does the pixel to the left (west) have the same value as the current pixel? Yes – We are in the same region. Assign the same label to the current pixel No – Check next condition Do both pixels to the north and west of the current pixel have the same value as the current pixel but not the same label? Yes – We know that the north and west pixels belong to the same region and must be merged. Assign the current pixel the minimum of the north and west labels, and record their equivalence relationship No – Check next condition Does the pixel to the left (west) have a different value and the one to the north the same value as the current pixel? Yes – Assign the label of the north pixel to the current pixel No – Check next condition Do the pixel's north and west neighbors have different pixel values than current pixel? Yes – Create a new label id and assign it to the current pixel The algorithm continues this way, and creates new region labels whenever necessary. The key to a fast algorithm, however, is how this merging is done. This algorithm uses the union-find data structure which provides excellent performance for keeping track of equivalence relationships. Union-find essentially stores labels which correspond to the same blob in a disjoint-set data structure, making it easy to remember the equivalence of two labels by the use of an interface method E.g.: findSet(l). findSet(l) returns the minimum label value that is equivalent to the function argument 'l'. Once the initial labeling and equivalence recording is completed, the second pass merely replaces each pixel label with its equivalent disjoint-set representative element. A faster-scanning algorithm for connected-region extraction is presented below. On the first pass: Iterate through each element of the data by column, then by row (Raster Scanning) If the element is not the background Get the neighboring elements of the current element If there are no neighbors, uniquely