标签:
使用socket 传递摄像头图像到pc。
确定安装好opencv和python后,确定自己作为服务器端设备ip:
首先是服务器端 server.py:
import socket import cv2 import numpy address = (‘127.0.0.1‘, 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 buf conn, 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) if cv2.waitKey(10) == 27: break s.close() cv2.destroyAllWindows()
然后是客户端 client.py:
import socket import cv2 import numpy address = (‘127.0.0.1‘, 8002) sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) sock.connect(address) capture = cv2.VideoCapture(0) ret, frame = capture.read() 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) if cv2.waitKey(10) == 27: break sock.close() cv2.destroyAllWindows()
调试过程出现下面这个问题,一般是ip不对,要把‘127.0.0.1‘改为服务器端的ip,
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]
若在window的cmd中可以ipconfig查看ip;
若在linux中可以ifconfig查看ip。
标签:
原文地址:http://my.oschina.net/RagingTyphoon/blog/492950