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
python类ThreadError()的实例源码
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)
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
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
def close(self):
try:
self.lock.release()
except threading.ThreadError:
pass # lock may not have been acquired.
self.socket.close()
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)
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
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
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
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
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
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)
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
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
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