Search code examples
pythonimageopencvraw

OpenCV put text on raw files


I need help to put a timestamp on images taken by an IP camera, I made a version of the code that save the image as a local file, then opencv write on it, now i'd like to write on it without saving it before, but i'm stucked. This is the code:

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)

The output is:

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_'

Plz help me and sorry for easy english


Solution

  • I solved, i just re-did the request to define resp_raw, i did this:

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

    instead of this:

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