Raspberry Pi 相机和 Python 脚本在检测对象崩溃时崩溃
Raspberry Pi Camera and Python Script Crashes while detecting Objects Crashes
我写了一段代码来检测我家发生的任何类型的入侵,如果检测到任何类型的对象,就会形成边界框,然后需要执行进一步的操作。当我在我的设备的摄像头(笔记本电脑摄像头)上测试代码时,它工作正常。但是当我 运行 Raspberry Pi 3B 上带有摄像头模块(非 USB 摄像头)的同一段代码时,它崩溃并且脚本停止执行。
我在此处附上代码片段
import cv2
import numpy as np
cv2.namedWindow("Preview")
cam = cv2.VideoCapture(0)
while cam.isOpened():
ret, frame1 = cam.read()
ret, frame2 = cam.read()
diff = cv2.absdiff(frame1,frame2)
grey = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(grey, (5, 5), 0)
_, thresh = cv2.threshold(blur, 20, 255,cv2.THRESH_BINARY)
dilated = cv2.dilate(thresh, None, iterations=3)
contours, _ = cv2.findContours(dilated, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for c in contours:
if cv2.contourArea(c) >= 10000:
x,y,w,h = cv2.boundingRect(frame1)
cv2.rectangle(frame1,(x,y),(x+w,y+h), (0,255,0),3)
else:
continue
if not ret:
break
cv2.imshow("Preview", frame1)
if cv2.waitKey(10)==ord('q'):
break
cam.release()
cv2.destroyAllWindows()
我收到的错误消息是
x,y,w,h = cv2.boundingRect(frame1)
cv2.error: OpenCV(4.4.0) /tmp/pip-wheel-ggn8r4df/opencv-contrib-python_52a54d5431f647899265a8f5082f7e73/opencv/modules/imgproc/src/shapedescr.cpp:1044: error: (-215:Assertion failed) img.depth() <= CV_8S && img.channels() == 1 in function 'maskBoundingRect'
感谢@toyata Supra。错误已解决,程序按预期执行。
解决方案:
x,y,w,h = cv2.boundingRect(c)
我写了一段代码来检测我家发生的任何类型的入侵,如果检测到任何类型的对象,就会形成边界框,然后需要执行进一步的操作。当我在我的设备的摄像头(笔记本电脑摄像头)上测试代码时,它工作正常。但是当我 运行 Raspberry Pi 3B 上带有摄像头模块(非 USB 摄像头)的同一段代码时,它崩溃并且脚本停止执行。
我在此处附上代码片段
import cv2
import numpy as np
cv2.namedWindow("Preview")
cam = cv2.VideoCapture(0)
while cam.isOpened():
ret, frame1 = cam.read()
ret, frame2 = cam.read()
diff = cv2.absdiff(frame1,frame2)
grey = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY)
blur = cv2.GaussianBlur(grey, (5, 5), 0)
_, thresh = cv2.threshold(blur, 20, 255,cv2.THRESH_BINARY)
dilated = cv2.dilate(thresh, None, iterations=3)
contours, _ = cv2.findContours(dilated, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
for c in contours:
if cv2.contourArea(c) >= 10000:
x,y,w,h = cv2.boundingRect(frame1)
cv2.rectangle(frame1,(x,y),(x+w,y+h), (0,255,0),3)
else:
continue
if not ret:
break
cv2.imshow("Preview", frame1)
if cv2.waitKey(10)==ord('q'):
break
cam.release()
cv2.destroyAllWindows()
我收到的错误消息是
x,y,w,h = cv2.boundingRect(frame1)
cv2.error: OpenCV(4.4.0) /tmp/pip-wheel-ggn8r4df/opencv-contrib-python_52a54d5431f647899265a8f5082f7e73/opencv/modules/imgproc/src/shapedescr.cpp:1044: error: (-215:Assertion failed) img.depth() <= CV_8S && img.channels() == 1 in function 'maskBoundingRect'
感谢@toyata Supra。错误已解决,程序按预期执行。
解决方案:
x,y,w,h = cv2.boundingRect(c)