opencv-python图片转换、尺寸、传输

环境介绍

python 3.7.3
opencv-python 4.4.0.46
numpy 1.19.3

图片转换

opencv读取文件

img1 = cv2.imread('buka.png')

opencv读取中文路径图片

img1 = cv2.imdecode(np.fromfile('buka吧.png', np.uint8), cv2.IMREAD_COLOR)

opencv读取二进制流

bts_1 = open('buka.png', 'rb').read()
img2 = cv2.imdecode(np.frombuffer(bts_1, np.uint8), cv2.IMREAD_COLOR)

opencv读取1d-ndarray

img3 = cv2.imdecode(np.fromfile('buka.png', np.uint8), cv2.IMREAD_COLOR)

opencv读取opencv-encode-bytes

enc_npy_2 = cv2.imencode('.jpg', cv2.imread('buka.png'))[1] # (47184, 1) uint8
bts_2 = enc_npy_2.tobytes()
img_1 = cv2.imdecode(np.frombuffer(bts_2, np.uint8), cv2.IMREAD_COLOR)

opencv读取base64串

b64_1 = base64.b64encode(bts_1).decode('utf8')
b64_2 = base64.b64encode(bts_2).decode('utf8')
img_2 = cv2.imdecode(np.frombuffer(base64.b64decode(b64_2), np.uint8), cv2.IMREAD_COLOR)

opencv读取mat-npy文件

npy_4 = np.save('buka.npy', cv2.imread('buka.jpg'))
img_4 = np.load('buka.npy')

opencv读取1d-ndarray-npy文件

npy_5 = np.save('buka.npy', np.frombuffer(base64.b64decode(b64_2), np.uint8))
img_5 = cv2.imdecode(np.load('buka.npy'), cv2.IMREAD_COLOR)

opencv读取opencv-encode-npy文件

npy_6 = np.save('buka.npy', enc_npy_2)
img_6 = cv2.imdecode(np.load('buka.npy'), cv2.IMREAD_COLOR)

图片尺寸

print(sys.getsizeof(bts_1))  # 160910
print(sys.getsizeof(enc_npy_2))  # 37370
print(sys.getsizeof(bts_2))  # 37291
print(sys.getsizeof(b64_1))  # 214553
print(sys.getsizeof(b64_2))  # 49729
print(sys.getsizeof(img1))  # 631928
print(sys.getsizeof(img_1))  # 631928

图片传输

依据上面尺寸介绍,我们给出下表,从左向右传输成本增大

图片格式\变量类型 bytes (encode-npy) base64 (w*h*c) mat-npy
jpg 37291 37370 49729 631800 631928
png 160910 158k 214553 631800 631928

由表可知,只考虑传输字节长度的情况下:
最优文件流传输,其次base64编码,最次mat-npy文件流

你可能感兴趣的:(人工智能,python,opencv,python,计算机视觉)