Python cv2.destroyAllWindows() Examples

The following are 30 code examples for showing how to use cv2.destroyAllWindows(). 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: Traffic_sign_detection_YOLO   Author: AmeyaWagh   File: misc.py    License: MIT License 7 votes vote down vote up
def show(im, allobj, S, w, h, cellx, celly):
    for obj in allobj:
        a = obj[5] % S
        b = obj[5] // S
        cx = a + obj[1]
        cy = b + obj[2]
        centerx = cx * cellx
        centery = cy * celly
        ww = obj[3]**2 * w
        hh = obj[4]**2 * h
        cv2.rectangle(im,
            (int(centerx - ww/2), int(centery - hh/2)),
            (int(centerx + ww/2), int(centery + hh/2)),
            (0,0,255), 2)
    cv2.imshow('result', im)
    cv2.waitKey()
    cv2.destroyAllWindows() 
Example 2
Project: OpenCV-Computer-Vision-Projects-with-Python   Author: PacktPublishing   File: chapter2.py    License: MIT License 7 votes vote down vote up
def main():
    device = cv2.CAP_OPENNI
    capture = cv2.VideoCapture(device)
    if not(capture.isOpened()):
        capture.open(device)

    capture.set(cv2.CAP_PROP_FRAME_WIDTH, 640)
    capture.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)

    app = wx.App()
    frame = MyFrame(None, -1, 'chapter2.py', capture)
    frame.Show(True)
#   self.SetTopWindow(frame)
    app.MainLoop()

    # When everything done, release the capture
    capture.release()
    cv2.destroyAllWindows() 
Example 3
def show(im, allobj, S, w, h, cellx, celly):
    for obj in allobj:
        a = obj[5] % S
        b = obj[5] // S
        cx = a + obj[1]
        cy = b + obj[2]
        centerx = cx * cellx
        centery = cy * celly
        ww = obj[3]**2 * w
        hh = obj[4]**2 * h
        cv2.rectangle(im,
            (int(centerx - ww/2), int(centery - hh/2)),
            (int(centerx + ww/2), int(centery + hh/2)),
            (0,0,255), 2)
    cv2.imshow('result', im)
    cv2.waitKey()
    cv2.destroyAllWindows() 
Example 4
def show2(im, allobj):
    for obj in allobj:
        cv2.rectangle(im,
            (obj[1], obj[2]), 
            (obj[3], obj[4]), 
            (0,0,255),2)
    cv2.imshow('result', im)
    cv2.waitKey()
    cv2.destroyAllWindows() 
Example 5
Project: Traffic-Signs-and-Object-Detection   Author: dark-archerx   File: misc.py    License: GNU General Public License v3.0 7 votes vote down vote up
def show(im, allobj, S, w, h, cellx, celly):
    for obj in allobj:
        a = obj[5] % S
        b = obj[5] // S
        cx = a + obj[1]
        cy = b + obj[2]
        centerx = cx * cellx
        centery = cy * celly
        ww = obj[3]**2 * w
        hh = obj[4]**2 * h
        cv2.rectangle(im,
            (int(centerx - ww/2), int(centery - hh/2)),
            (int(centerx + ww/2), int(centery + hh/2)),
            (0,0,255), 2)
    cv2.imshow('result', im)
    cv2.waitKey()
    cv2.destroyAllWindows() 
Example 6
Project: FunUtils   Author: HoussemCharf   File: facesearch.py    License: MIT License 7 votes vote down vote up
def handle_click(event, x, y, flags, params):
    """
    Records clicks on the image and lets the user choose one of the detected
    faces by simply pointing and clicking.

    params:
    (As needed by setMouseCallback)
    event: The event that occured
    x, y: Integers. Coordinates of the event
    flags: Any flags reported by setMouseCallback
    params: Any params returned by setMouseCallback
    """
    # Capture when the LClick is released
    if event == cv2.EVENT_LBUTTONUP and y > a // 2:  # Ignore clicks on padding
        response = x // (faces_copy.shape[1] // len(faces))
        cv2.destroyAllWindows()
        cv2.imwrite('_search_.png', faces[response])
        try:
            Search()
        except KeyboardInterrupt:  # Delete the generated image if user stops
            print("\nTerminated execution. Cleaning up...")  # the execution.
            os.remove('_search_.png')
        sys.exit()


