3 This program is demonstration for face and object detection using haar-like features. 4 The program finds faces in a camera image or video stream and displays a red box around them. 6 Original C implementation by: ? 7 Python implementation by: Roman Stanchak, James Bowman 8 Updated: Copyright (c) 2016, Tal Regev. 13 from optparse
import OptionParser
16 import sensor_msgs.msg
17 from cv_bridge
import CvBridge
35 if __name__ ==
'__main__':
38 haarfile =
'/usr/share/opencv/haarcascades/haarcascade_frontalface_alt.xml' 40 parser = OptionParser(usage =
"usage: %prog [options]")
41 parser.add_option(
"-c",
"--cascade", action=
"store", dest=
"cascade", type=
"str", help=
"Haar cascade file, default %default", default = haarfile)
42 parser.add_option(
"-t",
"--topic", action=
"store", dest=
"topic", type=
"str", help=
"Topic to find a face on, default %default", default =
'/camera/rgb/image_raw')
43 parser.add_option(
"-ct",
"--ctopic", action=
"store", dest=
"ctopic", type=
"str", help=
"Compressed topic to find a face on, default %default", default =
'/camera/rgb/image/compressed')
44 (options, args) = parser.parse_args()
46 cascade = cv2.CascadeClassifier()
47 cascade.load(options.cascade)
51 img = br.imgmsg_to_cv2(imgmsg,
"bgr8")
53 new_size = (int(img.shape[1] / image_scale), int(img.shape[0] / image_scale))
56 gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
59 small_img = cv2.resize(gray, new_size, interpolation = cv2.INTER_LINEAR)
61 small_img = cv2.equalizeHist(small_img)
64 faces = cascade.detectMultiScale(small_img, haar_scale, min_neighbors, haar_flags, min_size)
66 for (x, y, w, h)
in faces:
69 pt1 = (int(x * image_scale), int(y * image_scale))
70 pt2 = (int((x + w) * image_scale), int((y + h) * image_scale))
71 cv2.rectangle(img, pt1, pt2, (255, 0, 0), 3, 8, 0)
73 cv2.imshow(
"result", img)
77 img = br.compressed_imgmsg_to_cv2(compressed_imgmsg,
"bgr8")
79 new_size = (int(img.shape[1] / image_scale), int(img.shape[0] / image_scale))
82 gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
85 small_img = cv2.resize(gray, new_size, interpolation = cv2.INTER_LINEAR)
87 small_img = cv2.equalizeHist(small_img)
90 faces = cascade.detectMultiScale(small_img, haar_scale, min_neighbors, haar_flags, min_size)
92 for (x, y, w, h)
in faces:
95 pt1 = (int(x * image_scale), int(y * image_scale))
96 pt2 = (int((x + w) * image_scale), int((y + h) * image_scale))
97 cv2.rectangle(img, pt1, pt2, (255, 0, 0), 3, 8, 0)
99 cv2.imshow(
"compressed_result", img)
102 rospy.init_node(
'rosfacedetect')
103 rospy.Subscriber(options.topic, sensor_msgs.msg.Image, detect_and_draw)
104 rospy.Subscriber(options.ctopic, sensor_msgs.msg.CompressedImage, compressed_detect_and_draw)
def detect_and_draw(imgmsg)
def compressed_detect_and_draw(compressed_imgmsg)