-
Notifications
You must be signed in to change notification settings - Fork 28
/
chronolapse.py
2012 lines (1626 loc) · 72.8 KB
/
chronolapse.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
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
chronolapse.py
@author: Collin "Keeyai" Green
@url: keeyai.com, collingreen.com, chronolapse.com
@summary:
Chronolapse is a tool for making timelapses.
CL can save both screenshots and webcam captures, and can even do them both
at the same time so they are 'synced' together. In addition to saving the
images, CL has some processing tools to compile your images into video,
create a picture-in-picture effect, and resize images.
@license: MIT license
"""
VERSION = '1.9.0'
import wx
import wx.adv
import wx.lib.masked as masked
import logging
from easyconfig import EasyConfig
import cv2
import os, sys, shutil, argparse
import time, datetime
import tempfile
import textwrap
import numpy # so pyinstaller packages it
import math
import subprocess
import urllib
import urllib.request
import threading
from PIL import Image, ImageDraw, ImageFont
logging.basicConfig(level=logging.ERROR)
can_check_idle_time = False
try:
import win32api
can_check_idle_time = True
except:
pass
from chronolapsegui import *
ON_WINDOWS = sys.platform.startswith('win')
class ChronoFrame(chronoFrame):
def __init__(self, *args, **kwargs):
chronoFrame.__init__(self, *args, **kwargs)
# parse command line arguments
self.parseArguments()
# parse saved configuration file
self.loadConfiguration()
# set up the rest of the application
self.setup()
def parseArguments(self):
parser = argparse.ArgumentParser()
# -a, --autostart
parser.add_argument("-a", "--autostart",
help="Automatically start capturing as soon as Chronolapse opens",
action="store_true")
# -b, --background
parser.add_argument("-b", "--background",
help="Start Chronolapse in the background",
action="store_true")
# configuration file location
parser.add_argument("--config_file",
help="The location of the Chronolapse configuration file",
default="chronolapse.config")
# sequential image format
parser.add_argument('--sequential_image_format',
help="Sets the format string for sequential image file names",
default='%05d')
parser.add_argument('--timestamp_filename_format',
help="Sets the format string for timestamp image file names",
default='%Y-%m-%d_%H-%M-%S')
# --verbose and --debug
parser.add_argument("-v", "--verbose",
help="Increase output verbosity",
action="store_true")
parser.add_argument("-d", "--debug",
help="Increase output verbosity to maximum",
action="store_true")
# parse the command line arguments
self.settings = parser.parse_args()
# set verbosity on the logging module
if self.settings.debug:
logging.basicConfig(level=logging.DEBUG)
logging.debug("Verbosity set to DEBUG")
elif self.settings.verbose:
logging.basicConfig(level=logging.INFO)
logging.info("Verbosity set to INFO")
logging.debug("Parsed command line options")
def _bindUI(self, field, key, section='chronolapse'):
"""
Creates a two way binding for the UI element and the given
section/key in the config.
"""
logging.debug("Binding %s[%s] to %s" % (section, key, str(field)))
if hasattr(field, 'SetValue'):
# if field is a checkbox, treat it differently
if hasattr(field, 'IsChecked'):
# on checkbox events, update the config
self.Bind(wx.EVT_CHECKBOX,
lambda event: self.updateConfig(
{key: field.IsChecked()}, from_ui=True),
field)
else:
# on text events, update the config
self.Bind(wx.EVT_TEXT,
lambda event: self.updateConfig(
{key: field.GetValue()}, from_ui=True),
field)
# on config changes, update the UI
self.config.add_listener(
section, key, lambda x: field.SetValue(x))
elif hasattr(field, 'SetStringSelection'):
# on Selection
self.Bind(wx.EVT_COMBOBOX,
lambda event: self.updateConfig(
{key: field.GetStringSelection()}, from_ui=True),
field)
# on config changes, update the UI
self.config.add_listener(
section, key, lambda x: field.SetStringSelection(str(x)))
def updateConfig(self, config, section='chronolapse', from_ui=False):
if from_ui:
logging.debug("Updating config from UI: %s" % str(config))
else:
logging.debug("Updating config: %s" % str(config))
self.config.updateBatch(section, config, notify=not from_ui)
def getConfig(self, key, section='chronolapse', default=None):
return self.config.get(section, key, default=default)
def loadConfiguration(self):
logging.debug(
"Loading configuration file: %s" % self.settings.config_file)
config_file_path = os.path.abspath(self.settings.config_file)
self.config = EasyConfig(config_file_path, defaults={
'chronolapse': {
'frequency': '60',
'use_screenshot': True,
'screenshot_timestamp': True,
'screenshot_timestamp_format': '%Y-%m-%d %H:%M:%S',
'screenshot_save_folder': 'screenshots',
'screenshot_prefix': 'screen_',
'screenshot_format': 'jpg',
'screenshot_dual_monitor': False,
'skip_if_idle': False,
'screenshot_subsection': False,
'screenshot_subsection_top': '0',
'screenshot_subsection_left': '0',
'screenshot_subsection_width': '800',
'screenshot_subsection_height': '600',
'use_webcam': False,
'webcam_timestamp': True,
'webcam_timestamp_format': '%Y-%m-%d %H:%M:%S',
'webcam_save_folder': 'webcam',
'webcam_prefix': 'cam_',
'webcam_format': 'jpg',
'webcam_timestamp_top': 10,
'webcam_timestamp_left': 10,
'webcam_timestamp_red': 255,
'webcam_timestamp_green': 255,
'webcam_timestamp_blue': 255,
'webcam_device_number': 0,
'webcam_resolution_x': 0,
'webcam_resolution_y': 0,
'filename_format': 'timestamp',
'pip_main_folder': '',
'pip_pip_folder': '',
'pip_output_folder': '',
'pip_size': 'Small',
'pip_position': 'Top-Right',
'pip_ignore_unmatched': True,
'video_source_folder': '',
'video_output_folder': '',
'video_format': '',
'video_codec': 'mpeg4',
'video_framerate': '10',
'mencoder_path': 'mencoder',
'audio_source_video': '',
'audio_source': '',
'audio_output_folder': '',
'last_update': time.strftime('%Y-%m-%d'),
'update_check_frequency': 604800
}
})
# look for existing config file - load it if possible
if os.path.exists(self.settings.config_file):
try:
self.config.load()
logging.debug("Loaded config")
except IOError as e:
logging.error("Failed to load Config File: %s" % str(e))
self.showWarning(
"Failed to Load Config",
"Failed to Load Configuration File. " \
+ "Please check your file permissions."
)
self.Close()
# bind all the ui fields to the config manager
logging.debug("Binding events")
self._bindUI(self.frequencytext, 'frequency')
self._bindUI(self.screenshotcheck, 'use_screenshot')
self._bindUI(self.webcamcheck, 'use_webcam')
self._bindUI(self.ignoreidlecheck, 'skip_if_idle')
self._bindUI(self.pipmainimagefoldertext, 'pip_main_folder')
self._bindUI(self.pippipimagefoldertext, 'pip_pip_folder')
self._bindUI(self.pipoutputimagefoldertext, 'pip_output_folder')
self._bindUI(self.pipsizecombo, 'pip_size')
self._bindUI(self.pippositioncombo, 'pip_position')
self._bindUI(self.pipignoreunmatchedcheck, 'pip_ignore_unmatched')
self._bindUI(self.videosourcetext, 'video_source_folder')
self._bindUI(self.videodestinationtext, 'video_output_folder')
self._bindUI(self.videocodeccombo, 'video_codec')
self._bindUI(self.videoframeratetext, 'video_framerate')
self._bindUI(self.mencoderpathtext, 'mencoder_path')
self._bindUI(self.audiosourcevideotext, 'audio_source_video')
self._bindUI(self.audiosourcetext, 'audio_source')
self._bindUI(self.audiooutputfoldertext, 'audio_output_folder')
# bind fps
self.Bind(
wx.EVT_TEXT,
self.recalculateVideoLength,
self.videoframeratetext
)
# calculate video length now
self.recalculateVideoLength()
# create custom binding for filename format
self.Bind(wx.EVT_RADIOBUTTON ,
lambda event: self.updateConfig(
{'filename_format':
'timestamp'
if self.filename_format_timestamp.GetValue()
else 'sequential'},
from_ui=True),
self.filename_format_timestamp)
self.Bind(wx.EVT_RADIOBUTTON ,
lambda event: self.updateConfig(
{'filename_format':
'timestamp'
if self.filename_format_timestamp.GetValue()
else 'sequential'},
from_ui=True),
self.filename_format_sequential)
# on config changes, update the UI
self.config.add_listener(
'chronolapse',
'filename_format',
lambda x:
self.filename_format_timestamp.SetValue(x == 'timestamp')
)
self.config.add_listener(
'chronolapse',
'filename_format',
lambda x:
self.filename_format_sequential.SetValue(x == 'sequential')
)
def setup(self):
# bind OnClose method
self.Bind(wx.EVT_CLOSE, self.OnClose)
# save path to folder where chronolapse is currently running
self.CHRONOLAPSEPATH = os.path.dirname( os.path.abspath(sys.argv[0]))
# set X to close to taskbar -- windows only
# http://code.activestate.com/recipes/475155/
self.TBFrame = TaskBarFrame(None, self, -1, " ", self.CHRONOLAPSEPATH)
self.TBFrame.Show(False)
# webcam
self.cam = None
# image countdown
self.countdown = 60
try:
self.countdown = float(self.getConfig('frequency', default=60))
except ValueError:
pass
# create timer
self.timer = Timer(self.timerCallBack)
# constants
self.VERSION = VERSION
self.DOCFILE = 'manual.html'
self.VERSION_CHECK_PATH = 'http://chronolapse.com/versioncheck/'
# fill in codecs available
video_codecs = [
'mpeg4', 'msmpeg4', 'msmpeg4v2', 'wmv1', 'mjpeg', 'h263p', 'h264']
self.videocodeccombo.SetItems(video_codecs)
self.videocodeccombo.SetStringSelection(
self.getConfig('video_codec', default=video_codecs[0])
)
# check version
self.checkVersion()
# for idle checking (win only)
self.last_event_info = None
# load icon - #TODO: embed with base64?
if ON_WINDOWS:
icon_file = os.path.join(self.CHRONOLAPSEPATH, 'chronolapse.ico')
else:
icon_file = os.path.join(self.CHRONOLAPSEPATH, 'chronolapse_24.ico')
if os.path.isfile(icon_file):
self.SetIcon(wx.Icon(icon_file, wx.BITMAP_TYPE_ICO))
else:
logging.warning( 'Could not find %s' % icon_file)
# autostart
if self.settings.autostart:
self.startCapturePressed(None)
def doShow(self, *args, **kwargs):
if self.settings.background:
logging.debug("Starting minimized")
self.TBFrame.set_icon_action_text(True)
#self.ShowWithoutActivating(*args, **kwargs)
else:
logging.debug("Showing main frame")
self.Show(*args, **kwargs)
def OnClose(self, event):
try:
if hasattr(self, 'TBFrame') and self.TBFrame:
self.TBFrame.kill(event)
except: pass
event.Skip()
def startTimer(self):
# set countdown
self.countdown = float(self.frequencytext.GetValue())
# start timer - if frequency < 1 second, use small increments
# otherwise, 1 second will be plenty fast
if self.countdown < 1:
self.timer.Start( self.countdown * 1000)
else:
self.timer.Start(1000)
def stopTimer(self):
self.timer.Stop()
def timerCallBack(self):
# decrement timer
self.countdown -= 1
# adjust progress bar
self.progresspanel.setProgress(1- (self.countdown / float(self.frequencytext.GetValue())))
# on countdown
if self.countdown <= 0:
self.capture() # take screenshot and webcam capture
self.countdown = float(self.frequencytext.GetValue()) # reset timer
def fileBrowser(self, message, defaultFile=''):
dlg = wx.FileDialog(self, message, defaultFile=defaultFile,
style=wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)
if dlg.ShowModal() == wx.ID_OK:
path = dlg.GetPath()
else:
path = ''
dlg.Destroy()
return path
def saveFileBrowser(self, message, defaultFile=''):
dlg = wx.FileDialog(self, message, defaultFile=defaultFile,
style=wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
if dlg.ShowModal() == wx.ID_OK:
path = dlg.GetPath()
else:
path = ''
dlg.Destroy()
return path
def dirBrowser(self, message, defaultpath):
# show dir dialog
dlg = wx.DirDialog(
self, message=message,
defaultPath= defaultpath,
style=wx.DD_DEFAULT_STYLE)
# Show the dialog and retrieve the user response.
if dlg.ShowModal() == wx.ID_OK:
# load directory
path = dlg.GetPath()
else:
path = ''
# Destroy the dialog.
dlg.Destroy()
return path
def hasBeenIdle(self):
if can_check_idle_time:
previous_event_info = self.last_event_info
event_info = win32api.GetLastInputInfo()
self.last_event_info = event_info
if previous_event_info == event_info:
return True
return False
def capture(self, force=False):
# check if idle if necessary
if not force and self.getConfig('skip_if_idle'):
if self.hasBeenIdle():
logging.debug('Skipping Capture - Idle')
return
# get filename from time
if self.getConfig('filename_format') == 'timestamp':
filename = time.strftime(
self.settings.timestamp_filename_format)
# use microseconds if capture speed is less than 1
capture_delay = float(self.frequencytext.GetValue())
if capture_delay < 1:
filename = str( time.time() )
# get sequential filename
else:
highest_number = 0
if self.getConfig('use_screenshot'):
screenshot_file_list = os.listdir(
os.path.abspath(
self.getConfig('screenshot_save_folder')
)
)
prefix = self.getConfig('screenshot_prefix')
for fname in screenshot_file_list:
base, extension = os.path.splitext(fname)
if base.startswith(prefix):
numeric_base = base[len(prefix):]
try:
highest_number = max(highest_number, int(numeric_base))
except ValueError as e:
# ignore files that are not parsable as numbers
pass
if self.getConfig('use_webcam'):
webcam_file_list = os.listdir(
os.path.abspath(
self.getConfig('webcam_save_folder')
)
)
prefix = self.getConfig('webcam_prefix')
for fname in webcam_file_list:
base, extension = os.path.splitext(fname)
if base.startswith(prefix):
numeric_base = base[len(prefix):]
try:
highest_number = max(highest_number, int(numeric_base))
except ValueError as e:
# ignore files that are not parsable as numbers
pass
# create sequential filename
filename = (self.settings.sequential_image_format %
(highest_number + 1))
logging.debug('Capturing - ' + filename)
# if screenshots
if self.getConfig('use_screenshot'):
# take screenshot
self.saveScreenshot(filename)
# if webcam
if self.getConfig('use_webcam'):
# take webcam shot
self.saveWebcam(filename)
return filename
def saveScreenshot(self, filename):
timestamp = self.getConfig('screenshot_timestamp')
folder = self.getConfig('screenshot_save_folder')
prefix = self.getConfig('screenshot_prefix')
file_format = self.getConfig('screenshot_format')
rect = None
if self.getConfig('screenshot_subsection'):
if (self.getConfig('screenshot_subsection_top') > 0 and
self.getConfig('screenshot_subsection_left') > 0 and
self.getConfig('screenshot_subsection_width') > 0 and
self.getConfig('screenshot_subsection_height') > 0):
rect = wx.Rect(
int(self.getConfig('screenshot_subsection_top')),
int(self.getConfig('screenshot_subsection_left')),
int(self.getConfig('screenshot_subsection_width')),
int(self.getConfig('screenshot_subsection_height'))
)
img = self.takeScreenshot(rect, timestamp)
self.saveImage(img, filename, folder, prefix, file_format)
def takeScreenshot(self, rect = None, timestamp=False):
"""Takes a screenshot of the screen at give pos & size (rect).
Code from Andrea -
http://lists.wxwidgets.org/pipermail/wxpython-users/2007-October/069666.html
"""
# use whole screen if none specified
if not rect:
#width, height = wx.DisplaySize()
#rect = wx.Rect(0,0,width,height)
x, y, width, height = wx.Display().GetGeometry()
rect = wx.Rect(x,y,width,height)
try:
# use two monitors if checked and available
if (self.getConfig('screenshot_dual_monitor')
and wx.Display_GetCount() > 0):
second = wx.Display(1)
x2, y2, width2, height2 = second.GetGeometry()
x3 = min(x,x2)
y3 = min(y, y2)
width3 = max(x+width, x2+width2) - x3
height3 = max(height-y3, height2-y3)
rect = wx.Rect(x3, y3, width3, height3)
except Exception as e:
self.warning(
"Exception while attempting to capture second "
+ "monitor: %s" % repr(e))
#Create a DC for the whole screen area
dcScreen = wx.ScreenDC()
#Create a Bitmap that will later on hold the screenshot image
#Note that the Bitmap must have a size big enough to hold the screenshot
#-1 means using the current default colour depth
bmp = wx.EmptyBitmap(rect.width, rect.height)
#Create a memory DC that will be used for actually taking the screenshot
memDC = wx.MemoryDC()
#Tell the memory DC to use our Bitmap
#all drawing action on the memory DC will go to the Bitmap now
memDC.SelectObject(bmp)
#Blit (in this case copy) the actual screen on the memory DC
#and thus the Bitmap
memDC.Blit( 0, #Copy to this X coordinate
0, #Copy to this Y coordinate
rect.width, #Copy this width
rect.height, #Copy this height
dcScreen, #From where do we copy?
rect.x, #What's the X offset in the original DC?
rect.y #What's the Y offset in the original DC?
)
# write timestamp on image
if timestamp:
try:
stamp = time.strftime(self.getConfig('screenshot_timestamp_format'))
except ValueError:
logging.error("Invalid screenshot timestamp format")
return
if self.countdown < 1:
now = time.time()
micro = str(now - math.floor(now))[0:4]
stamp = stamp + micro
memDC.DrawText(stamp, 20, rect.height-30)
#Select the Bitmap out of the memory DC by selecting a new
#uninitialized Bitmap
memDC.SelectObject(wx.NullBitmap)
return bmp
def saveImage(self, bmp, filename, folder, prefix, format='jpg'):
# convert
img = bmp.ConvertToImage()
# save
if format == 'gif':
fileName = os.path.join(folder,"%s%s.gif" % (prefix, filename))
img.SaveFile(fileName, wx.BITMAP_TYPE_GIF)
elif format == 'png':
fileName = os.path.join(folder,"%s%s.png" % (prefix, filename))
img.SaveFile(fileName, wx.BITMAP_TYPE_PNG)
else:
fileName = os.path.join(folder,"%s%s.jpg" % (prefix, filename))
img.SaveFile(fileName, wx.BITMAP_TYPE_JPEG)
def saveWebcam(self, filename):
timestamp = self.getConfig('webcam_timestamp')
timestamp_format = self.getConfig('webcam_timestamp_format')
folder = self.getConfig('webcam_save_folder')
prefix = self.getConfig('webcam_prefix')
file_format = self.getConfig('webcam_format')
self.takeWebcam(
filename, folder, prefix, file_format, timestamp, timestamp_format)
def getWebcamCapture(self):
# get the device number from config
device_number = self.getConfig('webcam_device_number')
# turn on camera, capture, turn off
cam = cv2.VideoCapture(device_number)
resolution_x = int(self.getConfig('webcam_resolution_x'))
resolution_y = int(self.getConfig('webcam_resolution_y'))
if resolution_x != 0:
cam.set( cv2.CAP_PROP_FRAME_WIDTH, resolution_x )
if resolution_y != 0:
cam.set( cv2.CAP_PROP_FRAME_HEIGHT, resolution_y )
# first read from opencv cam seems unreliable
result, image = cam.read()
result, image = cam.read()
cam.release()
if result:
return image
return None
def takeWebcam(self,
filename, folder,
prefix, file_format='jpg',
use_timestamp=False, timestamp_format=None):
# build filepath
filepath = os.path.join(
folder,"%s%s.%s" % (prefix, filename, file_format))
# get image from webcam
image = self.getWebcamCapture()
if image is None:
logging.warning("No image returned from camera")
return None
# write timestamp as necessary
if use_timestamp:
# if no format passed in, get from config
if timestamp_format is None:
timestamp_format = self.getConfig('webcam_timestamp_format')
# build timestamp
stamp = None
try:
stamp = time.strftime(timestamp_format)
except ValueError:
logging.error("Invalid timestamp format")
if stamp:
logging.debug("Writing timestamp %s" % stamp)
top = self.getConfig('webcam_timestamp_top')
left = self.getConfig('webcam_timestamp_left')
# convert to pil image
converted = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
pil_image = Image.fromarray(converted)
r,g,b = (self.getConfig('webcam_timestamp_red'),
self.getConfig('webcam_timestamp_green'),
self.getConfig('webcam_timestamp_blue'))
draw = ImageDraw.Draw(pil_image)
#font = ImageFont.truetype("sans-serif.ttf", 16)
font = ImageFont.load_default()
#draw.text((0, 0), stamp, (255,255,255), font=font)
draw.text( (top, left), stamp, fill=(255,255,255), font=font)
pil_image.save(filepath)
else:
logging.debug("Not writing timestamp")
# write file
cv2.imwrite(filepath, image)
return filepath
def showWarning(self, title, message):
dlg = wx.MessageDialog(self, message, title, wx.OK | wx.ICON_ERROR)
dlg.ShowModal()
dlg.Destroy()
def screenshotConfigurePressed(self, event):
dlg = ScreenshotConfigDialog(self)
# save reference to this
self.screenshotdialog = dlg
# set current options in dlg
dlg.dualmonitorscheck.SetValue(
self.getConfig('screenshot_dual_monitor', default=False))
dlg.subsectioncheck.SetValue(
self.getConfig('screenshot_subsection', default=False))
dlg.subsectiontop.SetValue(
str(self.getConfig('screenshot_subsection_top')))
dlg.subsectionleft.SetValue(
str(self.getConfig('screenshot_subsection_left')))
dlg.subsectionwidth.SetValue(
str(self.getConfig('screenshot_subsection_width')))
dlg.subsectionheight.SetValue(
str(self.getConfig('screenshot_subsection_height')))
# call this to toggle subsection option enabled/disabled
dlg.Bind(wx.EVT_CHECKBOX, self.subsectionchecked)
self.subsectionchecked()
dlg.timestampcheck.SetValue(self.getConfig('screenshot_timestamp'))
dlg.screenshot_timestamp_format.SetValue(
self.getConfig('screenshot_timestamp_format'))
dlg.screenshotprefixtext.SetValue(self.getConfig('screenshot_prefix'))
dlg.screenshotsavefoldertext.SetValue(
self.getConfig('screenshot_save_folder'))
dlg.screenshotformatcombo.SetStringSelection(
self.getConfig('screenshot_format'))
if dlg.ShowModal() == wx.ID_OK:
# save dialog info
self.updateConfig({
'screenshot_timestamp': dlg.timestampcheck.IsChecked(),
'screenshot_timestamp_format': dlg.screenshot_timestamp_format.GetValue(),
'screenshot_prefix': dlg.screenshotprefixtext.GetValue(),
'screenshot_save_folder': dlg.screenshotsavefoldertext.GetValue(),
'screenshot_format': dlg.screenshotformatcombo.GetStringSelection(),
'screenshot_dual_monitor': dlg.dualmonitorscheck.IsChecked(),
'screenshot_subsection': dlg.subsectioncheck.IsChecked(),
'screenshot_subsection_top': dlg.subsectiontop.GetValue(),
'screenshot_subsection_left': dlg.subsectionleft.GetValue(),
'screenshot_subsection_width': dlg.subsectionwidth.GetValue(),
'screenshot_subsection_height': dlg.subsectionheight.GetValue()
})
dlg.Destroy()
def webcamConfigurePressed(self, event):
dlg = WebcamConfigDialog(self)
if dlg.has_cam:
# set current options in dlg
dlg.webcamtimestampcheck.SetValue(
self.getConfig('webcam_timestamp'))
dlg.webcam_timestamp_format.SetValue(
self.getConfig('webcam_timestamp_format'))
dlg.webcamprefixtext.SetValue(self.getConfig('webcam_prefix'))
dlg.webcamsavefoldertext.SetValue(
self.getConfig('webcam_save_folder'))
dlg.webcamformatcombo.SetStringSelection(
self.getConfig('webcam_format'))
if dlg.ShowModal() == wx.ID_OK:
logging.debug("Saving webcam folder %s" % dlg.webcamsavefoldertext.GetValue())
# save dialog info
self.updateConfig({
'webcam_timestamp': dlg.webcamtimestampcheck.IsChecked(),
'webcam_timestamp_format': dlg.webcam_timestamp_format.GetValue(),
'webcam_prefix': dlg.webcamprefixtext.GetValue(),
'webcam_save_folder': dlg.webcamsavefoldertext.GetValue(),
'webcam_format': dlg.webcamformatcombo.GetStringSelection()
})
dlg.Destroy()
def startCapturePressed(self, event): # wxGlade: chronoFrame.<event_handler>
text = self.startbutton.GetLabel()
# update video length
self.recalculateVideoLength()
if text == 'Start Capture':
use_screenshot = self.getConfig('use_screenshot')
screenshot_folder = os.path.abspath(
self.getConfig('screenshot_save_folder')
)
use_webcam = self.getConfig('use_webcam')
webcam_folder = os.path.abspath(
self.getConfig('webcam_save_folder')
)
# check that screenshot and webcam folders are available
if use_screenshot:
# check screenshot save folder
if not os.access(screenshot_folder, os.W_OK):
self.showWarning('Cannot Write to Screenshot Folder',
("""Error: Cannot write to screenshot folder %s.
Please add write permission and try again.""") % screenshot_folder)
return False
if use_webcam:
if not os.access(webcam_folder, os.W_OK):
self.showWarning('Cannot Write to Webcam Folder',
("""Error: Cannot write to webcam folder %s.
Please add write permission and try again.""") % webcam_folder)
return False
# disable config buttons, frequency
self.screenshotcheck.Disable()
self.ignoreidlecheck.Disable()
self.screenshotconfigurebutton.Disable()
self.configurewebcambutton.Disable()
self.webcamcheck.Disable()
self.frequencytext.Disable()
self.filename_format_timestamp.Disable()
self.filename_format_sequential.Disable()
# change start button text to stop capture
self.startbutton.SetLabel('Stop Capture')
# start timer
if float(self.getConfig('frequency')) > 0:
self.startTimer()
elif text == 'Stop Capture':
# enable config buttons, frequency
self.screenshotcheck.Enable()
self.ignoreidlecheck.Enable()
self.screenshotconfigurebutton.Enable()
self.configurewebcambutton.Enable()
self.webcamcheck.Enable()
self.frequencytext.Enable()
self.filename_format_timestamp.Enable()
self.filename_format_sequential.Enable()
# change start button text to start capture
self.startbutton.SetLabel('Start Capture')
# stop timer
self.stopTimer()
def forceCapturePressed(self, event):
# save a capture right now
self.capture(force=True)
def pipMainImageBrowsePressed(self, event):
path = self.dirBrowser('Select folder containing main images',
self.pipmainimagefoldertext.GetValue())
if path != '':
self.updateConfig({'pip_main_folder': path})
def pipPipImageBrowsePressed(self, event):
path = self.dirBrowser('Select folder containing PIP images',
self.pippipimagefoldertext.GetValue())
if path != '':
self.updateConfig({'pip_pip_folder': path})
def pipOutputBrowsePressed(self, event):
path = self.dirBrowser('Select save folder for PIP images',
self.pipoutputimagefoldertext.GetValue())
if path != '':
self.updateConfig({'pip_output_folder': path})
if not os.access( path, os.W_OK):
self.showWarning("Permission Error",
"Error: the PIP output path %s is not writable. "
+ "Please set write permissions and try again." % path)
def createPipPressed(self, event): # wxGlade: chronoFrame.<event_handler>
# make sure output file is writable
if not os.access( self.pipoutputimagefoldertext.GetValue(), os.W_OK):
self.showWarning('Permission Error',
'Error: Output file is not writable. Please check your ' +
' permissions and try again.')
return False
# get pip settings
sourcefolder = self.pipmainimagefoldertext.GetValue()
pipfolder = self.pippipimagefoldertext.GetValue()
outfolder = self.pipoutputimagefoldertext.GetValue()
# pip size and position
pipsizestring = self.pipsizecombo.GetStringSelection()
pippositionstring = self.pippositioncombo.GetStringSelection()
# sort files - match up by sorting so prefixes work
sourcefiles = os.listdir(sourcefolder)
sourcefiles.sort()
pipfiles = os.listdir(pipfolder)
pipfiles.sort()
logging.debug('Creating PIP')
# progress dialog
progressdialog = wx.ProgressDialog(
'PIP Progress',
'Processing Images',
maximum=len(sourcefiles),
parent=self,
style =
wx.PD_CAN_ABORT | wx.PD_APP_MODAL |
wx.PD_ELAPSED_TIME | wx.PD_REMAINING_TIME)
# for all images in main folder
count = 0
for i in xrange( min(len(sourcefiles), len(pipfiles))):
sourcefile = sourcefiles[i]
pipfile = pipfiles[i]
# update progress dialog
count += 1
cancel, somethingelse = progressdialog.Update(
count, 'Processing %s'%sourcefile)
# update progress dialog
if not cancel:
progressdialog.Destroy()
break
try:
# open with PIL -- will skip non-images
source = Image.open(os.path.join(sourcefolder, sourcefile))
pip = Image.open(os.path.join(pipfolder, pipfile))
# get pip size - sides
if pippositionstring == 'Left' or pippositionstring == 'Right':
if pipsizestring == 'Small':
pipsize = ( source.size[0] / 4, source.size[1])
elif pipsizestring == 'Medium':