# The path to the face detection Haar cascade. Specified in the install.sh file 
Example 7
Project: crop_row_detection   Author: petern3   File: camera_test.py    License: GNU General Public License v3.0 7 votes vote down vote up
def main():
	capture = cv2.VideoCapture(0)
	_, image = capture.read()
	previous = image.copy()
	
	
	while (cv2.waitKey(1) < 0):
		_, image = capture.read()
		diff = cv2.absdiff(image, previous)
		#image = cv2.flip(image, 3)
		#image = cv2.norm(image)
		_, diff = cv2.threshold(diff, 32, 0, cv2.THRESH_TOZERO)
		_, diff = cv2.threshold(diff, 0, 255, cv2.THRESH_BINARY)
		
		diff = cv2.medianBlur(diff, 5)
		
		cv2.imshow('video', diff)
		previous = image.copy()
		
	capture.release()
	cv2.destroyAllWindows() 
Example 8
Project: Traffic_sign_detection_YOLO   Author: AmeyaWagh   File: objectDetectorYOLO.py    License: MIT License 6 votes vote down vote up
def processFrames(self):
        try:
            for img in self.anotations_list:
                img = img.split(';')
                # print(img)
                # ret,imgcv = cap.read()
                if self.video:
                    ret,imgcv = self.cap.read()
                else:
                    imgcv = cv2.imread(os.path.join('../',self.config["dataset"],img[0]))
                result = self.tfnet.return_predict(imgcv)
                print(result)
                imgcv = self.drawBoundingBox(imgcv,result)        
                cv2.imshow('detected objects',imgcv)
                if cv2.waitKey(10) == ord('q'):
                    print('exitting loop')
                    break
        except KeyboardInterrupt:
            cv2.destroyAllWindows()
            print('exitting program') 
Example 9
Project: Traffic_sign_detection_YOLO   Author: AmeyaWagh   File: misc.py    License: MIT License 6 votes vote down vote up
def show2(im, allobj):
    for obj in allobj:
        cv2.rectangle(im,
            (obj[1], obj[2]), 
            (obj[3], obj[4]), 
            (0,0,255),2)
    cv2.imshow('result', im)
    cv2.waitKey()
    cv2.destroyAllWindows() 
Example 10
Project: pruning_yolov3   Author: zbyuan   File: datasets.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __next__(self):
        self.count += 1
        img0 = self.imgs.copy()
        if cv2.waitKey(1) == ord('q'):  # q to quit
            cv2.destroyAllWindows()
            raise StopIteration

        # Letterbox
        img = [letterbox(x, new_shape=self.img_size, interp=cv2.INTER_LINEAR)[0] for x in img0]

        # Stack
        img = np.stack(img, 0)

        # Normalize RGB
        img = img[:, :, :, ::-1].transpose(0, 3, 1, 2)  # BGR to RGB
        img = np.ascontiguousarray(img, dtype=np.float16 if self.half else np.float32)  # uint8 to fp16/fp32
        img /= 255.0  # 0 - 255 to 0.0 - 1.0

        return self.sources, img, img0, None 
Example 11
Project: derplearning   Author: notkarol   File: calibrate_camera.py    License: MIT License 6 votes vote down vote up
def main():
    """
    Calibrate the live camera and optionally do a live display of the results
    """
    parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
    parser.add_argument("config", type=Path, help="camera config path")
    parser.add_argument("--height", type=int, default=4)
    parser.add_argument("--width", type=int, default=10)
    parser.add_argument("--count", type=int, default=10)
    parser.add_argument("--view", action="store_true")
    args = parser.parse_args()

    config = {"camera": derp.util.load_config(args.config)}
    camera = Camera(config)
    pattern_shape = (args.height, args.width)

    camera_matrix, distortion_coefficients = live_calibrate(camera, pattern_shape, args.count)
    print(camera_matrix)
    print(distortion_coefficients)
    if args.view:
        live_undistort(camera, camera_matrix, distortion_coefficients)
    cv2.destroyAllWindows() 
Example 12
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 13
Project: BiblioPixel   Author: ManiacalLabs   File: mp4.py    License: MIT License 6 votes vote down vote up
def write(self, filename, frames, fps, show=False):
        fps = max(1, fps)
        out = None

        try:
            for image in frames:
                frame = cv2.imread(image)
                if show:
                    cv2.imshow('video', frame)

                if not out:
                    height, width, channels = frame.shape
                    fourcc = cv2.VideoWriter_fourcc(*'mp4v')
                    out = cv2.VideoWriter(filename, fourcc, 20, (width, height))

                out.write(frame)

        finally:
            out and out.release()
            cv2.destroyAllWindows() 
