def worker(index,inqueue,outqueue): """ Main function to process an image; performed in the context of a subprocess """ done = False print "Worker Started: ",index sys.stdout.flush() while not done: msg = inqueue.get() if (msg[0] <= 0.0): done = True break #valid request; decode the message timestamp = msg[0] img = msg[1] outline = msg[2] threshold = msg[3] # process the image and queue the results targets = ft.processImage(img,0,threshold,outline[0],outline[1]) retMsg = [timestamp,targets] outqueue.put(retMsg) sys.stdout.flush()
def displayResults(targets,img): """ Debug display of the results """ if (targets != None) : dispTargets = targets else: dispTargets = [] if len(dispTargets) > 0: for t in targets: ft.printTgt(t) ft.displayThresholdTimeout = 0; ft.showImages = True ft.drawAnnotatedImage(img,dispTargets) done = False startTime = ft.currentTimeMs() while not done: ch = 0xFF & cv2.waitKey(1) if ch == 27: done = True curTime = ft.currentTimeMs() if (curTime - startTime) > 1000: done = True
def main(): """ Main program that loops forever """ time.sleep(0.1) args = getArgs() sendReports = True ft.debugPrint = args['debugPrint'] ft.showImages = args['showVideo'] ft.showDebugImages = args['showDebugVideo'] resolution = args['resolution'].split(',') # Convert from string in the format '(w,h)' resolution = int(resolution[0][1:]),int(resolution[1][:-1]) cameraInit = False networkInit = False while not cameraInit or not networkInit: if not cameraInit: try: camera = PiCamera() # initialize the camera and grab a reference to the raw camera capture camera.resolution = resolution camera.framerate = int(args['frameRate']) rawCapture = PiRGBArray(camera, size=resolution) cameraInit = True except: print "Camera Exception" if not networkInit: try: hostPort = args['ds'].split(':') ds.init(hostPort[0],int(hostPort[1])) hostPort = args['robot'].split(':') ft.reportSetup(hostPort[0],int(hostPort[1])) broadcastSocket = socket.socket(socket.AF_INET, # Internet socket.SOCK_DGRAM) # UDP broadcastSocket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR,1) broadcastPort = args['bport'] listen_addr = ("",broadcastPort) broadcastSocket.bind(listen_addr) broadcastSocket.setblocking(False) print "brodcast Port: ",broadcastPort print "Socket Setup: ",broadcastSocket networkInit = True except: print "Network Exception" # allow the camera to warmup time.sleep(0.1) # capture frames from the camera for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True): # grab the raw NumPy array representing the image, then initialize the timestamp # and occupied/unoccupied text image = frame.array collectTime = ft.currentTimeMs() # Simplest color processing # TODO: add tracking, adaptive processing that includes light control if ft.targetOn: targets = ft.processImage(image,[],-ft.detectThreshold,0,0) else: targets = [] if sendReports: ft.sendReport(collectTime,targets) # show the frame (and forward to drivers station) ft.drawAnnotatedImage(image,targets) key = cv2.waitKey(1) & 0xFF # Perform message processing try: msg, addr = broadcastSocket.recvfrom(512) if (msg == ds.BroadcastData): # 'driverstation138' newIP = addr[0] if newIP != ds.UDP_IP: print "Changing Video address= ",newIP ds.init(newIP,ds.UDP_PORT,ds.messageResolution) if (msg == 'robot138'): newIP = addr[0] if newIP != ft.UDP_IP: print "Changing Report address= ",newIP ft.reportSetup(newIP,ft.UDP_PORT) if (msg == 'targetOn'): ft.targetOn = True if (msg == 'targetOff'): ft.targetOn = False if msg.find('detectThreshold') >= 0: fields = msg.split('=') thr = float(fields[1]) if (thr >= 0.80) and (thr <= 0.99): ft.detectThreshold = thr if msg.find('showThreshold') >= 0: fields = msg.split('=') if (fields[1] == None): timeout = 15 else: timeout = int(fields[1]) if (timeout >= 0) and (timeout <= 30): ft.displayThresholdMode(timeout*1000) except: pass # clear the stream in preparation for the next frame rawCapture.truncate(0) # if the `q` key was pressed, break from the loop if key == ord("q"): break
found = True return found,best if __name__ == '__main__': """ Test program """ init() makeProcesses(3) print "Workers Ready" imgDir = 'C:\\Users\\jeffrey.f.bryant\\Desktop\\FirstRobotics\\vision\\Images\\' imgInput = cv2.imread(imgDir + '5.JPG') imgCopy = imgInput.copy() collectTime = ft.currentTimeMs() targets = completeImage(collectTime,imgInput) displayResults(targets,imgInput) print print '-----------------------Track --------------------' print found, best = bestTarget(targets) if (found): for k in range(4): imgInput = imgCopy.copy() collectTime = ft.currentTimeMs() targets = track(collectTime,best,imgInput)
def wpiTest(imgdir, maxSize, resize): """ Perform an analysis on all the .jpg files in a directory """ results = [] onlyfiles = [f for f in listdir(imgdir) if isfile(join(imgdir, f))] for fn in onlyfiles: path = join(imgdir, fn) if fn[-4:].lower() == '.jpg': imgInput = cv2.imread(path) #Resise the image if desired if (imgInput.shape[0] > maxSize[0]) and (imgInput.shape[1] > maxSize[1]) and resize: imgResized = cv2.resize(imgInput, maxSize) else: imgResized = imgInput print 20 * '=', fn, imgResized.shape collectTime = ft.currentTimeMs() #targets,colors = ft.fullColorSearch(imgResized,0,0,True) targets = ft.subImageSearch(imgResized, True) ft.sendReport(collectTime, targets) if len(targets) > 0: ft.printTgt(targets[0]) ft.drawAnnotatedImage(imgResized, targets) results.append((fn, targets)) # fast execution ch = 0xFF & cv2.waitKey(100) if ch == 27: break elif (ch == ord('t')): ft.displayThresholdMode(10000) elif (ch == ord('u')): ft.displayThresholdMode(10000) ft.detectThreshold = ft.detectThreshold + 0.01 elif (ch == ord('d')): ft.detectThreshold = ft.detectThreshold - 0.01 ft.displayThresholdMode(10000)
if __name__ == '__main__': """ Main test program """ print "OpenCV Version:", cv2.__version__ ft.showImages = True ft.showDebugImages = False trackTargets = False resize = True maxSize = (640, 480) batchTest = True fullColorTest = False subImageTest = True ft.reportSetup('loopback', 5802) ft.printReport = False ds.init('loopback', 5800) ft.debugPrint = True # Read and resize the image #imgDir = 'C:\\Users\\jeffrey.f.bryant\\Desktop\\First2016\\' imgDir = 'C:\\Users\\jeffrey.f.bryant\\Desktop\\First2016\\RealFullField\\' #imgDir = 'C:\\Users\\jeffrey.f.bryant\\Desktop\\First2016\\CalShots\\' if (batchTest): wpiTest(imgDir, maxSize, resize) if (fullColorTest or subImageTest): imgInput = cv2.imread(imgDir + 'IMG_1087.JPG')