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 package org.openimaj.workinprogress;
31
32 import java.io.File;
33 import java.io.IOException;
34
35 import org.openimaj.image.DisplayUtilities;
36 import org.openimaj.image.FImage;
37 import org.openimaj.image.ImageUtilities;
38 import org.openimaj.image.MBFImage;
39 import org.openimaj.image.processing.algorithm.FilterSupport;
40 import org.openimaj.image.processing.algorithm.MedianFilter;
41 import org.openimaj.image.processing.resize.ResizeProcessor;
42 import org.openimaj.video.xuggle.XuggleVideo;
43
44 public class BackgroundSubtractor {
45 public static void main(String[] args) throws IOException {
46 final XuggleVideo xv = new XuggleVideo(new File("/Users/jon/Desktop/merlin/tunnel.mp4"));
47 final FImage bg = ResizeProcessor.halfSize(
48 ImageUtilities.readF(new File("/Users/jon/Desktop/merlin/tunnel-background.png"))
49 );
50
51
52
53
54
55 for (final MBFImage frc : xv) {
56 final FImage fr = ResizeProcessor.halfSize(frc.flatten());
57 final MBFImage diff = diff(bg, fr);
58
59
60 DisplayUtilities.displayName(diff, "");
61 }
62
63 }
64
65 static MBFImage diff(FImage bg, FImage fg) {
66 final FImage df = new FImage(bg.getWidth(), bg.getHeight());
67 final float[][] dff = df.pixels;
68
69 final float[][] bgfr = bg.pixels;
70 final float[][] fgfr = fg.pixels;
71
72 for (int y = 0; y < df.getHeight(); y++) {
73 for (int x = 0; x < df.getWidth(); x++) {
74 final float dr = bgfr[y][x] - fgfr[y][x];
75 final float ssd = dr * dr;
76
77 if (ssd < 0.03) {
78 dff[y][x] = 0;
79 } else {
80 dff[y][x] = 1;
81 }
82 }
83 }
84
85
86
87 df.processInplace(new MedianFilter(FilterSupport.createBlockSupport(3, 3)));
88 df.processInplace(new MedianFilter(FilterSupport.createBlockSupport(3, 3)));
89
90 return df.toRGB();
91 }
92 }