nerdegutta.no
Python: Take a picture every minute and upload it
06.08.24
Programming
This little Python program takes a picture every minute, and uploads it to a webserver. Be sure to have a working web-server, with the proper rights. On the server you'll need this PHP program: PHP: upload a image from a Python program In order to get this program to work, you need to install OpenCV, like this:
pip install opencv-pythonOr like this:
pip3 install opencv-pythonOr if you don't use Pip:
sudo apt-get install python3-opencv
import cv2
import requests
import time
def capture_photo(filename):
# Initialize the webcam
cap = cv2.VideoCapture(0)
if not cap.isOpened():
print("Error: Could not open webcam.")
return False
# Capture a single frame
ret, frame = cap.read()
if not ret:
print("Error: Could not read frame.")
return False
# Save the captured frame to a file
cv2.imwrite(filename, frame)
# Release the webcam
cap.release()
return True
def upload_photo(filename, url):
with open(filename, 'rb') as file:
# Send the file in a POST request
files = {'file': (filename, file, 'image/jpeg')}
response = requests.post(url, files=files)
# Check the response from the server
if response.status_code == 200:
print("Upload successful!")
else:
print(f"Upload failed with status code: {response.status_code}")
def main():
filename = 'captured_photo.jpg'
url = 'http://yourwebserver.something/upload.php' # Replace with your server URL
while True:
# Capture the photo
if capture_photo(filename):
# Upload the photo
upload_photo(filename, url)
time.sleep(60)
if __name__ == "__main__":
main()