Skip to content

Instantly share code, notes, and snippets.

@ricklon
Created January 3, 2021 20:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ricklon/6c86d3fed15550e2bd6371f83cf4ff4f to your computer and use it in GitHub Desktop.
Save ricklon/6c86d3fed15550e2bd6371f83cf4ff4f to your computer and use it in GitHub Desktop.
# https://www.codingforentrepreneurs.com/blog/opencv-python-web-camera-quick-test/
# https://stackoverflow.com/questions/41406547/how-to-detect-a-full-black-color-image-in-opencv-python
# Getting a USB error,
import numpy as np
import cv2
font = cv2.FONT_HERSHEY_SIMPLEX
NUM_CAMS = 2
cap=[]
for n in range(NUM_CAMS):
try:
# [ WARN:0] global C:\Users\appveyor\AppData\Local\Temp\1\pip-req-build-95hbg2jt\opencv\modules\videoio\src\cap_msmf.cpp (435) `anonymous-namespace'::SourceReaderCB::~SourceReaderCB terminating async callback
# cv2.CAP_DSHOW // This get's rid of the WARN:0 error
cap.append(cv2.VideoCapture(n))
except Exception as ex:
print(ex)
print(f'detected cameras: {len(cap)}')
for i in range(len(cap)):
print(f'cap[{i}]: {cap[i].isOpened()}')
try:
for i in range(len(cap)):
ret, frame = cap[i].read()
if frame is None:
print("Image is empty")
frame = np.zeros((512,512,3), np.uint8)
cv2.putText(frame,f'ret: {ret},Empty Image',(10,50), font, 1,(255,255,255),2)
elif np.mean(frame) == 0:
print ("Image is black")
else:
print ("Colored image")
# Display the resulting frame
cv2.imshow(f'Cam: {i}', frame)
except Exception as ex:
print(ex)
# input("Press Enter to continue...")
x = 0
y = 0
w = 500
h = 100
while(True):
try:
for i in range(len(cap)):
ret, frame = cap[i].read()
if (ret):
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
count = cv2.countNonZero(gray)
cv2.rectangle(frame, (x, x), (x + w, y + h), (0,0,0), -1)
cv2.putText(frame,f'countNonZero {count}',(10,50), font, 1,(255,255,255),2)
cv2.imshow(f'Cam: {i}', frame)
except Exception as ex:
print(ex)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
for n in range(NUM_CAMS):
cap[n].release()
cv2.destroyAllWindows()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment