|
| 1 | +package Algorithms |
| 2 | + |
| 3 | +import breeze.linalg.DenseMatrix |
| 4 | +import breeze.linalg.sum |
| 5 | +import breeze.linalg.DenseVector |
| 6 | +import breeze.numerics.exp |
| 7 | +import breeze.linalg.InjectNumericOps |
| 8 | +import scala.util.Random |
| 9 | +import java.io.File |
| 10 | + |
| 11 | +class Denoiser (MAX_BURNS :Int = 100, MAX_SAMPLES :Int = 200) extends Algorithm { |
| 12 | + val ITA = 0.9 |
| 13 | + val BETA = 2 |
| 14 | + val initialization = "same" |
| 15 | + |
| 16 | + private def energy (Y : DenseMatrix[Double], X: DenseMatrix[Double]) : Double = { |
| 17 | + val N = Y.rows |
| 18 | + val M = Y.cols |
| 19 | + -1 * sum( X *:* Y ) |
| 20 | + + sum( Y( 0 until N-1, :: ) *:* Y( 1 to -1, :: ) ) |
| 21 | + + sum( Y( ::, 0 until M-1 ) *:* Y( ::, 1 to -1 ) ) |
| 22 | + } |
| 23 | + |
| 24 | + private def sample (i: Int, j: Int, Y: DenseMatrix[Double], X: DenseMatrix[Double]) : Int = { |
| 25 | + val blanket = new DenseVector[Double]( Array(Y(i-1, j), Y(i, j-1), Y(i, j+1), Y(i+1, j), X(i, j)) ) |
| 26 | + |
| 27 | + val w = ITA * blanket(-1) + BETA * sum(blanket(0 until 4)) |
| 28 | + val prob = 1 / (1 + math.exp(-2*w)) |
| 29 | + //val prob = exp( 2 * sum(blanket).toDouble ) / ( 1 + exp( 2 * sum(blanket).toDouble )) |
| 30 | + if (Random.nextDouble < prob) 1 else -1 |
| 31 | + } |
| 32 | + |
| 33 | + def run (imageMatrix :DenseMatrix[Double]): DenseMatrix[Double] = { |
| 34 | + println("Denoiser: working") |
| 35 | + println(s"Initialization : $initialization") |
| 36 | + val X = adjustImageIn(imageMatrix) |
| 37 | + var Y = X.copy |
| 38 | + val N = Y.rows |
| 39 | + val M = Y.cols |
| 40 | + if (initialization == "neg") |
| 41 | + Y = -1.0 *:* Y |
| 42 | + if (initialization == "rand") |
| 43 | + Y = DenseMatrix.tabulate(imageMatrix.rows, imageMatrix.cols){ (i,j) => randomChoice (Array(-1, 1)) } |
| 44 | + |
| 45 | + |
| 46 | + var ctr = 0 |
| 47 | + for ( _ <- 0 until MAX_BURNS) { |
| 48 | + for { |
| 49 | + i <- 1 until N-1 |
| 50 | + j <- 1 until M-1 |
| 51 | + } Y(i,j) = sample(i, j, Y, X) |
| 52 | + ctr += 1 |
| 53 | + if( ctr % 10 == 0 ) { |
| 54 | + println(s"Burn-in ${ctr} done!") |
| 55 | + //println(s"Energy: ${energy(Y, X)}") |
| 56 | + } |
| 57 | + } |
| 58 | + println("Denoiser: done") |
| 59 | + adjustImageOut(Y) |
| 60 | + } |
| 61 | + |
| 62 | + def randomChoice [T] (values: Array[T]) : T = |
| 63 | + values (Random.nextInt(values.length)) |
| 64 | + |
| 65 | + private def adjustImageIn(matrix: DenseMatrix[Double]) : DenseMatrix[Double] = |
| 66 | + matrix.map( elem => if ( elem > 128 ) 1.0 else -1.0 ) |
| 67 | + |
| 68 | + private def adjustImageOut(matrix: DenseMatrix[Double]) : DenseMatrix[Double] = |
| 69 | + matrix.map( elem => if ( elem < 0.5 ) 0.0 else 255.0 ) |
| 70 | +} |
0 commit comments