OpenCV - Function to paint text to the Canvas - python

I am detecting a face from the camera and draw a rectangle around it.
Code below:
face_cascade = cv2.CascadeClassifier('face_classifier.xml')
def detect(gray, frame):
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x, y, w, h) in stops: # For each detected face:
cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)
return frame
video_capture = cv2.VideoCapture(0)
while True:
_, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
canvas = detect(gray, frame)
cv2.imshow('Video', canvas)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
Are there any functions in OpenCV that can print text?
When it detects a face on the screen say "Hi"?
Thank you for your time.

Should have done this first before asking the question but after some Googling and trying out a few things, here is the solution:
face_cascade = cv2.CascadeClassifier('face_classifier.xml')
def detect(gray, frame):
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x, y, w, h) in stops: # For each detected face:
cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)
font = cv2.FONT_HERSHEY_COMPLEX_SMALL
cv2.putText(frame,'Hello There!',(x+w, h),font, 0.8,(255,0,0),2,cv2.LINE_AA)
return frame
video_capture = cv2.VideoCapture(0)
while True:
_, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
canvas = detect(gray, frame)
cv2.imshow('Video', canvas)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
This will add "Hello There!" to the top right corner of the detection frame rectangle.

Related

<class 'cv2.CascadeClassifier'> returned a result with an error set

so, I'm trying to code face detection but its not working. this is my code:
import cv2
import sys
cascPath = sys.argv[0]
faceCascade = cv2.CascadeClassifier(cascPath)
video_capture = cv2.VideoCapture(0)
while True:
ret, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
flags=cv2.cv.CV_HAAR_SCALE_IMAGE
)
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
video_capture.release()
cv2.destroyAllWindows()
I'm very new to coding so I don't know if I'm missing something obvious
Change your code as follows:
faceCascade = cv2.CascadeClassifier(cv2.data.haarcascades + cascPath)
This worked for me.

OpenCV Human Body Detection through a webcam - No detections visible

I am trying to detect the human body through OpenCV. The code throws no error. The camera also starts but it is unable to detect anything.
import cv2
classifier = cv2.CascadeClassifier(r'C:\Users\dhruv\Desktop\DataScience\haarcascade_fullbody.xml')
video_captured = cv2.VideoCapture(0)
while (True):
ret, frame = video_captured.read()
frame = cv2.resize(frame,(640,360))
gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# pass the frame to the classifier
persons_detected = classifier.detectMultiScale(gray_frame)
# check if people were detected on the frame
for (x, y, w, h) in persons_detected:
cv2.rectangle(frame, (x,y), (x+w, y+h), (255, 0, 0), 2)
cv2.imshow('Video footage', frame)
if (cv2.waitKey(1) & 0xFF == ord('q')):
break
#cv2.VideoCapture(0).release()
I highly suspect its an indentation error. The camera does start, but your code to draw the bounding boxes of the faces are outside of the loop. Just indent that code. In addition, you'll need to free the camera resource properly or the next time you run the code, the camera will not be able to capture frames properly. I've changed the release call so that it releases the grabbed resource.
import cv2
classifier = cv2.CascadeClassifier(r'C:\Users\dhruv\Desktop\DataScience\haarcascade_fullbody.xml')
video_captured = cv2.VideoCapture(0)
while True:
ret, frame = video_captured.read()
frame = cv2.resize(frame,(640,360))
gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# pass the frame to the classifier
persons_detected = classifier.detectMultiScale(gray_frame)
# check if people were detected on the frame
for (x, y, w, h) in persons_detected:
cv2.rectangle(frame, (x,y), (x+w, y+h), (255, 0, 0), 2)
cv2.imshow('Video footage', frame)
if (cv2.waitKey(1) & 0xFF == ord('q')):
break
video_captured.release() # Changed so that you're releasing the grabbed resource

Webcam window alwasy crash while trying to detect a face

