使用socket 傳遞網路攝影機映像到pc。
確定安裝好opencv和python後,確定自己作為伺服器端裝置ip:
首先是伺服器端:
import socketimport cv2import 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 socketimport cv2import 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查看。