最近常用Python去接ESP32CAM影像回來辨識,例如算一下幾個人、幾台車經過這類的問題,不過ESP32CAM傳輸透過網路,總是偶爾會斷線
我的ESP32實做書籍:我出書了 ESP32 物聯網專題
博客來網址:https://www.books.com.tw/products/0010901195
最近常用Python去接ESP32CAM影像回來辨識,例如算一下幾個人、幾台車經過這類的問題,不過ESP32CAM傳輸透過網路,總是偶爾會斷線,之前寫的程式只要一段時間就會出錯,導致三不五時就要去自己重新按啟動。
python我算是新手,有些基礎語法到是沒那麼熟,其實只要加入我在.net程式中一定會用到的try catch就可以解決了。
1.ESP32CAM請安裝範例程式:Camerawebserver,這部份請參考:ESP32-CAM (arduino)影像伺服器及臉部辨識教學原始檔Video Stream Server
2.執行後,在序列視窗查看取得的IP
3.執行本python程式
完整程式碼可以在這裡下載:https://github.com/youjunjer/Python-Read-ESP32CAM
#ESP32CAM請使用CamerawebServer範例程式
import cv2 as cv
import numpy as np
from urllib.request import urlopen
#change to your ESP32-CAM ip
url="http://192.168.1.102:81/stream"
CAMERA_BUFFRER_SIZE=2048
stream=urlopen(url)
bts=b''
i=0
while True:
try:
bts+=stream.read(CAMERA_BUFFRER_SIZE)
jpghead=bts.find(b'\xff\xd8')
jpgend=bts.find(b'\xff\xd9')
if jpghead>-1 and jpgend>-1:
jpg=bts[jpghead:jpgend+2]
bts=bts[jpgend+2:]
img=cv.imdecode(np.frombuffer(jpg,dtype=np.uint8),cv.IMREAD_UNCHANGED)
#img=cv.flip(img,0) #>0:垂直翻轉, 0:水平翻轉, <0:垂直水平翻轉
#h,w=img.shape[:2]
#print('影像大小 高:' + str(h) + '寬:' + str(w))
img=cv.resize(img,(800,600))
cv.imshow("a",img)
k=cv.waitKey(1)
except Exception as e:
print("Error:" + str(e))
bts=b''
stream=urlopen(url)
continue
k=cv.waitKey(1)
# 按a拍照存檔
if k & 0xFF == ord('a'):
cv.imwrite(str(i) + ".jpg", img)
i=i+1
# 按q離開
if k & 0xFF == ord('q'):
break
cv.destroyAllWindows()