Debian Codegraph @

examples/advanced/opencv_movie.py

raw
1 """
2 An example that uses a function from external C library (OpenCV in this case).
3 Works for all C-based code generation targets (i.e. for cython and cpp_standalone
4 device) and for numpy (using the Python bindings).
5
6 This example needs a working installation of OpenCV 3.x and its Python bindings.
7 It has been tested on 64 bit Linux in a conda environment with packages from the
8 ``conda-forge`` channels (opencv 3.4.4, x264 1!152.20180717, ffmpeg 4.1).
9 """
10 import os
11 import urllib.request, urllib.error, urllib.parse
12 import cv2 # Import OpenCV2
13
14 from brian2 import *
15
16 defaultclock.dt = 1*ms
17 prefs.codegen.target = 'cython'
18 prefs.logging.std_redirection = False
19 set_device('cpp_standalone', clean=True)
20 filename = os.path.abspath('Megamind.avi')
21
22 if not os.path.exists(filename):
23 print('Downloading the example video file')
24 response = urllib.request.urlopen('http://docs.opencv.org/2.4/_downloads/Megamind.avi')
25 data = response.read()
26 with open(filename, 'wb') as f:
27 f.write(data)
28
29 video = cv2.VideoCapture(filename)
30 width, height, frame_count = (int(video.get(cv2.CAP_PROP_FRAME_WIDTH)),
31 int(video.get(cv2.CAP_PROP_FRAME_HEIGHT)),
32 int(video.get(cv2.CAP_PROP_FRAME_COUNT)))
33 fps = 24
34 time_between_frames = 1*second/fps
35
36 @implementation('cpp', '''
37 double* get_frame(bool new_frame)
38 {
39 // The following initializations will only be executed once
40 static cv::VideoCapture source("VIDEO_FILENAME");
41 static cv::Mat frame;
42 static double* grayscale_frame = (double*)malloc(VIDEO_WIDTH*VIDEO_HEIGHT*sizeof(double));
43 if (new_frame)
44 {
45 source >> frame;
46 double mean_value = 0;
47 for (int row=0; row<VIDEO_HEIGHT; row++)
48 for (int col=0; col<VIDEO_WIDTH; col++)
49 {
50 const double grayscale_value = (frame.at<cv::Vec3b>(row, col)[0] +
51 frame.at<cv::Vec3b>(row, col)[1] +
52 frame.at<cv::Vec3b>(row, col)[2])/(3.0*128);
53 mean_value += grayscale_value / (VIDEO_WIDTH * VIDEO_HEIGHT);
54 grayscale_frame[row*VIDEO_WIDTH + col] = grayscale_value;
55 }
56 // subtract the mean
57 for (int i=0; i<VIDEO_HEIGHT*VIDEO_WIDTH; i++)
58 grayscale_frame[i] -= mean_value;
59 }
60 return grayscale_frame;
61 }
62
63 double video_input(const int x, const int y)
64 {
65 // Get the current frame (or a new frame in case we are asked for the first
66 // element
67 double *frame = get_frame(x==0 && y==0);
68 return frame[y*VIDEO_WIDTH + x];
69 }
70 '''.replace('VIDEO_FILENAME', filename),
71 libraries=['opencv_core',
72 'opencv_highgui',
73 'opencv_videoio'],
74 headers=['<opencv2/core/core.hpp>',
75 '<opencv2/highgui/highgui.hpp>'],
76 define_macros=[('VIDEO_WIDTH', width),
77 ('VIDEO_HEIGHT', height)])
78 @check_units(x=1, y=1, result=1)
79 def video_input(x, y):
80 # we assume this will only be called in the custom operation (and not for
81 # example in a reset or synaptic statement), so we don't need to do indexing
82 # but we can directly return the full result
83 _, frame = video.read()
84 grayscale = frame.mean(axis=2)
85 grayscale /= 128. # scale everything between 0 and 2
86 return grayscale.ravel() - grayscale.ravel().mean()
87
88
89 N = width * height
90 tau, tau_th = 10*ms, time_between_frames
91 G = NeuronGroup(N, '''dv/dt = (-v + I)/tau : 1
92 dv_th/dt = -v_th/tau_th : 1
93 row : integer (constant)
94 column : integer (constant)
95 I : 1 # input current''',
96 threshold='v>v_th', reset='v=0; v_th = 3*v_th + 1.0',
97 method='exact')
98 G.v_th = 1
99 G.row = 'i//width'
100 G.column = 'i%width'
101
102 G.run_regularly('I = video_input(column, row)',
103 dt=time_between_frames)
104 mon = SpikeMonitor(G)
105 runtime = frame_count*time_between_frames
106 run(runtime, report='text')
107
108 # Avoid going through the whole Brian2 indexing machinery too much
109 i, t, row, column = mon.i[:], mon.t[:], G.row[:], G.column[:]
110
111 import matplotlib.animation as animation
112
113 # TODO: Use overlapping windows
114 stepsize = 100*ms
115 def next_spikes():
116 step = next_spikes.step
117 if step*stepsize > runtime:
118 next_spikes.step=0
119 raise StopIteration()
120 spikes = i[(t>=step*stepsize) & (t<(step+1)*stepsize)]
121 next_spikes.step += 1
122 yield column[spikes], row[spikes]
123 next_spikes.step = 0
124
125 fig, ax = plt.subplots()
126 dots, = ax.plot([], [], 'k.', markersize=2, alpha=.25)
127 ax.set_xlim(0, width)
128 ax.set_ylim(0, height)
129 ax.invert_yaxis()
130 def run(data):
131 x, y = data
132 dots.set_data(x, y)
133
134 ani = animation.FuncAnimation(fig, run, next_spikes, blit=False, repeat=True,
135 repeat_delay=1000)
136 plt.show()