shot.py 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import cv2
  2. def take_screenshot(cam, width=640, height=480):
  3. """
  4. Takes a screenshot of the primary display and returns it as a numpy array.
  5. """
  6. # Capture the screenshot using OpenCV
  7. print()
  8. "http://172.31.192.151/tmpfs/snap.jpg?usr=admin&pwd=admin"
  9. import requests
  10. import os
  11. import time
  12. # 请将此处的IP地址替换为您的ESP32在串口监视器中打印的实际IP地址
  13. # 例如: esp32_ip = "192.168.1.100"
  14. esp32_ip = "172.31.192.104" # <-- 替换为您的ESP32的IP地址
  15. # 图片保存路径和文件名
  16. output_directory = "captured_images"
  17. output_filename = "esp32_camera_image.jpg"
  18. output_filepath = os.path.join(output_directory, output_filename)
  19. def fetch_image_from_esp32(ip_address, save_path):
  20. """
  21. 从ESP32摄像头服务器获取图片并保存到指定路径。
  22. Args:
  23. ip_address (str): ESP32摄像头服务器的IP地址。
  24. save_path (str): 图片的保存路径,包括文件名。
  25. """
  26. url = f"http://{ip_address}/stream" # ESP32摄像头服务器通常在根路径提供图片
  27. print(f"尝试从 {url} 获取图片...")
  28. try:
  29. # 发送GET请求,设置超时时间
  30. response = requests.get(url, timeout=10)
  31. # 检查响应状态码
  32. if response.status_code == 200:
  33. # 确保保存目录存在
  34. os.makedirs(os.path.dirname(save_path), exist_ok=True)
  35. # 将图片内容写入文件
  36. with open(save_path, 'wb') as f:
  37. f.write(response.content)
  38. print(f"图片成功保存到: {save_path}")
  39. else:
  40. print(f"从 {url} 获取图片失败。状态码: {response.status_code}")
  41. print(f"响应内容: {response.text[:200]}...") # 打印部分响应内容以便调试
  42. except requests.exceptions.ConnectionError as e:
  43. print(f"连接错误: 无法连接到ESP32 ({ip_address})。请确保ESP32已连接到WiFi并运行摄像头服务器。错误: {e}")
  44. except requests.exceptions.Timeout as e:
  45. print(f"请求超时: 从ESP32 ({ip_address}) 获取图片超时。错误: {e}")
  46. except requests.exceptions.RequestException as e:
  47. print(f"请求发生未知错误: {e}")
  48. except Exception as e:
  49. print(f"发生意外错误: {e}")
  50. if __name__ == "__main__":
  51. if esp32_ip == "YOUR_ESP32_IP_ADDRESS":
  52. print("警告: 请将 'esp32_ip' 变量替换为您的ESP32的实际IP地址。")
  53. print("您可以在ESP32的串口监视器中找到这个IP地址,它通常在 'Camera Ready! Use http://...' 这一行显示。")
  54. else:
  55. fetch_image_from_esp32(esp32_ip, output_filepath)