Skip to content

Instantly share code, notes, and snippets.

@youjunjer
Last active August 21, 2023 13:34
Show Gist options
  • Star 15 You must be signed in to star a gist
  • Fork 5 You must be signed in to fork a gist
  • Save youjunjer/79e5dad5f47ee5757fcb9d401a95e76b to your computer and use it in GitHub Desktop.
Save youjunjer/79e5dad5f47ee5757fcb9d401a95e76b to your computer and use it in GitHub Desktop.
import cv2 as cv
import numpy as np
from urllib.request import urlopen
import os
import datetime
import time
import sys
#change to your ESP32-CAM ip
url="http://192.168.1.149:9601/stream"
CAMERA_BUFFRER_SIZE=4096
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,(640,480))
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()
@egafrandika
Copy link

it work

@kyteinsky
Copy link

there are two types of coders:

  1. import cv2
  2. import cv2 as cv

I am #2, glad to meet you!

@himakarbavikaty
Copy link

how to import cv2 in to micropython board?

@mchen07
Copy link

mchen07 commented Oct 11, 2021

I keep getting error like this

Video capture error:OpenCV(4.5.2) /private/var/folders/24/8k48jl6d249_n_qfxwsl6xvm0000gn/T/pip-req-build-yj1re3p/opencv/modules/imgcodecs/src/loadsave.cpp:736: error: (-215:Assertion failed) !buf.empty() in function 'imdecode'

Then it will reset, hard to get real-time effect.

Any idea what is going on?

@ixobert
Copy link

ixobert commented Jul 18, 2022

@mchen07, Check if jpg contains something before decoding:

if len(jpg):
    img=cv2.imdecode(np.frombuffer(jpg,dtype=np.uint8),cv2.IMREAD_UNCHANGED)
else:
    continue

@HarryJian622
Copy link

HarryJian622 commented Aug 21, 2023

anyone can tell me why I got this error thanks . and how to deal with it ConnectionRefusedError: [WinError 10061]

@ixobert
Copy link

ixobert commented Aug 21, 2023

@HarryJian622, here are few things you can check to address this issue:

  • Can you check it the url is valid (no typos) ?
  • Is the server-side application running on the ESP32?
  • Is the ESP32 connected to the same network as the client app ?
  • Any firewall on your system that may prevent such connections ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment