AttributeError:“模块"对象没有属性"InitFont" [英] AttributeError: 'module' object has no attribute 'InitFont'
问题描述
在Python 2.7 OpenCV 3.2 Windows 10上运行 以下代码引发错误
Run on Python 2.7 OpenCV 3.2 Windows 10 The below code is throwing error
AttributeError:模块"对象没有属性"InitFont"
AttributeError: 'module' object has no attribute 'InitFont'
我的最佳猜测是由于OpenCV 3在以下版本中运行良好.
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()
推荐答案
您不再需要初始化字体. cv
模块已弃用,您需要的所有内容都应来自cv2
.在cv2
api中,图像是数组,因此您无需转换fromarray
.调用putText
函数的语法也有所不同.
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.
在此处查看putText
的文档:这应该为您工作.确保删除程序开头的InitFont
函数.
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)
这是一个最小的工作示例,使用putText
将文本添加到VideoCapture
的帧中:
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()
这篇关于AttributeError:“模块"对象没有属性"InitFont"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!