async def classify(request): cam_id = request.match_info['stream'] cams = await get_cams(args.nvr_token) cam_info = [cam for cam in cams if str(cam['id']) == cam_id] if not cam_info: raise web.HTTPNotFound(text='No rtsp source related to this url') cam_info = cam_info[0] play_from = cam_info['rtsp'] if cam_id not in cam_rtsp: cam_rtsp[cam_id] = {} cam_rtsp[cam_id]['client'] = rtsp.Client(play_from) cam_rtsp[cam_id]['time'] = time() if (time() - cam_rtsp[cam_id]['time']) > 120: cam_rtsp[cam_id]['client'].close() cam_rtsp[cam_id]['client'] = rtsp.Client(play_from) cam_rtsp[cam_id]['time'] = time() im = cam_rtsp[cam_id]['client'].read() if im: im = im.resize((224, 224)) x = image.img_to_array(im) x = np.expand_dims(x, axis=0) x = preprocess_input(x) preds = model.predict(x) text = str([i[1] for i in decode_predictions(preds, top=3)[0]]) else: text = '' return web.Response(headers=cors_headers, text=text)
def AddWhiteRect(self): self.LabelStatusSaved.setText("Происходит проверка параметров камеры") self.repaint() # status = checkParametersCamera(Global.user, Global.passwd, Global.ip, Global.port) # Формируем ссылку на камеру ref = "rtsp://" + Global.user + ":" + Global.passwd + "@" + Global.ip + ":554/ISAPI/Streaming/Channels/101" # Пингуем ip камеры response = os.system("ping " + Global.ip) good = True # Если пинг прошел успешно if response == 0: # Пытаемся получить изображение с камеры try: Global.client = rtsp.Client(rtsp_server_uri=ref) # Если не удалось получить, значит пароль или логин неправильный, меняем флаг except: good = False if good == True: image = rtsp.Client(rtsp_server_uri=ref).read() qim = ImageQt(image) Global.pixmap = QPixmap.fromImage(qim) self.LabelStatusSaved.setText("") Global.StackWidgetsRects.addWidget(ui_AddWhiteRectWindow()) Global.StackWidgetsRects.setCurrentIndex( Global.StackWidgetsRects.count() - 1) else: self.LabelStatusSaved.setText( "Введен неверный логин или пароль") else: self.LabelStatusSaved.setText("Введен неверный ip")
async def check_image(addr, sleep_time=2): client = rtsp.Client(rtsp_server_uri=addr) result = False for i in range(3): # необходимо не срабатывать кадры, где камера двигается await asyncio.sleep(sleep_time) if await check_image_blur(client.read()): result = True break return result
def use_rtsp_con(socket_protocol, ip_cam_url=configs.RTSP_IP_CAM_URL): client = rtsp.Client(ip_cam_url)._capture image = client.read() now_ = datetime.datetime.now().timestamp() while True: img_bytes = io.BytesIO() image.save(img_bytes, format='JPEG') img_bytes = img_bytes.getvalue() new_now = send_img(img_bytes, now_, socket_protocol) now_ = new_now if new_now else now_ image = client.read()
def main(): # __init() print("start...") global discovery discovery = discover.Discover('test') devInfos = discovery.discover() for info in devInfos: res = url.urlparse(info.xaddr) print(res) tmp = res[1].split(':') ip = tmp[0] if len(tmp) > 1: port = tmp[1] else: port = 80 # get camera instance cam = ONVIFCamera(ip, port, '', '') # create media service media_service = cam.create_media_service() token = '000' # set video configuration configurations_list = media_service.GetVideoEncoderConfigurations() video_encoder_configuration = configurations_list[0] options = media_service.GetVideoEncoderConfigurationOptions( {'ProfileToken': token}) video_encoder_configuration.Encoding = 'H264' video_encoder_configuration.Resolution = options.H264.ResolutionsAvailable[ 0] request = media_service.create_type('SetVideoEncoderConfiguration') request.Configuration = video_encoder_configuration request.ForcePersistence = True media_service.SetVideoEncoderConfiguration(request) # get video stream streamSetup = { 'StreamSetup': { 'Stream': 'RTP-Unicast', 'Transport': { 'Protocol': 'TCP' } }, 'ProfileToken': '000' } res = media_service.GetStreamUri(streamSetup) rtspclt = rtsp.Client(rtsp_server_uri=res.Uri) content = rtspclt.read() img = cv2.cvtColor(numpy.asarray(content), cv2.COLOR_RGB2BGR) tmp = info.urn.split('-') name = tmp[-1] + '.jpg' cv2.imwrite(name, img)
def __init__(self, settings, callback, event_loop): threading.Thread.__init__(self) self.isRunning = True self.stream_uri = settings['streamURI'] self.client = rtsp.Client(rtsp_server_uri=self.stream_uri, verbose=True) self.cameraId = settings['cameraId'] self.location_name = settings['locationName'] self.fps = settings['FPS'] self.callback = callback self.loop = event_loop logger.info("RTSP stream initialized for camera %s at %s" % (self.cameraId, self.location_name))
def rtspGenericTester(self): pathOs = os.path.abspath(os.path.dirname(sys.argv[0])) vulnerable_host = open(pathOs + '/host/up_host.txt', 'r').read().splitlines() a = 0 while a < len(vulnerable_host): try: res = vulnerable_host[a] address = host.Host.addressRegex(res) try: client = rtsp.Client(rtsp_server_uri="rtsp://" + address['ip'] + ":554/play") except: pass except KeyboardInterrupt: pass
def checkParametersCamera(user, passwd, ip, port): # Формируем ссылку на камеру ref = "rtsp://" + user + ":" + passwd + "@" + ip + ":554/ISAPI/Streaming/Channels/101" # Пингуем ip камеры response = os.system("ping " + ip) # Если пинг прошел успешно if response == 0: # Пытаемся получить изображение с камеры try: Global.client = rtsp.Client(rtsp_server_uri=ref) # Если не удалось получить, значит пароль или логин неправильный, меняем флаг except: return 0 return 1 else: return -1
def generate_stream(url): client = rtsp.Client(rtsp_server_uri=url, verbose=False) while True: img = client.read() if img is None: continue w, h = img.size img = img.resize((640, int(640*h/w))) imgByteArr = io.BytesIO() img.save(imgByteArr, format='jpeg') b_img = imgByteArr.getvalue() yield (b'--frame\r\n' + b'Content-Type: image/jpeg\r\n\r\n' + b_img + b'\r\n') else: client.close()
def run(self): asyncio.set_event_loop(self.loop) last_ts = time.time() - 1 fps = 1 / self.fps while self.is_alive() and self.isRunning: frame = self.client.read() if not frame is None and self.client.isOpened(): new_ts = time.time() if new_ts - last_ts >= fps: last_ts = new_ts key = self.location_name + "_" + self.cameraId b64frame = self.image_encoder(frame) timestamp = datetime.utcnow().isoformat( timespec='milliseconds') + "Z" message = { "timestamp": timestamp, "cameraId": self.cameraId, "locationName": self.location_name, "image": b64frame } asyncio.run_coroutine_threadsafe( self.callback(json.dumps(message), key), self.loop) elif not self.client.isOpened(): logger.warning( "Stream from camera %s at %s got disconnected. Attempting reconnection" % (self.cameraId, self.location_name)) self.client.close() self.client.open() timeout = 0 while not self.client.isOpened() and timeout < 10: time.sleep(1) timeout = timeout + 1 if not self.client.isOpened(): logger.error( "Client didn't get reconnected. Resetting instance") self.client = rtsp.Client(rtsp_server_uri=self.stream_uri, verbose=True) else: logger.warning( "Stream from camera %s at %s is not transmitting" % (self.cameraId, self.location_name)) time.sleep(5)
def get_public_snapshot_url(self): # make sure that snapshots folder is exists if not os.path.isdir('snapshots'): os.makedirs('snapshots') private_uri = self.get_private_snapshot_url() if private_uri is not None: try: r = requests.get(private_uri, auth=(self.user, self.password)) if r.ok: filename = 'snapshots/' + self.ip + ":" + str( self.port) + gen_timestamp() + '.jpg' with open(filename, 'wb') as snapshot: snapshot.write(r.content) return "/" + filename except Exception as e: print('get_public_snapshot_url: request error: ', e) # try to get snapshot from stream private_stream_url = self.get_private_stream_url() if private_stream_url is not None: client = rtsp.Client(rtsp_server_uri=private_stream_url, verbose=False) image = client.read() if image is not None: imgByteArr = io.BytesIO() image.save(imgByteArr, format='jpeg') image = imgByteArr.getvalue() client.close() filename = 'snapshots/' + self.ip + ":" + str( self.port) + gen_timestamp() + '.jpg' with open(filename, 'wb') as snapshot: snapshot.write(image) return "/" + filename return None
def __init__(self, logger, cfg): if cfg['protocol'] in 'picamera': self.cam_address = 'picam' elif cfg['protocol'] in 'webcam': self.cam_address = 0 else: self.cam_address = cfg['protocol'] + cfg[ 'credentials'] + "@" + cfg['stream_address'] self.logger = logger self.cfg = cfg if not cfg['enabled']: logger.info("Camera is disabled.") else: self.discard_frames = self.cfg.get('discard_frames', 30) self.frame_ind = 1 self.old_frame = None self.frame = None self.logger.info("Connecting to " + str(self.cam_address)) self.cap = rtsp.Client(self.cam_address, verbose=True)
#!/home/jci/.pyenv/shims/python3 import rtsp from os import path import sys sys.path.append(path.dirname(__file__)+"/..") import detection im = rtsp.Client(0).read() dets = detection.FaceDetector().detect_faces(im) if dets: face = dets[0] A_face = face.size[0]*face.size[1] A_frame = im.size[0]*im.size[1] A_norm = float(A_face)/A_frame print("Face Proportionate-Area: {}".format(A_norm)) else: print("No faces found. Try again.")
import rtsp with rtsp.Client( 'rtsp://127.0.0.1:5554/user=user&password=&channel=1&stream=1.sdp?real_stream' ) as client: client.preview()
async def check_stream_connection(addr, sleep_time=1): client = rtsp.Client(rtsp_server_uri=addr) await asyncio.sleep(sleep_time) result = client.read() is not None return result
import rtsp import time try: with rtsp.Client(rtsp_server_uri='rtsp://174.0.247.195:554/1/') as client: _image = client.read() print(_image) # if client is None: # print(True) # else: # print(False) _image.save('1.jpg') except Exception as ex: print(ex)
def OpenImage(ip): client = rtsp.Client(rtsp_server_uri="rtsp://" + ip + ":554/user=admin&password=&channel=1&stream=0.sdp") client.read().save("cams\/" + ip + ".jpg")
import rtsp CAMERA_URI = 'rtsp://192.168.1.14:554' # single picture client = rtsp.Client(rtsp_server_uri=CAMERA_URI) image = client.read() f = open("pic.png", "w+") f.write(image) client.close() # stream Preview # with rtsp.Client(CAMERA_URI) as client: # client.preview()
import rtsp #add your rtsp url and type your username / password and IP of your NVR for the stream with rtsp.Client( rtsp_server_uri= 'rtsp://*****:*****@192.168.1.134:554/Streaming/Channels/401' ) as client: client.preview()
rtspUser = os.environ['RTSP_USER'] rtspPass = os.environ['RTSP_PASS'] os.environ['DISPLAY'] = ":0" timeout = 15 def showStream(url): with rtsp.Client(url) as client: client.preview() cameraList = [ 'rtsp://'+rtspUser+':'+rtspPass+'@10.0.1.150:554/ch01/1', 'rtsp://'+rtspUser+':'+rtspPass+'@10.0.1.150:554/ch02/1', 'rtsp://'+rtspUser+':'+rtspPass+'@10.0.1.150:554/ch03/1', 'rtsp://'+rtspUser+':'+rtspPass+'@10.0.1.150:554/ch04/1', 'rtsp://'+rtspUser+':'+rtspPass+'@10.0.1.152:554/ch01/1', 'rtsp://'+rtspUser+':'+rtspPass+'@10.0.1.152:554/ch02/1' ] while True: for url in cameraList: p = multiprocessing.Process(target=showStream(url), name="Stream") p.start() p.join(timeout) if p.is_alive(): print('function terminated') p.terminate() p.join() with rtsp.Client(url) as client: client.close()
import rtsp with rtsp.Client(verbose=True) as client: client.options() client.describe()
def showStream(url): with rtsp.Client(url) as client: client.preview()
import rtsp with rtsp.Client( rtsp_server_uri= 'rtsp://192.168.1.10:554/user=admin&password=123456&channel=1&stream=0' ) as client: client.preview()
import numpy as np import cv2 import rtsp #cap = cv2.VideoCapture("rtsp://*****:*****@[email protected]") #cap = cv2.VideoCapture('rtsp://169.254.24.88') while (True): with rtsp.Client(rtsp_server_uri='rtsp://169.254.24.88') as client: print(client) frame = client.read() frame = np.array(frame) print(frame.shape()) # Our operations on the frame come here gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Display the resulting frame cv2.imshow('frame', frame) if cv2.waitKey(1) & 0xFF == ord('q'): break # When everything done, release the capture cap.release() cv2.destroyAllWindows()
import rtsp import datetime # Get Streaming Date year = str(datetime.datetime.now().year) month = datetime.datetime.now().month if (int(month) < 10): month = "0" + str(month) day = str(datetime.datetime.now().day) if (int(day) < 10): day = "0" + str(day) hour = str(datetime.datetime.now().hour) if (int(hour) < 10): hour = "0" + str(hour) minute = str(datetime.datetime.now().minute) if (int(minute) < 10): minute = "0" + str(minute) second = str(datetime.datetime.now().second) if (int(second) < 10): second = "0" + str(second) # RTSP connection Setup RTSP_SERVER = "10.0.0.174" RTSP_PORT = "8554" RTSP_API = "/channel=0/subtype=0/vod=" RTSP_URL = "rtsp://" + RTSP_SERVER + ":" + RTSP_PORT + RTSP_API + year + month + day + "-" + hour + minute + second # RTSP Streaming connect client = rtsp.Client(rtsp_server_uri=RTSP_URL) client.preview() client.close()
#not work with me import rtsp client = rtsp.Client(rtsp_server_uri='rtsp://[email protected]') client.read().show() client.close()
def SaveChanged(self): # Так как пинг происходит долго, информируем пользователя, что идет проверка self.LabelStatusSaved.setText("Происходит проверка введенных данных") # Для того, чтобы текст высветился, перерисовываем виджет self.repaint() ip = self.lineEditIp.text() port = self.lineEditPort.text() user = self.lineEditUser.text() passwd = self.lineEditPassword.text() # Формируем ссылку на камеру ref = "rtsp://" + user + ":" + passwd + "@" + ip + ":554/ISAPI/Streaming/Channels/101" # Пингуем ip камеры response = os.system("ping " + ip) # Создаем флаг, True - правильный логин пароль, False - неправильный good = True # Если пинг прошел успешно if response == 0: # Пытаемся получить изображение с камеры try: client = rtsp.Client(rtsp_server_uri=ref) client.read() # Если не удалось получить, значит пароль или логин неправильный, меняем флаг except: good = False # Если пароль логин ip верен - меняем if good: self.LabelStatusSaved.setText("Новые данные сохранены") self.data['ip'] = self.lineEditIp.text() self.data['port'] = self.lineEditPort.text() self.data['user'] = self.lineEditUser.text() self.data['password'] = self.lineEditPassword.text() Global.ip = ip Global.user = user Global.passwd = passwd # Добавляем количество камер Global.countCameras += 1 # Объявляем новую камеру действующей камерой Global.numCamera = Global.countCameras # Получаем путь до файла касеры self.pathCamera = Global.pathCamera + "camera" + str( Global.numCamera) + ".json" # Создаем новый файл для новой камеру и записываем туда данные writeDataToJson(self.data, self.pathCamera) # Получаем данные из файла core dataCore = readDataFromJson(Global.pathCore) # Добавляем туда новую камеру dataCore['cameras'].append(Global.dataCoreCameraEmpty) # Меняем поля название и путь до файла настроек dataCore['cameras'][len(dataCore['cameras']) - 1]['name'] = "camera" + str( Global.numCamera) dataCore['cameras'][len(dataCore['cameras']) - 1]['config_path'] = "camera/camera" + \ str(Global.numCamera) + ".json" # Записываем новые данные в файл writeDataToJson(dataCore, Global.pathCore) # Нужно добавить кнопку новой камеры в окно камер # Для этого получаем окно камер CameraWindow = Global.StackWidgets.widget(1) # Создаем и добавляем кнопку камеры PushButtonCamera = QPushButton() PushButtonCamera.setText("camera " + str(Global.numCamera)) PushButtonCamera.setFixedSize(150, 50) CameraWindow.ButtonGroupCameras.addButton(PushButtonCamera) CameraWindow.layoutCameras.addWidget(PushButtonCamera) # Создаем и добавляем кнопку удаления камеры PushButtonDeleteCamera = QPushButton() PushButtonDeleteCamera.setText("Удалить камеру") PushButtonDeleteCamera.setFixedSize(200, 50) CameraWindow.ButtonGroupDeleteCameras.addButton( PushButtonDeleteCamera) CameraWindow.layoutDeleteCameras.addWidget( PushButtonDeleteCamera) PushButtonCamera.setObjectName("PushButtonCamera") PushButtonDeleteCamera.setObjectName("PushButtonDeleteCamera") # Меняем глобальные массивы соотношения id в массиве кнопок и номера камеры Global.idCamerasArrQt[ Global. numCamera] = CameraWindow.ButtonGroupDeleteCameras.id( PushButtonDeleteCamera) Global.idCamerasQtArr[CameraWindow.ButtonGroupDeleteCameras.id( PushButtonDeleteCamera)] = Global.numCamera # Объявляем кнопки добавления ректанглов действительными self.ButtonAddBlackRect.setDisabled(False) self.ButtonAddWhiteRect.setDisabled(False) self.ButtonAddMask.setDisabled(False) else: self.LabelStatusSaved.setText( "Введен неверный логин или пароль") else: self.LabelStatusSaved.setText("Введен неверный ip")
def Presentation_Detect(web_addr, input_num, pr_ip): # Настройки vMix таковы: # 1: презентация # 2: rtsp://172.18.200.51:554/Streaming/Channels/1 # 3: rtsp://172.18.200.52:554/Streaming/Channels/1 # 4: rtsp://172.18.200.53:554/Streaming/Channels/1 # 5: rtsp://172.18.200.54:554/Streaming/Channels/1 # 6: rtsp://172.18.200.55:554/Streaming/Channels/1 # 7: rtsp://172.18.200.56:554/Streaming/Channels/1 # В списке numbers - номера потоков камер в vMix. # Переключение происходит именно в таком порядке. Закольцованно. number = ['2', '7', '4', '3', '6', '5'] presentation_address = web_addr + '/api/?Function=Cut&Input=' + input_num # api адресс для переключения презентации в эфир return_to_address = web_addr + '/api/?Function=Cut&Input=0' # api адресс для переключения обратно в эфир потока на превью client = rtsp.Client( rtsp_server_uri=pr_ip ) # начало работы с RTSP потоком презентации для сравнения кадров и отслеживания переключения image = client.read() image.save( open('IMG_Compare\First.bmp', 'wb')) # сохранение "начлаьного" кадра в каталог IMG_Compare random.seed() im = Image.open('IMG_Compare\First.bmp') i = 0 while 1: time_crowd = random.randint(5, 15) # время кадра на экране для аудитории time_speaker = random.randint( 15, 35) # время кадра на экране для докладчика image1 = client.read() t1 = time.time() image1.save( open('IMG_Compare\Second.bmp', 'wb')) # сохранение текущего кадра в каталог IMG_Compare im1 = Image.open('IMG_Compare\Second.bmp') image_d = ImageChops.difference(im, im1) image_d.save(open('IMG_Compare\Diff.bmp', 'wb')) # разница "начального" и текущего кадров print( image_d.getpalette() ) # попытка получить палитру для .jpg (__у меня постоянно выводит None__) image_d2 = image_d.convert( "P", palette=Image.ADAPTIVE, colors=256) # первый параметр по умолчанию = RGB # при использовании convert("RGB", palette=Image.ADAPTIVE, colors=256) палитра не добавляется print(image_d2.getpalette()) image_d2.save(open('IMG_Compare\Diff_1.bmp', 'wb')) print(time.time() - t1) # время обработки if not image_d2.getpalette().count(0) == len( image_d2.getpalette() ): # сравнение количества нулей (не измененных элементов) и длины палитры im = Image.open( 'IMG_Compare\Second.bmp') # обновление "начального" кадра print('Переключение на презентацию ', rq.get(url=presentation_address) ) # переключение на презентацию и вывод ответа time.sleep(5) # время презентации в эфире print('Переключение с презентации ', rq.get(url=return_to_address) ) # переключение на превью и вывод ответа else: change_to = web_addr + '/api/?Function=Cut&Input=' + number[ i] # выбор камеры на которую переключиться print('Переключение между камерами ', rq.get(url=change_to)) if (i % 2) == 0: time.sleep(time_crowd) else: time.sleep(time_speaker) i = i + 1 if i == 6: i = 0 '''
import cv2 import rtsp import os import random from subprocess import Popen import time client = rtsp.Client( rtsp_server_uri='rtsp://*****:*****@192.168.1.6/onvif1') p = Popen([ 'ffmpeg', '-loglevel', 'panic', '-rtsp_transport', 'udp', '-i', 'rtsp://*****:*****@192.168.1.6/onvif1', '-f', 'image2', '-s', '640x480', '-pix_fmt', 'yuvj420p', '-r', '1/2', '-updatefirst', '1', '/tmp' ]) client.read().show() client.close()
import rtsp client = rtsp.Client(rtsp_server_uri = 'rtsp://*****:*****@199.199.51.203:554/mpeg/ch1/sub/av_stream') test = client.read() print(test) client.close()