0

我需要帮助在 IP 摄像机拍摄的图像上加上时间戳,我制作了一个将图像保存为本地文件的代码版本,然后 opencv 在上面写入,现在我想在上面写入而不保存之前,但我被困住了。这是代码:

import requests
import time
import shutil
import os
from requests.auth import HTTPBasicAuth
import cv2
from datetime import datetime
from datetime import 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), stream = True)
    resp_raw = response.raw

    if response.status_code == 200:

        # DEFINE TIMESTAMP
        current_date = str(date.today())
        current_time = datetime.now().strftime("%H:%M:%S")
        timestamp = (current_date + " | " + current_time)

        with open(path, 'wb') as out_file:
            shutil.copyfileobj(response.raw, out_file)
            img = np.asarray(bytearray(resp_raw.read()), 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)
    else:
        print("Connection failed")


    time.sleep(3)

    if os.path.exists(path):
            os.remove(path)
            print("image removed")
            time.sleep(2)

输出是:

cv2.error: OpenCV(4.5.2) C:\Users\runneradmin\AppData\Local\Temp\pip-req-build-m8us58q4\opencv\modules\imgcodecs\src\loadsave.cpp:736: error: (-215:Assertion failed) !buf.empty() in function 'cv::imdecode_'

请帮助我,对不起简单的英语

4

2 回答 2

0

您的错误表明,当您尝试使用 imdecode() 将数组解码为 img 时,缓冲区为空。

这意味着在上一行中:

img = np.asarray(bytearray(resp_raw.read()), dtype="uint8")

resp_raw.read() 给你一个空数组。

我会分析您使用 Postman 之类的工具执行的 GET 请求,或者只是尝试打印 resp_raw 的内容,因为它似乎没有返回图像。

于 2021-05-24T09:49:47.697 回答
-1

我解决了,我只是重新做了定义 resp_raw 的请求,我这样做了:

response = requests.get(url, auth=HTTPBasicAuth(user, psw), stream = True)
resp_raw = requests.get(url, auth=HTTPBasicAuth(user, psw), stream = True).raw

而不是这个:

response = requests.get(url, auth=HTTPBasicAuth(user, psw), stream = True)
resp_raw = response.raw
于 2021-05-24T13:27:07.780 回答