树莓派用Python写几个简单程序4:socket的使用

本文详细介绍了如何使用Python中的socket模块在服务器端接收并显示来自客户端摄像头的实时图像,包括服务器端和客户端的代码实现及解决常见错误的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用socket 传递摄像头图像到pc。

确定安装好opencv和python后,确定自己作为服务器端设备ip:

首先是服务器端:

import socket
import cv2
import numpy

<pre name="code" class="python">address = ('local ip',8002)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind(address)
s.listen(True)

def recvall(sock, count): buf = b'' while count: newbuf = sock.recv(count) if not newbuf: return None buf += newbuf count -= len(newbuf) return bufconn, addr = s.accept()while 1: length = recvall(conn,16) stringData = recvall(conn, int(length)) data = numpy.fromstring(stringData, dtype='uint8') decimg=cv2.imdecode(data,1) cv2.imshow('SERVER',decimg) cv2.waitKey(10) s.close()cv2.destroyAllWindows()

然后是客户端:

import socket
import cv2
import numpy
 <pre name="code" class="python">capture = cv2.VideoCapture(0)
ret, frame = capture.read()
address = ('local ip',8002)sock = socket.socket()sock.connect(address)encode_param=[int(cv2.IMWRITE_JPEG_QUALITY),90]while ret: result, imgencode = cv2.imencode('.jpg', frame, encode_param) data = numpy.array(imgencode) stringData = data.tostring() sock.send( str(len(stringData)).ljust(16)); sock.send( stringData ); ret, frame = capture.read() #decimg=cv2.imdecode(data,1) #cv2.imshow('CLIENT',decimg) cv2.waitKey(10)sock.close()cv2.destroyAllWindows()

出现下面这个问题,

Traceback (most recent call last):
  File "client.py", line 12, in <module>
    sock.connect((TCP_IP, TCP_PORT))
  File "C:\Python27\lib\socket.py", line 228, in meth
    return getattr(self._sock,name)(*args)
socket.error: [Errno 10061]
要确认 local ip是服务器端的ip,

ip在window的cmd中可以ipconfig查看;在linux中可以ifconfig查看。




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值