1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
|
import numpy as np
import cv2
import socket
from PIL import Image as Img
from PIL import ImageTk
from tkinter import*
import tkinter
#import threading
class Application(object):
def __init__(self, host, port):
""" Initialize application which uses OpenCV + Tkinter. It displays
a video stream in a Tkinter window """
self.server_socket = socket.socket()
self.server_socket.bind((host, port))
self.server_socket.listen(0)
self.connection, self.client_address = self.server_socket.accept()
self.connection = self.connection.makefile('rb')
self.host_name = socket.gethostname()
self.host_ip = socket.gethostbyname(self.host_name)
self.video_loop()
def video_loop(self):
""" Get frame from the video stream and show it in Tkinter """
try:
print("Host: ", self.host_name + ' ' + self.host_ip)
print("Connection from: ", self.client_address)
print("Streaming...")
print("Press 'q' to exit")
# need bytes here
stream_bytes = b' '
while True:
stream_bytes += self.connection.read(1024)
first = stream_bytes.find(b'\xff\xd8')
last = stream_bytes.find(b'\xff\xd9')
if first != -1 and last != -1:
jpg = stream_bytes[first:last + 2]
stream_bytes = stream_bytes[last + 2:]
image = cv2.imdecode(np.frombuffer(jpg, dtype=np.uint8), cv2.IMREAD_COLOR)
cv2.imshow('image', image)
# Rearrang the color channel
b, g, r = cv2.split(image)
image = cv2.merge((r, g, b))
root = tkinter.Tk() # initialize root window
longueur = 1080
hauteur = 700
root.geometry('%dx%d' % (longueur, hauteur))
im = Img.fromarray(image) # convert image for PIL
imgtk = ImageTk.PhotoImage(image=im) # convert image for tkinter
panel = tkinter.Label(root)
panel.pack()
panel.config(image=imgtk) # show the image
if cv2.waitKey(1) & 0xFF == ord('q'):
break
finally:
self.connection.close()
self.server_socket.close()
def destructor(self):
root.destroy()
cv2.destroyAllWindows() # it is not mandatory in this application
if __name__ == '__main__':
# host, port
h, p = "192.168.0.14", 8000
Application(h, p)
root.mainloop()
#thread = threading.Thread(target=video_loop, args=(1,))
#thread.start() |
Partager