python虚拟环境下使用opencv操作摄像头

使用摄像头实例:

#coding:utf-8

import cv2

def video_capture():
    camera = cv2.VideoCapture(0)

    while (True):
        ret, frame = camera.read()

        if ret == True:
            image = cv2.cvtColor(frame,  cv2.COLOR_BGR2GRAY)
            cv2.imshow("image", image)

            if cv2.waitKey(1) & 0xFF == ord('q'):
                break
        else:
            print("Camera read return None")
            break

    if camera.isOpened() == False:
        print("Can not Open Camera")

    camera.release()
    cv2.destroyAllWindows()


if __name__ == '__main__':
    video_capture()

系统未安装python-opencv的情况下,

import cv2 

会出现ImportError,但是如果使用如下操作安装opencv-python(opencv API)

pip install opencv-python 

引入cv2时不会出现错误,但是摄像头会出问题,具体问题体现如下:
- read()返回的ret永远为False,frame永远为None
- camera.isOpened()返回永远为False
- cvtColor,imshow等错误

总结:opencv使用摄像头时,tensorflow环境需要卸载opencv-python并安装python-opencv

pip uninstall opencv-python
sudo apt install python-opencv

你可能感兴趣的:(python,摄像头,opencv,tensorflow,tensorflow)