Python threading 模块,ThreadError() 实例源码

我们从Python开源项目中,提取了以下45个代码示例,用于说明如何使用threading.ThreadError()

项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
def _try_acquire(self, blocking, watch):
        try:
            self.trylock()
        except IOError as e:
            if e.errno in (errno.EACCES, errno.EAGAIN):
                if not blocking or watch.expired():
                    return False
                else:
                    raise _utils.RetryAgain()
            else:
                raise threading.ThreadError("Unable to acquire lock on"
                                            " `%(path)s` due to"
                                            " %(exception)s" %
                                            {
                                                'path': self.path,
                                                'exception': e,
                                            })
        else:
            return True
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
def release(self):
        """Release the previously acquired lock."""
        if not self.acquired:
            raise threading.ThreadError("Unable to release an unacquired"
                                        " lock")
        try:
            self.unlock()
        except IOError:
            self.logger.exception("Could not unlock the acquired lock opened"
                                  " on `%s`", self.path)
        else:
            self.acquired = False
            try:
                self._do_close()
            except IOError:
                self.logger.exception("Could not close the file handle"
                                      " opened on `%s`", self.path)
            else:
                self.logger.log(_utils.BLATHER,
                                "Unlocked and closed file lock open on"
                                " `%s`", self.path)
项目:OSPTF    作者:xSploited    | 项目源码 | 文件源码
def _get_my_tid(self):
        """determines this (self's) thread id"""
        if not self.isAlive():
            raise threading.ThreadError("the thread is not active")

        # do we have it cached?
        if hasattr(self, "_thread_id"):
            return self._thread_id

        # no, look for it in the _active dict
        for tid, tobj in threading._active.items():
            if tobj is self:
                self._thread_id = tid
                return tid

        raise AssertionError("could not determine the thread's id")
项目:deb-python-fasteners    作者:openstack    | 项目源码 | 文件源码
def _try_acquire(self, blocking, watch):
        try:
            self.trylock()
        except IOError as e:
            if e.errno in (errno.EACCES, errno.EAGAIN):
                if not blocking or watch.expired():
                    return False
                else:
                    raise _utils.RetryAgain()
            else:
                raise threading.ThreadError("Unable to acquire lock on"
                                            " `%(path)s` due to"
                                            " %(exception)s" %
                                            {
                                                'path': self.path,
                                                'exception': e,
                                            })
        else:
            return True
项目:pupy    作者:ru-faraon    | 项目源码 | 文件源码
def _get_my_tid(self):
        """determines this (self's) thread id"""
        if not self.isAlive():
            raise threading.ThreadError("the thread is not active")

        # do we have it cached?
        if hasattr(self, "_thread_id"):
            return self._thread_id

        # no, look for it in the _active dict
        for tid, tobj in threading._active.items():
            if tobj is self:
                self._thread_id = tid
                return tid

        raise AssertionError("could not determine the thread's id")
项目:RKSV    作者:ztp-at    | 项目源码 | 文件源码
def _get_my_tid(self):
            """determines this (self's) thread id
            CAREFUL : this function is executed in the context of the caller
            thread, to get the identity of the thread represented by this
            instance.
            """
            if not self.isAlive():
                raise threading.ThreadError("the thread is not active")

            # do we have it cached?
            if hasattr(self, "_thread_id"):
                return self._thread_id

            # no, look for it in the _active dict
            for tid, tobj in threading._active.items():
                if tobj is self:
                    self._thread_id = tid
                    return tid

            # TODO: in python 2.6, there's a simpler way to do : self.ident

            raise AssertionError("could not determine the thread's id")
项目:RKSV    作者:ztp-at    | 项目源码 | 文件源码
def _get_my_tid(self):
            """determines this (self's) thread id
            CAREFUL : this function is executed in the context of the caller
            thread, to get the identity of the thread represented by this
            instance.
            """
            if not self.isAlive():
                raise threading.ThreadError("the thread is not active")

            # do we have it cached?
            if hasattr(self, "_thread_id"):
                return self._thread_id

            # no, look for it in the _active dict
            for tid, tobj in threading._active.items():
                if tobj is self:
                    self._thread_id = tid
                    return tid

            # TODO: in python 2.6, there's a simpler way to do : self.ident

            raise AssertionError("could not determine the thread's id")
