python - 在 cv2 代码执行期间,MacOS 相机不可见
问题描述
下面是我的代码,我尝试在 jupyter notebook 上以及通过终端运行我的代码。但是当执行主要功能时,我收到以下错误(附照片)并且相机灯打开。此 python 文件也已形成,但处于无响应状态。当这个 python 文件被强制退出时,相机灯就会关闭。
MacOS 版本 -> MacOS Big Sur 11.0.1
如何修复错误并成功运行代码?
import imutils
import numpy as np
# global variables
bg = None
def run_avg(image, aWeight):
global bg
if bg is None:
image.copy().astype("float")
return
cv2.accumulateWeighted(image, bg, weight)
def segment(image, threshold=25):
global bg
diff = cv2.absdiff(bg.astype("uint8"), image)
thresholded = cv2.threshold(diff, threshold, 255, cv2.THRESH_BINARY)[1]
(_, cnts, _) = cv2.findContours(thresholded.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
if len(cnts) == 0:
return
else:
segmented = max(cnts, key=cv2.contourArea)
return (thresholded, segmented)
if __name__ == "__main__":
# initialize weight for running average
aWeight = 0.5
# get the reference to the webcam
camera = cv2.VideoCapture(0)
# region of interest (ROI) coordinates
top, right, bottom, left = 10, 350, 225, 590
# initialize num of frames
num_frames = 0
# keep looping, until interrupted
while(True):
# get the current frame
(grabbed, frame) = camera.read()
# resize the frame
frame = imutils.resize(frame, width=700)
# flip the frame so that it is not the mirror view
frame = cv2.flip(frame, 1)
# clone the frame
clone = frame.copy()
# get the height and width of the frame
(height, width) = frame.shape[:2]
# get the ROI
roi = frame[top:bottom, right:left]
# convert the roi to grayscale and blur it
gray = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)
gray = cv2.GaussianBlur(gray, (7, 7), 0)
# to get the background, keep looking till a threshold is reached
# so that our running average model gets calibrated
if num_frames < 30:
run_avg(gray, aWeight)
else:
# segment the hand region
hand = segment(gray)
# check whether hand region is segmented
if hand is not None:
# if yes, unpack the thresholded image and
# segmented region
(thresholded, segmented) = hand
# draw the segmented region and display the frame
cv2.drawContours(clone, [segmented + (right, top)], -1, (0, 0, 255))
cv2.imshow("Thesholded", thresholded)
# draw the segmented hand
cv2.rectangle(clone, (left, top), (right, bottom), (0,255,0), 2)
# increment the number of frames
num_frames += 1
# display the frame with segmented hand
cv2.imshow("Video Feed", clone)
# observe the keypress by the user
keypress = cv2.waitKey(1) & 0xFF
# if the user pressed "q", then stop looping
if keypress == ord("q"):
break
# free up memory
camera.release()
解决方案
推荐阅读
- java - 如何在 org.hibernate.type.TimestampType 和 Oracle SYSDATE 之间进行转换?
- internet-explorer - 日期格式在 chrome 中有效,但在 IE11 中无效
- python - 在 pandas DataFrame 中连接不同数量的列表列
- c# - 有没有办法在没有数据库等的情况下将 DataGridView 表保存在 WinForms C# 应用程序中?
- r - R中正则表达式的函数
- java - 我需要知道如何将方法的接口放入When() mockito 方法中
- javascript - 无法更改 innerHTML 属性
- javascript - 在 Puppeteer 中拦截请求时如何修改“表单数据”?
- c# - 在电子邮件正文中发送 pdf 文件
- entity-framework-core - 使用 GroupBy 时出现 System.InvalidOperationException