OpenCv code throws segmentation error(core dumped)

2019-09-06 03:52发布

问题:

I'm beginner learning opencv from the official documentation http://docs.opencv.org/trunk/doc/py_tutorials/py_gui/py_video_display/py_video_display.html#display-video

import numpy as np        
import cv2    

cap = cv2.VideoCapture(0)      
while(True):    
    ret, frame = cap.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    cv2.imshow('frame',gray)
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

It's giving me error "Segmentation fault (core dumped)" Can anyone please tell me Why is that happening and how to resolve that issue?
Thanks in advance.

回答1:

Maybe its a little late but what "user3154952" says is true, when you are working with the C++ api you don't need to use the release method, it is already in the video capture Destructor.

This is the code i tested and worked fine:

import sys
import cv2

cap = cv2.VideoCapture(0)

while(1):
    ret,frame = cap.read()
    gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    cv2.imshow('frame',gray)
    if cv2.waitKey(1) & 0xFF == 27:
        break

cv2.destroyAllWindows()

Update: i have been messing around with my ps3 eye and i've realized that with that camera you get the segmentation error for using only the destroyAllWindows method, to fix that i replaced the destroyAllWindows method with the release method and worked fine, i don't know exactly why that happened i'm just sharing in case someone get that issue. I hope that was helpful.