Python cv2.destroyWindow() Examples

The following are 30 code examples of cv2.destroyWindow(). 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 also want to check out all available functions/classes of the module cv2 , or try the search function .
Example #1
Source File: streaming.py    From olympe with 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 #2
Source File: ColorPalette.py    From Finger-Detection-and-Tracking with BSD 2-Clause "Simplified" License 7 votes vote down vote up
def main():
    windowName = "OpenCV BGR Color Palette"
    imageData = np.zeros((512, 512, 3), np.uint8)

    cv2.namedWindow(windowName)

    cv2.createTrackbar('Blue', windowName, 0, 255, passFunction)
    cv2.createTrackbar('Green', windowName, 0, 255, passFunction)
    cv2.createTrackbar('Red', windowName, 0, 255, passFunction)

    while (True):
        cv2.imshow(windowName, imageData)

        if cv2.waitKey(1) & 0xFF == 27:
            break

        blue = cv2.getTrackbarPos('Blue', windowName)
        green = cv2.getTrackbarPos('Green', windowName)
        red = cv2.getTrackbarPos('Red', windowName)

        imageData[:] = [blue, green, red]
        print(blue, green, red)

    cv2.destroyWindow(windowName) 
Example #3
Source File: eyeDetect.py    From optimeyes with MIT License 7 votes vote down vote up
def main():
    cv2.namedWindow(WINDOW_NAME) # open a window to show debugging images
    vc = cv2.VideoCapture(0) # Initialize the default camera
    try:
        if vc.isOpened(): # try to get the first frame
            (readSuccessful, frame) = vc.read()
        else:
            raise(Exception("failed to open camera."))
            readSuccessful = False
    
        while readSuccessful:
            pupilOffsetXYList = getOffset(frame, allowDebugDisplay=True)
            key = cv2.waitKey(10)
            if key == 27: # exit on ESC
                cv2.imwrite( "lastOutput.png", frame) #save the last-displayed image to file, for our report
                break
            # Get Image from camera
            readSuccessful, frame = vc.read()
    finally:
        vc.release() #close the camera
        cv2.destroyWindow(WINDOW_NAME) #close the window 
