OpenCV直接为IP摄像头图像加时间戳imdecode报错求解
错误原因
- 你在代码中先执行了
shutil.copyfileobj(response.raw, out_file),已经把HTTP响应流的全部内容读取并写入了本地文件,此时resp_raw的文件指针已经移动到流末尾,后续调用resp_raw.read()只能拿到空字节数组,传给cv2.imdecode时就触发了缓冲区为空的断言报错。 - 此外你当前的代码逻辑还是保留了预先写本地文件的步骤,并没有实现你要的跳过落盘直接在流上处理的需求。
修复后的代码
import requests import time import os from requests.auth import HTTPBasicAuth import cv2 from datetime import datetime, date import numpy as np url = 'http://192.168.0.138/image.jpg?cidx=366981845' user = '****' psw = '****' path = 'ipCameraScreen.png' font = cv2.FONT_HERSHEY_SIMPLEX position = (20, 30) color = (255, 255, 255) font_size = 0.5 font_stroke = 1 while True: response = requests.get(url, auth=HTTPBasicAuth(user, psw)) if response.status_code == 200: # 生成时间戳 current_date = str(date.today()) current_time = datetime.now().strftime("%H:%M:%S") timestamp = f"{current_date} | {current_time}" # 直接从响应内容解码图像,全程内存操作,不提前写本地 img = np.asarray(bytearray(response.content), dtype="uint8") img = cv2.imdecode(img, cv2.IMREAD_COLOR) # 添加时间戳后保存 cv2.putText(img, timestamp, position, font, font_size, color, font_stroke) cv2.imwrite(path, img) print("Screen saved, path:", path) time.sleep(3) # 不需要删除图片可以注释掉下面这段逻辑 if os.path.exists(path): os.remove(path) print("image removed") time.sleep(2) else: print("Connection failed") time.sleep(3)
修改说明
- 直接读取
response.content获取完整的图片二进制数据,不需要操作raw流,避免流指针偏移导致读空的问题 - 图像解码、添加时间戳全程在内存中完成,完全跳过了预先保存原始图片到本地的步骤,符合你的需求
- 省略了冗余的流复制、重复落盘逻辑,运行效率更高
内容的提问来源于stack exchange,提问作者Lorenzo_inirapmoC
相关产品推荐
相关产品推荐

