{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import cv2\n",
    "from darkflow.net.build import TFNet\n",
    "import time\n",
    "import threading\n",
    "import subprocess as sp"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "option={\n",
    "    'model':'cfg/yolo.cfg',\n",
    "    'load':'bin/yolov2.weights',\n",
    "    'threshold':0.3,\n",
    "#     'gpu':0.8\n",
    "}"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "tfnet=TFNet(option)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# capture=cv2.VideoCapture('Khare_testvideo_03.mp4')\n",
    "rtmpUrl='rtmp://stream.mivs.isrg.tw/analyze/yolov2_kr_1'\n",
    "URL=\"http://91.201.117.136/mjpg/video.mjpg#.W4ez7ApQikk.link\"\n",
    "capture=cv2.VideoCapture(URL)\n",
    "# colors=[tuple(255*np.random.rand(3)) for i in range(20)]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 取得影片參數\n",
    "size = (int(capture.get(cv2.CAP_PROP_FRAME_WIDTH)), int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT)))\n",
    "sizeStr = str(size[0]) + 'x' + str(size[1])\n",
    "fps = capture.get(cv2.CAP_PROP_FPS)  # 30p/self\n",
    "fps = int(fps)\n",
    "hz = int(1000.0 / fps)\n",
    "print('size:'+ sizeStr + ' fps:' + str(fps) + ' hz:' + str(hz))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 管道输出 ffmpeg推送rtmp 重点 ： 通过管道 共享数据的方式\n",
    "command = ['ffmpeg',\n",
    "    '-y',\n",
    "    '-f', 'rawvideo',\n",
    "    '-vcodec','rawvideo',\n",
    "    '-pix_fmt', 'bgr24',\n",
    "    '-s', sizeStr,\n",
    "    '-r', str(fps),\n",
    "    '-i', '-',\n",
    "    '-c:v', 'libx264',\n",
    "    '-pix_fmt', 'yuv420p',\n",
    "    '-preset', 'ultrafast',\n",
    "    '-f', 'flv', \n",
    "    rtmpUrl]\n",
    "# pipe = sp.Popen(command, stdout = sp.PIPE, bufsize=10**8)\n",
    "pipe = sp.Popen(command, stdin=sp.PIPE) #,shell=False"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "class ipcamCapture:\n",
    "    def __init__(self, URL):\n",
    "        self.Frame = []\n",
    "        self.status = False\n",
    "        self.isstop = False\n",
    "\t\t\n",
    "\t# 攝影機連接。\n",
    "        self.capture = cv2.VideoCapture(URL)\n",
    "\n",
    "    def start(self):\n",
    "\t# 把程式放進子執行緒，daemon=True 表示該執行緒會隨著主執行緒關閉而關閉。\n",
    "        print('ipcam started!')\n",
    "        threading.Thread(target=self.queryframe, daemon=True, args=()).start()\n",
    "\n",
    "    def stop(self):\n",
    "\t# 記得要設計停止無限迴圈的開關。\n",
    "        self.isstop = True\n",
    "        print('ipcam stopped!')\n",
    "   \n",
    "    def getframe(self):\n",
    "\t# 當有需要影像時，再回傳最新的影像。\n",
    "        return self.Frame\n",
    "        \n",
    "    def queryframe(self):\n",
    "        while (not self.isstop):\n",
    "            self.status, self.Frame = self.capture.read()\n",
    "        \n",
    "        self.capture.release()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# URL=\"http://91.201.117.136/mjpg/video.mjpg#.W4ez7ApQikk.link\"\n",
    "\n",
    "# 連接攝影機\n",
    "ipcam = ipcamCapture(URL)\n",
    "\n",
    "# 啟動子執行緒\n",
    "ipcam.start()\n",
    "\n",
    "# 暫停1秒，確保影像已經填充\n",
    "time.sleep(1)\n",
    "\n",
    "# 使用無窮迴圈擷取影像，直到按下Esc鍵結束\n",
    "while True:\n",
    "    stime=time.time()\n",
    "    # 使用 getframe 取得最新的影像\n",
    "    frame = ipcam.getframe()\n",
    "    \n",
    "    results = tfnet.return_predict(frame)\n",
    "    for result in results:\n",
    "        tl=(result['topleft']['x'],result['topleft']['y'])\n",
    "        br=(result['bottomright']['x'],result['bottomright']['y'])\n",
    "        label=result['label']\n",
    "        frame=cv2.rectangle(frame,tl,br,(0,255,0),2)\n",
    "        frame=cv2.putText(frame,label,tl,cv2.FONT_HERSHEY_COMPLEX,0.5, (255,255,255), 1, cv2.LINE_AA)\n",
    "    cv2.imshow('frame',frame)\n",
    "    pipe.stdin.write(frame.tostring())\n",
    "    pass\n",
    "    print('FPS {:.1f}'.format(1 / (time.time() - stime)))\n",
    "    if cv2.waitKey(33) == 27:\n",
    "        cv2.destroyAllWindows()\n",
    "        ipcam.stop()\n",
    "        break"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.5.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