Example #4
Source File: visualization_helpers.py    From CameraRadarFusionNet with Apache License 2.0 6 votes vote down vote up
def __rendering_loop(cls):
        window_names = set()
        while cls._rendering_thread:
            try:
                winname, img = cls._rendering_queue.get(block=False)
                cv2.imshow(winname, img)
                window_names.add(winname)
            except queue.Empty:
                pass

            event_time = max(1000 // cls.FPS, 1)
            key = cv2.waitKey(event_time)
            if key != -1:
                cls._keys_queue.put(key)
        
        # finalize
        for winname in window_names:
            cv2.destroyWindow(winname) 
Example #5
Source File: StitchingFromVideo.py    From ImageProcessingProjects with MIT License 6 votes vote down vote up
def stitch(self, image):
        print "stitch called"
        # cv2.imshow("StitchImage", utils.image_resize(image, height = 400))
        # cv2.waitKey()
        # cv2.destroyWindow("StitchImage")
        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        rightKps, rightDescriptor = self.detectAndDescribe(gray)
        H = self.getHomography(rightKps, rightDescriptor)
        if H is None:
            return None
        leftImageShape = self.leftImage.shape
        result = cv2.warpPerspective(image, H, (leftImageShape[1] + image.shape[1], image.shape[0]))
        result[0:leftImageShape[0], 0:leftImageShape[1]] = self.leftImage

    #     Update leftImage stats
    #     print(H)
        print("Stitch done!")
        self.leftImage = result
        self.leftKps = rightKps
        self.leftDescriptor = rightDescriptor
        # cv2.imshow("StitchImage", utils.image_resize(result, height = 400))
        # cv2.waitKey()
        # cv2.destroyWindow("StitchImage")
        return 
Example #6
Source File: test_android.py    From ATX with Apache License 2.0 6 votes vote down vote up
def test_minicap():
    from atx.drivers.android_minicap import AndroidDeviceMinicap

    cv2.namedWindow("preview")
    d = AndroidDeviceMinicap()

    while True:
        try:
            h, w = d._screen.shape[:2]
            img = cv2.resize(d._screen, (w/2, h/2))
            cv2.imshow('preview', img)
            key = cv2.waitKey(1)
            if key == 100: # d for dump
                filename = time.strftime('%Y%m%d%H%M%S.png')
                cv2.imwrite(filename, d._screen)
        except KeyboardInterrupt:
            break
    cv2.destroyWindow('preview') 
Example #7
Source File: ImageStitching.py    From ImageProcessingProjects with MIT License 6 votes vote down vote up
def stitch(self, image):
        print "stitch called"
        # cv2.imshow("StitchImage", utils.image_resize(image, height = 400))
        # cv2.waitKey()
        # cv2.destroyWindow("StitchImage")
        gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
        rightKps, rightDescriptor = self.detectAndDescribe(gray)
        H = self.getHomography(rightKps, rightDescriptor)
        if H is None:
            return None
        leftImageShape = self.leftImage.shape
        result = cv2.warpPerspective(image, H, (leftImageShape[1] + image.shape[1], image.shape[0]))
        result[0:leftImageShape[0], 0:leftImageShape[1]] = self.leftImage

    #     Update leftImage stats
        print("Stitch done!")
        self.leftImage = result
        self.leftKps = rightKps
        self.leftDescriptor = rightDescriptor
        return 
Example #8
Source File: VideoCamera.py    From Finger-Detection-and-Tracking with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def main():
    window_name = "Live Video Feed"
    cv2.namedWindow(window_name)

    capture = cv2.VideoCapture(0)

    capture.set(cv2.CAP_PROP_FRAME_WIDTH, 1280)
    capture.set(cv2.CAP_PROP_FRAME_HEIGHT, 720)

    if capture.isOpened():
        flag, frame = capture.read()
    else:
        flag = False

    while flag:

        flag, frame = capture.read()

        cv2.imshow(window_name, frame)
        if cv2.waitKey(1) & 0xFF == 27:
            break

    cv2.destroyWindow(window_name)
    capture.release() 
Example #9
Source File: testHaarCascade.py    From optimeyes with MIT License 6 votes vote down vote up
def main():
    previewWindow = cv2.namedWindow(WINDOW_NAME) # open a window to show debugging images

    vc = cv2.VideoCapture(0) # Initialize the default camera
    if vc.isOpened(): # try to get the first frame
        (readSuccessful, frame) = vc.read()
    else:
        print "Could not open the system camera. Is another instance already running?"
        readSuccessful = False

    while readSuccessful:
        handleFrame(frame, allowDebugDisplay=True)
        key = cv2.waitKey(10)
        if key == 27: # exit on ESC
#            cv2.imwrite( "lastOutput.png", frame) #save the last-displayed image to file, for our report
            break
        # Get Image from camera
        readSuccessful, frame = vc.read()
    vc.release() #close the camera
    cv2.destroyWindow(WINDOW_NAME) #close the window 
Example #10
Source File: MediaPlayer.py    From Finger-Detection-and-Tracking with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def main():
    windowname = "OpenCV Media Player"
    cv2.namedWindow(windowname)

    videoFilePath = "/media/amarpandey/Media Files/Movies/Game Of Thrones/Season Seven/Game.of.Thrones.S07E03.720p.WEB.h264-TBS[eztv].mkv"

    capture = cv2.VideoCapture(videoFilePath)
    cv2.createTrackbar('FrameSpeed', windowname, 10, 600, passFunction)

    while (capture.isOpened()):

        FrameSpeed = cv2.getTrackbarPos('FrameSpeed', windowname)
        flag, frame = capture.read()

        if FrameSpeed <= 0: FrameSpeed = 1

        if flag:
            cv2.imshow(windowname, frame)
            if cv2.waitKey(FrameSpeed) & 0xFF == 27:  # because 33 * FPS == 1 second
                break
        else:
            break

    cv2.destroyWindow(windowname)
    capture.release() 
Example #11
Source File: track.py    From animal-tracking with Creative Commons Zero v1.0 Universal 5 votes vote down vote up
def drawFloorCrop(event, x, y, flags, params):
    global perspectiveMatrix, name, RENEW_TETRAGON
    imgCroppingPolygon = np.zeros_like(params['imgFloorCorners'])
    if event == cv2.EVENT_RBUTTONUP:
        cv2.destroyWindow(f'Floor Corners for {name}')
    if len(params['croppingPolygons'][name]) > 4 and event == cv2.EVENT_LBUTTONUP:
        RENEW_TETRAGON = True
        h = params['imgFloorCorners'].shape[0]
        # delete 5th extra vertex of the floor cropping tetragon
        params['croppingPolygons'][name] = np.delete(params['croppingPolygons'][name], -1, 0)
        params['croppingPolygons'][name] = params['croppingPolygons'][name] - [h,0]
        
        # Sort cropping tetragon vertices counter-clockwise starting with top left
        params['croppingPolygons'][name] = counterclockwiseSort(params['croppingPolygons'][name])
        # Get the matrix of perspective transformation
        params['croppingPolygons'][name] = np.reshape(params['croppingPolygons'][name], (4,2))
        tetragonVertices = np.float32(params['croppingPolygons'][name])
        tetragonVerticesUpd = np.float32([[0,0], [0,h], [h,h], [h,0]])
        perspectiveMatrix[name] = cv2.getPerspectiveTransform(tetragonVertices, tetragonVerticesUpd)
    if event == cv2.EVENT_LBUTTONDOWN:
        if len(params['croppingPolygons'][name]) == 4 and RENEW_TETRAGON:
            params['croppingPolygons'][name] = np.array([[0,0]])
            RENEW_TETRAGON = False
        if len(params['croppingPolygons'][name]) == 1:
            params['croppingPolygons'][name][0] = [x,y]
        params['croppingPolygons'][name] = np.append(params['croppingPolygons'][name], [[x,y]], axis=0)
    if event == cv2.EVENT_MOUSEMOVE and not (len(params['croppingPolygons'][name]) == 4 and RENEW_TETRAGON):
        params['croppingPolygons'][name][-1] = [x,y]
        if len(params['croppingPolygons'][name]) > 1:
            cv2.fillPoly(
                imgCroppingPolygon,
                [np.reshape(
                    params['croppingPolygons'][name],
                    (len(params['croppingPolygons'][name]),2)
                )],
                BGR_COLOR['green'], cv2.LINE_AA)
            imgCroppingPolygon = cv2.addWeighted(params['imgFloorCorners'], 1.0, imgCroppingPolygon, 0.5, 0.)
            cv2.imshow(f'Floor Corners for {name}', imgCroppingPolygon) 
Example #12
Source File: screen.py    From ATX with Apache License 2.0 5 votes vote down vote up
def screen_simple(host, port, serial, scale=0.5):
    adb = get_adb(host, port, serial)

    img = adb.screenshot_cv2()
    while img is None:
        time.sleep(1)
        img = adb.screenshot_cv2()

    print 'Press Ctrl-C or Esc to quit.'

    winname = 'Sync Screen'
    cv2.namedWindow(winname)
    while True:
        try:
            img = adb.screenshot_cv2()
            if scale != 1.0:
                h, w = img.shape[:2]
                h, w = int(scale*h), int(scale*w)
                img = cv2.resize(img, (w, h))
            cv2.imshow(winname, img)
            key = cv2.waitKey(10)
            if key == 27: # Escape
                break
        except KeyboardInterrupt:
            print 'Done'
            break
        except:
            traceback.print_exc()
            break

    cv2.destroyWindow(winname) 
Example #13
Source File: annotate.py    From event-Python with MIT License 5 votes vote down vote up
def review(self, TD_object):
        """Displays the TD recording overlaid with the annotated track.
        On events are red, and off events are blue.
        Takes in:
            TD_object:  An Events object (see eventvision module).
        """
        
        cv2.namedWindow('review_frame')

        for i in range(1, len(self.data.ts)):

            current_frame = np.zeros((TD_object.height,TD_object.width,3), np.uint8)
            tmin = self.data.ts[i-1]
            tmax = self.data.ts[i]
            tminind = np.min(np.where(TD_object.data.ts >= tmin))
            tmaxind = np.max(np.where(TD_object.data.ts <= tmax))

            # Populate the current frame with all the events which occur between successive timestamps of the 
            # annotated track events. Track event which was saved at the end of the current frame is shown.
            current_frame[TD_object.data.y[tminind:tmaxind][TD_object.data.p[tminind:tmaxind] == 1], TD_object.data.x[tminind:tmaxind][TD_object.data.p[tminind:tmaxind] == 1], :] = [100, 100, 255] 
            current_frame[TD_object.data.y[tminind:tmaxind][TD_object.data.p[tminind:tmaxind] == 0], TD_object.data.x[tminind:tmaxind][TD_object.data.p[tminind:tmaxind] == 0], :] = [255, 255, 30]
            cv2.circle(current_frame, (self.data.x[i], self.data.y[i]), 10, (0,255,0), 2)
            cv2.imshow('review_frame', current_frame)
            key = cv2.waitKey(1)

        cv2.destroyWindow('review_frame') 
Example #14
Source File: guiutils.py    From opencv-gui-helper-tool with MIT License 5 votes vote down vote up
def __init__(self, image, filter_size=1, threshold1=0, threshold2=0):
        self.image = image
        self._filter_size = filter_size
        self._threshold1 = threshold1
        self._threshold2 = threshold2

        def onchangeThreshold1(pos):
            self._threshold1 = pos
            self._render()

        def onchangeThreshold2(pos):
            self._threshold2 = pos
            self._render()

        def onchangeFilterSize(pos):
            self._filter_size = pos
            self._filter_size += (self._filter_size + 1) % 2
            self._render()

        cv2.namedWindow('edges')

        cv2.createTrackbar('threshold1', 'edges', self._threshold1, 255, onchangeThreshold1)
        cv2.createTrackbar('threshold2', 'edges', self._threshold2, 255, onchangeThreshold2)
        cv2.createTrackbar('filter_size', 'edges', self._filter_size, 20, onchangeFilterSize)

        self._render()

        print "Adjust the parameters as desired.  Hit any key to close."

        cv2.waitKey(0)

        cv2.destroyWindow('edges')
        cv2.destroyWindow('smoothed') 
Example #15
Source File: interact.py    From DeepFaceLab with GNU General Public License v3.0 5 votes vote down vote up
def on_destroy_window (self, wnd_name):
        cv2.destroyWindow(wnd_name) 
Example #16
Source File: __init__.py    From magicwand with MIT License 5 votes vote down vote up
def show(self):
        """Draws a window with the supplied image."""
        self._update()
        print("Press [q] or [esc] to close the window.")
        while True:
            k = cv.waitKey() & 0xFF
            if k in (ord("q"), ord("\x1b")):
                cv.destroyWindow(self.name)
                break 
Example #17
Source File: main.py    From Hand-Gesture-Recognizer with MIT License 5 votes vote down vote up
def realtime():
    #initialize preview
    cv2.namedWindow("preview")
    vc = cv2.VideoCapture(0)
    
    if vc.isOpened(): #get the first frame
        rval, frame = vc.read()
        
    else:
        rval = False
    
    classes=["peace","punch","stop","thumbs_up"]
    
    while rval:
        frame=cv2.flip(frame,1)
        cv2.rectangle(frame,(300,200),(500,400),(0,255,0),1)
        cv2.putText(frame,"Place your hand in the green box.", (50,50), cv2.FONT_HERSHEY_PLAIN , 1, 255)
        cv2.putText(frame,"Press esc to exit.", (50,100), cv2.FONT_HERSHEY_PLAIN , 1, 255)
        
        cv2.imshow("preview", frame)
        frame=frame[200:400,300:500]
        #frame = cv2.resize(frame, (200,200))
        frame = cv2.cvtColor( frame, cv2.COLOR_RGB2GRAY)
        frame=frame.reshape((1,)+frame.shape)
        frame=frame.reshape(frame.shape+(1,))
        test_datagen = ImageDataGenerator(rescale=1./255)
        m=test_datagen.flow(frame,batch_size=1)
        y_pred=model.predict_generator(m,1)
        histarray2={'PEACE': y_pred[0][0], 'PUNCH': y_pred[0][1], 'STOP': y_pred[0][2], 'Thumbs Up': y_pred[0][3]}
        update(histarray2)
        print(classes[list(y_pred[0]).index(y_pred[0].max())])
        rval, frame = vc.read()
        key = cv2.waitKey(20)
        if key == 27: # exit on ESC
            break
    cv2.destroyWindow("preview")
    vc=None
    

#loading the model 
Example #18
Source File: app_synced.py    From cvcalib with Apache License 2.0 5 votes vote down vote up
def filter_frame_manually(self):
        display_image = np.hstack([video.frame for video in self.videos])
        cv2.imshow("frame", display_image)
        key = cv2.waitKey(0) & 0xFF
        add_corners = (key == ord('a'))
        cv2.destroyWindow("frame")
        return add_corners, key 
Example #19
Source File: calibration.py    From StereoVision with GNU General Public License v3.0 5 votes vote down vote up
def _show_corners(self, image, corners):
        """Show chessboard corners found in image."""
        temp = image
        cv2.drawChessboardCorners(temp, (self.rows, self.columns), corners,
                                  True)
        window_name = "Chessboard"
        cv2.imshow(window_name, temp)
        if cv2.waitKey(0):
            cv2.destroyWindow(window_name) 
Example #20
Source File: opencv_image_viewer.py    From dm2gym with MIT License 5 votes vote down vote up
def __del__(self):
        """Close the window"""
        cv2.destroyWindow(self._window_name)
        self._isopen = False 
Example #21
Source File: design.py    From barrista with MIT License 5 votes vote down vote up
def visualize(self,
                  layout_dir='LR',
                  display=False):
        """
        Create and optionally display an image of the net structure.

        :param layout_dir: string in ['LR', 'TB', 'BT'].
          Short string for graph layout direction.

        :param display: bool.
          If set to ``True``, displays the graphic in a window. Press enter
          to close it.

        :returns: 3D numpy array.
          Graphic of the visualization as (H, W, C) image in BGR format.
        """
        if _draw is None or _cv2 is None:  # pragma: no cover
            raise Exception('Drawing is not available!')
        else:  # pragma: no cover
            with _NamedTemporaryFile(mode='w+b', suffix='.png') as tmpfile:
                _draw.draw_net_to_file(self.to_pbuf_message(),
                                       tmpfile.name,
                                       rankdir=layout_dir)
                result_image = _cv2.imread(tmpfile.name)
                assert result_image is not None
            if display:  # pragma: no cover
                _cv2.imshow(self.name, result_image)
                _cv2.waitKey(0)
                _cv2.destroyWindow(self.name)
            return result_image 
Example #22
Source File: test_monkey.py    From ATX with Apache License 2.0 5 votes vote down vote up
def test_features():
    from atx.drivers.android_minicap import AndroidDeviceMinicap
    cv2.namedWindow("preview")
    d = AndroidDeviceMinicap()

    # r, h, c, w = 200, 100, 200, 100
    # track_window = (c, r, w, h)
    # oldimg = cv2.imread('base1.png')
    # roi = oldimg[r:r+h, c:c+w]
    # hsv_roi = cv2.cvtColor(roi, cv2.COLOR_BGR2HSV)
    # mask = cv2.inRange(hsv_roi, 0, 255)
    # roi_hist = cv2.calcHist([hsv_roi], [0], mask, [180], [0,180])
    # cv2.normalize(roi_hist, roi_hist, 0, 255, cv2.NORM_MINMAX)
    # term_cirt = (cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT,  10, 1)


    while True:
        try:
            w, h = d._screen.shape[:2]
            img = cv2.resize(d._screen, (h/2, w/2))
            cv2.imshow('preview', img)

            hist = cv2.calcHist([img], [0], None, [256], [0,256])
            plt.plot(plt.hist(hist.ravel(), 256))
            plt.show()
            # if img.shape == oldimg.shape:
            #     # hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
            #     # ret, track_window = cv2.meanShift(hsv, track_window, term_cirt)
            #     # x, y, w, h = track_window
            #     cv2.rectangle(img, (x, y), (x+w, y+h), 255, 2)
            #     cv2.imshow('preview', img)
            # # cv2.imshow('preview', img)
            cv2.waitKey(1)
        except KeyboardInterrupt:
            break

    cv2.destroyWindow('preview') 
Example #23
Source File: window_manager.py    From FaceRecognition with MIT License 5 votes vote down vote up
def destroy_window(self):
        """Destroy the video window.
        """
        cv2.destroyWindow(self._windowName)
        self._isWindowCreated = False 
Example #24
Source File: util.py    From OpenCV-Video-Label with GNU General Public License v3.0 5 votes vote down vote up
def get_rect(im, title='get_rect'):
    mouse_params = {'tl': None, 'br': None, 'current_pos': None,
                    'released_once': False}

    cv2.namedWindow(title)
    cv2.moveWindow(title, 100, 100)

    def onMouse(event, x, y, flags, param):

        param['current_pos'] = (x, y)

        if param['tl'] is not None and not (flags & cv2.EVENT_FLAG_LBUTTON):
            param['released_once'] = True

        if flags & cv2.EVENT_FLAG_LBUTTON:
            if param['tl'] is None:
                param['tl'] = param['current_pos']
            elif param['released_once']:
                param['br'] = param['current_pos']

    cv2.setMouseCallback(title, onMouse, mouse_params)
    cv2.imshow(title, im)

    while mouse_params['br'] is None:
        im_draw = np.copy(im)

        if mouse_params['tl'] is not None:
            cv2.rectangle(im_draw, mouse_params['tl'],
                          mouse_params['current_pos'], (255, 0, 0))

        cv2.imshow(title, im_draw)
        _ = cv2.waitKey(10)

    cv2.destroyWindow(title)

    tl = (min(mouse_params['tl'][0], mouse_params['br'][0]),
          min(mouse_params['tl'][1], mouse_params['br'][1]))
    br = (max(mouse_params['tl'][0], mouse_params['br'][0]),
          max(mouse_params['tl'][1], mouse_params['br'][1]))

    return (tl, br) 
Example #25
Source File: mnist_calc.py    From ncappzoo with MIT License 5 votes vote down vote up
def close(self):
        """Close and destroy the window."""
        cv2.destroyWindow(self._window_name)
        self._do_ncs_cleanup() 
Example #26
Source File: vchat.py    From lan-ichat with ISC 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 #27
Source File: vchat.py    From lan-ichat with ISC License 5 votes vote down vote up
def run(self):
        print ("VEDIO client starts...")
        while True:
            try:
                self.sock.connect(self.ADDR)
                break
            except:
                time.sleep(3)
                continue
        print ("video client <-> remote server success connected...")
        check = "F"
        check = self.sock.recv(1)
        if check.decode("utf-8") != "S":
            return
        print ("receive authend")
        #self.cap = cv2.VideoCapture(0)
        self.cap = cv2.VideoCapture("test.mp4")
        if self.showme:
            cv2.namedWindow('You', cv2.WINDOW_NORMAL)
        print ("remote 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')
            if self.level > 0:
                frame = cv2.resize(frame, (0,0), fx=self.fx, fy=self.fx)
            data = pickle.dumps(frame)
            zdata = zlib.compress(data, zlib.Z_BEST_COMPRESSION)
            try:
                self.sock.sendall(struct.pack("L", len(zdata)) + zdata)
                print("video send ", len(zdata))
            except:
                break
            for i in range(self.interval):
                self.cap.read() 
Example #28
Source File: VideoCapture.py    From Finger-Detection-and-Tracking with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def main():
    framerate = 30
    resolution = (640, 480)
    window_name = "Live Video Feed"
    videoCapturePath = "../Output/Output.avi"

    cv2.namedWindow(window_name)
    capture = cv2.VideoCapture(0)

    codec = cv2.VideoWriter_fourcc('W', 'M', 'V', '2')

    videoCapture = cv2.VideoWriter(videoCapturePath, codec, framerate, resolution)

    if capture.isOpened():
        flag, frame = capture.read()
    else:
        flag = False

    while flag:

        flag, frame = capture.read()
        videoCapture.write(frame)
        cv2.imshow(window_name, frame)
        if cv2.waitKey(1) & 0xFF == 27:
            break

    cv2.destroyWindow(window_name)
    videoCapture.release()
    capture.release() 
Example #29
Source File: DrawShape.py    From Finger-Detection-and-Tracking with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def main():
    global mode

    while True:
        preseedKey = cv2.waitKey(1)
        cv2.imshow(windowName, image)

        if preseedKey & 0xFF == ord('m') or preseedKey & 0xFF == ord('M'):
            mode = not mode
        elif preseedKey & 0xFF == 27:
            break

    cv2.destroyWindow(windowName) 
Example #30
Source File: image.py    From ImageAnalysis with MIT License 5 votes vote down vote up
def show_features(self, flags=0):
        # flags=0: draw only keypoints location
        # flags=4: draw rich keypoints
        rgb = self.load_rgb(equalize=True)
        w, h = self.get_size()
        scale = 1000.0 / float(h)
        kp_list = []
        for kp in self.kp_list:
            angle = kp.angle
            class_id = kp.class_id
            octave = kp.octave
            pt = kp.pt
            response = kp.response
            size = kp.size
            x = pt[0] * scale
            y = pt[1] * scale
            kp_list.append( cv2.KeyPoint(x, y, size, angle, response,
                                         octave, class_id) )

        scaled_image = cv2.resize(rgb, (0,0), fx=scale, fy=scale)
        #res = cv2.drawKeypoints(scaled_image, kp_list, None,
        #                        color=(0,255,0), flags=flags)
        for kp in kp_list:
            cv2.circle(scaled_image, (int(kp.pt[0]), int(kp.pt[1])), 3, (0,255,0), 1, cv2.LINE_AA)
            
        cv2.imshow(self.name, scaled_image)
        print('waiting for keyboard input...')
        key = cv2.waitKey() & 0xff
        cv2.destroyWindow(self.name)
        return key