python - CV2:关闭相机连接并以不同的功能重新打开
问题描述
所以基本上我在这个脚本中有两个函数。1 进行人脸识别并显示存储在数据库中的数据,第二个是在看到无法识别的人脸时触发,并存储临时数据。问题是,当第二个被触发时,我一直收到错误
VIDEOIO ERROR 无法通过索引 1 打开相机
无法停止流:设备或资源繁忙
我很确定我在 face_recog 函数中正确地释放了它,但我不确定。任何帮助表示赞赏。
video_capture = cv2.VideoCapture(1)
configured_datetime = str(datetime.datetime.now().strftime('%c'))
def gather_data():
faceDetect1=cv2.CascadeClassifier('frontal_cascade_improved.xml')
faceDetect2=cv2.CascadeClassifier('profilecascade.xml')
# #Input Info
# name = input('Input Name: ')
# position = input('Position/Title: ')
# Generate info later
name = 'Uknown Entity ' + ' Seen ' + configured_datetime
position = 'Unknown Position'
directory_path = (path + '/' + name)
os.makedirs(directory_path, exist_ok=True)
sampleNum = 0
while(True):
video_capture = cv2.VideoCapture(1)
ret,img=video_capture.read()
# gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
faces=faceDetect1.detectMultiScale(img)
for(x,y,w,h) in faces:
sampleNum=sampleNum+1;
cv2.imwrite(directory_path + '/' + str(name) + '.' + str(sampleNum) +'.jpg', img)
cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)
cv2.waitKey(100);
cv2.imshow("Face",img);
cv2.waitKey(1);
if(sampleNum>6):
break;
database_info = Faces(name=name, image_repository=str(directory_path), position=position)
db.session.add(database_info)
db.session.commit()
video_capture.release()
cv2.destroyAllWindows()
def face_recog():
# try:
image_info = Faces.query.all()
known_face_encodings = []
known_face_names = []
#manually set number of images, make it match sampleNum - more images DOESN'T increase recognizability---
for num, person in enumerate(image_info, 1):
# Go thru all iamges - doesn't improve recog
# for i, x in enumerate(range(6), 1):
image_file = str('datasets/' + person.name + '/' + person.name + '.' + str(1) + '.jpg')
print(image_file)
image_base = face_recognition.load_image_file(image_file)
image_encoding = face_recognition.face_encodings(image_base)[0]
known_face_encodings.append(image_encoding)
known_face_names.append(person.name)
# Initialize some variables
face_locations = []
face_encodings = []
face_names = []
process_this_frame = True
while True:
image_info = Faces.query.all()
# Grab a single frame of video
ret, frame = video_capture.read()
# Resize frame of video to 1/4 size for faster face recognition processing
# small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)
# Convert the image from BGR color (which OpenCV uses) to RGB color (which face_recognition uses)
rgb_small_frame = frame
# Only process every other frame of video to save time
if process_this_frame:
# Find all the faces and face encodings in the current frame of video
face_locations = face_recognition.face_locations(rgb_small_frame)
face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)
face_names = []
for face_encoding in face_encodings:
# See if the face is a match for the known face(s)
matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
name = "Unknown"
# If a match was found in known_face_encodings, just use the firsst one.
if True in matches:
first_match_index = matches.index(True)
name = known_face_names[first_match_index]
face_names.append(name)
process_this_frame = not process_this_frame
# Display the results
for (top, right, bottom, left), name in zip(face_locations, face_names):
# Scale back up face locations since the frame we detected in was scaled to 1/4 size
top *= 1
right *= 1
bottom *= 1
left *= 1
if name == 'Unknown':
video_capture.release()
gather_data()
elif 'Entity' in name:
cv2.rectangle(frame, (left, top), (right, bottom), (19, 198, 192), 2)
font = cv2.FONT_HERSHEY_DUPLEX
cv2.putText(frame, name, (left + 30, bottom + 20), font, 0.5, (0, 0, 0), 3)
cv2.putText(frame, name, (left + 30, bottom + 20), font, 0.5, (19, 198, 192), 1)
else:
person = Faces.query.filter_by(name=name).first()
# Draw a box around the face
cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), 2)
# Draw a label and text
cv2.rectangle(frame, (left, bottom - 12), (right, bottom), (0,255, 0), cv2.FILLED)
font = cv2.FONT_HERSHEY_DUPLEX
cv2.putText(frame, name, (left - 7, bottom + 20), font, 0.75, (0, 0, 0), 3)
cv2.putText(frame, name, (left - 7, bottom + 20), font, 0.75, (255, 255, 255), 1)
cv2.putText(frame, person.position, (left - 7, bottom + 45), font, 0.75, (0, 0, 0), 3)
cv2.putText(frame, person.position, (left - 7, bottom + 45), font, 0.75, (255, 255, 255), 1)
# Display the resulting image
cv2.imshow('Video', frame)
# Hit 'q' on the keyboard to quit!
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# Release handle to the webcam
video_capture.release()
cv2.destroyAllWindows()
编辑:固定格式,只是想补充一点,测试各种东西时有多余的代码,但除了通过相机的使用之外,它还可以工作。
解决方案
通过将 video_capture 变量从 face_recog 函数传递给 gather_data 解决了这个问题。因此,除了 face_recog 内部之外,所有对实际视频设备的引用都消失了。一个部分看起来像..
if name == 'Unknown':
gather_data(video_capture)
编辑:哦,我只是在gather_data结束时再次调用face_recog()
推荐阅读
- javascript - Javascript 函数在我创建的函数之后不运行
- windows - 请等待 git 正在初始化
- javascript - 用于角度的 Igx 日历 ui
- c# - Else 语句无法在 while 循环内工作
- c# - 在 Azure 函数中加密服务总线连接字符串
- django - Django Rest FrameWork 中的“many = True”有什么作用?
- javascript - 如何在悬停覆盖图像中包含文本 - 仅限 HTML、CSS、JavaScript
- python - 当我在 Django 上启动服务器时,这个问题怎么办?
- dynamics-crm - crm 2016 按类型代码获取实体逻辑名称?
- excel - VBA 跳转到下一列