项目:GAMADV-X    作者:taers232c    | 项目源码 | 文件源码
def _try_acquire(self, blocking, watch):
        try:
            self.trylock()
        except IOError as e:
            if e.errno in (errno.EACCES, errno.EAGAIN):
                if not blocking or watch.expired():
                    return False
                else:
                    raise _utils.RetryAgain()
            else:
                raise threading.ThreadError("Unable to acquire lock on"
                                            " `%(path)s` due to"
                                            " %(exception)s" %
                                            {
                                                'path': self.path,
                                                'exception': e,
                                            })
        else:
            return True
项目:GAMADV-X    作者:taers232c    | 项目源码 | 文件源码
def release(self):
        """Release the previously acquired lock."""
        if not self.acquired:
            raise threading.ThreadError("Unable to release an unacquired"
                                        " lock")
        try:
            self.unlock()
        except IOError:
            self.logger.exception("Could not unlock the acquired lock opened"
                                  " on `%s`", self.path)
        else:
            self.acquired = False
            try:
                self._do_close()
            except IOError:
                self.logger.exception("Could not close the file handle"
                                      " opened on `%s`", self.path)
            else:
                self.logger.log(_utils.BLATHER,
                                "Unlocked and closed file lock open on"
                                " `%s`", self.path)
项目:deb-python-fasteners    作者:openstack    | 项目源码 | 文件源码
def test_bad_acquire(self):
        lock_file = os.path.join(self.lock_dir, 'lock')
        lock = BrokenLock(lock_file, errno.EBUSY)
        self.assertRaises(threading.ThreadError, lock.acquire)
项目:deb-python-fasteners    作者:openstack    | 项目源码 | 文件源码
def test_bad_release(self):
        lock_file = os.path.join(self.lock_dir, 'lock')
        lock = pl.InterProcessLock(lock_file)
        self.assertRaises(threading.ThreadError, lock.release)
项目:deb-python-fasteners    作者:openstack    | 项目源码 | 文件源码
def __enter__(self):
        gotten = self.acquire()
        if not gotten:
            # This shouldn't happen, but just incase...
            raise threading.ThreadError("Unable to acquire a file lock"
                                        " on `%s` (when used as a"
                                        " context manager)" % self.path)
        return self
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def test_lock(self):
        lock = self.Lock()
        self.assertEqual(lock.acquire(), True)
        self.assertEqual(lock.acquire(False), False)
        self.assertEqual(lock.release(), None)
        self.assertRaises((ValueError, threading.ThreadError), lock.release)
项目:zippy    作者:securesystemslab    | 项目源码 | 文件源码
def test_limbo_cleanup(self):
        # Issue 7481: Failure to start thread should cleanup the limbo map.
        def fail_new_thread(*args):
            raise threading.ThreadError()
        _start_new_thread = threading._start_new_thread
        threading._start_new_thread = fail_new_thread
        try:
            t = threading.Thread(target=lambda: None)
            self.assertRaises(threading.ThreadError, t.start)
            self.assertFalse(
                t in threading._limbo,
                "Failed to cleanup _limbo map on failure of Thread.start().")
        finally:
            threading._start_new_thread = _start_new_thread
项目:oil    作者:oilshell    | 项目源码 | 文件源码
def test_lock(self):
        lock = self.Lock()
        self.assertEqual(lock.acquire(), True)
        self.assertEqual(lock.acquire(False), False)
        self.assertEqual(lock.release(), None)
        self.assertRaises((ValueError, threading.ThreadError), lock.release)
项目:python2-tracer    作者:extremecoders-re    | 项目源码 | 文件源码
def test_lock(self):
        lock = self.Lock()
        self.assertEqual(lock.acquire(), True)
        self.assertEqual(lock.acquire(False), False)
        self.assertEqual(lock.release(), None)
        self.assertRaises((ValueError, threading.ThreadError), lock.release)
项目:orizonhub    作者:gumblex    | 项目源码 | 文件源码
def acquire_lock(self, blocking=True):
        if self.lock.acquire(blocking):
            return True
        elif blocking:
            raise threading.ThreadError('Cannot acquire lock.')
        else:
            return False
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def test_lock(self):
        lock = self.Lock()
        self.assertEqual(lock.acquire(), True)
        self.assertEqual(lock.acquire(False), False)
        self.assertEqual(lock.release(), None)
        self.assertRaises((ValueError, threading.ThreadError), lock.release)
项目:web_ctp    作者:molebot    | 项目源码 | 文件源码
def test_limbo_cleanup(self):
        # Issue 7481: Failure to start thread should cleanup the limbo map.
        def fail_new_thread(*args):
            raise threading.ThreadError()
        _start_new_thread = threading._start_new_thread
        threading._start_new_thread = fail_new_thread
        try:
            t = threading.Thread(target=lambda: None)
            self.assertRaises(threading.ThreadError, t.start)
            self.assertFalse(
                t in threading._limbo,
                "Failed to cleanup _limbo map on failure of Thread.start().")
        finally:
            threading._start_new_thread = _start_new_thread
项目:cpy2py    作者:maxfischer2781    | 项目源码 | 文件源码
def put(self, item):
        """Put a single item in the queue"""
        with self._queue_mutex:
            self._queue_content.append(item)
            for w_idx in range(len(self._waiters)):
                try:
                    self._waiters[w_idx].release()
                except (ThreadError, RuntimeError, thread_error):
                    continue
                else:
                    break
项目:RKSV    作者:ztp-at    | 项目源码 | 文件源码
def __thread_apply__(f, args, callback):
        try:
            callback(f(*args))
        except threading.ThreadError:
            pass
项目:RKSV    作者:ztp-at    | 项目源码 | 文件源码
def __thread_map__(f, iterable, callback):
        try:
            callback(map(f, iterable))
        except threading.ThreadError:
            pass
项目:RKSV    作者:ztp-at    | 项目源码 | 文件源码
def terminate(self):
            try:
                if self._thread:
                    self._thread.raiseExc(threading.ThreadError)
            except (threading.ThreadError, TypeError, ValueError, SystemError):
                pass

            self._thread = None
项目:RKSV    作者:ztp-at    | 项目源码 | 文件源码
def __thread_map__(f, iterable, callback):
        try:
            callback(map(f, iterable))
        except threading.ThreadError:
            pass
项目:RKSV    作者:ztp-at    | 项目源码 | 文件源码
def terminate(self):
            try:
                if self._thread:
                    self._thread.raiseExc(threading.ThreadError)
            except (threading.ThreadError, TypeError, ValueError, SystemError):
                pass

            self._thread = None
项目:pefile.pypy    作者:cloudtracer    | 项目源码 | 文件源码
def test_lock(self):
        lock = self.Lock()
        self.assertEqual(lock.acquire(), True)
        self.assertEqual(lock.acquire(False), False)
        self.assertEqual(lock.release(), None)
        self.assertRaises((ValueError, threading.ThreadError), lock.release)
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_lock(self):
        lock = self.Lock()
        self.assertEqual(lock.acquire(), True)
        self.assertEqual(lock.acquire(False), False)
        self.assertEqual(lock.release(), None)
        self.assertRaises((ValueError, threading.ThreadError), lock.release)
项目:ouroboros    作者:pybee    | 项目源码 | 文件源码
def test_limbo_cleanup(self):
        # Issue 7481: Failure to start thread should cleanup the limbo map.
        def fail_new_thread(*args):
            raise threading.ThreadError()
        _start_new_thread = threading._start_new_thread
        threading._start_new_thread = fail_new_thread
        try:
            t = threading.Thread(target=lambda: None)
            self.assertRaises(threading.ThreadError, t.start)
            self.assertFalse(
                t in threading._limbo,
                "Failed to cleanup _limbo map on failure of Thread.start().")
        finally:
            threading._start_new_thread = _start_new_thread
项目:python_data_tools    作者:king3366ster    | 项目源码 | 文件源码
def _get_my_tid(self):
        """determines this (self's) thread id"""
        if not self.isAlive():
            raise threading.ThreadError("the thread is not active")
        # do we have it cached?
        if hasattr(self, "_thread_id"):
            return self._thread_id
        # no, look for it in the _active dict
        for tid, tobj in threading._active.items():
            if tobj is self:
                self._thread_id = tid
                return tid
        raise AssertionError("could not determine the thread's id")
