Help us understand the problem. What is going on with this article?

PythonとOpenCVで動画送信

More than 1 year has passed since last update.

環境

  • Python 3.5.2
  • OpenCV 3.1
server.py
# -*- coding:utf-8 -*-
# !/usr/bin/python

import socketserver
import cv2
import socket
import sys
import numpy


class TCPHandler(socketserver.BaseRequestHandler):
    videoCap = ''

    # リクエストを受け取るたびに呼ばれる関数
    def handle(self):
        # クライアントからデータを受け取ったらJPEG圧縮した映像を文字列にして送信
        self.data = self.request.recv(1024).strip()

        # readするたびにビデオのフレームを取得
        ret, frame = videoCap.read()

        # jpegの圧縮率を設定 0~100値が高いほど高品質。何も指定しなければ95
        encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 100]

        # 文字列に変換
        jpegsByte = cv2.imencode('.jpeg', frame, encode_param)[1].tostring()
        self.request.send(jpegsByte)


# このプログラムを起動している端末のIPアドレス
HOST = "192.168.0.100"
PORT = 5569

# ビデオの設定
videoCap = cv2.VideoCapture('C:\test.mp4')

if not videoCap:
    print ("ビデオが開けませんでした。")
    sys.exit()

socketserver.TCPServer.allow_reuse_address = True
server = socketserver.TCPServer((HOST, PORT), TCPHandler)

try:
    server.serve_forever()
except KeyboardInterrupt:
    pass
server.shutdown()
sys.exit()
client.py
# -*- coding:utf-8 -*-
#!/usr/bin/python
import socket  
import numpy  
import cv2  


def getimage():

    # 送信先のIPアドレスとポート番号を設定
    HOST = "192.168.0.100"
    PORT = 5569
    sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)  
    sock.connect((HOST,PORT))   
    sock.send(b'test')  

    # バイト型
    buf=b''   
    recvlen=100  
    while recvlen>0:  
        receivedstr=sock.recv(1024*8)  
        recvlen=len(receivedstr)  
        buf += receivedstr
    sock.close()

    narray=numpy.fromstring(buf,dtype='uint8')
    return cv2.imdecode(narray,1)

while True:  
    img = getimage()
    cv2.imshow('Capture',img)  

    # qを入力すれば処理終了
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away