0

I want to send an image which was imported by opencv imread to another computer via socket. But the data received and the data sent are not equal.

I have converted the numpy array data which I got by imread and converted it to byte array in order to send it via the socket. And then i have converted the byte array which was received at the other end back to the numpy array. But I can't view the image from the received data.

This is the code snippet in the senders end

im = cv2.imread('view.jpg')
stringimage = np.array_str(im)
byteimage = str.encode(stringimage)
sock.sendto(byteimage,("127.0.0.1",5002))

This is the code snippet in the receivers end

byteimage,addr = sock.recvfrom(1024)
decoded = bytes.decode(byteimage)
backstring = np.array(decoded)
cv2.imshow('RealSense', backstring)
cv2.waitKey(0)

I got this error

TypeError: mat data type = 19 is not supported

for this line of code

cv2.imshow('RealSense', backstring)

Update

After getting the suggestions bellow and referring some other materials I have come up with a solution which is working for my scenario.

Image senders side

#color_image is my opencv image

retval, data = cv2.imencode('.jpg', color_image, ENCODE_PARAMS)
b64_bytes = base64.b64encode(data)
b64_string = b64_bytes.decode()
sock.sendto(str.encode(b64_string), ("127.0.0.1", 5002))

Image receivers side

data, addr = sock.recvfrom(60000)
img = imread(io.BytesIO(base64.b64decode(data)))

Please tell me if there is any bad coding in my solution

2 Answers2

2

A similar question was helpfully answered here.

The issue is that constructing the numpy array from a string doesn't parse the data as a float/int the way you wrote it (and converting to a string to send the data is unnecessary).

Here's a simplified example to apply that solution:

import numpy as np
from io import BytesIO

a = np.array([1, 2])
b = BytesIO()
np.save(b, a)

"""-----send the data-----"""
# send(b.getvalue())


data = BytesIO(b.getvalue())
c = np.load(data)
print(a)
print(c)

Resulting in:

[1 2]
[1 2]
Katerina
  • 174
  • 7
1

byteimage,addr = sock.recvfrom(1024)

This limits your buffer size to 1024 bytes.

Read docs

Roy2511
  • 938
  • 1
  • 5
  • 22
  • I suspect the `np.array_str` command is the root of the issue. But all this is unnecessary. It seems like you want to send the image from one socket to another. See [this answer](https://stackoverflow.com/questions/51921631/how-to-send-and-receive-webcam-stream-using-tcp-sockets-in-python) – Roy2511 Nov 08 '19 at 06:41
  • Thank you for note that point out. I have increased the buffer size to 256,000 bytes . But the issue remains same. My image size is 71,470 bytes – Malith Prasanna Rathnasena Nov 08 '19 at 06:43
  • I had to compress the image and increase the buffer size in order to send the image. Thank you for the suggestion. – Malith Prasanna Rathnasena Nov 14 '19 at 00:31