项目:ndk-python    作者:gittor    | 项目源码 | 文件源码
def test_lock(self):
        lock = self.Lock()
        self.assertEqual(lock.acquire(), True)
        self.assertEqual(lock.acquire(False), False)
        self.assertEqual(lock.release(), None)
        self.assertRaises((ValueError, threading.ThreadError), lock.release)
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
def release(self):
        """
        Release the lock.  Raise an exception if the lock is not presently
        acquired.
        """
        if not self.acquired:
            raise ThreadError()
        self.acquired = False
项目:zenchmarks    作者:squeaky-pl    | 项目源码 | 文件源码
def test_fakeDoubleRelease(self):
        """
        The L{FakeLock} test fixture will alert us if there's a potential
        double-release.
        """
        lock = FakeLock()
        self.assertRaises(ThreadError, lock.release)
        lock.acquire()
        self.assertEqual(None, lock.release())
        self.assertRaises(ThreadError, lock.release)
项目:plex-for-kodi-mod    作者:mrclemds    | 项目源码 | 文件源码
def _get_my_tid(self):
        """determines this (self's) thread id

        CAREFUL : this function is executed in the context of the caller
        thread, to get the identity of the thread represented by this
        instance.
        """
        if not self.isAlive():
            raise threading.ThreadError("the thread is not active")

        return self.ident
项目:plex-for-kodi-mod    作者:mrclemds    | 项目源码 | 文件源码
def kill(self, force_and_wait=False):
        try:
            self._raiseExc(KillThreadException)

            if force_and_wait:
                time.sleep(0.1)
                while self.isAlive():
                    self._raiseExc(KillThreadException)
                    time.sleep(0.1)
        except threading.ThreadError:
            pass
项目:wade    作者:chartbeat-labs    | 项目源码 | 文件源码
def close(self):
        try:
            self.lock.release()
        except threading.ThreadError: 
            pass # lock may not have been acquired. 
        self.socket.close()
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def test_lock(self):
        lock = self.Lock()
        self.assertEqual(lock.acquire(), True)
        self.assertEqual(lock.acquire(False), False)
        self.assertEqual(lock.release(), None)
        self.assertRaises((ValueError, threading.ThreadError), lock.release)
项目:kbe_server    作者:xiaohaoppy    | 项目源码 | 文件源码
def test_limbo_cleanup(self):
        # Issue 7481: Failure to start thread should cleanup the limbo map.
        def fail_new_thread(*args):
            raise threading.ThreadError()
        _start_new_thread = threading._start_new_thread
        threading._start_new_thread = fail_new_thread
        try:
            t = threading.Thread(target=lambda: None)
            self.assertRaises(threading.ThreadError, t.start)
            self.assertFalse(
                t in threading._limbo,
                "Failed to cleanup _limbo map on failure of Thread.start().")
        finally:
            threading._start_new_thread = _start_new_thread
项目:PKM2    作者:Szonek    | 项目源码 | 文件源码
def run(self):
        bytes = b''
        while not self.thread_cancelled:
            try:
                bytes += self.stream.raw.read(1024)
                a = bytes.find(b'\xff\xd8')
                b = bytes.find(b'\xff\xd9')
                if a != -1 and b != -1:
                    jpg = bytes[a:b + 2]
                    bytes = bytes[b + 2:]
                    frame = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8), cv2.IMREAD_COLOR)
                    #------------------ insert algorythms HERE ------------------

                    # Display the resulting frame
                    cv2.imshow('Video', frame)
                    # ------------------ algorythms end HERE ------------------
                    if cv2.waitKey(1) & 0xFF == ord('q'):
                        exit(0)
            except ThreadError:
                self.thread_cancelled = True
项目:PKM2    作者:Szonek    | 项目源码 | 文件源码
def run(self):
        bytes = b''
        while not self.thread_cancelled:
            try:
                bytes += self.stream.raw.read(1024)
                a = bytes.find(b'\xff\xd8')
                b = bytes.find(b'\xff\xd9')
                if a != -1 and b != -1:
                    jpg = bytes[a:b + 2]
                    bytes = bytes[b + 2:]
                    frame = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8), cv2.IMREAD_COLOR)
                    #------------------ insert algorythms HERE ------------------
                    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

                    faces = faceCascade.detectMultiScale(
                        gray,
                        scaleFactor=1.15,
                        minNeighbors=5,
                        minSize=(20, 20),
                        flags=cv2.CASCADE_SCALE_IMAGE
                    )

                    # Draw a rectangle around the faces
                    for (x, y, w, h) in faces:
                        cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2)

                    # Display the resulting frame
                    cv2.imshow('Video', frame)
                    # ------------------ algorythms end HERE ------------------
                    if cv2.waitKey(1) & 0xFF == ord('q'):
                        exit(0)
            except ThreadError:
                self.thread_cancelled = True
