我做了一个用当前时间发送曲面的例子。在
(Pygame无法使用我的相机)。在
它使用struc.pack()在发送图像之前发送图像大小始终为4字节。所以客户机首先接收4个字节并具有图像大小。然后它就可以利用这些信息来接收图像。在
两者都使用循环发送/接收所有时间。在
服务器.py#!/usr/bin/env python
import pygame
from threading import Thread
import socket
import struct # to send int
as 4 bytes
import time # for test
- constants –
ADDRESS = (“localhost”, 12801)
SURFACE_SIZE = (640, 480)
WHITE = (255, 255, 255)
BLACK = ( 0, 0, 0)
GREEN = ( 0, 255, 0)
- classes –
class Streaming(Thread):
def init(self):
Thread.init(self)
pygame.init()
pygame.camera.init()
self.cam = pygame.camera.Camera(“/dev/video0”, SURFACE_SIZE)
self.cam.start()
create surface to imitate camera image
self.image = pygame.Surface(SURFACE_SIZE)
self.image_rect = self.image.get_rect()
create font to display text on surface
self.font = pygame.font.Font(None, 50)
def get_image(self):
emulate cam.get_image()
get current time as string
current_time = time.strftime(‘%H:%M:%S.%s’)
render surface with text (and center it)
text = self.font.render(current_time, True, BLACK, GREEN)
text_rect = text.get_rect(center=self.image_rect.center)
clear image and put new text
self.image.fill(WHITE)
self.image.blit(text, text_rect)
return self.image
def run(self):
s = socket.socket()
solution for: “socket.error: [Errno 98] Address already in use”
s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
s.bind(ADDRESS)
s.listen(1)
print(“Wait for connection”)
try:
sc, info = s.accept()
print(“Video client connected:”, info)
while True:
get image surface
image = self.cam.get_image()
image = self.get_image()
convert surface to string
img_str = pygame.image.tostring(image, ‘RGB’)
print(‘len:’, len(img_str))
send string size
len_str = struct.pack(‘!i’, len(img_str))
sc.send(len_str)
send string image
sc.send(img_str)
wait
time.sleep(0.5)
except Exception as e:
print(e)
finally:
exit
print(“Closing socket and exit”)
sc.close()
s.close()
pygame.quit()
- main –
Streaming().run()
客户端.py
^{pr2}$
Original: https://blog.csdn.net/weixin_35901475/article/details/112827969
Author: DDoS.Me
Title: pygame python3.5_Python3.5通过套接字发送对象(Pygame cam图像)
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/784216/
转载文章受原作者版权保护。转载请注明原作者出处!