Skip to content

Instantly share code, notes, and snippets.

@gyillikci
Created October 30, 2024 07:41
Show Gist options
  • Save gyillikci/a6e013827e93a764c36ae58925060946 to your computer and use it in GitHub Desktop.
Save gyillikci/a6e013827e93a764c36ae58925060946 to your computer and use it in GitHub Desktop.
from onvif import ONVIFCamera
import cv2
import requests
import numpy as np
from requests.auth import HTTPDigestAuth
from fastapi import FastApi
# Replace with your camera's details
CAMERA_HOST = "10.10.44.119"
CAMERA_PORT = 80
CAMERA_USER = "admin"
CAMERA_PASS = "Cnap2006*"
def get_snapshot_uri():
mycam = ONVIFCamera(CAMERA_HOST, CAMERA_PORT, CAMERA_USER, CAMERA_PASS)
media_service = mycam.create_media_service()
profiles = media_service.GetProfiles()
token = profiles[0].token
print(profiles)
request = media_service.create_type('GetSnapshotUri')
print(request)
request.ProfileToken = token
snapshot_uri = media_service.GetSnapshotUri(request).Uri
print(snapshot_uri)
return snapshot_uri
def capture_frame(snapshot_uri):
response = requests.get(snapshot_uri, auth=HTTPDigestAuth(CAMERA_USER, CAMERA_PASS), stream=True)
if response.status_code == 200:
with open("photo.jpg", "wb") as fp:
fp.write(response.content)
img_array = np.asarray(bytearray(response.content), dtype=np.uint8)
frame = cv2.imdecode(img_array, cv2.IMREAD_COLOR)
return frame
else:
print('Failed to get snapshot')
return None
def save_frame(frame, filename='snapshot.jpg'):
cv2.imwrite(filename, frame)
def main():
snapshot_uri = get_snapshot_uri()
if snapshot_uri:
frame = capture_frame(snapshot_uri)
if frame is not None:
save_frame(frame)
print('Snapshot saved as snapshot.jpg')
else:
print('Failed to capture frame')
else:
print('Failed to get snapshot URI')
if __name__ == "__main__":
#main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment