想实现局域网下不同设备的视频流通信,决定采用socket实现,由于socket无法直接实现图片通讯,采用将编码的字符串写入文件再读取写出拿来模拟socket通信,在解码端代码一直报bug,请求指点
编码段
import cv2
import win32gui
from PIL import ImageGrab
import numpy as np
im = cv2.imread('bus.jpg')
img_encode = cv2.imencode('.jpg', im,[cv.IMWRITE_JPEG_QUALITY, 50])[1]
data_encode = np.array(img_encode)
image_binary = data_encode.tobytes() # transform bytes stream
#send_data = "send".encode('utf-8') + (len(image_binary)).to_bytes(4, byteorder='little') + image_binary
send_data=str(image_binary)
with open('img_encode.txt', 'w') as f:
f.write(send_data)
f.flush
解码端
import cv2
import numpy as np
with open('img_encode.txt', 'r') as f:
str_encode = f.read()
str_encode = bytes(str_encode,encoding='utf-8')
image_np = np.frombuffer(str_encode, np.uint8) # transform image to np.uint8 format
image = cv2.imdecode(image_np, cv2.IMREAD_COLOR) # decode image to the type of opencv
cv2.imshow("img_decode",image)
cv2.waitKey(0)
报错内容
Traceback (most recent call last):
File "C:\Users\pc\Desktop\new\decode.py", line 11, in <module>
cv2.imshow("img_decode",image)
cv2.error: OpenCV(4.5.4) D:\a\opencv-python\opencv-python\opencv\modules\imgproc\src\color.cpp:182: error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor'