forked from stb-tester/stb-tester
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstbt.py
2224 lines (1802 loc) · 79.6 KB
/
stbt.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
"""Main stb-tester python module. Intended to be used with `stbt run`.
See `man stbt` and http://stb-tester.com for documentation.
Copyright 2012-2013 YouView TV Ltd and contributors.
License: LGPL v2.1 or (at your option) any later version (see
https://github.com/drothlis/stb-tester/blob/master/LICENSE for details).
"""
import argparse
from collections import namedtuple, deque
import ConfigParser
import contextlib
import datetime
import errno
import functools
import glob
import inspect
import os
import Queue
import re
import socket
import subprocess
import sys
import threading
import tempfile
import time
import warnings
import cv2
import numpy
import irnetbox
@contextlib.contextmanager
def hide_argv():
""" For use with 'with' statement: Provides a context with an empty
argument list.
This is used because otherwise gst-python will exit if '-h', '--help', '-v'
or '--version' command line arguments are given.
"""
old_argv = sys.argv[:]
sys.argv = [sys.argv[0]]
try:
yield
finally:
sys.argv = old_argv
@contextlib.contextmanager
def hide_stderr():
"""For use with 'with' statement: Hide stderr output.
This is used because otherwise gst-python will print
'pygobject_register_sinkfunc is deprecated'.
"""
fd = sys.__stderr__.fileno()
saved_fd = os.dup(fd)
sys.__stderr__.flush()
null_stream = open(os.devnull, 'w', 0)
os.dup2(null_stream.fileno(), fd)
try:
yield
finally:
sys.__stderr__.flush()
os.dup2(saved_fd, sys.__stderr__.fileno())
null_stream.close()
import pygst # gstreamer
pygst.require("0.10")
with hide_argv(), hide_stderr():
import gst
import gobject
import glib
warnings.filterwarnings(
action="always", category=DeprecationWarning, message='.*stb-tester')
_config = None
# Functions available to stbt scripts
#===========================================================================
def get_config(section, key, default=None, type_=str):
"""Read the value of `key` from `section` of the stbt config file.
See 'CONFIGURATION' in the stbt(1) man page for the config file search
path.
Raises `ConfigurationError` if the specified `section` or `key` is not
found, unless `default` is specified (in which case `default` is returned).
"""
global _config
if not _config:
_config = ConfigParser.SafeConfigParser()
_config.readfp(
open(os.path.join(os.path.dirname(__file__), 'stbt.conf')))
try:
# Host-wide config, e.g. /etc/stbt/stbt.conf (see `Makefile`).
system_config = _config.get('global', '__system_config')
except ConfigParser.NoOptionError:
# Running `stbt` from source (not installed) location.
system_config = ''
_config.read([
system_config,
# User config: ~/.config/stbt/stbt.conf, as per freedesktop's base
# directory specification:
'%s/stbt/stbt.conf' % os.environ.get(
'XDG_CONFIG_HOME', '%s/.config' % os.environ['HOME']),
# Config files specific to the test suite / test run:
os.environ.get('STBT_CONFIG_FILE', ''),
])
try:
return type_(_config.get(section, key))
except ConfigParser.Error as e:
if default is None:
raise ConfigurationError(e.message)
else:
return default
except ValueError:
raise ConfigurationError("'%s.%s' invalid type (must be %s)" % (
section, key, type_.__name__))
def press(
key,
interpress_delay_secs=get_config(
"press", "interpress_delay_secs", type_=float)):
"""Send the specified key-press to the system under test.
The mechanism used to send the key-press depends on what you've configured
with `--control`.
`key` is a string. The allowed values depend on the control you're using:
If that's lirc, then `key` is a key name from your lirc config file.
`interpress_delay_secs` is a floating-point number that specifies a minimum
time to wait after the preceding key press, in order to accommodate the
responsiveness of the device under test.
The global default for `interpress_delay_secs` can be set in the
configuration file, in section `press`.
"""
if getattr(_control, 'time_of_last_press', None):
# `sleep` is inside a `while` loop because the actual suspension time
# of `sleep` may be less than that requested.
while True:
seconds_to_wait = (
_control.time_of_last_press - datetime.datetime.now() +
datetime.timedelta(seconds=interpress_delay_secs)
).total_seconds()
if seconds_to_wait > 0:
time.sleep(seconds_to_wait)
else:
break
_control.press(key)
_control.time_of_last_press = ( # pylint:disable=W0201
datetime.datetime.now())
draw_text(key, duration_secs=3)
def draw_text(text, duration_secs=3):
"""Write the specified `text` to the video output.
`duration_secs` is the number of seconds that the text should be displayed.
"""
_display.draw_text(text, duration_secs)
class MatchParameters(object):
"""Parameters to customise the image processing algorithm used by
`wait_for_match`, `detect_match`, and `press_until_match`.
You can change the default values for these parameters by setting
a key (with the same name as the corresponding python parameter)
in the `[match]` section of your stbt.conf configuration file.
`match_method` (str) default: From stbt.conf
The method that is used by the OpenCV `cvMatchTemplate` algorithm to find
likely locations of the "template" image within the larger source image.
Allowed values are ``"sqdiff-normed"``, ``"ccorr-normed"``, and
``"ccoeff-normed"``. For the meaning of these parameters, see the OpenCV
`cvMatchTemplate` reference documentation and tutorial:
* http://docs.opencv.org/modules/imgproc/doc/object_detection.html
* http://docs.opencv.org/doc/tutorials/imgproc/histograms/
template_matching/template_matching.html
`match_threshold` (float) default: From stbt.conf
How strong a result from `cvMatchTemplate` must be, to be considered a
match. A value of 0 will mean that anything is considered to match,
whilst a value of 1 means that the match has to be pixel perfect. (In
practice, a value of 1 is useless because of the way `cvMatchTemplate`
works, and due to limitations in the storage of floating point numbers in
binary.)
`confirm_method` (str) default: From stbt.conf
The result of the previous `cvMatchTemplate` algorithm often gives false
positives (it reports a "match" for an image that shouldn't match).
`confirm_method` specifies an algorithm to be run just on the region of
the source image that `cvMatchTemplate` identified as a match, to confirm
or deny the match.
The allowed values are:
"``none``"
Do not confirm the match. Assume that the potential match found is
correct.
"``absdiff``" (absolute difference)
The absolute difference between template and source Region of
Interest (ROI) is calculated; thresholded and eroded to account for
potential noise; and if any white pixels remain then the match is
deemed false.
"``normed-absdiff``" (normalized absolute difference)
As with ``absdiff`` but both template and ROI are normalized before
the absolute difference is calculated. This has the effect of
exaggerating small differences between images with similar, small
ranges of pixel brightnesses (luminance).
This method is more accurate than ``absdiff`` at reporting true and
false matches when there is noise involved, particularly aliased
text. However it will, in general, require a greater
confirm_threshold than the equivalent match with absdiff.
When matching solid regions of colour, particularly where there are
regions of either black or white, ``absdiff`` is better than
``normed-absdiff`` because it does not alter the luminance range,
which can lead to false matches. For example, an image which is half
white and half grey, once normalised, will match a similar image
which is half white and half black because the grey becomes
normalised to black so that the maximum luminance range of [0..255]
is occupied. However, if the images are dissimilar enough in
luminance, they will have failed to match the `cvMatchTemplate`
algorithm and won't have reached the "confirm" stage.
`confirm_threshold` (float) default: From stbt.conf
Increase this value to avoid false negatives, at the risk of increasing
false positives (a value of 1.0 will report a match every time).
`erode_passes` (int) default: From stbt.conf
The number of erode steps in the `absdiff` and `normed-absdiff` confirm
algorithms. Increasing the number of erode steps makes your test less
sensitive to noise and small variances, at the cost of being more likely
to report a false positive.
Please let us know if you are having trouble with image matches so that we
can further improve the matching algorithm.
"""
def __init__(
self,
match_method=get_config('match', 'match_method'),
match_threshold=get_config(
'match', 'match_threshold', type_=float),
confirm_method=get_config('match', 'confirm_method'),
confirm_threshold=get_config(
'match', 'confirm_threshold', type_=float),
erode_passes=get_config('match', 'erode_passes', type_=int)):
if match_method not in (
"sqdiff-normed", "ccorr-normed", "ccoeff-normed"):
raise ValueError("Invalid match_method '%s'" % match_method)
if confirm_method not in ("none", "absdiff", "normed-absdiff"):
raise ValueError("Invalid confirm_method '%s'" % confirm_method)
self.match_method = match_method
self.match_threshold = match_threshold
self.confirm_method = confirm_method
self.confirm_threshold = confirm_threshold
self.erode_passes = erode_passes
class Position(namedtuple('Position', 'x y')):
"""A point within the video frame.
`x` and `y` are integer coordinates (measured in number of pixels) from the
top left corner of the video frame.
"""
pass
class Region(namedtuple('Region', 'x y width height')):
"""Rectangular region within the video frame.
`x` and `y` are the coordinates of the top left corner of the region,
measured in pixels from the top left of the video frame. The `width` and
`height` of the rectangle are also measured in pixels.
"""
pass
class MatchResult(object):
"""
* `timestamp`: Video stream timestamp.
* `match`: Boolean result.
* `position`: `Position` of the match.
* `first_pass_result`: Value between 0 (poor) and 1.0 (excellent match)
from the first pass of the two-pass templatematch algorithm.
* `frame`: The video frame that was searched, in OpenCV format.
"""
def __init__(
self, timestamp, match, position, first_pass_result, frame=None):
self.timestamp = timestamp
self.match = match
self.position = position
self.first_pass_result = first_pass_result
if frame is None:
warnings.warn(
"Creating a 'MatchResult' without specifying 'frame' is "
"deprecated. In a future release of stb-tester the 'frame' "
"parameter will be mandatory.",
DeprecationWarning, stacklevel=2)
self.frame = frame
def __str__(self):
return (
"MatchResult(timestamp=%s, match=%s, position=%s, "
"first_pass_result=%s, frame=%s)" % (
self.timestamp,
self.match,
self.position,
self.first_pass_result,
"None" if self.frame is None else "%dx%dx%d" % (
self.frame.shape[1], self.frame.shape[0],
self.frame.shape[2])))
def detect_match(image, timeout_secs=10, noise_threshold=None,
match_parameters=None):
"""Generator that yields a sequence of one `MatchResult` for each frame
processed from the source video stream.
Returns after `timeout_secs` seconds. (Note that the caller can also choose
to stop iterating over this function's results at any time.)
The templatematch parameter `noise_threshold` is marked for deprecation
but appears in the args for backward compatibility with positional
argument syntax. It will be removed in a future release; please use
`match_parameters.confirm_threshold` intead.
Specify `match_parameters` to customise the image matching algorithm. See
the documentation for `MatchParameters` for details.
"""
if match_parameters is None:
match_parameters = MatchParameters()
if noise_threshold is not None:
warnings.warn(
"noise_threshold is deprecated and will be removed in a future "
"release of stb-tester. Please use "
"match_parameters.confirm_threshold instead.",
DeprecationWarning, stacklevel=2)
match_parameters.confirm_threshold = noise_threshold
template_name = _find_path(image)
if not os.path.isfile(template_name):
raise UITestError("No such template file: %s" % image)
template = cv2.imread(template_name, cv2.CV_LOAD_IMAGE_COLOR)
if template is None:
raise UITestError("Failed to load template file: %s" % template_name)
debug("Searching for " + template_name)
for frame, timestamp in frames(timeout_secs):
matched, position, first_pass_certainty = _match(
frame, template, match_parameters, template_name)
result = MatchResult(
timestamp, matched, position, first_pass_certainty,
numpy.copy(frame))
cv2.rectangle(
frame,
(position.x, position.y),
(position.x + template.shape[1], position.y + template.shape[0]),
(32, 0 if matched else 255, 255), # bgr
thickness=3)
if matched:
debug("Match found: %s" % str(result))
else:
debug("No match found. Closest match: %s" % str(result))
yield result
class MotionResult(namedtuple('MotionResult', 'timestamp motion')):
"""
* `timestamp`: Video stream timestamp.
* `motion`: Boolean result.
"""
pass
def detect_motion(timeout_secs=10, noise_threshold=None, mask=None):
"""Generator that yields a sequence of one `MotionResult` for each frame
processed from the source video stream.
Returns after `timeout_secs` seconds. (Note that the caller can also choose
to stop iterating over this function's results at any time.)
`noise_threshold` (float) default: From stbt.conf
`noise_threshold` is a parameter used by the motiondetect algorithm.
Increase `noise_threshold` to avoid false negatives, at the risk of
increasing false positives (a value of 0.0 will never report motion).
This is particularly useful with noisy analogue video sources.
The default value is read from `motion.noise_threshold` in your
configuration file.
`mask` (str) default: None
A mask is a black and white image that specifies which part of the image
to search for motion. White pixels select the area to search; black
pixels the area to ignore.
"""
if noise_threshold is None:
noise_threshold = get_config('motion', 'noise_threshold', type_=float)
debug("Searching for motion")
mask_image = None
if mask:
mask_image = _load_mask(mask)
previous_frame_gray = None
log = functools.partial(_log_image, directory="stbt-debug/detect_motion")
for frame, timestamp in frames(timeout_secs):
frame_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
log(frame_gray, "source")
if previous_frame_gray is None:
if (mask_image is not None and
mask_image.shape[:2] != frame.shape[:2]):
raise UITestError(
"The dimensions of the mask '%s' %s don't match the video "
"frame %s" % (mask, mask_image.shape, frame.shape))
previous_frame_gray = frame_gray
continue
absdiff = cv2.absdiff(frame_gray, previous_frame_gray)
previous_frame_gray = frame_gray
log(absdiff, "absdiff")
if mask_image is not None:
absdiff = cv2.bitwise_and(absdiff, mask_image)
log(mask_image, "mask")
log(absdiff, "absdiff_masked")
_, thresholded = cv2.threshold(
absdiff, int((1 - noise_threshold) * 255), 255, cv2.THRESH_BINARY)
eroded = cv2.erode(
thresholded,
cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)))
log(thresholded, "absdiff_threshold")
log(eroded, "absdiff_threshold_erode")
motion = (cv2.countNonZero(eroded) > 0)
# Visualisation: Highlight in red the areas where we detected motion
if motion:
cv2.add(
frame,
numpy.multiply(
numpy.ones(frame.shape, dtype=numpy.uint8),
(0, 0, 255), # bgr
dtype=numpy.uint8),
mask=cv2.dilate(
thresholded,
cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (3, 3)),
iterations=1),
dst=frame)
result = MotionResult(timestamp, motion)
debug("%s found: %s" % (
"Motion" if motion else "No motion", str(result)))
yield result
def wait_for_match(image, timeout_secs=10, consecutive_matches=1,
noise_threshold=None, match_parameters=None):
"""Search for `image` in the source video stream.
Returns `MatchResult` when `image` is found.
Raises `MatchTimeout` if no match is found after `timeout_secs` seconds.
`consecutive_matches` forces this function to wait for several consecutive
frames with a match found at the same x,y position. Increase
`consecutive_matches` to avoid false positives due to noise.
The templatematch parameter `noise_threshold` is marked for deprecation
but appears in the args for backward compatibility with positional
argument syntax. It will be removed in a future release; please use
`match_parameters.confirm_threshold` instead.
Specify `match_parameters` to customise the image matching algorithm. See
the documentation for `MatchParameters` for details.
"""
if match_parameters is None:
match_parameters = MatchParameters()
if noise_threshold is not None:
warnings.warn(
"noise_threshold is deprecated and will be removed in a future "
"release of stb-tester. Please use "
"match_parameters.confirm_threshold instead.",
DeprecationWarning, stacklevel=2)
match_parameters.confirm_threshold = noise_threshold
match_count = 0
last_pos = Position(0, 0)
for res in detect_match(
image, timeout_secs, match_parameters=match_parameters):
if res.match and (match_count == 0 or res.position == last_pos):
match_count += 1
else:
match_count = 0
last_pos = res.position
if match_count == consecutive_matches:
debug("Matched " + image)
return res
raise MatchTimeout(res.frame, image, timeout_secs) # pylint: disable=W0631
def press_until_match(
key,
image,
interval_secs=get_config(
"press_until_match", "interval_secs", type_=int),
noise_threshold=None,
max_presses=get_config("press_until_match", "max_presses", type_=int),
match_parameters=None):
"""Calls `press` as many times as necessary to find the specified `image`.
Returns `MatchResult` when `image` is found.
Raises `MatchTimeout` if no match is found after `max_presses` times.
`interval_secs` is the number of seconds to wait for a match before
pressing again.
The global defaults for `interval_secs` and `max_presses` can be set
in the configuration file, in section `press_until_match`.
The templatematch parameter `noise_threshold` is marked for deprecation
but appears in the args for backward compatibility with positional
argument syntax. It will be removed in a future release; please use
`match_parameters.confirm_threshold` instead.
Specify `match_parameters` to customise the image matching algorithm. See
the documentation for `MatchParameters` for details.
"""
if match_parameters is None:
match_parameters = MatchParameters()
if noise_threshold is not None:
warnings.warn(
"noise_threshold is deprecated and will be removed in a future "
"release of stb-tester. Please use "
"match_parameters.confirm_threshold instead.",
DeprecationWarning, stacklevel=2)
match_parameters.confirm_threshold = noise_threshold
i = 0
while True:
try:
return wait_for_match(image, timeout_secs=interval_secs,
match_parameters=match_parameters)
except MatchTimeout:
if i < max_presses:
press(key)
i += 1
else:
raise
def wait_for_motion(
timeout_secs=10, consecutive_frames=None,
noise_threshold=None, mask=None):
"""Search for motion in the source video stream.
Returns `MotionResult` when motion is detected.
Raises `MotionTimeout` if no motion is detected after `timeout_secs`
seconds.
`consecutive_frames` (str) default: From stbt.conf
Considers the video stream to have motion if there were differences
between the specified number of `consecutive_frames`, which can be:
* a positive integer value, or
* a string in the form "x/y", where `x` is the number of frames with
motion detected out of a sliding window of `y` frames.
The default value is read from `motion.consecutive_frames` in your
configuration file.
`noise_threshold` (float) default: From stbt.conf
Increase `noise_threshold` to avoid false negatives, at the risk of
increasing false positives (a value of 0.0 will never report motion).
This is particularly useful with noisy analogue video sources.
The default value is read from `motion.noise_threshold` in your
configuration file.
`mask` (str) default: None
A mask is a black and white image that specifies which part of the image
to search for motion. White pixels select the area to search; black
pixels the area to ignore.
"""
if consecutive_frames is None:
consecutive_frames = get_config('motion', 'consecutive_frames')
consecutive_frames = str(consecutive_frames)
if '/' in consecutive_frames:
motion_frames = int(consecutive_frames.split('/')[0])
considered_frames = int(consecutive_frames.split('/')[1])
else:
motion_frames = int(consecutive_frames)
considered_frames = int(consecutive_frames)
if motion_frames > considered_frames:
raise ConfigurationError(
"`motion_frames` exceeds `considered_frames`")
debug("Waiting for %d out of %d frames with motion" % (
motion_frames, considered_frames))
matches = deque(maxlen=considered_frames)
for res in detect_motion(timeout_secs, noise_threshold, mask):
matches.append(res.motion)
if matches.count(True) >= motion_frames:
debug("Motion detected.")
return res
screenshot = get_frame()
raise MotionTimeout(screenshot, mask, timeout_secs)
class OcrMode(object):
"""Options to control layout analysis and assume a certain form of image.
For a (brief) description of each option, see the tesseract(1) man page:
http://tesseract-ocr.googlecode.com/svn/trunk/doc/tesseract.1.html
"""
ORIENTATION_AND_SCRIPT_DETECTION_ONLY = 0
PAGE_SEGMENTATION_WITH_OSD = 1
PAGE_SEGMENTATION_WITHOUT_OSD_OR_OCR = 2
PAGE_SEGMENTATION_WITHOUT_OSD = 3
SINGLE_COLUMN_OF_TEXT_OF_VARIABLE_SIZES = 4
SINGLE_UNIFORM_BLOCK_OF_VERTICALLY_ALIGNED_TEXT = 5
SINGLE_UNIFORM_BLOCK_OF_TEXT = 6
SINGLE_LINE = 7
SINGLE_WORD = 8
SINGLE_WORD_IN_A_CIRCLE = 9
SINGLE_CHARACTER = 10
def ocr(frame=None, region=None, mode=OcrMode.PAGE_SEGMENTATION_WITHOUT_OSD):
"""Return the text present in the video frame.
Perform OCR (Optical Character Recognition) using the "Tesseract"
open-source OCR engine, which must be installed on your system.
If `frame` isn't specified, take a frame from the source video stream.
If `region` is specified, only process that region of the frame; otherwise
process the entire frame.
"""
if frame is None:
frame = get_frame()
if region is not None:
frame = frame[
region.y:region.y + region.height,
region.x:region.x + region.width]
# $XDG_RUNTIME_DIR is likely to be on tmpfs:
tmpdir = os.environ.get("XDG_RUNTIME_DIR", None)
def mktmp(suffix):
return tempfile.NamedTemporaryFile(
prefix="stbt-ocr-", suffix=suffix, dir=tmpdir)
with mktmp(suffix=".png") as ocr_in, mktmp(suffix=".txt") as ocr_out:
cv2.imwrite(ocr_in.name, frame)
subprocess.check_call([
"tesseract", ocr_in.name, ocr_out.name[:-4], "-psm", str(mode)])
return ocr_out.read().strip()
def frames(timeout_secs=None):
"""Generator that yields frames captured from the GStreamer pipeline.
"timeout_secs" is in seconds elapsed, from the method call. Note that
you can also simply stop iterating over the sequence yielded by this
method.
Returns an (image, timestamp) tuple for every frame captured, where
"image" is in OpenCV format.
"""
return _display.frames(timeout_secs)
def save_frame(image, filename):
"""Saves an OpenCV image to the specified file.
Takes an image obtained from `get_frame` or from the `screenshot`
property of `MatchTimeout` or `MotionTimeout`.
"""
cv2.imwrite(filename, image)
def get_frame():
"""Returns an OpenCV image of the current video frame."""
return gst_to_opencv(_display.get_frame())
def is_screen_black(
frame, mask=None,
threshold=get_config('is_screen_black', 'threshold', type_=int)):
"""Check for the presence of a black screen in a video frame.
`frame` is the video frame to check, in OpenCV format (for example as
returned by `frames` and `get_frame`).
The optional `mask` is the filename of a black & white image mask. It must
have white pixels for parts of the frame to check and black pixels for any
parts to ignore.
Even when a video frame appears to be black, the intensity of its pixels
is not always 0. To differentiate almost-black from non-black pixels, a
binary threshold is applied to the frame. The `threshold` value is
in the range 0 (black) to 255 (white). The global default can be changed by
setting `threshold` in the `[is_screen_black]` section of `stbt.conf`.
"""
if mask:
mask = _load_mask(mask)
frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
_, frame = cv2.threshold(frame, threshold, 255, cv2.THRESH_BINARY)
_, maxVal, _, _ = cv2.minMaxLoc(frame, mask)
return maxVal == 0
def debug(msg):
"""Print the given string to stderr if stbt run `--verbose` was given."""
if _debug_level > 0:
sys.stderr.write(
"%s: %s\n" % (os.path.basename(sys.argv[0]), str(msg)))
@contextlib.contextmanager
def as_precondition(message):
"""Context manager that replaces UITestFailures with UITestErrors.
If you run your test scripts with stb-tester's batch runner, the reports it
generates will show test failures (that is, `UITestFailure` exceptions) as
red results, and unhandled exceptions of any other type as yellow results.
Note that `wait_for_match`, `wait_for_motion`, and similar functions raise
`UITestFailure` (red results) when they detect a failure. By running such
functions inside an `as_precondition` context, any `UITestFailure` (red)
they raise will be caught, and a `UITestError` (yellow) will be raised
instead.
When running a single test script hundreds or thousands of times to
reproduce an intermittent defect, it is helpful to mark unrelated failures
as test errors (yellow) rather than test failures (red), so that you can
focus on diagnosing the failures that are most likely to be the particular
defect you are interested in.
`message` is a string describing the precondition (it is not the error
message if the precondition fails).
For example:
>>> with as_precondition("Channels tuned"): #doctest:+NORMALIZE_WHITESPACE
... # Call tune_channels(), which raises:
... raise UITestFailure("Failed to tune channels")
Traceback (most recent call last):
...
PreconditionError: Didn't meet precondition 'Channels tuned'
(original exception was: Failed to tune channels)
"""
try:
yield
except UITestFailure as e:
raise PreconditionError(message, e)
class UITestError(Exception):
"""The test script had an unrecoverable error."""
pass
class UITestFailure(Exception):
"""The test failed because the system under test didn't behave as expected.
"""
pass
class NoVideo(UITestFailure):
"""No video available from the source pipeline."""
pass
class MatchTimeout(UITestFailure):
"""
* `screenshot`: An OpenCV image from the source video when the search
for the expected image timed out.
* `expected`: Filename of the image that was being searched for.
* `timeout_secs`: Number of seconds that the image was searched for.
"""
def __init__(self, screenshot, expected, timeout_secs):
super(MatchTimeout, self).__init__()
self.screenshot = screenshot
self.expected = expected
self.timeout_secs = timeout_secs
def __str__(self):
return "Didn't find match for '%s' within %d seconds." % (
self.expected, self.timeout_secs)
class MotionTimeout(UITestFailure):
"""
* `screenshot`: An OpenCV image from the source video when the search
for motion timed out.
* `mask`: Filename of the mask that was used (see `wait_for_motion`).
* `timeout_secs`: Number of seconds that motion was searched for.
"""
def __init__(self, screenshot, mask, timeout_secs):
super(MotionTimeout, self).__init__()
self.screenshot = screenshot
self.mask = mask
self.timeout_secs = timeout_secs
def __str__(self):
return "Didn't find motion%s within %d seconds." % (
" (with mask '%s')" % self.mask if self.mask else "",
self.timeout_secs)
class ConfigurationError(UITestError):
pass
class PreconditionError(UITestError):
"""Exception raised by `as_precondition`."""
def __init__(self, message, original_exception):
super(PreconditionError, self).__init__()
self.message = message
self.original_exception = original_exception
def __str__(self):
return (
"Didn't meet precondition '%s' (original exception was: %s)"
% (self.message, self.original_exception))
# stbt-run initialisation and convenience functions
# (you will need these if writing your own version of stbt-run)
#===========================================================================
def argparser():
parser = argparse.ArgumentParser()
parser.add_argument(
'--control',
default=get_config('global', 'control'),
help='The remote control to control the stb (default: %(default)s)')
parser.add_argument(
'--source-pipeline',
default=get_config('global', 'source_pipeline'),
help='A gstreamer pipeline to use for A/V input (default: '
'%(default)s)')
parser.add_argument(
'--sink-pipeline',
default=get_config('global', 'sink_pipeline'),
help='A gstreamer pipeline to use for video output '
'(default: %(default)s)')
parser.add_argument(
'--restart-source', action='store_true',
default=(get_config('global', 'restart_source').lower() in
("1", "yes", "true", "on")),
help='Restart the GStreamer source pipeline when video loss is '
'detected')
class IncreaseDebugLevel(argparse.Action):
num_calls = 0
def __call__(self, parser, namespace, values, option_string=None):
self.num_calls += 1
global _debug_level
_debug_level = self.num_calls
setattr(namespace, self.dest, _debug_level)
global _debug_level
_debug_level = get_config('global', 'verbose', type_=int)
parser.add_argument(
'-v', '--verbose', action=IncreaseDebugLevel, nargs=0,
default=get_config('global', 'verbose'), # for stbt-run arguments dump
help='Enable debug output (specify twice to enable GStreamer element '
'dumps to ./stbt-debug directory)')
return parser
def init_run(
gst_source_pipeline, gst_sink_pipeline, control_uri, save_video=False,
restart_source=False):
global _display, _control
_display = Display(
gst_source_pipeline, gst_sink_pipeline, save_video, restart_source)
_control = uri_to_remote(control_uri, _display)
def teardown_run():
if _display:
_display.teardown()
# Internal
#===========================================================================
_debug_level = 0
_mainloop = glib.MainLoop()
_display = None
_control = None
class Display:
def __init__(self, user_source_pipeline, user_sink_pipeline, save_video,
restart_source=False):
gobject.threads_init()
self.novideo = False
self.lock = threading.RLock() # Held by whoever is consuming frames
self.last_buffer = Queue.Queue(maxsize=1)
self.source_pipeline = None
self.start_timestamp = None
self.underrun_timeout = None
self.video_debug = []
self.restart_source_enabled = restart_source
appsink = (
"appsink name=appsink max-buffers=1 drop=true sync=false "
"emit-signals=true "
"caps=video/x-raw-rgb,bpp=24,depth=24,endianness=4321,"
"red_mask=0xFF,green_mask=0xFF00,blue_mask=0xFF0000")
self.source_pipeline_description = " ! ".join([
user_source_pipeline,
"queue leaky=downstream name=q",
"ffmpegcolorspace",
appsink])
self.create_source_pipeline()
if save_video:
if not save_video.endswith(".webm"):
save_video += ".webm"
debug("Saving video to '%s'" % save_video)
video_pipeline = (
"t. ! queue leaky=downstream ! ffmpegcolorspace ! "
"vp8enc speed=7 ! webmmux ! filesink location=%s" % save_video)
else:
video_pipeline = ""
sink_pipeline_description = " ".join([
"appsrc name=appsrc !",
"tee name=t",
video_pipeline,
"t. ! queue leaky=downstream ! ffmpegcolorspace !",
user_sink_pipeline
])
self.sink_pipeline = gst.parse_launch(sink_pipeline_description)
sink_bus = self.sink_pipeline.get_bus()
sink_bus.connect("message::error", self.on_error)
sink_bus.connect("message::warning", self.on_warning)
sink_bus.connect("message::eos", self.on_eos_from_sink_pipeline)
sink_bus.add_signal_watch()
self.appsrc = self.sink_pipeline.get_by_name("appsrc")
debug("source pipeline: %s" % self.source_pipeline_description)