I'm trying to make a simple haar cascade program to detect a face.
faceCascade = cv2.CascadeClassifier('D:\\Python\\Python37\\Lib\\site-packages\\cv2\\data\\haarcascade_frontalcatface.xml')
body_cascade = cv2.CascadeClassifier('haarcascade_upperbody.xml')
video_capture = cv2.VideoCapture(0)
img_counter = 0
while True:
# Capture frame-by-frame
ret, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.5,
minNeighbors=5,
minSize=(30, 30),
flags=cv2.CASCADE_SCALE_IMAGE
)
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.imshow('FaceDetection', frame)
k = input()
# ESC Pressed
if k % 256 == 27:
break
video_capture.release()
cv2.destroyAllWindows()
But every time I launch it, my webcam window just froze and crash :(
My PC is powerful enough for sure, why could it happen?
I have made few changes to your code. For human face use haarcascade_frontalface_default.xml and for the cat face use haarcascade_frontalcatface.xml. Try the code below and it will work like a charm :)
import cv2
#faceCascade = cv2.CascadeClassifier('D:\\Python\\Python37\\Lib\\site-packages\\cv2\\data\\haarcascade_frontalcatface.xml')
faceCascade = cv2.CascadeClassifier('D:\\Python\\Python37\\Lib\\site-packages\\cv2\\data\\haarcascade_frontalface_default.xml')
body_cascade = cv2.CascadeClassifier('haarcascade_upperbody.xml')
video_capture = cv2.VideoCapture(0)
img_counter = 0
while True:
# Capture frame-by-frame
ret, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.5,
minNeighbors=5,
minSize=(30, 30),
flags=cv2.CASCADE_SCALE_IMAGE
)
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.imshow('FaceDetection', frame)
#k = input()
k = cv2.waitKey(1) & 0xFF
if k == 27:
break
# ESC Pressed
# if k % 256 == 27:
# break
video_capture.release()
cv2.destroyAllWindows()

Haar- Cascade face detection OpenCv

I used the following code to detect a face using Haar cascade classifiers provided by OpenCv Python. But the faces are not detected and the square around the face is not drawn. How to solve this?
import cv2
index=raw_input("Enter the index No. : ")
cascPath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascPath)
cap = cv2.VideoCapture(0)
cont=0
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=10,
minSize=(30, 30),
flags = cv2.cv.CV_HAAR_SCALE_IMAGE
)
for (x, y, w, h) in faces:
#cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
# Display the resulting frame
cv2.imshow('frame',frame)
inpt=cv2.waitKey(1)
if inpt & 0xFF == ord('q'):
break
elif inpt & 0xFF == ord('s') :
#name='G:\XCODRA\Integrated_v_01\EigenFaceRecognizer\img2'+index+"."+(str(cont))+".png"
name='IC_image\\'+index+"."+(str(cont))+".png"
resized = cv2.resize(gray,None,fx=200, fy=200, interpolation = cv2.INTER_AREA)
img=cv2.equalizeHist(resized)
cv2.imwrite(name,img)
print cont
cont+=1
Use the full path for the classifier.

How to open an openCV window and a tkinter window together?

