Notes:
- Again, I'm using argparse. The IP address now has to be the server's address, not the client's!
- The client receives the image data, puts it into a PIL Image object, and then crops it to a square and resizes it to the dimensions of the Unicorn Hat (16 x 16).
- If the --debug flag was used, the original and cropped/resized image are saved to files.
- The client keeps sending requests to the server as fast as it can (which is not very fast given the other work it's doing).
If I run the client with the command below, the current webcam image is displayed on the Unicorn Hat (updating about twice a second) until I press CTRL-C.
pi@pibow:~/Python/camclient $ ./image-client.py -i 192.168.1.106
The code
#!/usr/bin/env python3
import sys
import socket
import argparse
import unicornhathd as uhat
from PIL import Image
from io import BytesIO
parser = argparse.ArgumentParser(description='Image client.')
parser.add_argument('--hostip', '-i', action='store', dest='address',
default='127.0.0.1', help='IP address of server host.')
parser.add_argument('--port', '-p', action='store', type=int, dest='port',
default=12345, help='Port number.')
parser.add_argument('--debug', '-d', action='store_true', default=False,
dest='debug', help='Print debugging information.')
args = parser.parse_args()
width, height = uhat.get_shape()
uhat.brightness(0.5)
while True:
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as sock:
try:
sock.connect((args.address, args.port))
data = b''
while True:
received = sock.recv(4096)
if not received: break
data = data + received
sock.close()
im = Image.open(BytesIO(data))
imx, imy = im.size
mindim = min(imx, imy)
xdiff = (imx - mindim)/2
ydiff = (imy - mindim)/2
im.crop((xdiff, ydiff, xdiff+mindim, ydiff+mindim))
if args.debug: im.save('original.jpg')
im = im.resize((width, height), Image.LANCZOS)
if args.debug: im.save('resized.jpg')
for x in range(width):
for y in range(height):
pixel = im.getpixel((x, y))
(r, g, b) = [pixel[i] for i in range(3)]
uhat.set_pixel(x, y, r, g, b)
uhat.show()
except Exception as e:
print(e)
uhat.off()
sys.exit()
except KeyboardInterrupt:
uhat.off()
sys.exit()
No comments:
Post a Comment