prosper patel
prosper patel

Reputation: 23

AttributeError: 'module' object has no attribute 'InitFont'

Run on Python 2.7 OpenCV 3.2 Windows 10 The below code is throwing error

AttributeError: 'module' object has no attribute 'InitFont'

My best guess is due to OpenCV 3 as it was working fine in below version.

import cv2
import numpy as np

recognizer = cv2.face.createLBPHFaceRecognizer()
recognizer.load('trainner/trainner.yml')
cascadePath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascadePath);


cam = cv2.VideoCapture(0)
font = cv2.InitFont(cv2.CV_FONT_HERSHEY_SIMPLEX, 1, 1, 0, 1, 1)
while True:
    ret, im =cam.read()
    gray=cv2.cvtColor(im,cv2.COLOR_BGR2GRAY)
    faces=faceCascade.detectMultiScale(gray, 1.2,5)
    for(x,y,w,h) in faces:
        cv2.rectangle(im,(x,y),(x+w,y+h),(225,0,0),2)
        Id, conf = recognizer.predict(gray[y:y+h,x:x+w])
        if(conf<50):
            if(Id==1):
                Id="Prosper"

        else:
            Id="Unknown"
        cv2.cv.PutText(cv2.cv.fromarray(im),str(Id), (x,y+h),font, 255)
    cv2.imshow('im',im) 
    if cv2.waitKey(10) & 0xFF==ord('q'):
        break
cam.release()
cv2.destroyAllWindows()

Upvotes: 2

Views: 12785

Answers (2)

HariRHK
HariRHK

Reputation: 11

This is the another way to handle the error.

cv2.putText(img,text,(x,y+h),cv2.FONT_HERSHEY_SIMPLEX, 1,(255,255,255))

Upvotes: 0

alkasm
alkasm

Reputation: 23012

You no longer need to initialize the font; the cv module is deprecated, everything you need should come from cv2. In the cv2 api, images are arrays, so you don't need to convert fromarray. The syntax is a bit different for calling the putText function as well.

See the documentation for putText here: http://docs.opencv.org/3.0-beta/modules/imgproc/doc/drawing_functions.html#cv2.putText

This should work for you. Be sure to delete the InitFont function in the beginning of your program.

fontface = cv2.FONT_HERSHEY_SIMPLEX
fontscale = 1
fontcolor = (255, 255, 255)
cv2.putText(im, str(Id), (x,y+h), fontface, fontscale, fontcolor) 

Edit: Here's a minimal working example adding text onto frames from VideoCapture using putText:

import cv2
import numpy as np

cam = cv2.VideoCapture(0)

fontFace = cv2.FONT_HERSHEY_SIMPLEX
fontScale = 1
fontColor = (255, 255, 255)

ret, im = cam.read()
locy = int(im.shape[0]/2) # the text location will be in the middle
locx = int(im.shape[1]/2) #           of the frame for this example

while True:
    ret, im = cam.read()
    cv2.putText(im, "Success!", (locx, locy), fontFace, fontScale, fontColor) 
    cv2.imshow('im', im)
    if cv2.waitKey(10) & 0xFF==ord('q'):
        break

cam.release()
cv2.destroyAllWindows()

Upvotes: 3

Related Questions