File: _camera_opencv.py

package info (click to toggle)
pygame 2.6.1-4
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 43,076 kB
  • sloc: ansic: 66,932; python: 48,797; javascript: 1,153; objc: 224; sh: 121; makefile: 59; cpp: 25
file content (210 lines) | stat: -rw-r--r-- 5,454 bytes parent folder | download | duplicates (3)
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
"""pygame.camera backend that uses OpenCV.

Uses the cv2 module opencv for python.
See https://pypi.org/project/opencv-python/ for wheels version.

python3 -m pip install opencv-python --user
"""

import sys
import time

import numpy
import cv2

import pygame


def list_cameras():
    """ """
    index = 0
    device_idx = []
    failed = 0

    # Sometimes there are gaps between the device index.
    # We keep trying max_gaps times.
    max_gaps = 3

    while failed < max_gaps:
        vcap = cv2.VideoCapture(index)
        if not vcap.read()[0]:
            failed += 1
        else:
            device_idx.append(index)
        vcap.release()
        index += 1
    return device_idx


def list_cameras_darwin():
    import subprocess
    from xml.etree import ElementTree

    # pylint: disable=consider-using-with
    flout, _ = subprocess.Popen(
        "system_profiler -xml SPCameraDataType",
        shell=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.PIPE,
    ).communicate()

    last_text = None
    cameras = []

    for node in ElementTree.fromstring(flout).iterfind("./array/dict/array/dict/*"):
        if last_text == "_name":
            cameras.append(node.text)
        last_text = node.text

    return cameras


class Camera:
    def __init__(self, device=0, size=(640, 480), mode="RGB", api_preference=None):
        """
        api_preference - cv2.CAP_DSHOW cv2.CAP_V4L2 cv2.CAP_MSMF and others

        # See https://docs.opencv.org/3.4/d4/d15/group__videoio__flags__base.html
        """
        self._device_index = device
        self._size = size

        self.api_preference = api_preference
        if api_preference is not None and sys.platform == "win32":
            # seems more compatible on windows?
            self.api_preference = cv2.CAP_DSHOW

        if mode == "RGB":
            self._fmt = cv2.COLOR_BGR2RGB
        elif mode == "YUV":
            self._fmt = cv2.COLOR_BGR2YUV
        elif mode == "HSV":
            self._fmt = cv2.COLOR_BGR2HSV
        else:
            raise ValueError("Not a supported mode")

        self._open = False

    # all of this could have been done in the constructor, but creating
    # the VideoCapture is very time consuming, so it makes more sense in the
    # actual start() method
    def start(self):
        if self._open:
            return

        self._cam = cv2.VideoCapture(self._device_index, self.api_preference)

        if not self._cam.isOpened():
            raise ValueError("Could not open camera.")

        self._cam.set(cv2.CAP_PROP_FRAME_WIDTH, self._size[0])
        self._cam.set(cv2.CAP_PROP_FRAME_HEIGHT, self._size[1])

        w = self._cam.get(cv2.CAP_PROP_FRAME_WIDTH)
        h = self._cam.get(cv2.CAP_PROP_FRAME_HEIGHT)
        self._size = (int(w), int(h))

        self._flipx = False
        self._flipy = False
        self._brightness = 1

        self._frametime = 1 / self._cam.get(cv2.CAP_PROP_FPS)
        self._last_frame_time = 0

        self._open = True

    def stop(self):
        if self._open:
            self._cam.release()
            self._cam = None
            self._open = False

    def _check_open(self):
        if not self._open:
            raise pygame.error("Camera must be started")

    def get_size(self):
        self._check_open()

        return self._size

    def set_controls(self, hflip=None, vflip=None, brightness=None):
        self._check_open()

        if hflip is not None:
            self._flipx = bool(hflip)
        if vflip is not None:
            self._flipy = bool(vflip)
        if brightness is not None:
            self._cam.set(cv2.CAP_PROP_BRIGHTNESS, brightness)

        return self.get_controls()

    def get_controls(self):
        self._check_open()

        return (self._flipx, self._flipy, self._cam.get(cv2.CAP_PROP_BRIGHTNESS))

    def query_image(self):
        self._check_open()

        current_time = time.time()
        if current_time - self._last_frame_time > self._frametime:
            return True
        return False

    def get_image(self, dest_surf=None):
        self._check_open()

        self._last_frame_time = time.time()

        _, image = self._cam.read()

        image = cv2.cvtColor(image, self._fmt)

        flip_code = None
        if self._flipx:
            if self._flipy:
                flip_code = -1
            else:
                flip_code = 1
        elif self._flipy:
            flip_code = 0

        if flip_code is not None:
            image = cv2.flip(image, flip_code)

        image = numpy.fliplr(image)
        image = numpy.rot90(image)

        surf = pygame.surfarray.make_surface(image)

        if dest_surf:
            dest_surf.blit(surf, (0, 0))
            return dest_surf

        return surf

    def get_raw(self):
        self._check_open()

        self._last_frame_time = time.time()

        _, image = self._cam.read()

        return image.tobytes()


class CameraMac(Camera):
    def __init__(self, device=0, size=(640, 480), mode="RGB", api_preference=None):
        if isinstance(device, int):
            _dev = device
        elif isinstance(device, str):
            _dev = list_cameras_darwin().index(device)
        else:
            raise TypeError(
                "OpenCV-Mac backend can take device indices or names, ints or strings, not ",
                str(type(device)),
            )

        super().__init__(_dev, size, mode, api_preference)