PageRenderTime 28ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 0ms

/Target Tracker Software/Target Tracker with Display.py

https://bitbucket.org/JamesHepworth_UCT/target-tracker
Python | 229 lines | 131 code | 61 blank | 37 comment | 20 complexity | ca3d65ea7898c8e5bfd0c6b232121104 MD5 | raw file
  1. ## IMPORTS ----------------------------------------------------------------------------------------------------------------------------------------------
  2. import RPi.GPIO as GPIO
  3. from imutils.video import WebcamVideoStream
  4. from imutils.video import FPS
  5. import numpy as np
  6. import time
  7. import serial
  8. import imutils
  9. import cv2
  10. import sys
  11. ## FUNCTIONS --------------------------------------------------------------------------------------------------------------------------------------------
  12. def nothing(x):
  13. pass
  14. def writePositions(cx, cy, targetAquired):
  15. cx_copy = cx
  16. cy_copy = cy
  17. xhigh = ((cx_copy >> 8) & 0xFF)
  18. xlow = (cx & 0xFF)
  19. yhigh = ((cy_copy >> 8) & 0xFF)
  20. ylow = (cy & 0xFF)
  21. GPIO.output(31,GPIO.HIGH) #Casues EXTI interrup on PA4 on STM32
  22. while GPIO.input(37) == 1: #wait for STM32 of acknowledge data is ready to be sent: STM32 lowers PB2
  23. nothing
  24. if ((GPIO.input(33) == 0) or (GPIO.input(35) == 1)):
  25. break
  26. if targetAquired == 1:
  27. targetPos = bytearray([xhigh, xlow, yhigh, ylow])
  28. ser.write(targetPos)
  29. print('cx = {0}, cy = {1}, xhigh = {2}, xlow = {3}, yhigh = {4}, ylow = {5}'.format(cx, cy, xhigh, xlow, yhigh, ylow))
  30. else:
  31. targetPos = bytearray([((0 >> 8) & 0xFF), (0 & 0xFF), ((0 >> 8) & 0xFF), (0 & 0xFF)])
  32. ser.write(targetPos)
  33. print('Target Lost')
  34. GPIO.output(31,GPIO.LOW)
  35. ## INITIALISATIONS --------------------------------------------------------------------------------------------------------------------------------------
  36. #IMAGE PROCESSING KERNELS
  37. kernel = np.ones((5,5),np.uint8)
  38. ekernel = np.ones((2,2),np.uint8)
  39. dkernel = np.ones((8,8),np.uint8)
  40. #DISPLAY FRAME
  41. cv2.namedWindow('Image')
  42. # Trackbars
  43. cv2.createTrackbar('H_Min','Image',50,179,nothing)
  44. cv2.createTrackbar('H_Max','Image',120,179,nothing)
  45. cv2.createTrackbar('S_Min','Image',150,255,nothing)
  46. cv2.createTrackbar('S_Max','Image',255,255,nothing)
  47. cv2.createTrackbar('V_Min','Image',190,255,nothing)
  48. cv2.createTrackbar('V_Max','Image',255,255,nothing)
  49. cv2.createTrackbar('Calibrated?','Image',0,1,nothing)
  50. lower_bright = np.array([cv2.getTrackbarPos('H_Min','Image'),cv2.getTrackbarPos('S_Min','Image'),cv2.getTrackbarPos('V_Min','Image')])
  51. upper_bright = np.array([cv2.getTrackbarPos('H_Max','Image'),cv2.getTrackbarPos('S_Max','Image'),cv2.getTrackbarPos('V_Max','Image')])
  52. calibrationMode = cv2.getTrackbarPos('Calibrated?','Image')
  53. #SERIAL COMMS SETUP
  54. ser = serial.Serial(port='/dev/ttyS0', baudrate = 230400, parity = serial.PARITY_EVEN, stopbits=serial.STOPBITS_ONE, bytesize=serial.EIGHTBITS, timeout=1)
  55. #GPIO SETUP
  56. GPIO.setmode(GPIO.BOARD)
  57. GPIO.setup(37,GPIO.IN)
  58. GPIO.setup(35,GPIO.IN)
  59. GPIO.setup(33,GPIO.IN)
  60. GPIO.setup(31,GPIO.OUT)
  61. GPIO.setup(11,GPIO.OUT)
  62. GPIO.setup(13,GPIO.IN)
  63. GPIO.output(11,GPIO.HIGH)
  64. GPIO.output(31,GPIO.LOW)
  65. cx = 0
  66. cy = 0
  67. state = 0
  68. fps_run = 0
  69. targetAquired = 0
  70. ## MAIN -------------------------------------------------------------------------------------------------------------------------------------------------
  71. # created a *threaded* video stream, allow the camera sensor to warmup,
  72. # and start the FPS counter
  73. print("[INFO] sampling THREADED frames from webcam...")
  74. vs = WebcamVideoStream(src=0, width=640, height=480).startgrab()
  75. while calibrationMode == 0:
  76. im = vs.readframe()
  77. hsv = cv2.cvtColor(im, cv2.COLOR_BGR2HSV)
  78. mask = cv2.inRange(hsv, lower_bright, upper_bright)
  79. #blur = cv2.GaussianBlur(mask, (1, 1), 1)
  80. cv2.imshow('Image',mask)
  81. k = cv2.waitKey(1) & 0xFF
  82. if k == 27:
  83. break
  84. lower_bright = np.array([cv2.getTrackbarPos('H_Min','Image'),cv2.getTrackbarPos('S_Min','Image'),cv2.getTrackbarPos('V_Min','Image')])
  85. upper_bright = np.array([cv2.getTrackbarPos('H_Max','Image'),cv2.getTrackbarPos('S_Max','Image'),cv2.getTrackbarPos('V_Max','Image')])
  86. calibrationMode = cv2.getTrackbarPos('Calibrated?','Image')
  87. cv2.destroyAllWindows()
  88. #vs.startdisplay(0, 0)
  89. while (1):
  90. if (GPIO.input(33) == 0):
  91. if state == 1:
  92. fps.stop()
  93. print('\nIm process FPS = {}'.format(fps.fps()))
  94. state = 0
  95. # grab the frame
  96. im = vs.readframe()
  97. im2 = im.copy()
  98. # Convert BGR to HSV
  99. hsv = cv2.cvtColor(im, cv2.COLOR_BGR2HSV)
  100. #if calibratationMode == 0:
  101. # Threshold the HSV image to get only bright colors
  102. mask = cv2.inRange(hsv, lower_bright, upper_bright)
  103. #blur = cv2.GaussianBlur(mask, (3, 3), 1)
  104. eroded = cv2.erode(mask,ekernel,iterations = 1)
  105. #dilation = cv2.dilate(eroded,dkernel,iterations = 1)
  106. #morphed = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
  107. contours = cv2.findContours(eroded,1,2)[-2]
  108. if len(contours) > 0:
  109. c = max(contours,key=cv2.contourArea)
  110. M = cv2.moments(c)
  111. #print M
  112. if M['m00'] != 0:
  113. cx = int(M['m10']/M['m00'])
  114. cy = int(M['m01']/M['m00'])
  115. cv2.circle(im,(cx,cy),5,(0,255,0), -1)
  116. print("Target Aquired")
  117. cv2.imshow('frame',im)
  118. #cv2.imshow('Mask',mask)
  119. #cv2.imshow('eroded',dilation)
  120. else:
  121. if state == 0:
  122. fps = FPS().start()
  123. state = 1
  124. fps_run = 1
  125. # grab the frame
  126. im = vs.readframe()
  127. im2 = im.copy()
  128. # Convert BGR to HSV
  129. hsv = cv2.cvtColor(im, cv2.COLOR_BGR2HSV)
  130. #if calibratationMode == 0:
  131. # Threshold the HSV image to get only bright colors
  132. mask = cv2.inRange(hsv, lower_bright, upper_bright)
  133. #blur = cv2.GaussianBlur(mask, (3, 3), 1)
  134. eroded = cv2.erode(mask,ekernel,iterations = 1)
  135. #dilation = cv2.dilate(eroded,dkernel,iterations = 1)
  136. #morphed = cv2.morphologyEx(mask, cv2.MORPH_OPEN, kernel)
  137. contours = cv2.findContours(eroded,1,2)[-2]
  138. if len(contours) > 0:
  139. c = max(contours,key=cv2.contourArea)
  140. M = cv2.moments(c)
  141. #print M
  142. if M['m00'] != 0:
  143. cx = int(M['m10']/M['m00'])
  144. cy = int(M['m01']/M['m00'])
  145. targetAquired = 1
  146. cv2.circle(im,(cx,cy),5,(0,255,0), -1)
  147. else:
  148. targetAquired = 0
  149. writePositions(cx, cy, targetAquired)
  150. cv2.imshow('frame',im)
  151. #cv2.imshow('Mask',mask)
  152. #cv2.imshow('eroded',dilation)
  153. # update the FPS counter
  154. fps.update()
  155. k = cv2.waitKey(1) & 0xFF
  156. if ((k == 27) or (GPIO.input(35) == 1)):
  157. break
  158. # stop the timer and display FPS information
  159. if fps_run == 1:
  160. fps.stop()
  161. print('\nIm process FPS = {}'.format(fps.fps()))
  162. cv2.destroyAllWindows()
  163. GPIO.output(11,GPIO.LOW)
  164. time.sleep(0.5)
  165. GPIO.output(11,GPIO.HIGH)
  166. ## END --------------------------------------------------------------------------------------------------------------------------------------------------
  167. #CLOSE THREADS
  168. vs.stop()