Example 14
Project: video-capture-async   Author: gilbertfrancois   File: videocapturethreading.py    License: Apache License 2.0 6 votes vote down vote up
def _run(self, n_frames=500, width=1280, height=720, with_threading=False):
        if with_threading:
            cap = VideoCaptureTreading(0)
        else:
            cap = cv2.VideoCapture(0)
        cap.set(cv2.CAP_PROP_FRAME_WIDTH, width)
        cap.set(cv2.CAP_PROP_FRAME_HEIGHT, height)
        if with_threading:
            cap.start()
        t0 = time.time()
        i = 0
        while i < n_frames:
            _, frame = cap.read()
            cv2.imshow('Frame', frame)
            cv2.waitKey(1) & 0xFF
            i += 1
        print('[i] Frames per second: {:.2f}, with_threading={}'.format(n_frames / (time.time() - t0), with_threading))
        if with_threading:
            cap.stop()
        cv2.destroyAllWindows() 
Example 15
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 16
Project: OpenCV-Python-Tutorial   Author: makelove   File: watershed.py    License: MIT License 6 votes vote down vote up
def run(self):
        while cv2.getWindowProperty('img', 0) != -1 or cv2.getWindowProperty('watershed', 0) != -1:
            ch = cv2.waitKey(50)
            if ch == 27:
                break
            if ch >= ord('1') and ch <= ord('7'):
                self.cur_marker = ch - ord('0')
                print('marker: ', self.cur_marker)
            if ch == ord(' ') or (self.sketch.dirty and self.auto_update):
                self.watershed()
                self.sketch.dirty = False
            if ch in [ord('a'), ord('A')]:
                self.auto_update = not self.auto_update
                print('auto_update if', ['off', 'on'][self.auto_update])
            if ch in [ord('r'), ord('R')]:
                self.markers[:] = 0
                self.markers_vis[:] = self.img
                self.sketch.show()
        cv2.destroyAllWindows() 
Example 17
Project: The-chat-room   Author: 11ze   File: vachat.py    License: MIT License 5 votes vote down vote up
def __del__(self):
        global TERMINATE
        TERMINATE = True
        self.sock.close()
        try:
            cv2.destroyAllWindows()
        except:
            pass 
Example 18
Project: The-chat-room   Author: 11ze   File: vachat.py    License: MIT License 5 votes vote down vote up
def __del__(self) :
        self.sock.close()
        self.cap.release()
        if self.showme:
            try:
                cv2.destroyAllWindows()
            except:
                pass 
Example 19
Project: pruning_yolov3   Author: zbyuan   File: datasets.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __next__(self):
        self.count += 1
        if cv2.waitKey(1) == ord('q'):  # q to quit
            self.cap.release()
            cv2.destroyAllWindows()
            raise StopIteration

        # Read frame
        if self.pipe == 0:  # local camera
            ret_val, img0 = self.cap.read()
            img0 = cv2.flip(img0, 1)  # flip left-right
        else:  # IP camera
            n = 0
            while True:
                n += 1
                self.cap.grab()
                if n % 30 == 0:  # skip frames
                    ret_val, img0 = self.cap.retrieve()
                    if ret_val:
                        break

        # Print
        assert ret_val, 'Camera Error %s' % self.pipe
        img_path = 'webcam.jpg'
        print('webcam %g: ' % self.count, end='')

        # Padded resize
        img = letterbox(img0, new_shape=self.img_size)[0]

        # Normalize RGB
        img = img[:, :, ::-1].transpose(2, 0, 1)  # BGR to RGB
        img = np.ascontiguousarray(img, dtype=np.float16 if self.half else np.float32)  # uint8 to fp16/fp32
        img /= 255.0  # 0 - 255 to 0.0 - 1.0

        return img_path, img, img0, None 
Example 20
def test_recognition(c1, c2):
    extracted_face1 = extract_face_features(gray1, face1[0], (c1, c2))
    print(predict_face_is_smiling(extracted_face1))
    extracted_face2 = extract_face_features(gray2, face2[0], (c1, c2))
    print(predict_face_is_smiling(extracted_face2))
    cv2.imshow('gray1', extracted_face1)
    cv2.imshow('gray2', extracted_face2)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

# test_recognition(0.3, 0.05)

