Monday, August 29, 2011

R is a cool image editor #2: Dithering algorithms

Here I implemented in R some dithering algorithms:
- Floyd-Steinberg dithering
- Bill Atkinson dithering
- Jarvis-Judice-Ninke dithering
- Sierra 2-4a dithering
- Stucki dithering
- Burkes dithering
- Sierra2 dithering
- Sierra3 dithering

For each algorithm, I wrote a 2-dimensional convolution function (a matrix passing over a matrix); it is slow because I didn't implemented any fasting tricks. It can be easily implemented in C, then used in R for a faster solution.
Then, a function to transform a grey image in a grey-dithered image is provided, with an example. The library rimage was used for loading and displaying images (see the other post R is a cool image editor).
These function can be easily re-coded for a RGB image.
Only the first code is commented, 'cause they're all very similar.


library(rimage)
y <- read.jpeg("valve.jpg")
plot(y)






Floyd-Steinberg dithering




plot(normalize(grey2FSdith(rgb2grey(y))))







Bill Atkinson dithering




plot(normalize(grey2ATKdith(rgb2grey(y))))







Jarvis-Judice-Ninke dithering




plot(normalize(grey2JJNdith(rgb2grey(y))))







Sierra 2-4a dithering filter




plot(normalize(grey2S24adith(rgb2grey(y))))







Stucki dithering




plot(normalize(grey2Stucki(rgb2grey(y))))







Burkes dithering




plot(normalize(grey2Burkes(rgb2grey(y))))







Sierra2 dithering




plot(normalize(grey2Sierra2(rgb2grey(y))))







Sierra3 dithering




plot(normalize(grey2Sierra3(rgb2grey(y))))



Thursday, August 25, 2011

Benford's law, or the First-digit law

Benford's law, also called the first-digit law, states that in lists of numbers from many (but not all) real-life sources of data, the leading digit is distributed in a specific, non-uniform way. According to this law, the first digit is 1 about 30% of the time, and larger digits occur as the leading digit with lower and lower frequency, to the point where 9 as a first digit occurs less than 5% of the time.
Wikipedia, retrieved 08/25/2011





R simulation:

library(MASS)
benford <- function(m, n){
list <- c()

# compute all m^n, for n= 1, 2, ..., i, ..., n
for(i in 1:n){
list[i] <- m^i
}

# a function to extract the first digit from a number
bben <- function(k){
as.numeric(head(strsplit(as.character(k),'')[[1]],n=1))
}

# extract the first digit from all numbers computed
first.digit <- sapply(list, bben)

# plot frequency of first digits
truehist(first.digit, nbins=10, main=m)
}

par(mfrow=c(2,2))
benford(2,1000)
benford(3,640) # if n is greater, it returns "inf" (on my pc)
benford(4,500)
benford(5,440)