How to Fix : AttributeError 'module' object has no attribute 'CV_FONT_HERSHEY_SIMPLEX'

This bug usually happens when we want to insert a text inside a window when using the OpenCV library.

How to Fix : AttributeError 'module' object has no attribute 'CV_FONT_HERSHEY_SIMPLEX'

Photo by alleksana on Pexels

The main reason why your IDE show you this Error is because there is a little difference between Python 2 and Python 3 when you try to call certain OpenCV functions.

Python 2:

cv2.CV_FONT_HERSHEY_SIMPLEX

Python 3:

cv2.FONT_HERSHEY_SIMPLEX

Tip: using autocomplete python tools (Kite, Jedi, Wing, Finisher ...etc) will help you avoid such errors.

Now let's try to use that OpenCV function in a real example to insert some text inside a window showing our webcam stream:

import cv2
 
cap = cv2.VideoCapture(2)
fps = cap.get(cv2.CAP_PROP_FPS)
while True:
    ret, img = cap.read()
    cv2.putText(img,str(fps) + " fps", (5, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, 255,2) #0.5 is the font size , 255 the font color and 2 the thickness of the text
    cv2.imshow('Window',img)
 
 
    if cv2.waitKey(1) == 13:
        break
 
cap.release()
cv2.destroyAllWindows()