蔡承諺
蔡承諺

Reputation: 31

cv2 has no attribute data

The code is from a book which teaching OpenCV. I ran the code but it always showing error.

import cv2 
casc_path = cv2.data.haarcascades + "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(casc_path)
faceCascade = cv2.CascadeClassifier(casc_path)
faces = faceCascade.detectMultiScale(image, scaleFactor=1.1, minNeighbors=5, minSize=(30,30), flags = cv2.CASCADE_SCALE_IMAGE)
imgheight=image.shape[0]
imgwidth=image.shape[1] 
cv2.rectangle(image, (10,imgheight-20), (110,imgheight), (0,0,0), -1)
cv2.putText(image,"Find " + str(len(faces)) + " face!", (10,imgheight-5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,255,255), 2)
for (x,y,w,h) in faces:
    cv2.rectangle(image,(x,y),(x+w, y+h),(128,255,0),2)

cv2.namedWindow("facedetect")
cv2.imshow("facedetect", image)
cv2.waitKey(0)  
cv2.destroyWindow("facedetect")

And the error is here.

File "K:/pyCharm_object/OpevCV.py", line 2, in <module>
casc_path = cv2.data.harrcascades + "harrcascade_frontalface_default.xml"
AttributeError: module 'cv2' has no attribute 'data'

Upvotes: 3

Views: 13809

Answers (4)

SamYoda
SamYoda

Reputation: 31

pip install opencv-contrib-python --upgrade 

As suggested by @Ruli in the comments has resolved this problem for me.

Upvotes: 3

Anupama Gautam
Anupama Gautam

Reputation: 9

Just find your location of haarcascade_frontalface_default.xml by searching in file explorer. Then copy the path of the required xml file and paste path in raw form:

casc_path = (r"**your path**\haarcascade_frontalface_default.xml")

Example:

casc_path = (r"C:\Users\User_name\miniconda3\pkgs\libopencv-4.5.3-py39h4b6fd43_5\Library\etc\haarcascades\haarcascade_frontalface_default.xml")

This worked for me. :)

Upvotes: -1

Are you confident about the openCV package you have installed? If you have the

opencv-contrib-python package you shouldn't be looking at that error.

Upvotes: -1

alecxe
alecxe

Reputation: 474191

OpenCV comes with and knows where to look for the pre-trained classifiers.

You could omit that line and simply do:

faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')

Upvotes: 5

Related Questions