Python Opencv destroyAllWindows() function allows users to destroy or close all windows at any time after exiting the script. If you have multiple windows open at the same time and you want to close then you would use this function. It doesn’t take any parameters and doesn’t return anything. It is similar to destroyWindow() function but this function only destroys a specific window unlike destroyAllWindows().
Example 1: Closing window using destroyWindow() function
In the Python script given below, we have created two windows named ‘P’ and ‘Q’ respectively that displayed an image of “gfg_logo.png” using the cv2.imshow() function that is supposed to display window ‘P’ first on the screen but before calling the waitKey() function to delay the closing of windows, we will destroy only the window named ‘P’ with destroyWindow(‘P’) function by passing the window name ‘P’ as its argument. We will see that the window ‘Q’ is only displayed on the screen which will close only when the user closes it.
Python
# importing cv2 module import cv2 # read the image img = cv2.imread( "gfg_logo.png" ) # showing the images cv2.imshow( 'P' , img) cv2.imshow( 'Q' , img) # Destroying the window named P before # calling the waitKey() function cv2.destroyWindow( 'P' ) # using the wait key function to delay the # closing of windows till any key is pressed cv2.waitKey( 0 ) |
Output:
Example 2: Closing window using destroyAllWindows() function
In this case, instead of calling destroyWindow() to delete or close a particular window, we will use destroyAllWindows() to destroy all windows on the screen here we have called this function before waitKey(0), so the images will not at all displayed on the screen. DestroyAllWindows() is just a good coding practice.
Python
# importing cv2 module import cv2 # read the image img = cv2.imread( "gfg_logo.png" ) # showing the images cv2.imshow( 'P' , img) cv2.imshow( 'Q' , img) # Destroying All the windows cv2.destroyAllWindows() # using the wait key function to delay # the closing of windows till any key is pressed cv2.waitKey( 0 ) |
Output: