python中如何获取视频流并上传OSS

目标是获取摄像头的数据,并转换成图片,上传阿里云OSS,开发语言是python,摄像头是海康的。

首先需要知道摄像头的用户名密码,通过opencv模块,可以轻松获取到视频流

import cv2

class videoCollect():
    def __init__(self, ip, user, passwd, channel = 1, userdata = None):
        self.ipcPath = "rtsp://"+str(user)+":"+str(passwd)+"@"+str(ip)+":554/Streaming/Channels/"+str(channel)+"01"
        cap = cv2.VideoCapture(self.ipcPath)
        if cap.isOpened():
            print("open success")
            ret, frame = self.cap.read()
            if(ret == True):
                return frame

        return None

如果需要将数据上传OSS,则需要知道OSS相关授权账号

import os
import oss2

class alioss():
    def __init__(self, accessKeyId, accessKeySecret, bucket) -> None:
        auth = oss2.Auth(accessKeyId, accessKeySecret)
        self.bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', bucket)

    #file:本地文件路径和名称,name:上传后的文件路径和名称
    def push_file(self, file, name):
        with open(file, 'rb') as fileobj:
            fileobj.seek(0, os.SEEK_SET)
            current = fileobj.tell()
            fileData = fileobj
            self.bucket.put_object(name, fileData)

接下去是思考如何将视频流上传OSS,这里可以看到OSS是需要使用本地文件打开的二进制流方式的,但是通过opencv获取的视频流格式是numpy.ndarray,因此需要通过转换才行

import os
import oss2
import videoCollect

class alioss():
    def __init__(self, accessKeyId, accessKeySecret, bucket) -> None:
        auth = oss2.Auth(accessKeyId, accessKeySecret)
        self.bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', bucket)

    def push_img(self, file, name):
        fileData = cv2.imencode(".jpg", file)[1].tobytes()
        self.bucket.put_object(name, fileData)


if __name__ == '__main__':
    aliosspush = alioss("accessKeyId", "accessKeySecret", "bucket")
    frame = videoCollect("192.168.0.10", "admin", "123456")
    if frame is not None:
        aliosspush.push_img(frame, "test.jpg")

你可能感兴趣的:(linux日常,opencv,计算机视觉)