Python中如何获取OpenCV生成的图像流字节大小?
获取JPG图像流的字节数方法
有几种简单的方法能拿到你这个JPG图像流的字节数:
方法一:直接从编码结果获取(最高效)
你不需要先把编码结果放进BytesIO再计算,cv2.imencode返回的第二个元素是numpy数组,直接用它的属性或转成bytes后取长度就行:
image = cv2.imread('test.png', 0) # 先拿到编码结果 encode_result = cv2.imencode(".jpg", image)[1] # 方式1:用numpy数组的nbytes属性 byte_count = encode_result.nbytes # 方式2:转成bytes后取长度 byte_count = len(encode_result.tobytes())
方法二:从已创建的BytesIO对象获取
如果已经创建了image_stream这个BytesIO对象,也可以直接从它身上获取字节数:
import io import cv2 image = cv2.imread('test.png', 0) image_stream = io.BytesIO(cv2.imencode(".jpg", image)[1].tobytes()) # 方式1:直接调用tell()(此时流的指针在末尾,tell()返回的就是总字节数) byte_count = image_stream.tell() # 方式2:获取缓冲区的字节数 byte_count = image_stream.getbuffer().nbytes # 要是之前移动过流的指针,先把指针移到末尾再tell() image_stream.seek(0, 2) # 参数2表示移动到流的末尾 byte_count = image_stream.tell()
内容的提问来源于stack exchange,提问作者granular_bastard
相关产品推荐
相关产品推荐

