python - 使用 OpenCV 出错,程序意外关闭
问题描述
代表https://stackexchange.com/users/17689558/evan-kiffel发帖,因为出于某种原因不会让他发帖(也就是说他每 90 分钟只能发帖一次)
我正在尝试运行形状检测器程序来打开我的网络摄像头并搜索形状。当我这样做时,网络摄像头会打开,但几秒钟后会关闭并打开 mac 错误窗口。如何修复此代码/更改计算机上的某些内容以解决此问题?谢谢您的帮助!
这是错误的样子:错误图像
import cv2
import numpy as np
def nothing(x):
# any operation
pass
cap = cv2.VideoCapture(0)
cv2.namedWindow("Trackbars")
cv2.createTrackbar("L-H", "Trackbars", 0, 180, nothing)
cv2.createTrackbar("L-S", "Trackbars", 66, 255, nothing)
cv2.createTrackbar("L-V", "Trackbars", 134, 255, nothing)
cv2.createTrackbar("U-H", "Trackbars", 180, 180, nothing)
cv2.createTrackbar("U-S", "Trackbars", 255, 255, nothing)
cv2.createTrackbar("U-V", "Trackbars", 243, 255, nothing)
font = cv2.FONT_HERSHEY_COMPLEX
while True:
_, frame = cap.read()
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
l_h = cv2.getTrackbarPos("L-H", "Trackbars")
l_s = cv2.getTrackbarPos("L-S", "Trackbars")
l_v = cv2.getTrackbarPos("L-V", "Trackbars")
u_h = cv2.getTrackbarPos("U-H", "Trackbars")
u_s = cv2.getTrackbarPos("U-S", "Trackbars")
u_v = cv2.getTrackbarPos("U-V", "Trackbars")
lower_red = np.array([l_h, l_s, l_v])
upper_red = np.array([u_h, u_s, u_v])
mask = cv2.inRange(hsv, lower_red, upper_red)
kernel = np.ones((5, 5), np.uint8)
mask = cv2.erode(mask, kernel)
# Contours detection
if int(cv2.__version__[0]) > 3:
# Opencv 4.x.x
contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
else:
# Opencv 3.x.x
_, contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
area = cv2.contourArea(cnt)
approx = cv2.approxPolyDP(cnt, 0.02*cv2.arcLength(cnt, True), True)
x = approx.ravel()[0]
y = approx.ravel()[1]
if area > 400:
cv2.drawContours(frame, [approx], 0, (0, 0, 0), 5)
if len(approx) == 3:
cv2.putText(frame, "Triangle", (x, y), font, 1, (0, 0, 0))
elif len(approx) == 4:
cv2.putText(frame, "Rectangle", (x, y), font, 1, (0, 0, 0))
elif 10 < len(approx) < 20:
cv2.putText(frame, "Circle", (x, y), font, 1, (0, 0, 0))
cv2.imshow("Frame", frame)
cv2.imshow("Mask", mask)
key = cv2.waitKey(1)
if key == 27:
break
cap.release()
cv2.destroyAllWindows()
解决方案
我发现这是一个权限问题。我们可以通过转到终端并使用 sudo 运行程序。
推荐阅读
- gremlin - 无法添加新顶点
- mysql - 制作最准确的数据结构——mySQL
- python - 根据某些值比较两个字典列表
- python - 如何让python在windows CMD中读取和输入内容
- reactjs - 导航栏组件不显示 react-bootstrap CSS
- json - 用于从非结构化 JSON 文件中提取所有特定键值的 Bash 脚本
- android - 使用谷歌 API(或其他)查找距离历史
- c++ - 为什么 C++ 中 if 语句中 long int 范围内的所有可能整数都是“真”,但 0 不是?
- dart - ExpansionPanelList 不展开也不折叠 ExpansionPanel
- android - 如何在 xml 中显示 ChipGroup 中的占位符芯片?