树莓派用python打开摄像头常用两种方法,一种是使用picamare库,另一种是使用OpenCV的库,本文分别介绍两种方式
1.代码如下:
from picamera import PiCamera import time camera = PiCamera() camera.start_preview() time.sleep(10) camera.stop_preview()
此方法注意如果使用VNC远程运行,会出现原画面有图像,但VNC无图像的情况,此时需要在树莓派端的VNC内修改VNC的模式,由传输指令变更为传输画面,但VNC会非常卡顿,慎用。解决方式参考这篇文章
树莓派远程连接工具VNC不显示视频或摄像头画面解决方式
#!/usr/bin/python # -*- coding: utf-8 -*- """ 机器人摄像头测试demo 1.打开摄像头画面; 2.按键q退出程序,s保存照片 3.可作为程序基础框架使用 """ __author__ = "River.Yang" __date__ = "2021/3/24" __version__ = "1.0" from picamera.array import PiRGBArray from picamera import PiCamera import cv2 # define resolution resX = 640 resY = 480 def main(): # 照片存储序列计数 count = 0 # 版本管理 print("当前版本:", __version__) # 初始化摄像头 camera = PiCamera() camera.resolution = (resX, resY) camera.framerate = 30 # Use this as our output rawCapture = PiRGBArray(camera, size=(resX, resY)) # capture frames from the camera for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True): image = frame.array # show the frame cv2.imshow("Raw Frame", image) # if the `q` key was pressed, break from the loop key = cv2.waitKey(1) & 0xFF if key == ord("q"): break if key == ord("s"): count = count + 1 cv2.imwrite("testbak" + str(count) + ".jpg", image) print("save success") # clear the stream in preparation for the next frame rawCapture.truncate(0) # When everything done, release the capture cv2.destroyAllWindows() if __name__ == '__main__': main()
.
.
.
.
欢迎各位老铁一键三连,本号后续会不断更新树莓派、人工智能、STM32、ROS小车相关文章和知识。
大家对感兴趣的知识点可以在文章下面留言,我可以优先帮大家讲解哦
原创不易,转载请说明出处。