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
评论列表
文章目录