项目:GAMADV-XTD    作者:taers232c    | 项目源码 | 文件源码
def locked(*args, **kwargs):
    """A locking **method** decorator.

    It will look for a provided attribute (typically a lock or a list
    of locks) on the first argument of the function decorated (typically this
    is the 'self' object) and before executing the decorated function it
    activates the given lock or list of locks as a context manager,
    automatically releasing that lock on exit.

    NOTE(harlowja): if no attribute name is provided then by default the
    attribute named '_lock' is looked for (this attribute is expected to be
    the lock/list of locks object/s) in the instance object this decorator
    is attached to.

    NOTE(harlowja): a custom logger (which will be used if lock release
    failures happen) can be provided by passing a logger instance for keyword
    argument ``logger``.
    """

    def decorator(f):
        attr_name = kwargs.get('lock', '_lock')
        logger = kwargs.get('logger')

        @six.wraps(f)
        def wrapper(self, *args, **kwargs):
            attr_value = getattr(self, attr_name)
            if isinstance(attr_value, (tuple, list)):
                with _utils.LockStack(logger=logger) as stack:
                    for i, lock in enumerate(attr_value):
                        if not stack.acquire_lock(lock):
                            raise threading.ThreadError("Unable to acquire"
                                                        " lock %s" % (i + 1))
                    return f(self, *args, **kwargs)
            else:
                lock = attr_value
                with lock:
                    return f(self, *args, **kwargs)

        return wrapper

    # This is needed to handle when the decorator has args or the decorator
    # doesn't have args, python is rather weird here...
    if kwargs or not args:
        return decorator
    else:
        if len(args) == 1:
            return decorator(args[0])
        else:
            return decorator
项目:deb-python-fasteners    作者:openstack    | 项目源码 | 文件源码
def locked(*args, **kwargs):
    """A locking **method** decorator.

    It will look for a provided attribute (typically a lock or a list
    of locks) on the first argument of the function decorated (typically this
    is the 'self' object) and before executing the decorated function it
    activates the given lock or list of locks as a context manager,
    automatically releasing that lock on exit.

    NOTE(harlowja): if no attribute name is provided then by default the
    attribute named '_lock' is looked for (this attribute is expected to be
    the lock/list of locks object/s) in the instance object this decorator
    is attached to.

    NOTE(harlowja): a custom logger (which will be used if lock release
    failures happen) can be provided by passing a logger instance for keyword
    argument ``logger``.
    """

    def decorator(f):
        attr_name = kwargs.get('lock', '_lock')
        logger = kwargs.get('logger')

        @six.wraps(f)
        def wrapper(self, *args, **kwargs):
            attr_value = getattr(self, attr_name)
            if isinstance(attr_value, (tuple, list)):
                with _utils.LockStack(logger=logger) as stack:
                    for i, lock in enumerate(attr_value):
                        if not stack.acquire_lock(lock):
                            raise threading.ThreadError("Unable to acquire"
                                                        " lock %s" % (i + 1))
                    return f(self, *args, **kwargs)
            else:
                lock = attr_value
                with lock:
                    return f(self, *args, **kwargs)

        return wrapper

    # This is needed to handle when the decorator has args or the decorator
    # doesn't have args, python is rather weird here...
    if kwargs or not args:
        return decorator
    else:
        if len(args) == 1:
            return decorator(args[0])
        else:
            return decorator
