I know this question came up already a couple of times and I read it all ( I hope...) But in my programm I can't display the image after I have send it through the socket no matter what I try.
I am using Python 2.7 on client side and Python 3.4 on server side
Here is the code:
Server:
pygame.init()
pygame.camera.init()
cam = pygame.camera.Camera("/dev/video0",(640,480),'RGB')
cam.start()
host='192.168.0.11'
port=8080
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((host,port))
image = cam.get_raw()
data_64 = base64.b64encode(image)
data_utf = data_64.decode('utf-8')
print (data_utf)
print (len(data_utf))
s.sendall(data_utf)
s.close
Client:
host='192.168.0.11'
port=8080
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host,port))
s.listen(1)
conn, addr = s.accept()
string = ''
while True:
d = conn.recv(640*480)
if not d:
break
else:
d = d.decode('UTF-8')
string += d
print (string)
print (len(string))
fh = open("imageToSave.jpeg", "wb")
fh.write(string)
fh.close()
In the end I tried different formats (.png, .gif, etc.) but none will show me an acutal picture. The programm creates an image file with data in it but I can't open it or see a picture.
Both strings are equal according to the prints and the len(). The lenghts is 819200. So it seems the transfer is correct becaus it is the same string. The question is how do I get a picture out of the string?
My plan is to feed the webcam stream into a Tkinter gui.
I also tried things like pygame.image.tostring(image, "RGB") on server side and pygame.image.fromstring(string,(640,480),"RGB") But here I always get an "ValueError: String length does not equal format and resolution size" no matter what I try.
I am quite new to Python so maybe I did something a little complicated. Can somebody point me in the right direction? For days I am stuck here.
Ok I figured it out myself. With the code below it works. Apperantly I had some troubles with formatting the string in a correct way.
Client:
pygame.init()
pygame.camera.init()
cam = pygame.camera.Camera("/dev/video0",(300,300),'RGB')
cam.start()
image = cam.get_image()
print = cam.get_size()
img_str = pygame.image.tostring(img,"RGB")
host='192.168.0.11'
port=8080
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((host,port))
s.sendall(img_str)
s.close
Host:
host='192.168.0.11'
port=8080
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host,port))
s.listen(1)
conn, addr = s.accept()
string = bytes('','UTF-8')
while True:
d = conn.recv(640*480)
if not d:
print ("break")
break
else:
string += d
pil_image = Image.fromstring("RGB",(352,288),string)
#(352,288) is the return of cam.get_size()