# rtx2080測試機 暈到死安裝程序-------------- https://visualstudio.microsoft.com/zh-hant/downloads/ ![](https://i.imgur.com/NEKQjdw.png) ![](https://i.imgur.com/IDBDEVN.png) ``` { "version": "1.0", "components": [ "Microsoft.VisualStudio.Component.RoslynrCompiler", "Microsoft.Component.MSBuild", "Microsoft.VisualStudio.Component.CoreBuildTools", "Microsoft.VisualStudio.Workload.MSBuildTools", "Microsoft.VisualStudio.Component.Windows10SDK", "Microsoft.VisualStudio.Component.VC.CoreBuildTools", "Microsoft.VisualStudio.Component.VC.Tools.x86.x64", "Microsoft.VisualStudio.Component.VC.Redist.14.Latest", "Microsoft.VisualStudio.Component.Windows10SDK.19041", "Microsoft.VisualStudio.Component.VC.CMake.Project", "Microsoft.VisualStudio.Component.TestTools.BuildTools", "Microsoft.VisualStudio.Component.VC.ASAN", "Microsoft.VisualStudio.Component.TextTemplating", "Microsoft.VisualStudio.Component.VC.CoreIde", "Microsoft.VisualStudio.ComponentGroup.NativeDesktop.Core", "Microsoft.Component.VC.Runtime.UCRTSDK", "Microsoft.VisualStudio.Component.VC.140", "Microsoft.VisualStudio.Workload.VCTools" ] } ``` 安裝驅動 sudo ubuntu-drivers autoinstall 安裝cuda cudnn 要選 ubuntu 18 runfile 要取消driver https://developer.nvidia.com/cuda-10.2-download-archive?target_os=Windows&target_arch=x86_64&target_version=10&target_type=exenetwork 安裝anaconda wget https://repo.anaconda.com/archive/Anaconda3-2022.10-Linux-x86_64.sh sh Anaconda3-2022.10-Linux-x86_64.sh https://repo.anaconda.com/archive/Anaconda3-2020.11-Windows-x86_64.exe 安裝pytorch https://www.anaconda.com/products/individual conda create --name yolact python==3.7 -y conda activate yolact conda install pytorch torchvision torchaudio cudatoolkit=10.2 -c pytorch -y pip install opencv-python pip install pycocotools-windows -------------- AnyDesk安裝 sudo apt update; sudo apt upgrade wget -qO - https://keys.anydesk.com/repos/DEB-GPG-KEY | sudo apt-key add - sudo nano /etc/apt/sources.list.d/anydesl.list 新增 deb http://deb.anydesk.com/ all main ![](https://i.imgur.com/AOCp4Hx.png) anydesk display server not supported問題 修改/etc/gdm3/custom.conf ``` # GDM configuration storage # # See /usr/share/gdm/gdm.schemas for a list of available options. [daemon] # Uncoment the line below to force the login screen to use Xorg WaylandEnable=false # Enabling automatic login AutomaticLoginEnable = true AutomaticLogin = $USERNAME # Enabling timed login # TimedLoginEnable = true # TimedLogin = user1 # TimedLoginDelay = 10 [security] [xdmcp] [chooser] [debug] # Uncomment the line below to turn on debugging # More verbose logs # Additionally lets the X server dump core if it crashes #Enable=true ``` RDP安裝///////////////// https://zhuanlan.zhihu.com/p/93438433 sudo add-apt-repository ppa:martinx/xrdp-hwe-18.04 sudo apt-get update sudo apt-get install xrdp xorg xrdp sudo adduser xrdp ssl-cert echo xfce4-session > ~/.xsession sudo nano /etc/xrdp/startwm.sh 加這些:----------------- if test -r /etc/profile; then . /etc/profile fi startxfce4 test -x /etc/X11/Xsession && exec /etc/X11/Xsession exec /bin/sh /etc/X11/Xsession ------------------------------- n ////////////////////////// conda 安裝教學----------------------- conda create --name yolact python==3.7 -y conda activate yolact conda install pytorch torchvision torchaudio cudatoolkit=10.2 -c pytorch -y ubuntu@192.168.43.43 pip install opencv-python pip install pycocotools-windows pip install requests docker 更新 docker commit -m="explain" -a="author" a7829c13f2fc michael/curve | 參數 | 說明 | | -------- | -------- | | -m | 描述 | | -a |作者 | |a7829c13f2fc|container id| |michael/curve|mirror名稱| SCP傳檔案教學------------ scp -r ubuntu@192.168.43.43:/home/ubuntu/Desktop/yolact-master ./ /home/ubuntu/Desktop/yolact-master -r 船資料夾 ./放在目前的目錄 ------------------------- output.py No module named ‘torch.cuda.amp.autocast’ conda env create -f pip install torch==1.7.1+cu110 torchvision==0.8.2+cu110 torchaudio==0.7.2 -f https://download.pytorch.org/whl/torch_stable.html ![](https://i.imgur.com/t5vNAIh.png) ``` import os import getpass import torch from time import time config = 'yolact_base_config' pth_path = 'yolact_base_2777_133333.pth' val_dir = 'data/test/' output_dir = './out' os.system(f'python -W ignore eval.py --trained_model={pth_path} --score_threshold=0.1 --top_k=15 --config {config} --video=rtsp://admin:rdfg1235@210.240.245.72:554/main_0') ``` eval.py 網頁Flask部分 Flask教學 https://ithelp.ithome.com.tw/articles/10222132 ``` def web_view(): app = Flask(__name__) def get_image(): while True: ret, jpeg = cv2.imencode('.jpg', web_out) jpeg = jpeg.tobytes() yield(b'--frame\r\n' b'Content-Type: image/jpeg\r\n\r\n'+ jpeg + b'\r\n') time.sleep(0.03) # my Firefox needs some time to display image / Chrome displays image without it @app.route("/") def stream(): return Response(get_image(), mimetype="multipart/x-mixed-replace; boundary=frame") def one_image(wb): ret, jpeg = cv2.imencode('.jpg', wb) jpeg = jpeg.tobytes() #yield(b'--frame\r\n' # b'Content-Type: image/jpeg\r\n\r\n'+ jpeg + b'\r\n') return(jpeg) time.sleep(0.03) # my Firefox needs some time to display image / Chrome displays image without it @app.route("/out") def out(): return Response(one_image(web_out), mimetype="image/jpeg") @app.route("/in") def webin(): return Response(one_image(web_in), mimetype="image/jpeg") @app.route("/shutdown") def shutdown(): #exit() os.system('ps -ef | grep monitor.py| grep -v grep | awk \'{print $2}\' | xargs kill -9') os.system('ps -ef | grep eval.py| grep -v grep | awk \'{print $2}\' | xargs kill -9') return Response('shutdown') # If the path is a digit, parse it as a webcam index app.run('0.0.0.0') ``` screen部分 ``` if out_path is None: ret, jpeg = cv2.imencode('.jpg', frame_buffer.get()) screen=jpeg.tobytes() ``` 多工部分 pool.apply_async(web_view) process異常偵測 monitor HA切換 container 狀態偵測 彎曲鋼鐵截圖一秒鐘 log存檔 alert機制 發email 及時抓mp4 及時變是 done 192.168.43.47 必須 reboot 和 裝nvidia-docker 然後重啟docker這樣container才能使用 unbuntu auto send gmail config https://blog.gtwang.org/linux/linux-send-mail-command-using-ssmtp-and-gmail/ gmail script: echo "alert" | ssmtp anos71334@gmail.com https://wsgzao.github.io/post/keepalived/ #netcat port monitoring nc -v 210.240.245.72 554 -w1 https://blog.gtwang.org/linux/linux-utility-netcat-examples/ yolact.sh ``` #!/bin/bash cd /home/ubuntu/yolact-master/ source /home/ubuntu/anaconda3/etc/profile.d/conda.sh conda activate yolact && python3 output.py ``` user=root /etc/keepaliveed/ccc.sh echo "1"> /test.txt OK user=ubuntu /home/ubuntu/yolact-master/ccc.sh echo "1"> ./tes1t.txt bad xfce4-terminal --command='/home/ubuntu/yolact-master/ccc.sh -t ls' --title=todo >/dev/pts/5 echo 'yetr5678' | sudo -S service keepalived status echo 'yetr5678' | sudo -S service keepalived stop echo 'yetr5678' | sudo -S service keepalived start live streaming web https://www.pyimagesearch.com/2019/09/02/opencv-stream-video-to-web-browser-html-page/ ``` f = open("demofile2.txt", "w+") localtime = time.asctime( time.localtime(time.time()) ) f.write(str(localtime)) f.close() ``` os.system(f'python -W ignore eval.py --trained_model={pth_path} --fast_nms False --score_threshold=0.1 --top_k=15 --config {config} --video_multiframe=20 --video=123.wmv:123.mp4') ![](https://i.imgur.com/BvSXtDg.png) https://towardsdatascience.com/video-streaming-in-web-browsers-with-opencv-flask-93a38846fe00 opencv-django https://github.com/wenyenwei/opencv_django/blob/master/opencv_webapp/views.py ubuntu enviroment mess up:install synaptic-pkexec app to resolve reverse ssh tunnel https://xenby.com/b/220-%E6%95%99%E5%AD%B8-%E7%94%A2%E7%94%9Fssh-key%E4%B8%A6%E4%B8%94%E9%80%8F%E9%81%8Ekey%E9%80%B2%E8%A1%8C%E5%85%8D%E5%AF%86%E7%A2%BC%E7%99%BB%E5%85%A5 sudo systemctl start rc-local sudo systemctl status rc-local 新增root publc key ``` echo "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQC4pG9yGLIkYQVYqRk4UODYez81KNSKCM2iQsq5FKn0C2kuzXqaMZRqsEBaIzclh8gUt8o63eyH974Wd3cdSNzOueRih9uoRzsoZYtM//CQ9Yj2+kIJYcEdupaHVr1Y4yOGxa/whE7bfOWY9flRuFVM3QoFUqvIFjMXEYIdsHwwevxsnVTMGYIZXMVSphPbZjH9kU5e5IXWrBKstVQ8nJSCC8Z+1EZYwqdGPMCcxjtQx1zfZKihNa+kYK3b7nG6elJASpE5OHeIsfTXiUps+HGnHJz6ccwiqWk+OnSS/p7kzternZOAD0GfsQguAmkywSEwp7Ys+0uXCPIKLUM/PyDF ubuntu@ubuntu-SYS-5039A-I " >> ~/.ssh/authorized_keys autossh -M 0 -f -nNT -R 5002:localhost:5000 -o "ServerAliveInterval 5" -o "ServerAliveCountMax 3" -o "StrictHostKeyChecking=no" hdfsadmin@210.240.245.72 -p9111 autossh -M 0 -f -nNT -R 3302:localhost:3389 -o "ServerAliveInterval 5" -o "ServerAliveCountMax 3" -o "StrictHostKeyChecking=no" hdfsadmin@210.240.245.72 -p9111 autossh -M 0 -f -nNT -R 9488:192.168.1.101:80 -o "ServerAliveInterval 5" -o "ServerAliveCountMax 3" -o "StrictHostKeyChecking=no" hdfsadmin@210.240.245.72 -p9111 autossh -M 0 -f -nNT -R 2202:localhost:22 -o "ServerAliveInterval 5" -o "ServerAliveCountMax 3" -o "StrictHostKeyChecking=no" hdfsadmin@210.240.245.72 -p9111 ``` echo "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABgQCsQpSEVS887EWLc2Q8BlvdQjOg1eaD+AeUQQNV7ElfAr6EZm/QSExUEBjIUFtYk+ZnS1S6pfeUpChrkENi7fvYGQacat06P5wJ2q5X0vXKRAnQAckm+GHSZuX3Ks9IHnjiordkEThZ/UKt71aW6ThlV3h82B/cfih3sHlZok0JieeEYS8cwu/pQkE5wtvnvN4lr9BdKjwFMVO/zSzRJ4a3fB32zHSuVFvbQU0DocA2kZYPGmCqE83rhb4EN0H0MTann/WPHU84lItTduwJc8vOpoVvXKK5ZnlxWFblrCnL7lJOpZ+RtH+2SWh+j2Qfl6IaRmQy/SYR4mYQk9DDbN8jY7vDWF9eH8rOmVWs35MD91I2SlsWqkhjVfn6skJg5u/lgF+wzcWf+x5ROAW0ehLSbfeb7zs07CZmT19WrU3YJv/Yl1skWGfKy82emJ45gbpLLuIo6aOQhoQUugNa236FBGLoSAmiORXFKin0JNNcuGzPQoKxK0T0zNGo2ryvLyE= root@yolo-5d57f77b9b-ggqnp ">> ~/.ssh/authorized_keys ``` autossh -M 0 -f -nNT -R 5001:localhost:5000 -o "ServerAliveInterval 5" -o "ServerAliveCountMax 3" -o "StrictHostKeyChecking=no" hdfsadmin@210.240.245.72 -p9111 autossh -M 0 -f -nNT -R 3301:localhost:3389 -o "ServerAliveInterval 5" -o "ServerAliveCountMax 3" -o "StrictHostKeyChecking=no" hdfsadmin@210.240.245.72 -p9111 autossh -M 0 -f -nNT -R 5555:192.168.1.101:554 -o "ServerAliveInterval 5" -o "ServerAliveCountMax 3" -o "StrictHostKeyChecking=no" hdfsadmin@210.240.245.72 -p9111 ``` 直播 ``` import cv2 cap = cv2.VideoCapture('rtsp://admin:123456@172.16.1.81:5555/main_0') ret,frame = cap.read() while ret: ret,frame = cap.read() cv2.imshow("current frame",frame) #cv2.imwrite('frame.jpg', frame) if cv2.waitKey(1) & 0xFF == ord('q'): break cv2.destroyAllWindows() cap.release() ``` 檢驗區測試 ``` import cv2 import numpy as np median_list=[] vid = cv2.VideoCapture('2.mp4') avg_step=2 temp1=0 temp2=0 while(True): temp1=temp1+1 ret, frame = vid.read() frame = frame[100:,400:1200] #frame=frame[658:680,150:500]#辨識區 pro_frame = cv2.morphologyEx(frame, cv2.MORPH_OPEN, np.ones((2,2))) pro_frame = np.median(pro_frame[658:680,150:500])#辨識區 median_list.append(pro_frame) avg=np.mean(median_list[-avg_step:])#中位數計算區 avg1=np.mean(median_list[:]) cv2.putText(frame,str(avg), (100, 50), cv2.FONT_HERSHEY_SIMPLEX,1, (0, 255, 255), 1, cv2.LINE_AA) cv2.putText(frame,str(avg1), (200, 50), cv2.FONT_HERSHEY_SIMPLEX,1, (0, 255, 255), 1, cv2.LINE_AA) cv2.putText(frame,str(avg-avg1), (300, 100), cv2.FONT_HERSHEY_SIMPLEX,1, (0, 255, 255), 1, cv2.LINE_AA) if( np.mean(median_list[:])-np.mean(median_list[-avg_step:]))>2: temp2=temp1 cv2.putText(frame,str(temp1-temp2), (400, 200), cv2.FONT_HERSHEY_SIMPLEX,1, (0, 255, 255), 1, cv2.LINE_AA) cv2.imshow('aaa',frame) if cv2.waitKey(1) & 0xFF == ord('q'): break cv2.destroyAllWindows() ``` django及時辨識網頁 ``` def steel_monitoring(request): global raw_img,out_img switch = request.GET.get('switch', '') pause = request.GET.get('pause', '') save = request.GET.get('save', '') if switch == 'on': os.system("/home/ubuntu/yolact-master/yolact.sh") if switch == 'off': requests.get('http://'+ip_addr+':5000/shutdown') if pause == 'pause': raw_img = requests.get('http://'+ip_addr+':5000/in') out_img = requests.get('http://'+ip_addr+':5000/out') now_time=[time.strftime("%Y%m%d", time.localtime()),time.strftime("%H%M%S", time.localtime())] save_time=time.strftime("%Y%m%d_%H%M%S", time.localtime()) pause='' if save == 'save': localdate=str(time.strftime("%m%d", time.localtime())) localtime=str(time.strftime("%Y%m%d_%H%M%S", time.localtime())) if os.path.exists("../screenshot/"+localdate) == False: os.mkdir("../screenshot/"+localdate) with open("../screenshot/"+localdate+"/"+localtime+"_in.jpg", "wb") as file: # 開啟資料夾及命名圖片檔 file.write(raw_img.content) with open("../screenshot/"+localdate+"/"+localtime+"_out.jpg", "wb") as file: # 開啟資料夾及命名圖片檔 file.write(out_img.content) save='' context = { 'msg':request.GET.get('msg'), } return render(request, 'steel/steel_monitoring.html', context) ``` post_ajax ``` <div class="card mb-3"> <div class="card-header"> <i><img src="/static/icon/sis_icon_2_bk.png" width="20px" class="m_b5p_imp"></i> 即時監控 </div> <div class="card-body"> <div class="table-responsive" id=""> <div class="w_49p9 h_600p float-left"> <iframe class="w_100 h_600p" id="demo1" name="demo1" src="http://192.168.43.43:5000/" frameborder="0" allowfullscreen="true"></iframe> </div> <div class="w_49p9 h_600p float-left"> <iframe class="w_100 h_600p" id="demo2" name="demo2" src="" frameborder="0" style="display: none;" allowfullscreen="true"></iframe> </div> <div class="w_100 float-left"> <hr> <div class="btn btn-primary btn-sm btn-self w_5r_imp" onclick="pause_Btn()">暫停</div> <div class="btn btn-primary btn-sm btn-self w_5r_imp" onclick="myFunction()">開始</div> <div class="btn btn-primary btn-sm btn-self w_5r_imp" onclick="myFunction2()">比較</div> <div class="btn btn-primary btn-sm btn-self w_5r_imp" onclick="save_Btn()">存檔</div> <div class="btn btn-primary btn-sm btn-self w_5r_imp" onClick="poweron_Btn()">開啟</div> <div class="btn btn-primary btn-sm btn-self w_5r_imp" onClick="poweroff_Btn()">關閉</div> </div> </div> </div> </div> <script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script> <script type="text/javascript"> function myFunction() { document.getElementById("demo2").style.display = "none"; document.getElementById("demo1").src = "http://192.168.43.43:5000/"; }; function myFunction2() { document.getElementById("demo2").style.display = "block"; }; function pause_Btn() { document.getElementById("demo2").style.display = "none"; document.getElementById("demo2").src = "http://192.168.43.43:5000/in"; document.getElementById("demo1").src = "http://192.168.43.43:5000/out"; $.ajax({ url: '/steel/steel_monitoring/', type: 'get', data: { 'pause': 'pause' }, success: function (msg) { //alert('結果' + msg); }, error: function (data) { alert('status:' + data.status); // the status code alert(data.responseJSON.error); // the message } }); }; function poweron_Btn() { $.ajax({ url: '/steel/steel_monitoring/', type: 'get', data: { 'switch': 'on' }, success: function (msg) { alert('啟動成功'); }, error: function (data) { alert('status:' + data.status); // the status code alert(data.responseJSON.error); // the message } }); }; function poweroff_Btn() { $.ajax({ url: '/steel/steel_monitoring/', type: 'get', data: { 'switch': 'off' }, success: function (msg) { }, error: function (data) { alert('關閉成功'); //alert('status:' + data.status); // the status code //alert(data.responseJSON.error); // the message } }); }; function save_Btn() { $.ajax({ url: '/steel/steel_monitoring/', type: 'get', data: { 'save': 'save' }, success: function (msg) { //alert('存檔成功'); }, error: function (data) { alert('status:' + data.status); // the status code alert(data.responseJSON.error); // the message } }); }; </script> ``` 尋找類似名子資料夾 ``` import os,time now_time=[time.strftime("%Y%m%d", time.localtime()),time.strftime("%H%M%S", time.localtime())] #now_time=['20210618','103804'] dir_list_time=[] dir_list=[] for root, dirs, files in os.walk("../yolact/outimage", topdown=False): for name in dirs: dir_list.append(name) sn=name.split('_') if sn[0]==now_time[0] and int(sn[1])<=int(now_time[1]): dir_list_time.append(sn) time_key=min(dir_list_time, key=lambda x: abs(int(x[1]) - int(now_time[1]))) print(time_key) string = '_'.join(time_key) print(string) ``` conda env create -f yolo.yml -y pip install torch==1.7.1+cu110 torchvision==0.8.2+cu110 torchaudio==0.7.2 -f https://download.pytorch.org/whl/torch_stable.html pip3 install torch==1.10.2+cu113 torchvision==0.11.3+cu113 torchaudio==0.10.2+cu113 -f https://download.pytorch.org/whl/cu113/torch_stable.html pip install seaborn pip install pandas pip install pyyaml pip install opencv-python pip install requests pip install tqdm pip install wandb pip install flask python detect_steel_light.py pip install screen C:\Users\aiuser\anaconda3\envs\yolo\python.exe cd C:\Users\aiuser\Documents\steel_detect_n\steel_detect_n C:\Users\aiuser\anaconda3\envs\yolo\python.exe detect_steel_light.py conda env create -f yolo.yml -y http://210.240.245.72:8777/video/yolo.yml http://210.240.245.72:8777/video/steel_detect_n.zip python detect_steel_light_stream.py --source rtsp://admin:123456@192.168.1.101:554/main_0 apt install htop python train.py --data allscene_aftersplit/allscene.yaml --workers 10 --cache --batch 220 --device 0,1 --weights yolov5m6.pt python train.py --data allscene_aftersplit/allscene.yaml --workers 25 --cache --batch 120 --device 0 --weights yolov5m.pt python train.py --data allscene_aftersplit/allscene.yaml --workers 15 --cache --batch 80 --device 0,1 --imgsz 960 --weights yolov5m.pt python train.py --data handlecrop/handle_crop.yaml --workers 25 --cache --batch 80 --device 0,1 --weights yolov5s6.pt python train.py --data niddle_mi/niddle_mi.yaml --hyp niddle_mi/hyp.scratch_niddle.yaml --workers 15 --cache --batch 80 --device 0,1 --weights yolov5s6.pt wandb key 4b3c2f767868cec053d8006e94423e08742e5ec1