项目:captiv8    作者:wraith-wireless    | 项目源码 | 文件源码
def _setup(self):
        """ setup radio and tuning thread """
        # set up the radio for collection
        nlsock = None
        try:
            # get a netlink socket for this
            nlsock = nl.nl_socket_alloc()

            # get dev info for dev and it's phy index
            self._dinfo = pyw.devinfo(self._dev,nlsock)
            phy = self._dinfo['card'].phy

            # delete all associated interfaces
            for c,_ in pyw.ifaces(self._dinfo['card'],nlsock): pyw.devdel(c,nlsock)

            # create a new card in monitor mode
            self._card = pyw.phyadd(phy,'cap8','monitor',None,nlsock)
            pyw.up(self._card)

            # determine scannable channels, then go to first channel
            scan = []
            for rf in pyw.devfreqs(self._card,nlsock):
                for chw in channels.CHTYPES:
                    try:
                        pyw.freqset(self._card,rf,chw,nlsock)
                        scan.append((rf, chw))
                    except pyric.error as e:
                        if e.errno != pyric.EINVAL: raise
            assert scan
            pyw.freqset(self._card,scan[0][0],scan[0][1],nlsock)

            # create the tuner & sniffer
            self._pktq = mp.Queue()
            self._tuner = Tuner(self._card,scan)
            self._sniffer = Sniffer(self._pktq,self._card.dev)
        except RuntimeError as e:
            self._teardown()
            raise RuntimeError("Error binding socket {0}".format(e))
        except threading.ThreadError as e:
            self._teardown()
            raise RuntimeError("Unexepected error in the workers {0}".format(e))
        except AssertionError:
            self._teardown()
            raise RuntimeError("No valid scan channels found")
        except nl.error as e:
            self._teardown()
            raise RuntimeError("ERRNO {0} {1}".format(e.errno, e.strerror))
        except pyric.error as e:
            self._teardown() # attempt to restore
            raise RuntimeError("ERRNO {0} {1}".format(e.errno, e.strerror))
        finally:
            nl.nl_socket_free(nlsock)
项目:vision-code    作者:FIRST-Team-1699    | 项目源码 | 文件源码
def run(self):
    bytes='' 
    while not self.thread_cancelled:
      try:
        bytes+=self.stream.raw.read(1024) 
        a = bytes.find('\xff\xd8')
        b = bytes.find('\xff\xd9')
        if a!=-1 and b!=-1:
          jpg = bytes[a:b+2]
          bytes= bytes[b+2:]
          img = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8),cv2.IMREAD_COLOR)

          # Convert BGR to HSV
          hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
          # define range of blue color in HSV
          #lower_blue = np.array([self.L_RED, self.L_GREEN, self.L_BLUE], np.uint8)
          #upper_blue = np.array([self.U_RED, self.U_GREEN, self.L_BLUE], np.uint8)

          # Threshold the HSV image to get only blue colors
          mask = cv2.inRange(hsv, np.array([53,187,37]), np.array([97,244,153]))

          # Bitwise-AND mask and original image
          res = cv2.bitwise_and(img,img, mask= mask)
####        blurred = cv2.GaussianBlur(mask, (5, 5), 0)
          blurred = cv2.boxFilter(mask, 0, (7, 7), mask, (-1, -1), False, cv2.BORDER_DEFAULT)
          thresh = cv2.threshold(blurred, 60, 255, cv2.THRESH_BINARY)[1]
          cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
          cnts = cnts[0] if imutils.is_cv2() else cnts[1]
          cv2.filterSpeckles(mask, 0, 100, 25)
##          cv2.filterSpeckles(mask, 0, 50, 25)
##          cv2.filterSpeckles(mask, 0, 100, 100)
          for c in cnts:
              M = cv2.moments(c)
              if int(M["m00"]) != 0:
                  cX = int(M["m10"] / M["m00"])
                  cY = int(M["m01"] / M["m00"])
              else:
                  (cX, cY) = (0, 0)
              print(cX, cY)
              cv2.drawContours(res, [c], -1, (0, 255, 0), 2)
              cv2.circle(res, (cX, cY), 7, (255, 255, 255), 1)

             # table.putNumber("center X", cX)
          cv2.imshow('img',img)
          cv2.imshow('mask',mask)
          cv2.imshow('Final',res)
          cv2.imshow('cam',img)
          #sd.putNumber('Center X', cX) ##send the x value of the center
          #sd.putNumber('Center Y', cY) ##send the y value of the center
##          print(sd.getNumber('Center Y'), sd.getNumber('Center X'))
          if cv2.waitKey(1) ==27:
            exit(0)
      except ThreadError:
        self.thread_cancelled = True
