Reputation: 439
I'm really new to OpenCV but I need to find a way to detect faces using a webcam. I have found following code from here. This is the original code. I'm using Python 2.7
and opencv 3.0.0-beta
version and Windows 8.1.
import cv2 as cv
import time
import Image
def DetectFace(image, faceCascade):
min_size = (20,20)
image_scale = 2
haar_scale = 1.1
min_neighbors = 3
haar_flags = 0
grayscale = cv.CreateImage((image.width, image.height), 8, 1)
smallImage = cv.CreateImage(
(
cv.Round(image.width / image_scale),
cv.Round(image.height / image_scale)
), 8 ,1)
cv.CvtColor(image, grayscale, cv.CV_BGR2GRAY)
cv.Resize(grayscale, smallImage, cv.CV_INTER_LINEAR)
cv.EqualizeHist(smallImage, smallImage)
faces = cv.HaarDetectObjects(
smallImage, faceCascade, cv.CreateMemStorage(0),
haar_scale, min_neighbors, haar_flags, min_size)
if faces:
for ((x, y, w, h), n) in faces:
pt1 = (int(x * image_scale), int(y * image_scale))
pt2 = (int((x + w) * image_scale), int((y + h) * image_scale))
cv.Rectangle(image, pt1, pt2, cv.RGB(255, 0, 0), 5, 8, 0)
return image
capture = cv.CaptureFromCAM(0)
faceCascade = cv.Load("haarcascades/haarcascade_frontalface_alt.xml")
while (cv.WaitKey(15)==-1):
img = cv.QueryFrame(capture)
image = DetectFace(img, faceCascade)
cv.ShowImage("face detection test", image)
cv.ReleaseCapture(capture)
When I was running this program I've got errors saying, No module named Image. I commented it and run again and did following changes to the code.
capture = cv.CaptureFromCAM(0)
to capture = cv.VideoCapture(0)
and
WaitKey
to waitKey
according to the errors popped up.
But now it says AttributeError: 'module' object has no attribute 'QueryFrame'
I think there is a version problem or something. I've already included haarcascades
files as well. Please help me to correct that error and run this code well. As I mention I'm a fresher to opencv.
Upvotes: 0
Views: 11115
Reputation: 7036
In cv2
, you use:
result, img = capture.read() #capture is a cv2.VideoCapture instance
instead of QueryFrame
.
You can also queue a frame for capture using
capture.grab()
followed by
result, img = capture.retrieve()
to actually retrieve it. Use this second method if you want to queue up a frame, then do other stuff while you wait for it.
Edit:
You clearly are just trying to run a bunch of OpenCV1 functions using OpenCV2, and are going to have a lot of problems if you don't read the OpenCV2 documentation to know what functions have changed and what hasn't. StackOverflow isn't a "convert this old code" service, so I'm not going to go through every single old function in your program.
However, to answer your follow up question, in OpenCV2 it is recommended to just create images using the numpy.zeros()
function (as opposed to the old cv.CreateImage
function).
Upvotes: 4
Reputation: 3077
cv2 does not have a method QueryFrame, it is located in cv.
import cv
img = cv.QueryFrame(capture)
Upvotes: 0