树莓派:python3通过usb摄像头拍照并通过socket传到PC机
程序员文章站
2022-04-24 11:09:09
...
首先,树莓派要能够使用摄像头,具体使用树莓派完成拍照参照以下两位作者的博客。
https://blog.csdn.net/NCTU_to_prove_safety/article/details/64923572 @ NCTU_to_prove_safety
https://blog.csdn.net/weixin_42828324/article/details/81938977 @ 淹不死的狐狸
server.py
# -*- coding: UTF-8 -*-
from imageai.Prediction import ImagePrediction
import socket
import os
import sys
import struct
import time
def socket_service():
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(('192.168.1.178', 6666))
s.listen(10)
except socket.error as msg:
print(msg)
sys.exit(1)
print("Wait")
while True:
sock, addr = s.accept()
deal_data(sock, addr)
break
s.close()
def deal_data(sock, addr):
print("Accept connection from {0}".format(addr))
while True:
fileinfo_size = struct.calcsize('128sl')
buf = sock.recv(fileinfo_size)
if buf:
filename, filesize = struct.unpack('128sl', buf)
fn = filename.decode().strip('\x00')
new_filename = os.path.join('./', 'new_' + fn)
recvd_size = 0
fp = open(new_filename, 'wb')
while not recvd_size == filesize:
if filesize - recvd_size > 1024:
data = sock.recv(1024)
recvd_size += len(data)
else:
data = sock.recv(1024)
recvd_size = filesize
fp.write(data)
fp.close()
sock.close()
break
if __name__ == '__main__':
socket_service()
Client.py
import socket
import time
import os
import sys
import struct
def sock_client():
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('192.168.1.178', 6666))
except socket.error as msg:
print(msg)
print(sys.exit(1))
while True:
#filepath = input('input the file: ')
os.system("fswebcam -S 10 image2.jpg")
time.sleep(1)
filepath = 'image2.jpg'
fhead = struct.pack(b'128sl', bytes(os.path.basename(filepath).encode('utf-8')), os.stat(filepath).st_size)
s.send(fhead)
print('client filepath: {0}'.format(filepath))
fp = open(filepath, 'rb')
while 1:
data = fp.read(1024)
if not data:
print('{0} file send over...'.format(filepath))
break
s.send(data)
s.close()
break
if __name__ == '__main__':
sock_client()