项目:vision-code    作者:FIRST-Team-1699    | 项目源码 | 文件源码
def run(self):
    bytes='' 
    while not self.thread_cancelled:  ####see lines 18, 80, 88 ....
      try:        
        bytes+=self.stream.raw.read(1024) ##limit max bytes read in 1 itteration? need to read more on this
        a = bytes.find('\xff\xd8')##find start of stream of data  
        b = bytes.find('\xff\xd9')##find our end of data stream
        if a!=-1 and b!=-1:  ##so as long as we have a stream of data....do the following
          jpg = bytes[a:b+2]  ##converts to image or a specific variable...
          bytes= bytes[b+2:]  
          img = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8),cv2.IMREAD_COLOR)  ##decode the data

          # Convert BGR to HSV
          hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)  ##converting color format for easier proccessing/ math
          # define range of blue color in HSV
          #lower_blue = np.array([self.L_RED, self.L_GREEN, self.L_BLUE], np.uint8)
          #upper_blue = np.array([self.U_RED, self.U_GREEN, self.L_BLUE], np.uint8)

          # Threshold the HSV image to get only blue colors
          mask = cv2.inRange(hsv, np.array([53,187,37]), np.array([97,244,153]))  ##get colors in the range of these HSV values

          # Bitwise-AND mask and original image
          res = cv2.bitwise_and(img,img, mask= mask)

          blurred = cv2.boxFilter(mask, 0, (7, 7), mask, (-1, -1), False, cv2.BORDER_DEFAULT) ##the next few line create outlines and 
          thresh = cv2.threshold(blurred, 60, 255, cv2.THRESH_BINARY)[1]                      ##remove any noise
          cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)  #find countors
          cnts = cnts[0] if imutils.is_cv2() else cnts[1]   
          cv2.filterSpeckles(mask, 0, 100, 25)      ##remove speckles aka random dots and white noise
          for c in cnts:
              M = cv2.moments(c)
              if int(M["m00"]) != 0:  ##Checks for division by zero
                  cX = int(M["m10"] / M["m00"])
                  cY = int(M["m01"] / M["m00"])
              else:
                  (cX, cY) = (0, 0)
              cv2.drawContours(res, [c], -1, (0, 255, 0), 2)  ##draw box/highlighting 
              cv2.circle(res, (cX, cY), 7, (255, 255, 255), 1)  ##draw box/highlighting 

              ##Try-Catch for appending cX to table
              try:
                self.table.putNumber('centerX', cX)  ##Adds cX to the networktables
              except KeyError:
                print("centerX failed.")

          cv2.imshow('img',img)   ##display original image
          cv2.imshow('mask',mask)  ##display masked image
          cv2.imshow('Final',res)  ##show final image


          cv2.imshow('cam',img)  ##see line 71/comments
          if cv2.waitKey(1) ==27:  ##now we close if esc key is pressed
            exit(0)
      except ThreadError:
        self.thread_cancelled = True
项目:GAMADV-X    作者:taers232c    | 项目源码 | 文件源码
def locked(*args, **kwargs):
    """A locking **method** decorator.

    It will look for a provided attribute (typically a lock or a list
    of locks) on the first argument of the function decorated (typically this
    is the 'self' object) and before executing the decorated function it
    activates the given lock or list of locks as a context manager,
    automatically releasing that lock on exit.

    NOTE(harlowja): if no attribute name is provided then by default the
    attribute named '_lock' is looked for (this attribute is expected to be
    the lock/list of locks object/s) in the instance object this decorator
    is attached to.

    NOTE(harlowja): a custom logger (which will be used if lock release
    failures happen) can be provided by passing a logger instance for keyword
    argument ``logger``.
    """

    def decorator(f):
        attr_name = kwargs.get('lock', '_lock')
        logger = kwargs.get('logger')

        @six.wraps(f)
        def wrapper(self, *args, **kwargs):
            attr_value = getattr(self, attr_name)
            if isinstance(attr_value, (tuple, list)):
                with _utils.LockStack(logger=logger) as stack:
                    for i, lock in enumerate(attr_value):
                        if not stack.acquire_lock(lock):
                            raise threading.ThreadError("Unable to acquire"
                                                        " lock %s" % (i + 1))
                    return f(self, *args, **kwargs)
            else:
                lock = attr_value
                with lock:
                    return f(self, *args, **kwargs)

        return wrapper

    # This is needed to handle when the decorator has args or the decorator
    # doesn't have args, python is rather weird here...
    if kwargs or not args:
        return decorator
    else:
        if len(args) == 1:
            return decorator(args[0])
        else:
            return decorator