You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
19 lines
804 B
19 lines
804 B
import cv2
|
|
import base64
|
|
def frame_to_base64(frame, format="JPEG"):
|
|
"""将 OpenCV 读取的图片帧转换为 Base64 编码的字符串"""
|
|
# 将图片帧编码为 JPEG 或 PNG 格式
|
|
if format.upper() == "JPEG":
|
|
encode_param = [int(cv2.IMWRITE_JPEG_QUALITY), 80] # JPEG 压缩质量
|
|
elif format.upper() == "PNG":
|
|
encode_param = [int(cv2.IMWRITE_PNG_COMPRESSION), 9] # PNG 压缩级别
|
|
else:
|
|
raise ValueError("Unsupported format. Use 'JPEG' or 'PNG'.")
|
|
|
|
result, encoded_frame = cv2.imencode(f".{format.lower()}", frame, encode_param)
|
|
if not result:
|
|
raise ValueError("Failed to encode frame.")
|
|
|
|
# 将编码后的字节流转换为 Base64 字符串
|
|
base64_string = base64.b64encode(encoded_frame).decode("utf-8")
|
|
return base64_string
|