# ------------------- LIVE FACE RECOGNITION ----------------------------------- 
Example 21
Project: derplearning   Author: notkarol   File: label.py    License: MIT License 5 votes vote down vote up
def __del__(self):
        """Deconstructor to close window"""
        cv2.destroyAllWindows() 
Example 22
Project: pluralsight   Author: jamesbannan   File: CameraCapture.py    License: MIT License 5 votes vote down vote up
def __exit__(self, exception_type, exception_value, traceback):
        if not self.isWebcam:
            self.capture.release()
        if self.showVideo:
            self.imageServer.close()
            cv2.destroyAllWindows() 
Example 23
Project: 3D-HourGlass-Network   Author: Naman-ntc   File: functions.py    License: MIT License 5 votes vote down vote up
def playVideoFromAVI(s):
    cap = cv2.VideoCapture(s)
 
    # Check if camera opened successfully
    if (cap.isOpened()== False): 
      print("Error opening video stream or file")
     
    # Read until video is completed
    while(cap.isOpened()):
      # Capture frame-by-frame
      ret, frame = cap.read()
      if ret == True:
     
        # Display the resulting frame
        cv2.imshow('Frame',frame)
     
        # Press Q on keyboard to  exit
        if cv2.waitKey(1) & 0xFF == ord('q'):
          break
     
      # Break the loop
      else: 
        break
     
    # When everything done, release the video capture object
    cap.release()
     
    # Closes all the frames
    cv2.destroyAllWindows() 
Example 24
Project: 3D-HourGlass-Network   Author: Naman-ntc   File: functions.py    License: MIT License 5 votes vote down vote up
def playVideoFromArray(s):
       # Capture frame-by-frame
    for frame in s:
        cv2.imshow('Frame',frame)
     
        # Press Q on keyboard to  exit
        if cv2.waitKey(20) & 0xFF == ord('q'):
          break
     
    # Closes all the frames
    cv2.destroyAllWindows() 
Example 25
Project: 3D-HourGlass-Network   Author: Naman-ntc   File: functions.py    License: MIT License 5 votes vote down vote up
def playVideoFromAVI(s):
    cap = cv2.VideoCapture(s)
 
    # Check if camera opened successfully
    if (cap.isOpened()== False): 
      print("Error opening video stream or file")
     
    # Read until video is completed
    while(cap.isOpened()):
      # Capture frame-by-frame
      ret, frame = cap.read()
      if ret == True:
     
        # Display the resulting frame
        cv2.imshow('Frame',frame)
     
        # Press Q on keyboard to  exit
        if cv2.waitKey(1) & 0xFF == ord('q'):
          break
     
      # Break the loop
      else: 
        break
     
    # When everything done, release the video capture object
    cap.release()
     
    # Closes all the frames
    cv2.destroyAllWindows() 
Example 26
Project: 3D-HourGlass-Network   Author: Naman-ntc   File: functions.py    License: MIT License 5 votes vote down vote up
def playVideoFromArray(s):
       # Capture frame-by-frame
    for frame in s:
        cv2.imshow('Frame',frame)
     
        # Press Q on keyboard to  exit
        if cv2.waitKey(20) & 0xFF == ord('q'):
          break
     
    # Closes all the frames
    cv2.destroyAllWindows() 
Example 27
Project: Traffic-Signs-and-Object-Detection   Author: dark-archerx   File: guir.py    License: GNU General Public License v3.0 5 votes vote down vote up
def close():
    pygame.quit()
    sys.exit()
    videoFeed.release()
    cv2.destroyAllWindows() 
Example 28
Project: Traffic-Signs-and-Object-Detection   Author: dark-archerx   File: main.py    License: GNU General Public License v3.0 5 votes vote down vote up
def close():
    pygame.quit()
    sys.exit()
    videoFeed.release()
    cv2.destroyAllWindows() 
Example 29
Project: Traffic-Signs-and-Object-Detection   Author: dark-archerx   File: guilat.py    License: GNU General Public License v3.0 5 votes vote down vote up
def close():
    pygame.quit()
    sys.exit()
    videoFeed.release()
    cv2.destroyAllWindows() 
Example 30
Project: Traffic-Signs-and-Object-Detection   Author: dark-archerx   File: misc.py    License: GNU General Public License v3.0 5 votes vote down vote up
def show2(im, allobj):
    for obj in allobj:
        cv2.rectangle(im,
            (obj[1], obj[2]), 
            (obj[3], obj[4]), 
            (0,0,255),2)
    cv2.imshow('result', im)
    cv2.waitKey()
    cv2.destroyAllWindows()