I am currently receiving frames from a socket in Python and the image type being received is bytes. The image is then saved to a directory. As below:
from socket import *
import cv2
port = 9999
s = socket(AF_INET, SOCK_STREAM)
s.bind(('', port))
s.listen(1)
conn, addr = s.accept()
print("Connected by the ",addr)
with open('/home/Desktop/frame/my_image.png', 'wb') as file:
while True:
data = conn.recv(1024*8)
if not data: break
file.write(data)
conn.close()
However, what I want to do actually is instead of having to read the image from the saved directory, I would like to directly convert the bytes to image and display it before having to save and open the image.
Code now fully works:
from socket import *
import datetime
import cv2
import PIL.Image as Image
from PIL import ImageFile, Image
import io
import base64
import numpy as np
import pickle
date_string = datetime.datetime.now().strftime("%Y-%m-%d-%H:%M")
port = 9999
s = socket(AF_INET, SOCK_STREAM)
s.bind(('', port))
s.listen(1)
conn, addr = s.accept()
img_dir = '/home/Desktop/frames_saved/'
img_format = '.png'
b=bytearray()
print("Connected by the ",addr)
with open(img_dir+date_string+img_format, 'wb') as file:
while True:
data = conn.recv(1024*1024*1)
if not data: break
file.write(data)
b += data
conn.close()
ImageFile.LOAD_TRUNCATED_IMAGES = True
image = Image.open(io.BytesIO(b))
image.show()