我在python中使用库pygame将视频从RasberryPi的网络摄像头传输到我的电脑。 但我收到图像时遇到问题。它没有转换真实的图像。 这是我的代码:
服务器:
import socket,os
from PIL import *
import pygame,sys
import pygame.camera
from pygame.locals import *
#Create server:
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server.bind(("192.168.2.100",5000))
server.listen(5)
#Start Pygame
pygame.init()
pygame.camera.init()
screen = pygame.display.set_mode((320,240))
cam = pygame.camera.Camera("/dev/video0",(320,240),"RGB")
cam.start()
#Send data
while True:
s,add = server.accept()
print "Connected from",add
image = cam.get_image()
screen.blit(image,(0,0))
data = cam.get_raw()
s.sendall(data)
pygame.display.update()
#Interupt
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
客户端:
import socket,sys
import pygame
from PIL import Image
#Create a var for storing an IP address:
ip = "192.168.2.100"
#Start PyGame:
pygame.init()
screen = pygame.display.set_mode((320,240))
pygame.display.set_caption('Remote Webcam Viewer')
font = pygame.font.SysFont("Arial",14)
clock = pygame.time.Clock()
timer = 0
previousImage = ""
image = ""
#Main program loop:
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
#Receive data
if timer < 1:
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client_socket.connect((str(ip),5000))
data = client_socket.recv(1024000)
timer = 30
else:
timer -= 1
previousImage = image
#Convert image
try:
image = Image.fromstring("RGB",(120,90),data)
image = image.resize((320,240))
image = pygame.image.frombuffer(image.tostring(),(320,240),"RGB")
#Interupt
except:
image = previousImage
output = image
screen.blit(output,(0,0))
clock.tick(60)
pygame.display.flip()
但这是转移后的结果:
答案 0 :(得分:0)
您正在重新组合收到的原始数据中的图像,但由于您要发送的是您正在重新创建的更高分辨率,因此像素会溢出&#39;创造这种效果。
违规行是:
image = Image.fromstring("RGB",(120,90),data)
应该是:
image = Image.fromstring("RGB",(320,240),data)
*未经测试但应该有效。