I want to control something in a tkinter window by the movement of the detected face from a openCV window. For tkinter window, here is my settings:
def run(width=300, height=300):
root = Tk()
def redrawAllWrapper(canvas, data):
canvas.delete(ALL)
redrawAll(canvas, data)
canvas.update()
def mousePressedWrapper(event, canvas, data):
mousePressed(event, data)
redrawAllWrapper(canvas, data)
def mouseMovedWrapper(event, canvas, data):
mouseMoved(event, data)
redrawAllWrapper(canvas, data)
def keyPressedWrapper(event, canvas, data):
keyPressed(event, data)
redrawAllWrapper(canvas, data)
def timerFiredWrapper(canvas, data):
timerFired(data)
redrawAllWrapper(canvas, data)
# pause, then call timerFired again
canvas.after(data.timerDelay, timerFiredWrapper, canvas, data)
# Set up data and call init
class Struct(object): pass
data = Struct()
data.width = width
data.height = height
data.timerDelay = 50 # milliseconds
init(data)
# create the root and the canvas
# root = Tk()
canvas = Canvas(root, width=data.width, height=data.height)
canvas.pack()
# set up events
root.bind("<B1-Motion>", lambda event: mouseMovedWrapper(event, canvas, data))
timerFiredWrapper(canvas, data)
root.bind("<Button-1>", lambda event:
mousePressedWrapper(event, canvas, data))
root.bind("<Key>", lambda event:
keyPressedWrapper(event, canvas, data))
# and launch the app
root.mainloop() # blocks until window is closed
print("bye!")
run(1000, 750)
About the openCV part is like this:
faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eyeCascade = cv2.CascadeClassifier('haarcascade_eye.xml')
video_capture = cv2.VideoCapture(0)
while True:
# Capture frame-by-frame
ret, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30),
flags=cv2.cv.CV_HAAR_SCALE_IMAGE)
# Draw a rectangle around the faces
for (x, y, w, h) in faces:
# cv2.imread('face2.jpg',1)
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
# img = cv2.imread('face2.jpg',1)
# img = cv2.resize(img, (x,y), fx=0.1, fy=0.1)
# cv2.imshow('img', img)
roi_gray = gray[y:y+h, x:x+w]
roi_color = frame[y:y+h, x:x+w]
eyes = eyeCascade.detectMultiScale(roi_gray, 1.1, 2, minSize=(70, 70), flags=cv2.cv.CV_HAAR_SCALE_IMAGE)
for (x1, y1, w1, h1) in eyes:
cv2.rectangle(roi_color, (x1, y1), (x1+w1, y1+h1), (0, 0, 255), 2)
# Display the resulting frame
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows()
So how can I achieve like that? Can anybody help me?
You can have the openCV script write the (x, y, w, h) to a file and the tkinter script read from that file, and then run both programs at one. Alternatively, you could run both in the same program, but display the openCV images using a tkinter canvas. I coded up the first one, it works for me.
Tkinter code
import Tkinter as tk
import time
import re
root = tk.Tk()
# Canvas to display the rectangle
w = tk.Canvas(root, width=640, height=480)
w.pack()
global rect
rect = None
def UpdateRectangle():
global rect
# Read the rectangle data
fid = open('rect.txt','r')
boundstr = fid.read()
fid.close()
tmp = tuple(int(v) for v in re.findall("[0-9]+", boundstr))
# Rearrange since bbox should be (x1, y1, x2, y2)
bbox = (tmp[0],tmp[1],tmp[0]+tmp[2],tmp[1]+tmp[3],)
# Delete old rectangle
if rect is not None:
w.delete(rect)
# Draw new one
rect = w.create_rectangle(bbox, fill='', outline='blue', width=2)
root.after(200, UpdateRectangle) # every 0.2 seconds...
UpdateRectangle()
root.mainloop()
OpenCV code
import cv2
faceCascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
eyeCascade = cv2.CascadeClassifier('haarcascade_eye.xml')
video_capture = cv2.VideoCapture(0)
while True:
# Capture frame-by-frame
ret, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30),flags=cv2.CASCADE_SCALE_IMAGE)
# Draw a rectangle around the faces
for (x, y, w, h) in faces:
# cv2.imread('face2.jpg',1)
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
# img = cv2.imread('face2.jpg',1)
# img = cv2.resize(img, (x,y), fx=0.1, fy=0.1)
# cv2.imshow('img', img)
roi_gray = gray[y:y+h, x:x+w]
roi_color = frame[y:y+h, x:x+w]
eyes = eyeCascade.detectMultiScale(roi_gray, 1.1, 2, minSize=(70, 70),flags=cv2.CASCADE_SCALE_IMAGE)
for (x1, y1, w1, h1) in eyes:
cv2.rectangle(roi_color, (x1, y1), (x1+w1, y1+h1), (0, 0, 255), 2)
# Write the rectangle data
fid = open('rect.txt','w')
rect = "%d %d %d %d" % (x, y, w, h)
fid.write(rect)
fid.close()
# Display the resulting frame
cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything is done, release the capture
video_capture.release()
cv2.destroyAllWindows()
See Read an image with OpenCV and display it with Tkinter ff you want to display and openCV image file in a Tkinter canvas. You can use the same root.after(command,delay) to make this canvas update as well.

Categories