import cv2
import numpy as np
import os
import pyautogui
directory = r'H:\1403\08'
count = 0
while True:
if cv2.waitKey(1) == ord('s'):
print("Drag to select window...")
x1, y1, x2, y2 = pyautogui.locateOnScreen(None)
screenshot = pyautogui.screenshot(region=(x1, y1, x2-x1, y2-y1))
screenshot_array = np.asarray(screenshot)
cv2.imwrite(os.path.join(directory, f"screenshot{count}.png"), screenshot_array)
count += 1
my opencv version installed on windows: 4.10
when I run above code the following error: appeared:
if cv2.waitKey(1) == ord('s'):
error: OpenCV(4.10.0) D:\a\opencv-python\opencv-python\opencv\modules\highgui\src\window.cpp:1367: error: (-2:Unspecified error) The function is not implemented. Rebuild the library with Windows, GTK+ 2.x or Cocoa support. If you are on Ubuntu or Debian, install libgtk2.0-dev and pkg-config, then re-run cmake or configure script in function 'cvWaitKey'
Assistant
The error you're encountering stems from the use of cv2.waitKey() without creating an OpenCV window. The waitKey function is designed to work in conjunction with OpenCV's HighGUI module, which manages window creation and event handling for GUI operations. Without an active window, waitKey cannot function properly, leading to the error you've observed.
Additionally, there are a few other issues and improvements that can be addressed in your script:
Incorrect Use of pyautogui.locateOnScreen(None):
The locateOnScreen function requires an image to pattern-match on the screen. Passing None will not work. If your goal is to select a region interactively, you might need a different approach.
Capturing Keyboard Events:
Using OpenCV solely for capturing key presses is not ideal, especially if you're not displaying any images or windows. Libraries like keyboard or pynput are better suited for global key event handling.
Graceful Termination:
Implementing a way to exit the infinite loop gracefully can prevent the script from running indefinitely.
Here's a revised version of your script addressing these points:
Option 1: Using OpenCV with a Dummy Window
If you prefer to stick with OpenCV and use waitKey, you'll need to create a window first. Here's how you can modify your script:
python
import cv2
import numpy as np
import os
import pyautogui
directory = r'H:\1403\08'
count = 0
# Create a dummy window
cv2.namedWindow("ScreenCaptureWindow", cv2.WINDOW_NORMAL)
print("Press 's' to take a screenshot or 'q' to quit.")
while True:
# Display a black image in the window (optional)
black_image = np.zeros((100, 300, 3), dtype=np.uint8)
cv2.imshow("ScreenCaptureWindow", black_image)
key = cv2.waitKey(1) & 0xFF # Mask for compatibility
if key == ord('s'):
print("Initiating screenshot process...")
# Implement region selection here
# Example: You might predefine the region or use another method to get coordinates
# For demonstration, let's assume fixed coordinates
x1, y1, x2, y2 = 100, 200, 800, 600 # Replace with your method to get these values
width, height = x2 - x1, y2 - y1
screenshot = pyautogui.screenshot(region=(x1, y1, width, height))
screenshot_array = np.array(screenshot)
save_path = os.path.join(directory, f"screenshot{count}.png")
cv2.imwrite(save_path, cv2.cvtColor(screenshot_array, cv2.COLOR_RGB2BGR))
print(f"Screenshot saved to {save_path}")
count += 1
elif key == ord('q'):
print("Exiting...")
break
cv2.destroyAllWindows()
Key Changes:
Window Creation: A dummy window named "ScreenCaptureWindow" is created to facilitate waitKey.
Image Display: A simple black image is displayed in the window. This isn't necessary for screenshot functionality but ensures waitKey works.
Graceful Exit: Pressing 'q' will terminate the loop and close the window.
Region Selection: Replace the hardcoded coordinates with a suitable method to select the desired screen region.
Option 2: Using the keyboard Library for Key Detection
If you want to avoid using OpenCV for key detection, you can use the keyboard library, which is more suited for this purpose.
First, install the keyboard library:
bash
pip install keyboard
Revised Script:
python
import numpy as np
import os
import pyautogui
import keyboard # For global key detection
directory = r'H:\1403\08'
count = 0
print("Press 's' to take a screenshot or 'q' to quit.")
while True:
if keyboard.is_pressed('s'):
print("Initiating screenshot process...")
# Implement region selection here
# Example: Predefine the region or implement an interactive selection
# For demonstration, let's assume fixed coordinates
x1, y1, x2, y2 = 100, 200, 800, 600 # Replace with your method to get these values
width, height = x2 - x1, y2 - y1
screenshot = pyautogui.screenshot(region=(x1, y1, width, height))
screenshot_array = np.array(screenshot)
save_path = os.path.join(directory, f"screenshot{count}.png")
# Convert RGB to BGR for OpenCV compatibility if needed
cv2.imwrite(save_path, cv2.cvtColor(screenshot_array, cv2.COLOR_RGB2BGR))
print(f"Screenshot saved to {save_path}")
count += 1
# Sleep briefly to prevent multiple captures from a single press
keyboard.wait('s', suppress=True)
elif keyboard.is_pressed('q'):
print("Exiting...")
break
Key Changes:
Removed OpenCV Window: No need to create an OpenCV window since we’re not displaying any images.
Global Key Detection: Utilizes the keyboard library to detect key presses globally.
Graceful Exit: Pressing 'q' will terminate the script.
Debouncing: After capturing a screenshot, the script waits for the key to be released to prevent multiple captures from a single press.
Additional Considerations
Region Selection:
If you want users to select a region interactively, consider using libraries like tkinter to create a selection tool or use pyautogui's drag functions. Alternatively, capture the screen continuously and let the user define coordinates via UI or prompts.
Error Handling:
Implement error handling to manage scenarios where the screenshot region is out of bounds or inaccessible.
Performance:
Continuously capturing screenshots can be resource-intensive. Ensure that the region selection and saving processes are optimized.
Permissions:
Some libraries like keyboard might require elevated permissions to detect global key presses on certain operating systems. Ensure that your script has the necessary permissions to run correctly.
Summary
The primary issue was the absence of an OpenCV window when using cv2.waitKey(). By either creating a dummy window or switching to a more appropriate library for key detection like keyboard, you can resolve the error and achieve the desired functionality. Additionally, refining the region selection process and ensuring graceful termination will enhance the robustness of your script.