python socket传输摄像头画面

实现两台机器之间传输摄像头画面。其中服务端拍摄画面并传输,客户端接收再显示。

传输方法用了之前的socket传输图片。视频就是连续的图片。摄像头画面的采集使用opencv。

1,服务端:

#!/usr/bin/env python
# -*- coding=utf-8 -*-

import socket
import numpy as np
import urllib
import cv2 as cv
import threading
import time


print('this is Server')

cap = cv.VideoCapture(0)
cap.set(cv.CAP_PROP_FRAME_WIDTH, 260)
cap.set(cv.CAP_PROP_FRAME_HEIGHT, 200)

def socket_service():
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        # 防止socket server重启后端口被占用(socket.error: [Errno 98] Address already in use)
        s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        #s.bind(('127.0.0.1', 6666))
        s.bind(('192.168.203.134', 6666))#这个是服务端机器的ip
        s.listen(10)
    except socket.error as msg:
        print (msg)
        sys.exit(1)
    print ('Waiting connection...')

    while True:
        conn, addr = s.accept()
        t = threading.Thread(target=deal_data, args=(conn, addr))
        t.start()

def deal_data(conn, addr):
    print ('Accept new connection from {0}'.format(addr))
    while True:
        # get a frame
        ret, frame = cap.read()
        # '.jpg'表示把当前图片img按照jpg格式编码,按照不同格式编码的结果不一样
        img_encode = cv.imencode('.jpg', frame)[1] 
        data_encode = np.array(img_encode)
        str_encode = data_encode.tostring()
        encode_len = str(len(str_encode))
        print('img size : %s'%encode_len)
        try:
            conn.send(str_encode)#发送图片的encode码
        except Exception as e:
            print(e)
        time.sleep(0.1)
    conn.close()

socket_service()

2,客户端:

#!/usr/bin/env python
# -*- coding=utf-8 -*-

import socket
import numpy as np
import urllib
import cv2
import threading
import time


def socket_client():
    try:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.connect(('192.168.203.134', 6666))#连接服务端
    except socket.error as msg:
        print (msg)
        sys.exit(1)
    #c_sock, c_addr =s.accept()
    print('this is Client')
    while True:
        try:
            receive_encode = s.recv(77777)#接收的字节数 最大值 2147483647 (31位的二进制)
            nparr = np.fromstring(receive_encode, dtype='uint8')
            img_decode = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
            cv2.imshow("Client_show", img_decode)
            cv2.waitKey(1)
        except Exception as e:
            print(e)
        

socket_client()

效果图:

 注:

这次在之前的基础上加了try语句,避免偶然的故障导致程序退出。错误提示不太懂。个人理解是,传输建立的时候可能会有些问题,之后传输的过程中也可能会有小概率的错误,表现出来的可能就是画面卡顿,但并不是致命影响。

你可能感兴趣的:(python,服务器,socket,opencv)