forked from osteffen/PhotonCam
-
Notifications
You must be signed in to change notification settings - Fork 0
/
frame2hist.py
executable file
·506 lines (405 loc) · 14.8 KB
/
frame2hist.py
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
#!/usr/bin/python
import numpy as np
import cv2
import ROOT
from epics import PV
import sys
import os
import datetime
import curses
from time import sleep
###### Default Settings #########
class settings:
xpixels = 640
ypixels = 480
mm2pix = 0.13
pix2bin = 10
mm2bin = 1.3
xbins = 64
ybins = 48
numframes = 25
automode = True
epicson = True
windowsize = (1200,800)
average_factor = 0.01
dumpdata = False
fits=True
videostandard = "0x00000400"
v4l2settings = os.environ['HOME'] + "/.v4l2-default-optimized"
epics_ladderp2 = "TAGG:TAGG:LadderP2Ratio" # which tagger is used? TAGG:TAGG or TAGG:EPT
logbookName = "Main Logbook 2016"
experimentName = "2016_10_Eta_4He"
if not os.path.isfile(v4l2settings):
print("Optimized v4l2-configuration doesn't exist yet!!")
print(" 1.) Optimize using v4l2ucp.")
print(" 2.) Store: v4l2ctrl -s " + v4l2settings)
def PrintKeys():
print("======= Beam Camera =====================")
print("")
print("Keys (in camera windows):")
print("")
print(" Options:")
print(" a: toggle auto mode < " + str(automode) + " >")
print(" e: toggle EPICS logging < " + str(epicson) + " >")
print(" f: toggle fitting < " + str(fits) + " >")
print(" Actions:")
print(" r: remeasure")
print(" s: save histograms as png")
print(" p: save camera picture as png")
print(" l: generate an entry for Elog")
print(" q: quit")
print("")
### Parse Command Line ###
for arg in sys.argv:
if arg.startswith("--numframes="):
numframes = int(arg.split('=')[1])
if arg.startswith("--mm2pix="):
settings.mm2pix = float(arg.split('=')[1])
if arg.startswith("--pix2bin="):
settings.pix2bin = int(arg.split('=')[1])
if arg.startswith("--noauto"):
automode=False
if arg.startswith("--v4l2-settings="):
v4l2settings = arg.split('=')[1];
if not os.path.isfile(v4l2settings):
print(" Error loading v4l2-config-file: " + v4l2settings + " doesn't exist!")
sys.exit(128)
if arg.startswith("--dump-data"):
dumpdata = True;
if arg.startswith("--help" or "-help" ):
print "===== OpenCV beam camera analyzer ======"
print ""
print " Usage:"
print ""
print " ",sys.argv[0]," [--numframes=< # frames to for fitting center = 25> "
print " --mm2pix=<0.13> "
print " --pix2bin=<10> "
print " --noauto turn of auto mode"
print " --v4l2-settings=<user-settings-file>"
print ""
PrintKeys()
print ""
### Init ###
settings.mm2bin = float(settings.mm2pix * settings.pix2bin)
settings.xbins = int(settings.xpixels/settings.pix2bin)
settings.ybins = int(settings.ypixels/settings.pix2bin)
# Init v4l2-driver:
print
print "===== Initializing v4l2 - driver ==================="
print
os.system("v4l2-ctl --set-standard=" + videostandard)
if os.system("v4l2ctrl -l " + v4l2settings):
print("Error loading v4l2-config-file!")
# Init Video Capture
cap = cv2.VideoCapture(0)
###### Initialize EPICS-Records #########
print
print "===== Initializing all PVs ========================="
print
EpicsRecords = dict( [ ( record , PV(record) ) for record in
[ "BEAM:IonChamber",
epics_ladderp2,
"BEAM:PhotonCam:CenterX",
"BEAM:PhotonCam:CenterX.A",
"BEAM:PhotonCam:CenterY",
"BEAM:PhotonCam:CenterY.A",
"BEAM:PhotonCam:WidthX.A",
"BEAM:PhotonCam:WidthY.A",
"BEAM:PhotonCam:Sum.A" ]
] )
def check_records():
return [ pv.pvname for pv in EpicsRecords.itervalues() if not pv.connected ]
print(" +-"+4*len(EpicsRecords)*"-"+"-+")
sys.stdout.write(" ")
sys.stdout.flush()
for pv in EpicsRecords.itervalues():
pv.connect()
sys.stdout.write(4*"#")
sys.stdout.flush()
sys.stdout.write(" ")
sys.stdout.flush()
print
print(" +-"+4*len(EpicsRecords)*"-"+"-+")
print
if check_records():
print "Warning, Following PVs are not connected:"
print check_records()
print
print " --> Check your EpicsRecords-dict"
print " for full EPICS support! "
print
raw_input("Smash head on keyboard, then hit return to continue!")
def caget(record):
if EpicsRecords[record].connected:
return EpicsRecords[record].get()
#print(" Warning: PV {0} not connected. Check your EpicsRecords!".format(EpicsRecords[record].pvname) )
return False
def caput(record,value):
if EpicsRecords[record].connected:
EpicsRecords[record].put(value)
#else:
#print(" Warning: PV {0} not connected. Check your EpicsRecords!".format(EpicsRecords[record].pvname) )
# Set up ROOT
# Canvas
print
print "===== Initializing ROOT canvas ====================="
print
c = ROOT.TCanvas("profile","Beam Profile")
c.Divide(2,2)
c.SetWindowSize(windowsize[0], windowsize[1])
# 2D profile histogram
hist = ROOT.TH2D("frame","Beam Profile",settings.xbins,0,settings.mm2bin*settings.xbins,settings.ybins,0,settings.mm2bin*settings.ybins)
hist.SetXTitle("x")
hist.SetYTitle("y")
hist.SetZTitle("Intensity [a.u.]")
histx = ROOT.TH1D()
histx.SetTitle("X-Projection")
histy = ROOT.TH1D()
histy.SetTitle("Y-Projection")
# Fit functions
f2 = ROOT.TF2("f2","xygaus",0 ,settings.mm2bin*settings.xbins,0,settings.mm2bin*settings.ybins);
f1 = ROOT.TF1("f1","gaus",0 ,settings.mm2bin*settings.xbins);
curframe = 0
last_p = 0
if dumpdata:
datafile = open("beam.dat","w")
def CheckBeam():
#listhistx = [ histx.GetBinContent(i+1) for i in range(histx.GetNbinsX()) ]
hasbeam = caget("BEAM:IonChamber") > 500
return hasbeam
# ======= init curses ============
def refreshWin(window,windowTitle=""):
window.box()
if not windowTitle=="":
window.addstr(0,2,"< " + windowTitle + " >")
window.refresh()
mscreen = curses.initscr()
refreshWin(mscreen,"Photon Camera Programm")
mmaxy, mmaxx = mscreen.getmaxyx()
loadscreen = curses.newwin(3, mmaxx - 16 ,2, 8)
keyscreen = curses.newwin(14, 40 ,6,4)
statescreen = curses.newwin(14, mmaxx - 42 - 8 ,6,42 + 4 )
mscreen.keypad(1)
curses.noecho()
curses.cbreak()
curses.curs_set(0)
def putLoading(p):
loadscreen.erase()
pstring = "Accumulating " +str(numframes) + " frames... "
pstring = pstring + int(p) * 2 * "#"
loadscreen.addstr(1,2,pstring)
def putState(analysed):
statescreen.erase()
statescreen.addstr( 2,4,"screen size: (" + str(sumbuf.shape[1]) + ", " + str(sumbuf.shape[0])+")")
statescreen.addstr( 4,4, "Has beam: " + str(CheckBeam()))
formstr = "{:>.2f}"
if analysed and fits:
statescreen.addstr( 6,4,"x-center: " + formstr.format(hist.GetFunction("f2").GetParameter(1)))
statescreen.addstr( 7,4,"y-center: " + formstr.format(hist.GetFunction("f2").GetParameter(3)))
statescreen.addstr( 8,4,"x-width: " + formstr.format(hist.GetFunction("f2").GetParameter(2)))
statescreen.addstr( 9,4,"y-width: " + formstr.format(hist.GetFunction("f2").GetParameter(4)))
if check_records():
statescreen.addstr(11,4,"Warning:")
statescreen.addstr(12,4,"{0} disconnected PVs!".format(len(check_records())))
def putKeys():
keyscreen.erase()
keyscreen.addstr( 2,4,"Options:")
keyscreen.addstr( 3,9,"a: auto mode < " + str(automode) + " >")
keyscreen.addstr( 4,9,"e: EPICS logging < " + str(epicson) + " >")
keyscreen.addstr( 5,9,"f: fitting < " + str(fits) + " >")
keyscreen.addstr( 6,4,"Actions:")
keyscreen.addstr( 7,9,"r: remeasure")
keyscreen.addstr( 8,9,"s: save histograms as png")
keyscreen.addstr( 9,9,"p: save camera picture as png")
keyscreen.addstr(10,9,"l: generate an entry for Elog")
keyscreen.addstr(11,9,"q: quit")
def undoCurses():
mscreen.keypad(0)
curses.nocbreak()
curses.echo()
curses.curs_set(1)
curses.endwin()
# Grab a grayscale video frame as 64bit floats
def GrabFrame():
ret, frame = cap.read()
# convert to grayscale and floats
return ret, cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY).astype(float)
def Clear():
sys.stderr.write("\x1b[2J\x1b[H")
def ToEpics():
hsum = hist.GetSum()
beam = CheckBeam()
if beam and fits:
caput("BEAM:PhotonCam:CenterX.A",hist.GetFunction("f2").GetParameter(1))
caput("BEAM:PhotonCam:CenterY.A",hist.GetFunction("f2").GetParameter(3))
caput("BEAM:PhotonCam:WidthX.A",hist.GetFunction("f2").GetParameter(2))
caput("BEAM:PhotonCam:WidthY.A",hist.GetFunction("f2").GetParameter(4))
caput("BEAM:PhotonCam:Sum.A",hsum)
else:
caput("BEAM:PhotonCam:CenterX.A",float('nan'))
caput("BEAM:PhotonCam:CenterY.A",float('nan'))
caput("BEAM:PhotonCam:WidthX.A",float('nan'))
caput("BEAM:PhotonCam:WidthY.A",float('nan'))
caput("BEAM:PhotonCam:Sum.A",hsum)
def GenerateElog():
filename1 = SaveHistograms()
filename2 = SaveCamera()
statescreen.erase()
date = datetime.datetime.now()
elog_cmd = "echo 'Beamspot Pictures from " + date.strftime("%Y-%m-%d-%H:%M:%S") + "\\n\\n"
elog_cmd = elog_cmd + " Center is at: (x,y) = ( {:>.2f} , {:>.2f} )\\n".format(caget("BEAM:PhotonCam:CenterX"),
caget("BEAM:PhotonCam:CenterY") )
elog_cmd = elog_cmd + " Ratio: Ladder/p2 = {:>.2f}".format(caget(epics_ladderp2)) + "' | "
elog_cmd = elog_cmd + "/opt/elog/bin/elog -h elog.office.a2.kph -u a2online a2messung "
elog_cmd = elog_cmd + "-l '" + logbookName +"' "
elog_cmd = elog_cmd + "-a Experiment='"+ experimentName +"' "
elog_cmd = elog_cmd + "-a Author='PLEASE FILL IN' -a Type=Routine "
elog_cmd = elog_cmd + "-a Subject='Photon beam profile' "
elog_cmd = elog_cmd + "-f " + filename1 + " ";
elog_cmd = elog_cmd + "-f " + filename2;
statescreen.addstr( 2,2, "Generate Elog-entry: ")
statescreen.addstr( 3,4, "Saving histograms...")
statescreen.addstr( 4,4, "Saving beamspot images...")
if os.system(elog_cmd) == 0:
statescreen.addstr( 6,6, "Elog, entry ready,")
statescreen.addstr( 7,6, "please add names!")
else:
statescreen.addstr( 6,6, "Error:")
statescreen.addstr( 7,6, "Posting elog entry failed!")
os.remove(filename1)
os.remove(filename2)
def SaveHistograms():
date = datetime.datetime.now()
filename = date.strftime('BeamspotFit-%Y-%m-%d_%H-%M-%S.png')
#print "Saving Histograms to ",filename
c.SetWindowSize(windowsize[0], windowsize[1])
c.Update()
c.SaveAs(filename)
return filename
def SaveCamera():
date = datetime.datetime.now()
filename = date.strftime('Beamspot-%Y-%m-%d_%H-%M-%S.png')
#print "Saving Camera Picture to ",filename
cv2.imwrite( filename, sumbuf )
return filename
def StartMeasurement():
global last_p
global curframe
curframe = 0
last_p = 0
def Analyse():
global buf
hist.Reset()
date = datetime.datetime.now()
Title = date.strftime('Beam Profile %Y-%m-%d %H:%M:%S')
hist.SetTitle(Title)
#print("Filling Histogram...")
buf /= numframes
size=buf.shape
# this is SLOOOOOW
for x in range(size[1]):
xpos = float(settings.mm2pix*x)
for y in range(size[0]):
ypos = float(settings.mm2pix*y)
hist.Fill(xpos,ypos, buf[size[0] - y - 1][x])
histx = hist.ProjectionX()
histx.SetTitle(date.strftime('Beam X-Projection %Y-%m-%d %H:%M:%S'))
histy = hist.ProjectionY()
histy.SetTitle(date.strftime('Beam Y-Projection %Y-%m-%d %H:%M:%S'))
#print("Fitting...")
c.cd(1)
if fits:
hist.Fit("f2","Q")
if dumpdata:
datafile.write(str(f2.GetChisquare()) + " " )
hist.Draw("ARR")
c.cd(2)
if fits:
hist.GetFunction("f2").SetBit(ROOT.TF2.kNotDraw);
hist.Draw("col")
c.cd(1)
if fits:
f2.Draw("same")
c.cd(3)
if fits:
histx.Fit("f1","Q")
if dumpdata:
datafile.write(str(f1.GetChisquare()) + " " )
histx.Draw("")
c.cd(4)
if fits:
histy.Fit("f1","Q")
if dumpdata:
datafile.write(str(f1.GetChisquare()) + " ")
datafile.write(str(f2.GetParameter(1)) + " " + str(f2.GetParameter(3)) + " ")
datafile.write(str(caget(epics_ladderp2)))
datafile.write("\n" )
histy.Draw("")
c.Update()
#print("Done")
if(epicson):
ToEpics()
if(automode):
StartMeasurement()
if( cap.isOpened()):
ret, sumbuf = GrabFrame()
buf = sumbuf
analysed = False
while(cap.isOpened()):
ret, frame = GrabFrame()
if curframe == 0:
mscreen.clear()
refreshWin(mscreen,"Photon Camera Programm")
refreshWin(statescreen,"Status")
putState(analysed)
buf=frame
if ret==True:
sumbuf = cv2.addWeighted(sumbuf, 1-average_factor, frame, average_factor, 0)
if curframe < numframes:
p = round(1.0 * curframe/numframes*10)
if( p > last_p):
putKeys()
refreshWin(keyscreen, "Hotkeys (in CV2-frames)")
putLoading(p)
refreshWin(loadscreen)
last_p = p
# accumulate frames
buf+=frame
# show actual frame, converted to 8bit
cv2.imshow("BEAMCAMERA", frame.astype(np.uint8))
cv2.imshow("BEAMCAMERA - Averaged", sumbuf.astype(np.uint8))
curframe = curframe + 1
else:
#print("Error reading video.")
break
# Keyboad Input
cvkey = cv2.waitKey(1) & 0xFF;
#nckey = mscreen.getkey() #blocks programm, fix this?
if(cvkey == ord('q')):
break
elif( cvkey == ord('r')):
StartMeasurement()
elif( cvkey == ord('p')):
SaveCamera()
elif( cvkey == ord('s')):
SaveHistograms()
elif( cvkey == ord('l')):
GenerateElog()
elif( cvkey == ord('e')):
epicson ^= True;
elif( cvkey == ord('a')):
automode ^= True;
if(automode):
StartMeasurement()
elif( cvkey == ord('f')):
fits ^= True
#epicson = fits
if (curframe == numframes):
Analyse()
analysed = True
# Release everything if job is finished
cap.release()
cv2.destroyAllWindows()
if dumpdata:
datafile.close()
undoCurses()