树莓派+pythonista实时监控系统

 

客户端(pythonista)

import ui
from PIL import Image
import socket, time, StringIO

global closeFlat
closeFlat = False

def btnStart_tapped(sender):
        global closeFlat
        closeFlat = True
        sender.hidden = True
        

v = ui.load_view()

btnStart = ui.Button(title='End')
btnStart.x = 20
btnStart.y = 250
btnStart.width = 100
btnStart.height = 40
btnStart.background_color = '#a3d6ef'
btnStart.action = btnStart_tapped
v.add_subview(btnStart)

iv = ui.ImageView()
iv.x = 0
iv.y = 0
iv.width = 320
iv.height = 240
v.add_subview(iv)

v.present('sheet')

host, port = '192.168.199.231', 9996
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((host, port))

sock.sendall('next')

f = sock.makefile()

while True:
        msg = f.readline()
        if not msg:
                break
        #print len(msg), msg[-2]
        if closeFlat:
                sock.sendall('close')
                break
        else:
                sock.sendall('next')
        jpeg = msg.replace("\-n", "\n")
        buf = StringIO.StringIO(jpeg[0:-1])
        buf.seek(0)
        #imgg = Image.open(buf)
        #img = ui.Image.from_data(imgg.tostring())
        #imgg.save('1122.jpg')
        img = ui.Image.from_data(buf.getvalue())
        buf.close()
        #img = ui.Image('1122.jpg')
        #img = (ui.Image)imgg
        iv.image = img
        #time.sleep(1)

sock.close() 

 

服务器(树莓派)

import numpy as np
import cv2
import time, socket, StringIO
from PIL import Image

print 'Program start...'

capture = cv2.VideoCapture(0)
capture.set(cv2.cv.CV_CAP_PROP_FRAME_WIDTH, 320)
capture.set(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT, 240)

sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('192.168.199.231', 9996))
sock.listen(2)

dst, dst_addr = sock.accept()
print 'Destination connected by', dst_addr


while True:
    msg = dst.recv(1024)
    print msg
    if msg == 'next': 

        ret, img = capture.read()
        ret, img = capture.read()
        #print img.shape
    
        img[:, :, [0, 2]] = img[:, :, [2, 0]]   
    
        pi = Image.fromstring("RGB", (img.shape[1], img.shape[0]), img.tostring())
        buf = StringIO.StringIO()
        pi.save(buf, format='JPEG')
        jpeg = buf.getvalue()
        buf.close()
        transfer = jpeg.replace("\n", "\-n")
        print len(transfer), transfer[-1]
    
        try:
            dst.sendall(transfer + "\n")
            #print 'sendall complete'
        except Exception as ex:
            dst, dat_addr = sock.accept()
            print 'Destination connected again by', dst_addr
        except KeyboardInterrupt:
            print 'Interrupted'
            break

    elif msg == 'close':
        break
    else:
        print 'Error:The msg from socket is unknow'
        break


dst.close()
sock.close() 
capture.release()
print 'Program end----'

 

转载于:https://www.cnblogs.com/lulu147/p/6803500.html

你可能感兴趣的:(树莓派+pythonista实时监控系统)