Python cv2.destroyAllWindows() Examples
The following are 30
code examples of cv2.destroyAllWindows().
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: tkinter_functions.py From simba with GNU Lesser General Public License v3.0 | 8 votes |
def clahe(filename): os.chdir(os.path.dirname(filename)) print('Applying CLAHE, this might take awhile...') currentVideo = os.path.basename(filename) fileName, fileEnding = currentVideo.split('.',2) saveName = str('CLAHE_') + str(fileName) + str('.avi') cap = cv2.VideoCapture(currentVideo) imageWidth = int(cap.get(3)) imageHeight = int(cap.get(4)) fps = cap.get(cv2.CAP_PROP_FPS) fourcc = cv2.VideoWriter_fourcc(*'XVID') out = cv2.VideoWriter(saveName, fourcc, fps, (imageWidth, imageHeight), 0) try: while True: ret, image = cap.read() if ret == True: im = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) claheFilter = cv2.createCLAHE(clipLimit=2, tileGridSize=(16, 16)) claheCorrecttedFrame = claheFilter.apply(im) out.write(claheCorrecttedFrame) if cv2.waitKey(10) & 0xFF == ord('q'): break else: print(str('Completed video ') + str(saveName)) break except: print('clahe not applied') cap.release() out.release() cv2.destroyAllWindows() return saveName
Example #2
Source File: camera_test.py From crop_row_detection with GNU General Public License v3.0 | 7 votes |
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 #3
Source File: misc.py From Traffic-Signs-and-Object-Detection with GNU General Public License v3.0 | 7 votes |
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
Source File: facesearch.py From FunUtils with MIT License | 7 votes |
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 #5
Source File: misc.py From Automatic-Identification-and-Counting-of-Blood-Cells with GNU General Public License v3.0 | 7 votes |
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 #6
Source File: misc.py From Automatic-Identification-and-Counting-of-Blood-Cells with GNU General Public License v3.0 | 7 votes |
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 #7
Source File: chapter2.py From OpenCV-Computer-Vision-Projects-with-Python with MIT License | 7 votes |
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 #8
Source File: misc.py From Traffic_sign_detection_YOLO with MIT License | 7 votes |
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 #9
Source File: objectDetectorYOLO.py From Traffic_sign_detection_YOLO with MIT License | 6 votes |
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 #10
Source File: RtspClient.py From ReolinkCameraAPI with GNU General Public License v3.0 | 6 votes |
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 #11
Source File: videocapturethreading.py From video-capture-async with Apache License 2.0 | 6 votes |
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 #12
Source File: captures.py From holodeck with MIT License | 6 votes |
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
Source File: calibrate_camera.py From derplearning with MIT License | 6 votes |
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 #14
Source File: misc.py From Traffic_sign_detection_YOLO with MIT License | 6 votes |
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 #15
Source File: watershed.py From OpenCV-Python-Tutorial with MIT License | 6 votes |
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 #16
Source File: datasets.py From pruning_yolov3 with GNU General Public License v3.0 | 6 votes |
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 #17
Source File: cv_detection_right_hand.py From AI-Robot-Challenge-Lab with MIT License | 5 votes |
def test_right_hand_debug(): """ Test the cube orientation sensing using images on disk """ # Get files path = rospkg.RosPack().get_path('sorting_demo') + "/share/test_right_hand_simulator" files = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))] #files = ["border.png"] #print(files) # Process files for f in files: # Get image path image_path = os.path.join(path, f) print(image_path) # Read image cv_image = cv2.imread(image_path) # Get cube rotation angles = get_cubes_z_rotation(cv_image) print(angles) # Wait for a key press cv2.waitKey(0) # Exit cv2.destroyAllWindows()
Example #18
Source File: cv_detection_right_hand.py From AI-Robot-Challenge-Lab with MIT License | 5 votes |
def test_right_hand_cam(): """ Test the blob detection using a USB camera """ # Create a video capture object capture = cv2.VideoCapture(1) capture.set(cv2.CAP_PROP_FRAME_WIDTH, 1280) capture.set(cv2.CAP_PROP_FRAME_HEIGHT, 720) while True: # Capture a frame ret, cv_image = capture.read() if ret: # Save for debugging #cv2.imwrite("/tmp/debug.png", cv_image) # Get cube rotation angles = get_cubes_z_rotation(cv_image) print(angles) # Check for a press on the Escape key if cv2.waitKey(1) & 0xFF == 27: break # Exit capture.release() cv2.destroyAllWindows()
Example #19
Source File: lk_homography.py From OpenCV-Python-Tutorial with MIT License | 5 votes |
def main(): import sys try: video_src = sys.argv[1] except: video_src = 0 print(__doc__) App(video_src).run() cv2.destroyAllWindows()
Example #20
Source File: mazeexplorer.py From MazeExplorer with MIT License | 5 votes |
def generate_video(images_path, movie_path): """ Generates a video of the agent from the images saved using record_path Example: ```python images_path = "path/to/save_images_dir" movie_path = "path/to/movie.ai" env = MazeNavigator(record_path=images_path) env.reset() for _ in range(100): env.step_record(env.action_space.sample(), record_path=images_path) MazeNavigator.generate_video(images_path, movie_path) ``` :param images_path: path of the folder containg the generated images :param movie_path: file path ending with .avi to where the movie should be outputted to. """ if not movie_path.endswith(".avi"): raise ValueError("movie_path must end with .avi") images = sorted([img for img in os.listdir(images_path) if img.endswith(".png")]) if not len(images): raise FileNotFoundError("Not png images found within the images path") frame = cv2.imread(os.path.join(images_path, images[0])) height, width, _ = frame.shape video = cv2.VideoWriter(movie_path, 0, 30, (width, height)) for image in images: video.write(cv2.imread(os.path.join(images_path, image))) cv2.destroyAllWindows() video.release()
Example #21
Source File: camera_demo.py From R2CNN_Faster-RCNN_Tensorflow with MIT License | 5 votes |
def testCamera(): cap = cv2.VideoCapture(0) while(1): # get a frame ret, frame = cap.read() # show a frame cv2.imshow("capture", frame) if cv2.waitKey(1) & 0xFF == ord('q'): break cap.release() cv2.destroyAllWindows()
Example #22
Source File: cv_detection_head.py From AI-Robot-Challenge-Lab with MIT License | 5 votes |
def test_head_debug(): """ Test the blob detection using images on disk """ # Get files path = rospkg.RosPack().get_path('sorting_demo') + "/share/test_head_simulator" files = [f for f in os.listdir(path) if os.path.isfile(os.path.join(path, f))] #print(files) # Process files for f in files: # Get image path image_path = os.path.join(path, f) print(image_path) # Read image cv_image = cv2.imread(image_path) # Get color blobs info blob_info = get_blobs_info(cv_image) print(blob_info) # Wait for a key press cv2.waitKey(0) # Exit cv2.destroyAllWindows()
Example #23
Source File: CameraCapture.py From Custom-vision-service-iot-edge-raspberry-pi with MIT License | 5 votes |
def __exit__(self, exception_type, exception_value, traceback): if not self.isWebcam: self.capture.release() if self.showVideo: self.imageServer.close() cv2.destroyAllWindows()
Example #24
Source File: example.py From crappy with GNU General Public License v2.0 | 5 votes |
def stop(): ximea.release() cv2.destroyAllWindows() cv2.destroyWindow("Displayer")
Example #25
Source File: mp4.py From BiblioPixel with MIT License | 5 votes |
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 #26
Source File: process_videos_automation.py From simba with GNU Lesser General Public License v3.0 | 5 votes |
def clahe_queue(files): filesFound= [files] os.chdir(os.path.dirname(files)) print('Applying CLAHE, this might take awhile...') for i in filesFound: currentVideo = os.path.basename(i) saveName = str('CLAHE_') + str(currentVideo[:-4]) + str('.avi') cap = cv2.VideoCapture(currentVideo) imageWidth = int(cap.get(3)) imageHeight = int(cap.get(4)) fps = cap.get(cv2.CAP_PROP_FPS) fourcc = cv2.VideoWriter_fourcc(*'XVID') out = cv2.VideoWriter(saveName, fourcc, fps, (imageWidth, imageHeight), 0) while True: ret, image = cap.read() if ret == True: im = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) claheFilter = cv2.createCLAHE(clipLimit=2, tileGridSize=(16, 16)) claheCorrecttedFrame = claheFilter.apply(im) out.write(claheCorrecttedFrame) if cv2.waitKey(10) & 0xFF == ord('q'): break else: print(str('Completed video ') + str(saveName)) break cap.release() out.release() cv2.destroyAllWindows() return saveName
Example #27
Source File: process_videos_automation.py From simba with GNU Lesser General Public License v3.0 | 5 votes |
def clahe_batch(directory): filesFound= [] ########### FIND FILES ########### for i in os.listdir(directory): filesFound.append(i) os.chdir(directory) print('Applying CLAHE, this might take awhile...') for i in filesFound: currentVideo = i saveName = str('CLAHE_') + str(currentVideo[:-4]) + str('.avi') cap = cv2.VideoCapture(currentVideo) imageWidth = int(cap.get(3)) imageHeight = int(cap.get(4)) fps = cap.get(cv2.CAP_PROP_FPS) fourcc = cv2.VideoWriter_fourcc(*'XVID') out = cv2.VideoWriter(saveName, fourcc, fps, (imageWidth, imageHeight), 0) while True: ret, image = cap.read() if ret == True: im = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) claheFilter = cv2.createCLAHE(clipLimit=2, tileGridSize=(16, 16)) claheCorrecttedFrame = claheFilter.apply(im) out.write(claheCorrecttedFrame) if cv2.waitKey(10) & 0xFF == ord('q'): break else: print(str('Completed video ') + str(saveName)) break cap.release() out.release() cv2.destroyAllWindows() return saveName
Example #28
Source File: process_videos_automation.py From simba with GNU Lesser General Public License v3.0 | 5 votes |
def clahe_auto(directory): filesFound= [] ########### FIND FILES ########### for i in os.listdir(directory): if i.__contains__(".mp4"): filesFound.append(i) os.chdir(directory) print('Applying CLAHE, this might take awhile...') for i in filesFound: currentVideo = i saveName = str('CLAHE_') + str(currentVideo[:-4]) + str('.avi') cap = cv2.VideoCapture(currentVideo) imageWidth = int(cap.get(3)) imageHeight = int(cap.get(4)) fps = cap.get(cv2.CAP_PROP_FPS) fourcc = cv2.VideoWriter_fourcc(*'XVID') out = cv2.VideoWriter(saveName, fourcc, fps, (imageWidth, imageHeight), 0) while True: ret, image = cap.read() if ret == True: im = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) claheFilter = cv2.createCLAHE(clipLimit=2, tileGridSize=(16, 16)) claheCorrecttedFrame = claheFilter.apply(im) out.write(claheCorrecttedFrame) if cv2.waitKey(10) & 0xFF == ord('q'): break else: print(str('Completed video ') + str(saveName)) break cap.release() out.release() cv2.destroyAllWindows() return saveName
Example #29
Source File: tkinter_functions.py From simba with GNU Lesser General Public License v3.0 | 5 votes |
def youOnlyCropOnce(inputdir,outputdir): filesFound=[] ########### FIND FILES ########### for i in os.listdir(inputdir): if i.endswith(('.avi', '.mp4', '.mov', 'flv')): filesFound.append(os.path.join(inputdir,i)) filenames=filesFound[0] #extract one frame currentDir = str(os.path.dirname(filenames)) videoName = str(os.path.basename(filenames)) os.chdir(currentDir) cap = cv2.VideoCapture(videoName) cap.set(1, 0) ret, frame = cap.read() fileName = str(0) + str('.bmp') filePath = os.path.join(currentDir, fileName) cv2.imwrite(filePath, frame) #find ROI img = cv2.imread(filePath) cv2.namedWindow('Select ROI', cv2.WINDOW_NORMAL) ROI = cv2.selectROI("Select ROI", img) width = abs(ROI[0] - (ROI[2] + ROI[0])) height = abs(ROI[2] - (ROI[3] + ROI[2])) topLeftX = ROI[0] topLeftY = ROI[1] cv2.waitKey(0) cv2.destroyAllWindows() for i in filesFound: #crop video with ffmpeg fileOut, fileType = i.split(".", 2) fileOutName = outputdir + '\\'+ os.path.basename(str(fileOut)) + str('_cropped.')+ str(fileType) command = str('ffmpeg -i ') +'"'+ str(i) +'"'+ str(' -vf ') + str('"crop=') + str(width) + ':' + str( height) + ':' + str(topLeftX) + ':' + str(topLeftY) + '" ' + str('-c:v libx264 -crf 21 -c:a copy ') +'"'+ str( fileOutName)+'"' total = width + height + topLeftX + topLeftY file = pathlib.Path(fileOutName) if file.exists(): print(os.path.basename(fileOutName), 'already exist') else: if width==0 and height ==0: print('Video not cropped') elif total != 0: print('Cropping video...') print(command) subprocess.call(command, shell=True) elif total ==0: print('Video not cropped') os.remove(filePath) print('Process completed.')
Example #30
Source File: face_recognizer.py From ros_people_object_detection_tensorflow with Apache License 2.0 | 5 votes |
def initialize_database(self): """ Reads the PNG images from ./people folder and creates a list of peoples The names of the image files are considered as their real names. For example; /people - mario.png - jennifer.png - melanie.png Returns: (tuple) (people_list, name_list) (features of people, names of people) """ filenames = glob.glob(cd + '/people/*.png') people_list = [] name_list = [] for f in filenames: im = cv2.imread(f, 1) #cv2.imshow("Database Image", im) #cv2.waitKey(500) im = im.astype(np.uint8) people_list.append(fr.face_encodings(im)[0]) name_list.append(f.split('/')[-1].split('.')[0]) #cv2.destroyAllWindows() return (people_list, name_list)