Computer Vision OpenCV (F) Adding Text

Previously, we captured the size of the video stream image by default, and we can also capture the size of the video stream by parameter configuration.

import cv2

cap = cv2.VideoCapture(0)
print(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
print(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

while(cap.isOpened()):
    ret, frame = cap.read()
    if ret == True:
        
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        cv2.imshow('frame',gray)

        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        break
cap.release()
cv2.destroyAllWindows()

The width and height of video stream can be set by CV2 constant, cv2.CAP_PROP_FRAME_WIDTH corresponds to bit integer 3 and CAP_PROP_FRAME_HEIGHT corresponds to integer 4, so the height of video stream can also be specified by 3,4.

cap.set(cv2.CAP_PROP_FRAME_WIDTH,640)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT,480)

Add text (time) to the video stream

import cv2

cap = cv2.VideoCapture(0)
# print(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
# print(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))

cap.set(cv2.CAP_PROP_FRAME_WIDTH,640)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT,480)

while(cap.isOpened()):
    ret, frame = cap.read()
    if ret == True:
        
        font = cv2.FONT_HERSHEY_SIMPLEX
        text = 'Width: ' + str(cap.get(3)) + ' Height: ' + str(cap.get(4))
        frame = cv2.putText(frame,text,(10,50),font,1,(0,255,255),2,cv2.LINE_AA)
        # gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        cv2.imshow('frame',frame)

        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        break
cap.release()
cv2.destroyAllWindows()

Font is used to specify the font for displaying text. We add text to the picture by putText method. The first parameter is the image resource, the second parameter is the position of the text, the next parameter is the size of the text, which is controlled by a scale value (zoom value). Here, we specify 1, (0, 255, 255) the color of the text, then parameter 2 is the width of the line, and finally LINE_AA. It's the type of line.


chart
      datet = str(datetime.datetime.now())
        frame = cv2.putText(frame,datet,(10,50),font,1,(0,255,255),2,cv2.LINE_AA)
        # gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
chart

Posted by besly98 on Fri, 04 Oct 2019 18:54:59 -0700