Python cv2.namedWindow() Examples

The following are 30 code examples for showing how to use cv2.namedWindow(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module cv2 , or try the search function .

Example 1
Project: The-chat-room   Author: 11ze   File: vachat.py    License: MIT License 10 votes vote down vote up
def run(self):
        print("VEDIO server starts...")
        self.sock.bind(self.ADDR)
        self.sock.listen(1)
        conn, addr = self.sock.accept()
        print("remote VEDIO client success connected...")
        data = "".encode("utf-8")
        payload_size = struct.calcsize("L")
        cv2.namedWindow('Remote', cv2.WINDOW_AUTOSIZE)
        while True:
            while len(data) < payload_size:
                data += conn.recv(81920)
            packed_size = data[:payload_size]
            data = data[payload_size:]
            msg_size = struct.unpack("L", packed_size)[0]
            while len(data) < msg_size:
                data += conn.recv(81920)
            zframe_data = data[:msg_size]
            data = data[msg_size:]
            frame_data = zlib.decompress(zframe_data)
            frame = pickle.loads(frame_data)
            cv2.imshow('Remote', frame)
            if cv2.waitKey(1) & 0xFF == 27:
                break 
Example 2
Project: olympe   Author: Parrot-Developers   File: streaming.py    License: BSD 3-Clause "New" or "Revised" License 8 votes vote down vote up
def run(self):
        window_name = "Olympe Streaming Example"
        cv2.namedWindow(window_name, cv2.WINDOW_NORMAL)
        main_thread = next(
            filter(lambda t: t.name == "MainThread", threading.enumerate())
        )
        while main_thread.is_alive():
            with self.flush_queue_lock:
                try:
                    yuv_frame = self.frame_queue.get(timeout=0.01)
                except queue.Empty:
                    continue
                try:
                    self.show_yuv_frame(window_name, yuv_frame)
                except Exception:
                    # We have to continue popping frame from the queue even if
                    # we fail to show one frame
                    traceback.print_exc()
                finally:
                    # Don't forget to unref the yuv frame. We don't want to
                    # starve the video buffer pool
                    yuv_frame.unref()
        cv2.destroyWindow(window_name) 
Example 3
Project: OpenCV-3-x-with-Python-By-Example   Author: PacktPublishing   File: object_tracker.py    License: MIT License 8 votes vote down vote up
def __init__(self): 
        # Initialize the video capture object 
        # 0 -> indicates that frame should be captured 
        # from webcam 
        self.cap = cv2.VideoCapture(0) 
 
        # Capture the frame from the webcam 
        ret, self.frame = self.cap.read() 
 
        # Downsampling factor for the input frame 
        self.scaling_factor = 0.8 
        self.frame = cv2.resize(self.frame, None, fx=self.scaling_factor, fy=self.scaling_factor, interpolation=cv2.INTER_AREA) 
 
        cv2.namedWindow('Object Tracker') 
        cv2.setMouseCallback('Object Tracker', self.mouse_event) 
 
        self.selection = None 
        self.drag_start = None 
        self.tracking_state = 0 
 
    # Method to track mouse events 
Example 4
Project: srl-zoo   Author: araffin   File: enjoy_latent.py    License: MIT License 7 votes vote down vote up
def createFigureAndSlider(name, state_dim):
    """
    Creating a window for the latent space visualization, an another for the slider to control it
    :param name: name of model (str)
    :param state_dim: (int)
    :return:
    """
    # opencv gui setup
    cv2.namedWindow(name, cv2.WINDOW_NORMAL)
    cv2.resizeWindow(name, 500, 500)
    cv2.namedWindow('slider for ' + name)
    # add a slider for each component of the latent space
    for i in range(state_dim):
        # the sliders MUST be between 0 and max, so we placed max at 100, and start at 50
        # So that when we substract 50 and divide 10 we get [-5,5] for each component
        cv2.createTrackbar(str(i), 'slider for ' + name, 50, 100, (lambda a: None)) 
Example 5
Project: holodeck   Author: BYU-PCCL   File: captures.py    License: MIT License 6 votes vote down vote up
def display_multiple(images: List[Tuple[List, Optional[str]]]):
    """Displays one or more captures in a CV2 window. Useful for debugging

    Args:
        images: List of tuples containing MxNx3 pixel arrays and optional titles OR
            list of image data
    """
    for image in images:
        if isinstance(image, tuple):
            image_data = image[0]
        else:
            image_data = image

        if isinstance(image, tuple) and len(image) > 1:
            title = image[1]
        else:
            title = "Camera Output"

        cv2.namedWindow(title)
        cv2.moveWindow(title, 500, 500)
        cv2.imshow(title, image_data)
    cv2.waitKey(0)
    cv2.destroyAllWindows() 
Example 6
Project: ReolinkCameraAPI   Author: Benehiko   File: RtspClient.py    License: GNU General Public License v3.0 6 votes vote down vote up
def preview(self):
        """ Blocking function. Opens OpenCV window to display stream. """
        self.connect()
        win_name = 'RTSP'
        cv2.namedWindow(win_name, cv2.WINDOW_AUTOSIZE)
        cv2.moveWindow(win_name, 20, 20)

        while True:
            cv2.imshow(win_name, self.get_frame())
            # if self._latest is not None:
            #    cv2.imshow(win_name,self._latest)
            if cv2.waitKey(25) & 0xFF == ord('q'):
                break
        cv2.waitKey()
        cv2.destroyAllWindows()
        cv2.waitKey() 
Example 7
Project: crappy   Author: LaboratoireMecaniqueLille   File: discorrel.py    License: GNU General Public License v2.0 6 votes vote down vote up
def prepare(self):
    if self.save_folder and not os.path.exists(self.save_folder):
      try:
        os.makedirs(self.save_folder)
      except OSError:
        assert os.path.exists(self.save_folder),\
            "Error creating "+self.save_folder
    self.cam = Camera.classes[self.camera]()
    self.cam.open(**self.cam_kwargs)
    config = DISConfig(self.cam)
    config.main()
    self.bbox = config.box
    t,img0 = self.cam.get_image()
    self.correl = DIS(img0,bbox=self.bbox)
    if self.show_image:
      try:
        flags = cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO
      except AttributeError:
        flags = cv2.WINDOW_NORMAL
      cv2.namedWindow("DISCorrel",flags)
    self.loops = 0
    self.last_fps_print = 0
    self.last_fps_loops = 0 
Example 8
Project: crappy   Author: LaboratoireMecaniqueLille   File: videoExtenso.py    License: GNU General Public License v2.0 6 votes vote down vote up
def prepare(self):
    if self.save_folder and not os.path.exists(self.save_folder):
      try:
        os.makedirs(self.save_folder)
      except OSError:
        assert os.path.exists(self.save_folder),\
            "Error creating "+self.save_folder
    self.cam = Camera.classes[self.camera]()
    self.cam.open(**self.cam_kwargs)
    self.ve = VE(**self.ve_kwargs)
    config = VE_config(self.cam,self.ve)
    config.main()
    self.ve.start_tracking()
    if self.show_image:
      try:
        flags = cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO
      except AttributeError:
        flags = cv2.WINDOW_NORMAL
      cv2.namedWindow("Videoextenso",flags)
    self.loops = 0
    self.last_fps_print = 0
    self.last_fps_loops = 0 
Example 9
Project: face_landmark_dnn   Author: junhwanjang   File: kalman_filter.py    License: MIT License 6 votes vote down vote up
def main():
    """Test code"""
    global mp
    mp = np.array((2, 1), np.float32)  # measurement

    def onmouse(k, x, y, s, p):
        global mp
        mp = np.array([[np.float32(x)], [np.float32(y)]])

    cv2.namedWindow("kalman")
    cv2.setMouseCallback("kalman", onmouse)
    kalman = Stabilizer(4, 2)
    frame = np.zeros((480, 640, 3), np.uint8)  # drawing canvas

    while True:
        kalman.update(mp)
        point = kalman.prediction
        state = kalman.filter.statePost
        cv2.circle(frame, (state[0], state[1]), 2, (255, 0, 0), -1)
        cv2.circle(frame, (point[0], point[1]), 2, (0, 255, 0), -1)
        cv2.imshow("kalman", frame)
        k = cv2.waitKey(30) & 0xFF
        if k == 27:
            break 
Example 10
Project: SolveSudoku   Author: aakashjhawar   File: SudokuExtractor.py    License: MIT License 6 votes vote down vote up
def parse_grid(path):
    original = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
    processed = pre_process_image(original)
    
#    cv2.namedWindow('processed',cv2.WINDOW_AUTOSIZE)
#    processed_img = cv2.resize(processed, (500, 500))          # Resize image
#    cv2.imshow('processed', processed_img)
    
    corners = find_corners_of_largest_polygon(processed)
    cropped = crop_and_warp(original, corners)
    
#    cv2.namedWindow('cropped',cv2.WINDOW_AUTOSIZE)
#    cropped_img = cv2.resize(cropped, (500, 500))              # Resize image
#    cv2.imshow('cropped', cropped_img)
    
    squares = infer_grid(cropped)
#    print(squares)
    digits = get_digits(cropped, squares, 28)
#    print(digits)
    final_image = show_digits(digits)
    return final_image 
Example 11
Project: keras-image-segmentation   Author: dhkim0225   File: train.py    License: MIT License 6 votes vote down vote up
def train_generator(self, image_generator, mask_generator):
        # cv2.namedWindow('show', 0)
        # cv2.resizeWindow('show', 1280, 640)
        while True:
            image = next(image_generator)
            mask = next(mask_generator)
            label = self.make_regressor_label(mask).astype(np.float32)
            # print (image.dtype, label.dtype)
            # print (image.shape, label.shape)
            # exit()
            # cv2.imshow('show', image[0].astype(np.uint8))
            # cv2.imshow('label', label[0].astype(np.uint8))
            # mask = self.select_labels(mask)
            # print (image.shape)
            # print (mask.shape)
            # image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
            # mask = (mask.astype(np.float32)*255/33).astype(np.uint8)
            # mask_color = cv2.applyColorMap(mask, cv2.COLORMAP_JET)
            # print (mask_color.shape)
            # show = cv2.addWeighted(image, 0.5, mask_color, 0.5, 0.0)
            # cv2.imshow("show", show)
            # key = cv2.waitKey()
            # if key == 27:
            #     exit()
            yield (image, label) 
Example 12
Project: ip_basic   Author: kujason   File: vis_utils.py    License: MIT License 6 votes vote down vote up
def cv2_show_image(window_name, image,
                   size_wh=None, location_xy=None):
    """Helper function for specifying window size and location when
    displaying images with cv2.

    Args:
        window_name: str window name
        image: ndarray image to display
        size_wh: window size (w, h)
        location_xy: window location (x, y)
    """

    if size_wh is not None:
        cv2.namedWindow(window_name,
                        cv2.WINDOW_KEEPRATIO | cv2.WINDOW_GUI_NORMAL)
        cv2.resizeWindow(window_name, *size_wh)
    else:
        cv2.namedWindow(window_name, cv2.WINDOW_AUTOSIZE)

    if location_xy is not None:
        cv2.moveWindow(window_name, *location_xy)

    cv2.imshow(window_name, image) 
Example 13
Project: Color-Tracker   Author: gaborvecsei   File: color_range_detector.py    License: MIT License 6 votes vote down vote up
def _init_trackbars(self):
        trackbars_window_name = "hsv settings"
        cv2.namedWindow(trackbars_window_name, cv2.WINDOW_NORMAL)

        # HSV Lower Bound
        h_min_trackbar = _Trackbar("H min", trackbars_window_name, 0, 255)
        s_min_trackbar = _Trackbar("S min", trackbars_window_name, 0, 255)
        v_min_trackbar = _Trackbar("V min", trackbars_window_name, 0, 255)

        # HSV Upper Bound
        h_max_trackbar = _Trackbar("H max", trackbars_window_name, 255, 255)
        s_max_trackbar = _Trackbar("S max", trackbars_window_name, 255, 255)
        v_max_trackbar = _Trackbar("V max", trackbars_window_name, 255, 255)

        # Kernel for morphology
        kernel_x = _Trackbar("kernel x", trackbars_window_name, 0, 30)
        kernel_y = _Trackbar("kernel y", trackbars_window_name, 0, 30)

        self._trackbars = [h_min_trackbar, s_min_trackbar, v_min_trackbar, h_max_trackbar, s_max_trackbar,
                           v_max_trackbar, kernel_x, kernel_y] 
Example 14
Project: PyIntroduction   Author: tody411   File: video_capture.py    License: MIT License 6 votes vote down vote up
def cvCaptureVideo():
    capture = cv2.VideoCapture(0)

    if capture.isOpened() is False:
        raise("IO Error")

    cv2.namedWindow("Capture", cv2.WINDOW_NORMAL)

    while True:
        ret, image = capture.read()

        if ret == False:
            continue

        cv2.imshow("Capture", image)

        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

    capture.release()
    cv2.destroyAllWindows()


# MatplotによるWebカメラのキャプチャと表示 
Example 15
Project: imgaug   Author: aleju   File: check_add_to_hue_and_saturation.py    License: MIT License 6 votes vote down vote up
def main():
    image = data.astronaut()

    cv2.namedWindow("aug", cv2.WINDOW_NORMAL)
    cv2.imshow("aug", image)
    cv2.waitKey(TIME_PER_STEP)

    # for value in cycle(np.arange(-255, 255, VAL_PER_STEP)):
    for value in np.arange(-255, 255, VAL_PER_STEP):
        aug = iaa.AddToHueAndSaturation(value=value)
        img_aug = aug.augment_image(image)
        img_aug = iaa.pad(img_aug, bottom=40)
        img_aug = ia.draw_text(img_aug, x=0, y=img_aug.shape[0]-38, text="value=%d" % (value,), size=30)

        cv2.imshow("aug", img_aug)
        cv2.waitKey(TIME_PER_STEP)

    images_aug = iaa.AddToHueAndSaturation(value=(-255, 255), per_channel=True).augment_images([image] * 64)
    ia.imshow(ia.draw_grid(images_aug))

    image = ia.quokka_square((128, 128))
    images_aug = []
    images_aug.extend(iaa.AddToHue().augment_images([image] * 10))
    images_aug.extend(iaa.AddToSaturation().augment_images([image] * 10))
    ia.imshow(ia.draw_grid(images_aug, rows=2)) 
Example 16
Project: imgaug   Author: aleju   File: check_superpixels.py    License: MIT License 6 votes vote down vote up
def main():
    image = data.astronaut()[..., ::-1]  # rgb2bgr
    print(image.shape)

    cv2.namedWindow("aug", cv2.WINDOW_NORMAL)
    cv2.imshow("aug", image)
    cv2.waitKey(TIME_PER_STEP)

    for n_segments in cycle(reversed(np.arange(1, 200, SEGMENTS_PER_STEP))):
        aug = iaa.Superpixels(p_replace=0.75, n_segments=n_segments)
        time_start = time.time()
        img_aug = aug.augment_image(image)
        print("augmented %d in %.4fs" % (n_segments, time.time() - time_start))
        img_aug = ia.draw_text(img_aug, x=5, y=5, text="%d" % (n_segments,))

        cv2.imshow("aug", img_aug)
        cv2.waitKey(TIME_PER_STEP) 
Example 17
Project: imgaug   Author: aleju   File: check_directed_edge_detect.py    License: MIT License 6 votes vote down vote up
def main():
    image = data.astronaut()

    cv2.namedWindow("aug", cv2.WINDOW_NORMAL)
    cv2.imshow("aug", image)
    cv2.waitKey(TIME_PER_STEP)

    height, width = image.shape[0], image.shape[1]
    center_x = width // 2
    center_y = height // 2
    r = int(min(image.shape[0], image.shape[1]) / 3)

    for deg in cycle(np.arange(0, 360, DEG_PER_STEP)):
        rad = np.deg2rad(deg-90)
        point_x = int(center_x + r * np.cos(rad))
        point_y = int(center_y + r * np.sin(rad))

        direction = deg / 360
        aug = iaa.DirectedEdgeDetect(alpha=1.0, direction=direction)
        img_aug = aug.augment_image(image)
        img_aug[point_y-POINT_SIZE:point_y+POINT_SIZE+1, point_x-POINT_SIZE:point_x+POINT_SIZE+1, :] =\
            np.array([0, 255, 0])

        cv2.imshow("aug", img_aug)
        cv2.waitKey(TIME_PER_STEP) 
Example 18
Project: DL.EyeSight   Author: liuguiyangnwpu   File: check_color.py    License: GNU General Public License v3.0 6 votes vote down vote up
def main_WithColorspace():
    image = data.astronaut()
    print("image shape:", image.shape)

    aug = WithColorspace(
        from_colorspace="RGB",
        to_colorspace="HSV",
        children=WithChannels(0, Add(50))
    )

    aug_no_colorspace = WithChannels(0, Add(50))

    img_show = np.hstack([
        image,
        aug.augment_image(image),
        aug_no_colorspace.augment_image(image)
    ])

    cv2.namedWindow("aug", cv2.WINDOW_NORMAL)
    cv2.imshow("aug", img_show[..., ::-1])
    cv2.waitKey(TIME_PER_STEP) 
Example 19
Project: Gesture-Recognition   Author: NVIDIA-AI-IOT   File: DisplayThread.py    License: MIT License 6 votes vote down vote up
def display_loop(self, display_queue):
        # global display_queue
        cv2.namedWindow(self.window_name)
        while not self.stopped:
            fps = 1.0 / (time.time() - self.fps_time)
            self.fps_time = time.time()
            with self.lock:
                img = display_queue.get()
                cv2.putText(img,
					"FPS: %f" % fps,
					(10, 10),  cv2.FONT_HERSHEY_SIMPLEX, 0.5,
					(0, 255, 0), 2)
                cv2.imshow(self.window_name, img)
                display_queue.task_done()
                cv2.waitKey(self.delay)
                if cv2.waitKey(1) == 27:
                    self.stop() 
Example 20
Project: The-chat-room   Author: 11ze   File: vachat.py    License: MIT License 5 votes vote down vote up
def run(self):
        while True:
            try:
                self.sock.connect(self.ADDR)
                break
            except:
                time.sleep(3)
                continue
        if self.showme:
            cv2.namedWindow('You', cv2.WINDOW_NORMAL)
        print("VEDIO client connected...")
        while self.cap.isOpened():
            ret, frame = self.cap.read()
            if self.showme:
                cv2.imshow('You', frame)
                if cv2.waitKey(1) & 0xFF == 27:
                    self.showme = False
                    cv2.destroyWindow('You')
            sframe = cv2.resize(frame, (0, 0), fx=self.fx, fy=self.fx)
            data = pickle.dumps(sframe)
            zdata = zlib.compress(data, zlib.Z_BEST_COMPRESSION)
            try:
                self.sock.sendall(struct.pack("L", len(zdata)) + zdata)
            except:
                break
            for i in range(self.interval):
                self.cap.read() 
Example 21
Project: facemoji   Author: PiotrDabrowskey   File: webcam.py    License: MIT License 5 votes vote down vote up
def show_webcam_and_run(model, emoticons, window_size=None, window_name='webcam', update_time=10):
    """
    Shows webcam image, detects faces and its emotions in real time and draw emoticons over those faces.
    :param model: Learnt emotion detection model.
    :param emoticons: List of emotions images.
    :param window_size: Size of webcam image window.
    :param window_name: Name of webcam image window.
    :param update_time: Image update time interval.
    """
    cv2.namedWindow(window_name, WINDOW_NORMAL)
    if window_size:
        width, height = window_size
        cv2.resizeWindow(window_name, width, height)

    vc = cv2.VideoCapture(0)
    if vc.isOpened():
        read_value, webcam_image = vc.read()
    else:
        print("webcam not found")
        return

    while read_value:
        for normalized_face, (x, y, w, h) in find_faces(webcam_image):
            prediction = model.predict(normalized_face)  # do prediction
            if cv2.__version__ != '3.1.0':
                prediction = prediction[0]

            image_to_draw = emoticons[prediction]
            draw_with_alpha(webcam_image, image_to_draw, (x, y, w, h))

        cv2.imshow(window_name, webcam_image)
        read_value, webcam_image = vc.read()
        key = cv2.waitKey(update_time)

        if key == 27:  # exit on ESC
            break

    cv2.destroyWindow(window_name) 
Example 22
Project: OpenCV-Python-Tutorial   Author: makelove   File: feature_homography.py    License: MIT License 5 votes vote down vote up
def __init__(self, src):
        self.cap = video.create_capture(src, presets['book'])
        self.frame = None
        self.paused = False
        self.tracker = PlaneTracker()

        cv2.namedWindow('plane')
        self.rect_sel = common.RectSelector('plane', self.on_rect) 
Example 23
Project: OpenCV-Python-Tutorial   Author: makelove   File: plane_tracker.py    License: MIT License 5 votes vote down vote up
def __init__(self, src):
        self.cap = video.create_capture(src, presets['book'])
        self.frame = None
        self.paused = False
        self.tracker = PlaneTracker()

        cv2.namedWindow('plane')
        self.rect_sel = common.RectSelector('plane', self.on_rect) 
Example 24
Project: OpenCV-Python-Tutorial   Author: makelove   File: plane_ar.py    License: MIT License 5 votes vote down vote up
def __init__(self, src):
        self.cap = video.create_capture(src, presets['book'])
        self.frame = None
        self.paused = False
        self.tracker = PlaneTracker()

        cv2.namedWindow('plane')
        cv2.createTrackbar('focal', 'plane', 25, 50, common.nothing)
        self.rect_sel = common.RectSelector('plane', self.on_rect) 
Example 25
Project: OpenCV-Python-Tutorial   Author: makelove   File: match_template.py    License: MIT License 5 votes vote down vote up
def main(argv):

   if (len(sys.argv) < 3):
      print 'Not enough parameters'
      print 'Usage:\nmatch_template_demo.py <image_name> <template_name> [<mask_name>]'
      return -1

   ## [load_image]
   global img
   global templ
   img = cv2.imread(sys.argv[1], cv2.IMREAD_COLOR)
   templ = cv2.imread(sys.argv[2], cv2.IMREAD_COLOR)

   if (len(sys.argv) > 3):
      global use_mask
      use_mask = True
      global mask
      mask = cv2.imread( sys.argv[3], cv2.IMREAD_COLOR )

   if ((img is None) or (templ is None) or (use_mask and (mask is None))):
      print 'Can\'t read one of the images'
      return -1
   ## [load_image]

   ## [create_windows]
   cv2.namedWindow( image_window, cv2.WINDOW_AUTOSIZE )
   cv2.namedWindow( result_window, cv2.WINDOW_AUTOSIZE )
   ## [create_windows]

   ## [create_trackbar]
   trackbar_label = 'Method: \n 0: SQDIFF \n 1: SQDIFF NORMED \n 2: TM CCORR \n 3: TM CCORR NORMED \n 4: TM COEFF \n 5: TM COEFF NORMED'
   cv2.createTrackbar( trackbar_label, image_window, match_method, max_Trackbar, MatchingMethod )
   ## [create_trackbar]

   MatchingMethod(match_method)

   ## [wait_key]
   cv2.waitKey(0)
   return 0
   ## [wait_key] 
Example 26
Project: OpenCV-Python-Tutorial   Author: makelove   File: camshift.py    License: MIT License 5 votes vote down vote up
def __init__(self, video_src):
        self.cam = video.create_capture(video_src, presets['cube'])
        ret, self.frame = self.cam.read()
        cv2.namedWindow('camshift')
        cv2.setMouseCallback('camshift', self.onmouse)

        self.selection = None
        self.drag_start = None
        self.show_backproj = False
        self.track_window = None 
Example 27
Project: crappy   Author: LaboratoireMecaniqueLille   File: displayer.py    License: GNU General Public License v2.0 5 votes vote down vote up
def begin_cv(self):
    try:
      flags = cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO
    # WINDOW_KEEPRATIO is not implemented in all opencv versions...
    except AttributeError:
      flags = cv2.WINDOW_NORMAL
    cv2.namedWindow(self.title, flags) 
Example 28
Project: crappy   Author: LaboratoireMecaniqueLille   File: example.py    License: GNU General Public License v2.0 5 votes vote down vote up
def start():
    try:
        cv2.namedWindow("Displayer", cv2.WINDOW_NORMAL)
        ret, buf = ximea.read()
        if ret:
            cv2.imshow('Displayer', buf.get('data'))
            cv2.waitKey(1)
        else:
            print "failed to grab a frame"
        ximea.addTrigger(10000000, True)
    except Exception as e:
        print "exception: ", e 
Example 29
Project: keras-image-segmentation   Author: dhkim0225   File: callbacks.py    License: MIT License 5 votes vote down vote up
def train_visualization_seg(self, model, epoch, path):
        # image_name_list = sorted(glob(os.path.join(self.flag.data_path,'val/IMAGE/*/frankfurt_000000_014480_leftImg8bit.png')))
        # print (image_name_list)

        image_name = path #'./result/frankfurt_000000_014480_leftImg8bit.png'
        image_height = self.flag.image_height
        image_width = self.flag.image_width
        
        imgInput = cv2.imread(image_name, self.flag.color_mode)
        imgInput = cv2.cvtColor(imgInput, cv2.COLOR_BGR2RGB)
        output_path = self.flag.output_dir
        input_data = imgInput.reshape((1,image_height,image_width,self.flag.color_mode*2+1))

        t_start = cv2.getTickCount()
        result = model.predict(input_data, 1)
        t_total = (cv2.getTickCount() - t_start) / cv2.getTickFrequency() * 1000
        print ("[*] Predict Time: %.3f ms"%t_total)
        
        imgMask = (result[0]*255).astype(np.uint8)
        imgShow = cv2.cvtColor(imgInput, cv2.COLOR_RGB2BGR).copy()
        #cv2.cvtColor(imgInput, cv2.COLOR_GRAY2BGR)
        # imgMaskColor = cv2.applyColorMap(imgMask, cv2.COLORMAP_JET)
        imgMaskColor = imgMask
        imgShow = cv2.addWeighted(imgShow, 0.5, imgMaskColor, 0.6, 0.0)
        output_path = os.path.join(self.flag.output_dir, '%04d_'%epoch+os.path.basename(image_name))
        mask_path = os.path.join(self.flag.output_dir, 'mask_%04d_'%epoch+os.path.basename(image_name))
        cv2.imwrite(output_path, imgShow)
        cv2.imwrite(mask_path, imgMaskColor)
        # print "SAVE:[%s]"%output_path
        # cv2.imwrite(os.path.join(output_path, 'img%04d.png'%epoch), imgShow)
        # cv2.namedWindow("show", 0)
        # cv2.resizeWindow("show", 800, 800)
        # cv2.imshow("show", imgShow)
        # cv2.waitKey(1) 
Example 30
Project: pyERA   Author: mpatacchiola   File: icub.py    License: MIT License 5 votes vote down vote up
def _track_movement(self, template_path, delay=0.5):
        """ Given a colour template it tracks the 
        
        @param delay: 
        @return: 
        """
        my_mask_analyser = BinaryMaskAnalyser()
        t = threading.currentThread()
        template = cv2.imread(template_path)  # Load the image
        my_back_detector = BackProjectionColorDetector()  # Defining the deepgaze color detector object
        my_back_detector.setTemplate(template)  # Set the template
        #cv2.namedWindow('filtered')
        while getattr(t, "do_run", True):
            #img_array = np.zeros((360,240,3), dtype=np.uint8)
            img_array = self.return_left_camera_image(mode='BGR')
            image_filtered = my_back_detector.returnFiltered(img_array, morph_opening=True,
                                                             blur=True, kernel_size=7, iterations=2)
            cx, cy = my_mask_analyser.returnMaxAreaCenter(image_filtered)
            if cx is not None:
                cv2.circle(image_filtered,(cx,cy), 5, (0, 0, 255), -1)
                bottle = yarp.Bottle()
                bottle.clear()
                bottle.addString('left')
                bottle.addDouble(cx)
                bottle.addDouble(cy)
                bottle.addDouble(1.0)
                self.port_ikin_mono.write(bottle)
            #images_stack = np.hstack((img_array, image_filtered))
            #cv2.imshow('filtered', images_stack)
            #cv2.waitKey(100) #waiting 50 msec
            time.sleep(0.1)
        #cv2.destroyWindow('filtered')