def selective_search(im, type='f'): # speed-up using multithreads print("Selective Search") cv.setUseOptimized(True) cv.setNumThreads(4) # create Selective Search Segmentation Object using default parameters ss = cv.ximgproc.segmentation.createSelectiveSearchSegmentation() # set input image on which we will run segmentation ss.setBaseImage(im) # Switch to fast but low recall Selective Search method if (type == 'f'): ss.switchToSelectiveSearchFast() # Switch to high recall but slow Selective Search method elif (type == 'q'): ss.switchToSelectiveSearchQuality() print("Searching") # run selective search segmentation on input image rects = ss.process() return rects[0:13]
def main(): if cv2.useOptimized == False: cv2.setUseOptimized(True) print 'CV optimized: ON' else: print 'CV optimized: ON' set_cameras((640, 400)) #create named window to add sliders to cv2.namedWindow('Object') cv2.createTrackbar('error', 'Object', 15, 1000, nothing) cv2.createTrackbar('param1', 'Object', 25, 1000, nothing) cv2.createTrackbar('param2', 'Object', 60, 1000, nothing) cv2.createTrackbar('minRad', 'Object', 110, 255, nothing) #initialize node to send contour data rospy.init_node('CVTest', anonymous = True) conversion = img_processing() try: rospy.spin() except KeyboardInterrupt: print 'Quitting...' baxterImage.unregister() sys.exit() cv2.destroyAllWindows
def blurTime(optimize: bool): # read img = cv.imread("lena.tif", cv.IMREAD_UNCHANGED) # set optimized cv.setUseOptimized(optimize) # mark tick e1 = cv.getTickCount() # median filter must use odd ksize for i in range(1, 100, 2): img = cv.medianBlur(img, i) pass # mark tick e2 = cv.getTickCount() # deduction t = (e2 - e1) / cv.getTickFrequency() # print print("use optimized ", optimize, " time ", t) # show cv.imshow("medianBlur", img) cv.waitKey() cv.destroyAllWindows()
def select_regions(im, method='q'): # speed-up using multithreads cv2.setUseOptimized(True) cv2.setNumThreads(4) # resize image # newHeight = 400 # newWidth = int(im.shape[1]*400/im.shape[0]) # im = cv2.resize(im, (newWidth, newHeight)) # create Selective Search Segmentation Object using default parameters ss = cv2.ximgproc.segmentation.createSelectiveSearchSegmentation() # set input image on which we will run segmentation ss.setBaseImage(im) # Switch to fast but low recall Selective Search method if (method == 'f'): ss.switchToSelectiveSearchFast(sigma=0.5) # Switch to high recall but slow Selective Search method elif (method == 'q'): ss.switchToSelectiveSearchQuality(sigma=0.5) # if argument is neither f nor q print help message else: print(__doc__) sys.exit(1) # run selective search segmentation on input image rects = ss.process() return rects
def search_selective(current: Image) -> List: curr = cv2.cvtColor( np.array(current, dtype=np.uint8), cv2.COLOR_RGB2BGR ) cv2.setUseOptimized(True) ss = cv2.ximgproc.segmentation.createSelectiveSearchSegmentation() ss.setBaseImage(curr) if SELECTIVE_MODE == 'single': ss.switchToSingleStrategy() elif SELECTIVE_MODE == 'fast': ss.switchToSelectiveSearchFast() elif SELECTIVE_MODE == 'quality': ss.switchToSelectiveSearchQUality() else: raise ValueError('SELECTIVE_MODE is invalid') rects = ss.process() bboxes = list() for rect in rects: x, y, w, h = rect area = w * h if area < MIN_RECT_AREA: continue bboxes.append(rect) if len(bboxes) >= MAX_RECTS: break return bboxes
def selective_search(pil_image=None,quality='f',size=800): # speed-up using multithreads cv2.setUseOptimized(True); cv2.setNumThreads(4); # resize image to limit number of proposals and to bypass a bug in OpenCV with non-square images w,h = pil_image.size h_factor,w_factor=h/size,w/size pil_image=pil_image.resize((size,size)) im = cv2.cvtColor(np.array(pil_image), cv2.COLOR_RGB2BGR) # create Selective Search Segmentation Object using default parameters ss = cv2.ximgproc.segmentation.createSelectiveSearchSegmentation() # set input image on which we will run segmentation ss.setBaseImage(im) # Switch to fast but low recall Selective Search method if (quality == 'f'): ss.switchToSelectiveSearchFast() # Switch to high recall but slow Selective Search method elif (quality == 'q'): ss.switchToSelectiveSearchQuality() # run selective search segmentation on input image rects = ss.process() # rect is in x,y,w,h format # convert to xmin,ymin,xmax,ymax format rects = np.vstack((rects[:,0]*w_factor, rects[:,1]*h_factor, (rects[:,0]+rects[:,2])*w_factor, (rects[:,1]+rects[:,3])*h_factor)).transpose() return rects
def __init__(self, camera_port): self.camera = cv2.VideoCapture(int(camera_port)) self.camera.set(cv2.CAP_PROP_FRAME_WIDTH, self.image_width) self.camera.set(cv2.CAP_PROP_FRAME_HEIGHT, self.image_height) cv2.setUseOptimized(True)
def selective_search(img, opt='q'): # If image path and f/q is not passed as command # line arguments, quit and display help message # speed-up using multithreads cv2.setUseOptimized(True) cv2.setNumThreads(8) # read image im = img # create Selective Search Segmentation Object using default parameters ss = cv2.ximgproc.segmentation.createSelectiveSearchSegmentation() # set input image on which we will run segmentation ss.setBaseImage(im) # Switch to fast but low recall Selective Search method if (opt == 'f'): ss.switchToSelectiveSearchFast() # Switch to high recall but slow Selective Search method elif (opt == 'q'): ss.switchToSelectiveSearchQuality() rects = ss.process() return rects
def test_with_optimization(self): cv2.setUseOptimized(True) filename = "pause_and_skip" in_file = TEST_FILES_DIR / f"{filename}.mp4" out_file = TEST_FILES_DIR / f"{filename}_processed" pause_and_skip(in_file, out_file, 10)
def propose_regions(self, img, fast_mode=True): canny_img = cv2.Canny(img, 100, 150, apertureSize=3) # speed-up using multithreads cv2.setUseOptimized(True) cv2.setNumThreads(4) # create Selective Search Segmentation Object using default parameters ss = cv2.ximgproc.segmentation.createSelectiveSearchSegmentation() strategy_color = cv2.ximgproc.segmentation.createSelectiveSearchSegmentationStrategyColor( ) ss.addStrategy(strategy_color) # set input image on which we will run segmentation ss.setBaseImage(img) # Switch to fast but low recall Selective Search method if fast_mode: ss.switchToSelectiveSearchFast() # Switch to high recall but slow Selective Search method else: ss.switchToSelectiveSearchQuality() # run selective search segmentation on input image rects = ss.process() print('Total Number of Region Proposals: {}'.format(len(rects))) return rects, canny_img
def ObjectDetection(im): rectangles = [] # speed-up using multithreads cv2.setUseOptimized(True) cv2.setNumThreads(8) # resize image newHeight = 200 newWidth = int(im.shape[1] * 200 / im.shape[0]) im = cv2.resize(im, (newWidth, newHeight)) ss = cv2.ximgproc.segmentation.createSelectiveSearchSegmentation() ss.setBaseImage(im) ss.switchToSelectiveSearchFast() rects = ss.process() print('Total Number of Region Proposals: {}'.format( len(rects))) # number of region proposals to show numShowRects = 100 copy = im.copy() # itereate over all the region proposals for i, rect in enumerate(rects): # draw rectangle for region proposal till numShowRects if (i < numShowRects): x, y, w, h = rect if rect[2] * rect[3] < (0.4 * im.shape[0] * im.shape[1]): rectangles.append((x, y, x + w, y + h)) cv2.rectangle(copy, (x, y), (x + w, y + h), (0, 0, 255), 2) else: break cv2.imshow("object", copy) cv2.waitKey(0) cv2.destroyAllWindows() return rectangles
def selective_search(im, quality): """ Run selective search on image and return rectanculars (boxes). """ # speed-up using multithreads cv2.setUseOptimized(True) cv2.setNumThreads(4) # create Selective Search Segmentation Object using default parameters ss = cv2.ximgproc.segmentation.createSelectiveSearchSegmentation() # set input image on which we will run segmentation ss.setBaseImage(im) # Switch to fast but low recall Selective Search method if quality == 'f': ss.switchToSelectiveSearchFast() # Switch to high recall but slow Selective Search method elif quality == 'q': ss.switchToSelectiveSearchQuality() print("run selective search on image") rects = ss.process() return rects
def imgSegment(img): # multithreads of opencv to speed-up cv.setUseOptimized(True) cv.setNumThreads(4) # create Selective Search Segmentation Object using default parameters ss = cv.ximgproc.segmentation.createSelectiveSearchSegmentation() fill = cv.ximgproc.segmentation.createSelectiveSearchSegmentationStrategyFill( ) color = cv.ximgproc.segmentation.createSelectiveSearchSegmentationStrategyColor( ) texture = cv.ximgproc.segmentation.createSelectiveSearchSegmentationStrategyTexture( ) strategy = cv.ximgproc.segmentation.createSelectiveSearchSegmentationStrategyMultiple( ) weight = 1.0 #strategy.addStrategy(fill, weight) strategy.addStrategy(color, weight) strategy.addStrategy(texture, weight) ss.addStrategy(strategy) ss.setBaseImage(img) # high recall but slow Selective Search method ss.switchToSelectiveSearchQuality() # fast but low recall Selective Search method #ss.switchToSelectiveSearchFast() # run selective search segmentation on input image rects = ss.process() return rects
def main(): if cv2.useOptimized == False: cv2.setUseOptimized(True) print 'CV optimized: ON' else: print 'CV optimized: ON' set_cameras((640, 400)) #create named window to add sliders to cv2.namedWindow('Object') #create sliders for upper and lower bounds for HSV values (FOR RED BALL) cv2.createTrackbar('H upper', 'Object', 130, 179, nothing) cv2.createTrackbar('H lower', 'Object', 100, 179, nothing) cv2.createTrackbar('S upper', 'Object', 255, 255, nothing) cv2.createTrackbar('S lower', 'Object', 70, 255, nothing) cv2.createTrackbar('V upper', 'Object', 255, 255, nothing) cv2.createTrackbar('V lower', 'Object', 65, 255, nothing) rospy.init_node('CVTest', anonymous=True) conversion = img_processing() try: rospy.spin() except KeyboardInterrupt: print 'Quitting...' baxterImage.unregister() sys.exit() cv2.destroyAllWindows
def make_prediction(model, image): """ Finds the coordinates of the bounding boxes that satisfy a threshold. The coordinates get appended in the order of xMin, xMax, yMin, YMax to a 1D list. Inputs - image: the image to detect objects for - model: the trained model that will do the predictions Returns - results: list of coordinates of the bounding boxes that satisfy the threshold. """ cv2.setUseOptimized(True) selective_search = cv2.ximgproc.segmentation.createSelectiveSearchSegmentation() selective_search.setBaseImage(image) selective_search.switchToSelectiveSearchFast() boxes = selective_search.process() imout = image.copy() results = [] for e,result in enumerate(boxes): if e < 2000: x,y,w,h = result timage = imout[y:y+h,x:x+w] resized = cv2.resize(timage, (hp.img_size,hp.img_size), interpolation = cv2.INTER_AREA) img = np.expand_dims(resized, axis=0) out= model.predict(img) if out[0][0] > 0.70: results.append(x) results.append(x + w) results.append(y) result.append(y+ h) return results
def optimized_setup(): """ SSE2, NEON, etc. """ if not useOptimized(): setUseOptimized(True) info("useOptimized() = %s" % useOptimized())
def selective_search(im, method='reg'): # speed-up using multithreads cv2.setUseOptimized(True) cv2.setNumThreads(4) # create Selective Search Segmentation Object using default parameters ss = cv2.ximgproc.segmentation.createSelectiveSearchSegmentation() # set input image on which we will run segmentation ss.setBaseImage(im) # Switch to fast but low recall Selective Search method if method == 'fast': ss.switchToSelectiveSearchFast() # Switch to high recall but slow Selective Search method else: ss.switchToSelectiveSearchQuality() # run selective search segmentation on input image rects = ss.process() print('Total Number of Region Proposals: {}'.format(len(rects))) return rects
def main(): parser = argparse.ArgumentParser() parser.add_argument( '--model', help='File path of .tflite file.', required=True) parser.add_argument( '--labels', help='File path of labels file.', required=True) args = parser.parse_args() cv2.setUseOptimized(True) client = mqtt.Client() client.connect("127.0.0.1", 1883, 600) labels = load_labels(args.labels) interpreter = ip.Interpreter(args.model) interpreter.allocate_tensors() _, height, width, _ = interpreter.get_input_details()[0]['shape'] cap = cv2.VideoCapture("rtsp://192.168.1.164:554/user=admin&password=&channel=1&stream=1.sdp?") while True: ret, image_np = cap.read() if ret == False: break; image = Image.fromarray(image_np.astype('uint8')).convert('RGB').resize((width, height), Image.ANTIALIAS) results = classify_image(interpreter, image) label_id, prob = results[0] output = {} prob = "scores %.f%%" % (prob * 100) output[labels[label_id]] = prob obj_ret = json.dumps(output) print("output ", output) client.publish('object_detection', obj_ret, qos=0) cap.release()
def cam_loop(pipe_parent): #cv2.namedWindow("pepe") lc = 0 tstamp_prev = None motion_on = 0 motion_off = 0 config = read_config() print (config['cam_ip']) cap = cv2.VideoCapture("rtsp://" + config['cam_ip'] + "/av0_0&user=admin&password=admin") cv2.setUseOptimized(True) image_acc = None time.sleep(5) frames = deque(maxlen=200) frame_times = deque(maxlen=200) time_start = datetime.datetime.now() count = 0 record = 0 while True: _ , frame = cap.read() if _ is True: frame_time = datetime.datetime.now() frames.appendleft(frame) frame_times.appendleft(frame_time) #pipe_parent.send(frame) write_alert = Path("/home/pi/fireball_camera/write_buffer"); if (write_alert.is_file()): record = 1 else: record = 0 if record == 1: print("RECORD BUFFER NOW!\n") motion_on = 0 format_time = frame_time.strftime("%Y%m%d%H%M%S") outfile = "{}/{}.avi".format("/var/www/html/out", format_time) outfile_text = "{}/{}.txt".format("/var/www/html/out", format_time) df = open(outfile_text, 'w', 1) dql = len(frame_times) - 1 time_diff = frame_times[1] - frame_times[dql] fps = 200 / time_diff.total_seconds() print ("FPS: ", fps) writer = cv2.VideoWriter(outfile, cv2.VideoWriter_fourcc(*'MJPG'), fps, (frames[0].shape[1], frames[0].shape[0]), True) while frames: img = frames.pop() ft = frame_times.pop() format_time = ft.strftime("%Y-%m-%d %H:%M:%S.") dec_sec = ft.strftime("%f") format_time = format_time + dec_sec df.write(format_time +"\n") writer.write(img) #i = i + 1 writer.release() df.close() count = count + 1
def ssearch(imageFilename, qOrf, j): # If image path and f/q is not passed as command # line arguments, quit and display help message # speed-up using multithreads cv2.setUseOptimized(True) cv2.setNumThreads(4) # read image im = cv2.imread(imageFilename) # resize image # newHeight = 200 # newWidth = int(im.shape[1] * 200 / im.shape[0]) # im = cv2.resize(im, (newWidth, newHeight)) # create Selective Search Segmentation Object using default parameters ss = cv2.ximgproc.segmentation.createSelectiveSearchSegmentation() # set input image on which we will run segmentation ss.setBaseImage(im) # Switch to fast but low recall Selective Search method if (qOrf == 'f'): ss.switchToSelectiveSearchFast() # Switch to high recall but slow Selective Search method elif (qOrf == 'q'): ss.switchToSelectiveSearchQuality() # if argument is neither f nor q print help message # run selective search segmentation on input image rects = ss.process() print('Total Number of Region Proposals: {}'.format(len(rects))) # number of region proposals to show numShowRects = 100 # increment to increase/decrease total number # of reason proposals to be shown increment = 50 # create a copy of original image imOut = im.copy() # itereate over all the region proposals for i, rect in enumerate(rects): # draw rectangle for region proposal till numShowRects # if (i < numShowRects): x, y, w, h = rect cv2.rectangle(imOut, (x, y), (x + w, y + h), (0, 255, 0), 1, cv2.LINE_AA) # else: # break # show output # cv2.imshow("Output", imOut) cv2.imwrite( "/Users/ping/Documents/thesis/data/ssearch_test/Proposal_{0}_chop_{1}.png" .format(qOrf, j), imOut) print '{0} is finished!'.format(j)
def __init__(self, **kwargs): super(Heuristics, self).__init__(**kwargs) # Sigma for lower & upper bound threshold. self._sigma = kwargs.get('sigma', 0.33) # Initialize OpenCL runtime to optimize performance. cv2.setUseOptimized(True)
def test_112(self): # 11.2OpenCV中的默认优化 # OpenCV 运行的就是优化后的代码 # 使用函数cv2.useOptimized()来查看优化是否被开启 print(cv2.useOptimized()) cv2.setUseOptimized(False) print(cv2.useOptimized()) print("")
def generate_candidates_by_selective_search(imgpath, ss_type='f', show_result=False): """ generate candidates by selective search algorithm :param imgpath: :param ss_type: fast (f) or quality (q) :param show_result :return: """ # number of region proposals to show num_show_rects = 10 # speed-up using multi-threads cv2.setUseOptimized(True) cv2.setNumThreads(4) # read image im = cv2.imread(imgpath) # resize image to a smaller size for fast computation new_height = 200 new_width = int(im.shape[1] * new_height / im.shape[0]) im = cv2.resize(im, (new_width, new_height)) # create Selective Search Segmentation Object using default parameters ss = cv2.ximgproc.segmentation.createSelectiveSearchSegmentation() # set input image on which we will run segmentation ss.setBaseImage(im) # Switch to fast but low recall Selective Search method if ss_type == 'f': ss.switchToSelectiveSearchFast() # Switch to high recall but slow Selective Search method elif ss_type == 'q': ss.switchToSelectiveSearchQuality() # if argument is neither f nor q print help message else: print('Invalid type!') # run selective search segmentation on input image rects = ss.process() print('Total Number of Region Proposals: {}'.format(len(rects))) if show_result: im_out = im.copy() for i, rect in enumerate(rects): # draw rectangle for region proposal till num_show_rects if i < num_show_rects: x, y, w, h = rect cv2.rectangle(im_out, (x, y), (x + w, y + h), (0, 255, 0), 1, cv2.LINE_AA) else: break cv2.imshow("Output", im_out) cv2.waitKey(0) cv2.destroyAllWindows()
def __init__(self): # Make publisher to be able to see video frame with detected face surrounded by square self.image_pub = rospy.Publisher( 'face_detector', # Topic to publish to Image, # Datatype of message. DO NOT CHANGE queue_size=10) # Amount of sends to make until waits for next send # Make sure OpenCV is running optimized code. Increases efficiency cv2.setUseOptimized(True) # Load required XML classifier self.face_cascade = cv2.CascadeClassifier('haarcascade_frontface_default.xml') self.bridge = CvBridge() # Load the png files to numpy arrays self.ahmad_image = fr.load_image_file('ahmad.png') self.belyi_image = fr.load_image_file('belyi.png') self.cruz_image = fr.load_image_file('cruz.png') self.fishberg_image = fr.load_image_file('fishberg.png') self.hassan_image = fr.load_image_file('hassan.png') self.mali_image = fr.load_image_file('mali.png') self.nguyen_image = fr.load_image_file('nguyen.png') self.plancher_image = fr.load_image_file('plancher.png') # Get encodings for first face found self.ahmad_encoding = fr.face_encodings(self.ahmad_image)[0] self.belyi_encoding = fr.face_encodings(self.belyi_image)[0] self.cruz_encoding = fr.face_encodings(self.cruz_image)[0] self.fishberg_encoding = fr.face_encodings(self.fishberg_image)[0] self.hassan_encoding = fr.face_encodings(self.hassan_image)[0] self.mali_encoding = fr.face_encodings(self.mali_image)[0] self.nguyen_encoding = fr.face_encodings(self.nguyen_image)[0] self.plancher_encoding = fr.face_encodings(self.plancher_image)[0] # ==========================Edit================================================== # List of TA faces. Order is important, since it will later be used in a int to string mapping self.known_faces = [self.ahmad_encoding, self.belyi_encoding, self.cruz_encoding, self.fishberg_encoding, self.hassan_encoding, self.mali_encoding, self.nguyen_encoding, self.plancher_encoding] # Dictionary of number keys to TA last names strings. Indicates which TA corresponds to which index self.ta_dict = {0:"Ahmad", 1:"Belyi", 2:"Cruz", 3:"Fisberg", 4:"Hassan", 5:"Mali", 6:"Nguyen", 7:"Plancher"}
def cvInit(): ''' actually dont use cv ''' print('BM3D Initializing at {}'.format(time.time())) print('Initializing OpenCV') start = time.time() cv2.setUseOptimized(True) end = time.time() print('Initialized in {}s'.format(end - start))
def selective_search(input): cv2.setUseOptimized(True) cv2.setNumThreads(4) ss = cv2.ximgproc.segmentation.createSelectiveSearchSegmentation() ss.setBaseImage(input) ss.switchToSingleStrategy() #ss.switchToSelectiveSearchFast() rects = ss.process() return rects
def tick_count(): # 检查是否启用了优化 print(cv.useOptimized()) # 关闭优化 cv.setUseOptimized(False) e1 = cv.getTickCount() # 执行代码 e2 = cv.getTickCount() time = (e2 - e1) / cv.getTickFrequency()
def selective_search(img): # speed-up using multithreads cv2.setUseOptimized(True) # 使用优化 cv2.setNumThreads(4) # 开启多线程计算 ss = cv2.ximgproc.segmentation.createSelectiveSearchSegmentation() ss.setBaseImage(img) ss.switchToSelectiveSearchFast() rects = ss.process() rects[:,2] += rects[:,0] rects[:,3] += rects[:,1] return rects[:,[1,0,3,2]]
def ssearch(img, para): # if __name__ == '__main__': # If image path and f/q is not passed as command # line arguments, quit and display help message # if len(sys.argv) < 3: # print(__doc__) # sys.exit(1) proposals = list() # speed-up using multithreads cv2.setUseOptimized(True) cv2.setNumThreads(4) # read image im = cv2.imread(img) # resize image newHeight = 200 newWidth = int(im.shape[1] * 200 / im.shape[0]) # im = cv2.resize(im, (newWidth, newHeight)) numShowRects = 150 # create Selective Search Segmentation Object using default parameters ss = cv2.ximgproc.segmentation.createSelectiveSearchSegmentation() # set input image on which we will run segmentation ss.setBaseImage(im) # Switch to fast but low recall Selective Search method if (para == 'f'): ss.switchToSelectiveSearchFast() # Switch to high recall but slow Selective Search method elif (para == 'q'): ss.switchToSelectiveSearchQuality() # run selective search segmentation on input image rects = ss.process() print('Total Number of Region Proposals: {}'.format(len(rects))) imOut = im.copy() for i, rect in enumerate(rects): if (i < numShowRects): x, y, w, h = rect proposals.append((x, y, w, h)) cv2.rectangle(imOut, (x, y), (x + w, y + h), (0, 0, 255), 1, cv2.LINE_AA) print "SSearch finished!" cv2.imwrite("/Users/ping/Downloads/chop_0_ssearch.png", imOut)
def __init__(self): cv2.setUseOptimized(True) self.img = cv2.imread('test_imgs/digits.png') rospy.init_node('handwriting_recognition', anonymous=True) self.bridge = CvBridge() rospy.Subscriber("usb_cam/image_raw", Image, self.img_callback) rospack = rospkg.RosPack() PACKAGE_PATH = rospack.get_path("edwin") self.detect = True cv2.namedWindow('image') cv2.setMouseCallback('image',self.fill_test_data) self.test_data = np.zeros((200,200),np.uint8) self.test_filled = 0
def frames(): camera = cv2.VideoCapture(Camera.video_source) camera.set(3,320) camera.set(4,240) width = int(camera.get(3)) height = int(camera.get(4)) M = cv2.getRotationMatrix2D((width / 2, height / 2), 180, 1) camera.set(cv2.CAP_PROP_BUFFERSIZE,1) # camera.rotation = 180 # rawCapture = PiRGBArray(camera, size=(320, 240)) # if not camera.isOpened(): # raise RuntimeError('Could not start camera.') start_time = time.time() fpscount = 0 # print(cv2.useOptimized()) cv2.setUseOptimized(True) # print(cv2.useOptimized()) while True: # read current frame # img = cv2.warpAffine(img, M, (640, 480)) # print(time.time()- start_time) _, img = camera.read() img = cv2.warpAffine(img, M, (320, 240)) img = Vilib.human_detect_func(img) img = Vilib.color_detect_func(img) ## FPS # fpscount += 1 # if (time.time()- start_time) >= 1: # print(fpscount) # start_time = time.time() # fpscount = 0 ## FPS # start_time = time.time() # t1 = cv2.getTickCount() # img = Vilib.human_detect_func(img) # t2 = cv2.getTickCount() # print(int(1/round((t2-t1)/cv2.getTickFrequency(),2))) # img = cv2.resize(img, (320,240), interpolation=cv2.INTER_LINEAR) # img = Vilib.color_detect_func(img) # encode as a jpeg image and return it yield cv2.imencode('.jpg', img)[1].tobytes()
''' e1 = cv2.getTickCount() # your code execution e2 = cv2.getTickCount() time = (e2 - e1)/ cv2.getTickFrequency() ''' img1 = cv2.imread('messi.png') e1 = cv2.getTickCount() for i in xrange(5,49,2): img1 = cv2.medianBlur(img1,i) e2 = cv2.getTickCount() t = (e2 - e1)/cv2.getTickFrequency() print t # check if optimization is enabled cv2.useOptimized() # True # %timeit res = cv2.medianBlur(img,49) # 10 loops, best of 3: 34.9 ms per loop # Disable it cv2.setUseOptimized(False) cv2.useOptimized() # False # %timeit res = cv2.medianBlur(img,49) # 10 loops, best of 3: 64.1 ms per loop
import cv2, sys, pyautogui # Setup cv2.setUseOptimized(True) facePath = sys.argv[1] eyePath = sys.argv[2] faceCascade = cv2.CascadeClassifier(facePath) eyeCascade = cv2.CascadeClassifier(eyePath) videoCapture = cv2.VideoCapture(0) videoCapture.set(cv2.CAP_PROP_FPS, 1) # Saved information from previous frame oldFace = (0, 0, -1, -1) oldLeftEye = (0, 0, -1, -1) oldRightEye = (0, 0, -1, -1) # Learning rest position (do this for turns 0-(learnPhase - 1)) turns = 0 learnPhase = 64 restFace = (0, 0, -1, -1) restLeftEye = (0, 0, -1, -1) restRightEye = (0, 0, -1, -1)