1#!/usr/bin/env python3
2# This file is part of Xpra.
3# Copyright (C) 2016-2020 Antoine Martin <antoine@xpra.org>
4# Xpra is released under the terms of the GNU GPL v2, or, at your option, any
5# later version. See the file COPYING for details.
6
7
8import sys
9
10def main():
11    from xpra.platform import program_context, command_error
12    from xpra.platform.gui import init, set_default_icon
13    with program_context("Webcam", "Webcam"):
14        from xpra.log import Logger, add_debug_category
15        log = Logger("webcam")
16        for x in list(sys.argv):
17            if x in ("-v", "--verbose"):
18                sys.argv.remove(x)
19                add_debug_category("webcam")
20                log.enable_debug()
21
22        set_default_icon("webcam.png")
23        init()
24
25        log("importing opencv")
26        try:
27            import cv2
28        except ImportError as e:
29            command_error("Error: no opencv support module: %s" % e)
30            return 1
31        log("cv2=%s", cv2)
32        device = 0
33        if len(sys.argv)==2:
34            try:
35                device = int(sys.argv[1])
36            except ValueError:
37                command_error("Warning: failed to parse value as a device number: '%s'" % sys.argv[1])
38        log("opening %s with device=%s", cv2.VideoCapture, device)  # @UndefinedVariable
39        try:
40            cap = cv2.VideoCapture(device)  # @UndefinedVariable
41        except Exception as e:
42            command_error("Error: failed to capture video using device %s:\n%s" % (device, e))
43            return 1
44        log.info("capture device for %i: %s", device, cap)
45        while True:
46            ret, frame = cap.read()
47            if not ret:
48                command_error("Error: frame capture failed using device %s" % device)
49                return 1
50            cv2.imshow('frame', frame)  # @UndefinedVariable
51            if cv2.waitKey(10) & 0xFF in (ord('q'), 27):    # @UndefinedVariable
52                break
53        cap.release()
54        cv2.destroyAllWindows() # @UndefinedVariable
55    return 0
56
57if __name__ == "__main__":
58    v = main()
59    sys.exit(v)
60