Skip to content

Instantly share code, notes, and snippets.

@statistic-on-air
Created August 29, 2011 08:46
Show Gist options
  • Save statistic-on-air/1178029 to your computer and use it in GitHub Desktop.
Save statistic-on-air/1178029 to your computer and use it in GitHub Desktop.
# Floyd-Steinberg dithering
# the 2-dimensional convolution function
FloydConvolution <- function(a){
c <- matrix(0, nrow=dim(a)[1], ncol=dim(a)[2])
for(i in 1:(dim(a)[1]-1)){
for(j in 1:(dim(a)[2]-1)){
P <- trunc(a[i,j]+0.5)
e <- a[i,j] - P
a[i,j] <- P
a[i,j+1] <- a[i,j+1] + (e * 7/16)
a[i+1,j-1] <- a[i+1,j-1] + (e * 3/16)
a[i+1,j] <- a[i+1,j] + (e * 5/16)
a[i+1,j+1] <- a[i+1,j+1] + (e * 1/16)
}
}
a
}
# the main function
grey2FSdith <- function(img){
greyMatrix <- img[1:nrow(img),1:ncol(img)]
dim1 <- 1
dim2 <- 1
dim1x <- 1
dim2x <- 1
dim1a <- dim(greyMatrix)[1]
dim2a <- dim(greyMatrix)[2]
# this code creates a bigger matrix (image) adding 0.5 values in first/last row/col
tempMatrix <- matrix(0.5, nrow=nrow(greyMatrix)+2, ncol=ncol(greyMatrix)+2)
tempMatrix[2:(nrow(tempMatrix)-1),2:(ncol(tempMatrix)-1)] <- greyMatrix
# apply the convolution function
igrey <- FloydConvolution(tempMatrix)
# create the image
imagematrix(igrey[1:(nrow(igrey)-1),1:(ncol(igrey)-1)], type="grey", noclipping=TRUE)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment