乘着空闲时间想做一个基于树莓派的监控,所以第一步就需要实现树莓派的摄像功能。
我这里用到的是树莓派盗版的摄像头(CSI接口摄像头),在淘宝上购买的价格也就在30RMB左右,很便宜。
个人博客:https://www.xiaokai1999.cn/
一、树莓派的摄像头操作
1.查看是否加载到了对应的video device设备:
ls /dev/
可以看到在里面没有看到vedio device,如果有的话会有vedioX(X={0,1,2,3…})
2.使能树莓派摄像头
sudo raspi-config
选择Interfacing Option
,选中Select然后Enter进入;
接下来机会问你是否同意使能Pi camera,选择是然后会让你重启,选择 “是”
3、重启完之后,看看/dev下面是否存在摄像头设备:
ls -al /dev/ | grep video
如果有vedio device 就可以确定没有问题了。
4.拍摄照片
raspistill -o new.jpg
5.查看照片
xdg-open new.jpg
二、远程流视频传输1(python实现)
主机.py
import cv2
import socket
import numpy as np
cap = cv2.VideoCapture(0)
s = socket.socket()
img_param = [int(cv2.IMWRITE_JPEG_QUALITY), 95]#opencv 图像清晰度,帧数
port = 12345
s.bind(("192.168.229.129",port)) #绑定ip地址和端口
s.listen(5) #等待客户机连接
c,addr = s.accept() #接受客户机连接
while True:
ret,frame = cap.read()
frame = cv2.resize(frame, (320,230))
print("连接地址:"+addr[0])
_, img_encode = cv2.imencode('.jpg', frame, img_param)#opencv图像编码
img_code = np.array(img_encode)
img_data = img_code.tostring()#将数组格式转为字符串格式
print(img_data)
c.send(bytes(str(len(img_data)).ljust(16),encoding="utf8"))# 先发送数据的长度
c.send(img_data)#再发送数据内容
cv2.imshow("主机",frame)
if cv2.waitKey(1)==27:
c.close()
break
客户机.py
import socket
import cv2
import numpy as np
import gzip
def recv_all(s,count):
buf=bytes()
while count:
newbuf = s.recv(count)
if not newbuf:return None
buf+=newbuf
count-=len(newbuf)
return buf
s = socket.socket()
host = socket.gethostname()
port = 12345
while True:
try:
s.connect(("192.168.229.129",port))
except:
print("有错误")
else:
break
while True:
data_len = recv_all(s,16)
if len(data_len) == 16:
stringData = recv_all(s, int(data_len))
data = np.fromstring(stringData, dtype='uint8')
tmp = cv2.imdecode(data, 1) # 解码处理,返回mat图片
img = cv2.resize(tmp, (320, 230))
print(img)
cv2.imshow('客户机', img)
if cv2.waitKey(1) == 27:
break
s.close()
效果
缺点
我程序不够完善,只实现了一发一接,能实现一发多接就完美了。但是这种方法会比较麻烦。