我们从Python开源项目中,提取了以下40个代码示例,用于说明如何使用cv2.CASCADE_SCALE_IMAGE。
def _detectFace(self, imgPath): img = cv2.imread(imgPath) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) rects = self.cc.detectMultiScale(gray, scaleFactor=1.2, minNeighbors=2, \ minSize=(30, 30), flags = cv2.CASCADE_SCALE_IMAGE) if not len(rects): self.errorLogger.writeMsg("%s\n" % imgPath) return for rect in rects: rect[2:] += rect[:2] self.successLogger.writeMsg("%s\n" % imgPath) ''' boundingbox format: left right top bottom ''' self.boundingboxFile.writeMsg("%s %s %s %s %s\n" % \ (imgPath, str(rect[0]), str(rect[2]), str(rect[1]), str(rect[3])))
def detect(self, img): gray = self._process_img(img) for cascade in [self.cascade, self.cascade_profile]: faces = cascade.detectMultiScale(img, scaleFactor=self.scale, minNeighbors=2, minSize=(30, 30), flags = cv2.CASCADE_SCALE_IMAGE) if len(faces) > 0: faces[:,2:] += faces[:,:2] common.non_max_suppression(faces, 0.5) true_faces = [] not_faces = [] for rect in faces: #hard negative svm predict processed = hard_negative.process(img[rect[1]:rect[3], rect[0]:rect[2]]) processed_hog = np.transpose(self.hog.compute(processed)) results = self.svm.predict(processed_hog) results_profile = self.svm_profile.predict(processed_hog) if results[1].ravel()[0] == 1 or results_profile[1].ravel()[0] == 1: true_faces.append(rect) else: not_faces.append(rect) return (true_faces, not_faces) return ([], [])
def detect_face(img): global position_x, position_y, width, high gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) face = face_cascade.detectMultiScale( image=gray, scaleFactor=1.2, minNeighbors=2, minSize=(30, 30), flags=cv2.CASCADE_SCALE_IMAGE ) for (x, y, w, h) in face: cv2.rectangle(img, (position_x, position_y), (position_x + width, position_y + high), (0, 255, 0), 2) position_x = x position_y = y width = w high = h
def does_opencv_detect_face_correctly(image, face_bounding_box, cascade_classifier): detections = cascade_classifier.detectMultiScale( image, scaleFactor=1.3, minNeighbors=4, minSize=(30, 30), flags=cv2.CASCADE_SCALE_IMAGE) # There should be exactly one face detection in image if len(detections) != 1: return False else: left, top, width, height = detections[0] detection_bounding_box = shapely.geometry.box(left, top, left + width, top + height) is_detection_correct = face.geometry.get_intersection_over_union( face_bounding_box, detection_bounding_box) > 0.5 return is_detection_correct
def detectFaces(image_path): """ Open the image based on the image_path and find all faces in the image. Finally, return the coordinates , width and height as a list """ img = cv2.imread(image_path) face_cascade = cv2.CascadeClassifier("cvdata\\haarcascades\\haarcascade_frontalface_default.xml") if img.ndim == 3: gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) else: gray = img faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=3, minSize=(10,10), flags=cv2.CASCADE_SCALE_IMAGE) result = [] for (x,y,width,height) in faces: result.append((x,y,x+width,y+height)) return result
def detect_faces(image): face_cascade1 = cv2.CascadeClassifier(XML_PATH1) if image.ndim == 3: gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) else: gray = image faces = face_cascade1.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=3, minSize=(10,10), flags=cv2.CASCADE_SCALE_IMAGE) result=[] for (x,y,width,height) in faces : result.append((x,y,x+width,y+height)) return result
def track(self, image,i): faceRects = self.faceCascade.detectMultiScale(image, scaleFactor = 1.1, minNeighbors = 10, minSize = (40, 40), flags = cv2.CASCADE_SCALE_IMAGE ) rects = [] faceROI=[] for (fX, fY, fW, fH) in faceRects: if(i<25): i=i+1 else: i=0 fH=fW faceROI.append (image[fY:fY + fH, fX:fX + fW]) rects.append((fX, fY, fX + fW, fY + fH)) return rects,i,faceROI
def face_image_slot(self, face_image, label: int): eyes = self._eye_classifier.detectMultiScale(face_image, scale_factor=1.3, minNeighbors=3, flags=cv2.CASCADE_SCALE_IMAGE) if len(eyes) > 2: # TODO: error? signal? return face_image = CropFace(face_image, eyes[0], eyes[1]) try: self._images[label].append(face_image) except KeyError: self._images[label] = [face_image,]
def detect_face(raw_image): face = face_detector.detectMultiScale(raw_image, scaleFactor=1.1, minNeighbors=10, minSize=(5, 5), flags=cv2.CASCADE_SCALE_IMAGE) if len(face) == 1: return face else: return ""
def detect_faces(emotion): files = glob.glob("datasets/sorted_dataset/%s/*" %emotion) # Get list of all images with emotion filenumber = 0 for f in files: frame = cv2.imread(f) # Open image gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Convert image to grayscale # Detect face using 4 different classifiers face = faceDet.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=10, minSize=(5, 5), flags=cv2.CASCADE_SCALE_IMAGE) face2 = faceDet2.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=10, minSize=(5, 5), flags=cv2.CASCADE_SCALE_IMAGE) face3 = faceDet3.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=10, minSize=(5, 5), flags=cv2.CASCADE_SCALE_IMAGE) face4 = faceDet4.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=10, minSize=(5, 5), flags=cv2.CASCADE_SCALE_IMAGE) # Go over detected faces, stop at first detected face, return empty if no face. if len(face) == 1: facefeatures = face elif len(face2) == 1: facefeatures == face2 elif len(face3) == 1: facefeatures = face3 elif len(face4) == 1: facefeatures = face4 else: facefeatures = "" # Cut and save face for (x, y, w, h) in facefeatures: # Get coordinates and size of rectangle containing face print "Face detected in file: %s" %f gray = gray[y:y+h, x:x+w] # Cut the frame to size try: out = cv2.resize(gray, (350, 350)) # Resize face so all images have same size cv2.imwrite("datasets/faces_dataset/%s/%s.jpg" %(emotion, filenumber), out) # Write image except: pass # If error, pass file filenumber += 1 # Increment image number
def main(FLAG): Model = SimpleModel(FLAG.input_dim, FLAG.hidden_dim, FLAG.output_dim, optimizer=tf.train.RMSPropOptimizer(FLAG.learning_rate), using_gpu=False) image_path = sys.argv[1] cascPath = "./haarcascade_frontalface_default.xml" faceCascade = cv2.CascadeClassifier(cascPath) image = cv2.imread(image_path) src_height, src_width, src_channels = image.shape gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) faces = faceCascade.detectMultiScale( gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30), flags = cv2.CASCADE_SCALE_IMAGE ) for x, y, w, h in faces: print("faceLocation : ({},{}), width={}, height={}".format(x,y,w,h)) cropped_image = gray[x:x+w, y:y+h] resized_image = imresize(cropped_image, (FLAG.Width, FLAG.Height)) resized_image = resized_image.flatten() / 255 pred_feature = Model.predict(resized_image).flatten() pred_feature[::2] = pred_feature[::2] * w + x pred_feature[1::2] = pred_feature[1::2] * h + y result_img = draw_features_point_on_image(image, [pred_feature], src_width, src_height) print(pred_feature) for (x, y, w, h) in faces: cv2.rectangle(result_img, (x, y), (x+w, y+h), (0, 255, 0), 1) cv2.imshow('Result', result_img) cv2.imwrite("./result_img.png", result_img) cv2.waitKey(0) cv2.destroyAllWindows()
def detect(img, cascade): """ ???????????? :param img: ?????? :param cascade: ??????? :return: ?????? """ rects = cascade.detectMultiScale(img, scaleFactor=1.3, minNeighbors=4, minSize=(30, 30), flags=cv2.CASCADE_SCALE_IMAGE) if len(rects) == 0: return [] rects[:,2:] += rects[:,:2] return rects
def function_second(): ret, image=camera.read() # gray = cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) gray = cv2.cvtColor(image,cv2.COLOR_RGB2GRAY) # faces = face_cascade.detectMultiScale(gray, 1.3, 4) faces = face_cascade.detectMultiScale(gray, scaleFactor=1.3, minNeighbors=3, minSize=(30,30), flags=cv2.CASCADE_SCALE_IMAGE) print "Found "+str(len(faces))+" face(s)" #Draw a rectangle around every found face for (x,y,w,h) in faces: cv2.rectangle(image,(x,y),(x+w,y+h),(255,0,0),2) if len(faces)>=1: send_message_to_clients(str(len(faces))+" Visitors") cv2.imwrite('/home/pi/visitor_project/result.jpg',image) gt=datetime.now().strftime('%Y-%m-%d- %H:%M:%S - ') m="log-"+gt+str(len(faces))+" Visitors" f.write("\n"+m) tornado.ioloop.IOLoop.instance().add_timeout(timedelta(seconds=1), function_second)
def face_areas(self): return cv2.CascadeClassifier('haarcascade_frontalface_default.xml') \ .detectMultiScale(self._img, scaleFactor=1.2, minNeighbors=5, minSize=(50, 50), flags=cv2.CASCADE_SCALE_IMAGE)
def get_images_and_labels(path): # Append all the absolute image paths in a list image_paths # We will not read the image with the .sad extension in the training set # Rather, we will use them to test our accuracy of the training image_paths = [os.path.join(path, f) for f in os.listdir(path)] # images will contains face images images = [] # labels will contains the label that is assigned to the image labels = [] for image_path in image_paths: # Read the image and convert to grayscale image_pil = Image.open(image_path).convert('L') # Convert the image format into numpy array image = np.array(image_pil, 'uint8') # Get the label of the image nbr = int(os.path.split(image_path)[1].split(".")[0].replace("subject", "")) # Detect the face in the image faces = faceCascade.detectMultiScale( image, scaleFactor=1.1, minNeighbors=5, minSize=(200, 200), flags = cv2.CASCADE_SCALE_IMAGE) # If face is detected, append the face to images and the label to labels for (x, y, w, h) in faces: images.append(image[y: y + h, x: x + w]) labels.append(nbr) cv2.imshow("Adding faces to traning set...", image[y: y + h, x: x + w]) cv2.waitKey(10) # return the images list and labels list return images, labels # capture frames from video
def face_recognize_video(lab_person_map,stream): ret=True ctr = 0 cap = cv2.VideoCapture(stream) while(1): # ret, img = cap.read() ret, img = cap.read() if not ret: break gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # gray = Image.open(img).convert('L') predict_image = np.array(gray, 'uint8') # break faces = face_cascade.detectMultiScale( predict_image, scaleFactor=1.1, minNeighbors=5, minSize=(200,200), flags = cv2.CASCADE_SCALE_IMAGE ) for (x,y,w,h) in faces: nbr_predicted, conf = recognizer.predict(predict_image[y: y + h, x: x + w]) print "{} is Recognized with confidence {}".format(lab_person_map[nbr_predicted], conf) cv2.imshow("Recognizing Face", predict_image[y: y + h, x: x + w]) cv2.waitKey(2) cap.release() cv2.destroyAllWindows() #emptying directory
def crop_face(i_path): image=cv2.imread(i_path) gray=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) dest_i = 'test.png' # Loading all the HAAR Cascade classifiers face1 = cv2.CascadeClassifier("data/HAARCascades/haarcascade_frontalface_default.xml") face2 = cv2.CascadeClassifier("data/HAARCascades/haarcascade_frontalface_alt2.xml") face3 = cv2.CascadeClassifier("data/HAARCascades/haarcascade_frontalface_alt.xml") face4 = cv2.CascadeClassifier("data/HAARCascades/haarcascade_frontalface_alt_tree.xml") # Detecting faces face_1 = face1.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=10, minSize=(5, 5),flags=cv2.CASCADE_SCALE_IMAGE) face_2 = face2.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=10, minSize=(5, 5),flags=cv2.CASCADE_SCALE_IMAGE) face_3 = face3.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=10, minSize=(5, 5),flags=cv2.CASCADE_SCALE_IMAGE) face_4 = face4.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=10, minSize=(5, 5), flags=cv2.CASCADE_SCALE_IMAGE) # ensuring that no other object in the image has been wrongly classified as a face and at least one face is # detected. if len(face_1)==1: req_face=face_1 elif len(face_2) == 1: req_face = face_2 elif len(face_3) == 1: req_face = face_3 elif len(face_4) == 1: req_face = face_4 else: req_face="" if len(req_face)==1: #print("\n Face Cropped Using HAAR Cascade\n") for (x, y, w, h) in req_face: roi_gray = gray[y:y + h, x:x + w] # Writing the final cropped image to the required directory cv2.imwrite(dest_i, cv2.resize(roi_gray, (350, 350))) else: #print("\n Face Not Cropped Using HAAR Cascade\n") cv2.imwrite(dest_i,gray) return dest_i
def crop_face(i_path,e_path): image=cv2.imread(i_path) gray=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) # Loading all the HAAR Cascade classifiers face1 = cv2.CascadeClassifier("data/HAARCascades/haarcascade_frontalface_default.xml") face2 = cv2.CascadeClassifier("data/HAARCascades/haarcascade_frontalface_alt2.xml") face3 = cv2.CascadeClassifier("data/HAARCascades/haarcascade_frontalface_alt.xml") face4 = cv2.CascadeClassifier("data/HAARCascades/haarcascade_frontalface_alt_tree.xml") # Detecting faces face_1 = face1.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=10, minSize=(5, 5),flags=cv2.CASCADE_SCALE_IMAGE) face_2 = face2.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=10, minSize=(5, 5),flags=cv2.CASCADE_SCALE_IMAGE) face_3 = face3.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=10, minSize=(5, 5),flags=cv2.CASCADE_SCALE_IMAGE) face_4 = face4.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=10, minSize=(5, 5), flags=cv2.CASCADE_SCALE_IMAGE) # ensuring that no other object in the image has been wrongly classified as a face and at least one face is # detected. if len(face_1)==1: req_face=face_1 elif len(face_2) == 1: req_face = face_2 elif len(face_3) == 1: req_face = face_3 elif len(face_4) == 1: req_face = face_4 else: req_face="" for (x, y, w, h) in req_face: roi_gray = gray[y:y + h, x:x + w] # Writing the final cropped image to the required directory temp_1=i_path temp_split=temp_1.split('/') final_name=temp_split[len(temp_split)-1] cv2.imwrite(dest_m_dir+e_path[48:]+'/'+final_name, cv2.resize(roi_gray, (350, 350)))
def crop_face(i_path): image=cv2.imread(i_path) gray=cv2.cvtColor(image,cv2.COLOR_BGR2GRAY) dest_i = 'data/cap_image/test.png' # Loading all the HAAR Cascade classifiers face1 = cv2.CascadeClassifier("data/HAARCascades/haarcascade_frontalface_default.xml") face2 = cv2.CascadeClassifier("data/HAARCascades/haarcascade_frontalface_alt2.xml") face3 = cv2.CascadeClassifier("data/HAARCascades/haarcascade_frontalface_alt.xml") face4 = cv2.CascadeClassifier("data/HAARCascades/haarcascade_frontalface_alt_tree.xml") # Detecting faces face_1 = face1.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=10, minSize=(5, 5),flags=cv2.CASCADE_SCALE_IMAGE) face_2 = face2.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=10, minSize=(5, 5),flags=cv2.CASCADE_SCALE_IMAGE) face_3 = face3.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=10, minSize=(5, 5),flags=cv2.CASCADE_SCALE_IMAGE) face_4 = face4.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=10, minSize=(5, 5), flags=cv2.CASCADE_SCALE_IMAGE) # ensuring that no other object in the image has been wrongly classified as a face and at least one face is # detected. if len(face_1)==1: req_face=face_1 elif len(face_2) == 1: req_face = face_2 elif len(face_3) == 1: req_face = face_3 elif len(face_4) == 1: req_face = face_4 else: req_face="" if len(req_face)==1: print("\n Face Cropped Using HAAR Cascade\n") for (x, y, w, h) in req_face: roi_gray = gray[y:y + h, x:x + w] # Writing the final cropped image to the required directory cv2.imwrite(dest_i, cv2.resize(roi_gray, (350, 350))) else: print("\n Face Not Cropped Using HAAR Cascade\n") cv2.imwrite(dest_i,gray) return dest_i
def detect(img, cascade): faces = cascade.detectMultiScale(img, scaleFactor=1.3, minNeighbors=4, minSize=(30, 30), flags=cv2.CASCADE_SCALE_IMAGE) # print faces (x,y,w,h) if len(faces) == 0: return [] faces[:,2:] += faces[:,:2] return faces
def detect_single(image): """Return bounds (x, y, width, height) of detected face in grayscale image. If no face or more than one face are detected, None is returned. """ faces = haar_faces.detectMultiScale(image, scaleFactor=config.HAAR_SCALE_FACTOR, minNeighbors=config.HAAR_MIN_NEIGHBORS, minSize=config.HAAR_MIN_SIZE, flags=cv2.CASCADE_SCALE_IMAGE) if len(faces) != 1: return None return faces[0]
def detect_single(image): """Return bounds (x, y, width, height) of detected face in grayscale image. If no face or more than one face are detected, None is returned. """ faces = haar_faces.detectMultiScale(image, scaleFactor=config.HAAR_SCALE_FACTOR, minNeighbors=config.HAAR_MIN_NEIGHBORS_FACE, minSize=config.HAAR_MIN_SIZE_FACE, flags=cv2.CASCADE_SCALE_IMAGE) if len(faces) != 1: return None return faces[0]
def detect_faces(image): """Return bounds (x, y, width, height) of detected face in grayscale image. return all faces found in the image """ faces = haar_faces.detectMultiScale(image, scaleFactor=config.HAAR_SCALE_FACTOR, minNeighbors=config.HAAR_MIN_NEIGHBORS_FACE, minSize=config.HAAR_MIN_SIZE_FACE, flags=cv2.CASCADE_SCALE_IMAGE) return faces
def detect_eyes(image): eyes = haar_eyes.detectMultiScale(image, scaleFactor=config.HAAR_SCALE_FACTOR, minNeighbors=config.HAAR_MIN_NEIGHBORS_EYES, minSize=config.HAAR_MIN_SIZE_EYES, flags=cv2.CASCADE_SCALE_IMAGE) return eyes
def detect(img, cascade): rects = cascade.detectMultiScale(img, scaleFactor=1.3, minNeighbors=4, minSize=( 30, 30), flags=cv2.CASCADE_SCALE_IMAGE) if len(rects) == 0: return [] rects[:, 2:] += rects[:, :2] return rects
def run(self): bytes = b'' while not self.thread_cancelled: try: bytes += self.stream.raw.read(1024) a = bytes.find(b'\xff\xd8') b = bytes.find(b'\xff\xd9') if a != -1 and b != -1: jpg = bytes[a:b + 2] bytes = bytes[b + 2:] frame = cv2.imdecode(np.fromstring(jpg, dtype=np.uint8), cv2.IMREAD_COLOR) #------------------ insert algorythms HERE ------------------ gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) faces = faceCascade.detectMultiScale( gray, scaleFactor=1.15, minNeighbors=5, minSize=(20, 20), flags=cv2.CASCADE_SCALE_IMAGE ) # Draw a rectangle around the faces for (x, y, w, h) in faces: cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 2) # Display the resulting frame cv2.imshow('Video', frame) # ------------------ algorythms end HERE ------------------ if cv2.waitKey(1) & 0xFF == ord('q'): exit(0) except ThreadError: self.thread_cancelled = True
def detect(img, cascade): rects = cascade.detectMultiScale(img, scaleFactor=1.3, minNeighbors=4, minSize=(30, 30), flags=cv2.CASCADE_SCALE_IMAGE) if len(rects) == 0: return [] rects[:,2:] += rects[:,:2] return rects
def detect_faces(self, image: np.ndarray): # haarclassifiers work better in black and white gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) gray_image = cv2.equalizeHist(gray_image) faces = self.classifier.detectMultiScale(gray_image, scaleFactor=1.3, minNeighbors=4, flags=cv2.CASCADE_SCALE_IMAGE, minSize=self._min_size) return faces
def detect_multi(image): """Return bounds (x, y, width, height) of detected face in grayscale image. If no face or more than one face are detected, None is returned. """ faces = haar_faces.detectMultiScale(image, scaleFactor=config.get("haar_scale_factor"), minNeighbors=config.get("haar_min_neighbors"), minSize=tuple(config.get("haar_min_size")), flags=cv2.CASCADE_SCALE_IMAGE) if len(faces) > 0: return faces else: return None
def main(parser): capture = cv2.VideoCapture(parser.source) src_width, src_height = int(capture.get(cv2.CAP_PROP_FRAME_WIDTH)), int(capture.get(cv2.CAP_PROP_FRAME_HEIGHT)) if(parser.record == True): fourcc = cv2.VideoWriter_fourcc(*'XVID') out = cv2.VideoWriter(parser.output_path,fourcc, 20.0, (src_width,src_height)) cascPath = "./haarcascade_frontalface_default.xml" faceCascade = cv2.CascadeClassifier(cascPath) while True: ret, frame = 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 ) pred_features = detect_features(gray, faces, src_width, src_height, parser.width, parser.height) result_img = draw_features_point_on_image(frame, pred_features, src_width, src_height) for (x, y, w, h) in faces: cv2.rectangle(result_img, (x, y), (x+w, y+h), (0, 255, 0), 1) if (ret==True) and (parser.record == True): out.write(result_img) cv2.imshow('Video', result_img) if cv2.waitKey(1) & 0xFF == ord('q'): break capture.release() if parser.record == True: out.release() cv2.destroyAllWindows()
def detect(request): # initialize the data dictionary to be returned by the request data = {"success": False} # check to see if this is a post request if request.method == "POST": # check to see if an image was uploaded if request.FILES.get("image", None) is not None: # grab the uploaded image image = _grab_image(stream=request.FILES["image"]) # otherwise, assume that a URL was passed in else: # grab the URL from the request url = request.POST.get("url", None) # if the URL is None, then return an error if url is None: data["error"] = "No URL provided." return JsonResponse(data) # load the image and convert image = _grab_image(url=url) # convert the image to grayscale, load the face cascade detector, # and detect faces in the image image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) detector = cv2.CascadeClassifier(FACE_DETECTOR_PATH) rects = detector.detectMultiScale( image, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30), flags=cv2.CASCADE_SCALE_IMAGE ) # construct a list of bounding boxes from the detection rects = [(int(x), int(y), int(x + w), int(y + h)) for (x, y, w, h) in rects] # update the data dictionary with the faces detected data.update({"num_faces": len(rects), "faces": rects, "success": True}) # return a JSON response return JsonResponse(data)
def detect(self, image, biggest_only=True): """ Detect face in an image. Find the biggest face in an image and return its position and dimensions (top, left, width and height). :param image: the image in which to detect faces :type image: numpy array :return: top, left, width and height of the rectangle around the face :rtype: tuple of length 4 """ is_color = 4 if is_color: image_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) else: image_gray = image # The algorithm checks for faces of different sizes, # the scale_factor is how much difference is between each size # that you want to check. # A bigger scale_factor means bigger jumps so it will perform # faster but less accuratelly, it is recommended 1.2 or 1.3 scale_factor = 1.2 # Treshold to detect a face, it needs a minimum of min_neighbors # neighbor pixels to return a detected a face on that pixel min_neighbors = 5 # Sets the min_size of the face we want to detect. Default is 20x20 min_size = (30, 30) # Change to True if we want to detect only one face flags = cv2.CASCADE_FIND_BIGGEST_OBJECT | \ cv2.CASCADE_DO_ROUGH_SEARCH if biggest_only else \ cv2.CASCADE_SCALE_IMAGE face_coord = self.classifier.detectMultiScale( image_gray, scaleFactor=scale_factor, minNeighbors=min_neighbors, minSize=min_size, flags=flags ) return face_coord
def getNewInstances(ytURL, faceDet, faceDet2, faceDet3, faceDet4, maxCount): framepath = tempfile.mkdtemp() # mp4Frames(ytURL, framepath, maxCount) # files = glob.glob("%s/*" %framepath) #Get list of all images with emotion # prediction_data = [] predictDataSrcImg = [] predictFaceDims = [] fileInd = 0 for f in files: fileInd += 1 print("detecting faces in frame: %d of %d" %(fileInd, files.__len__())) if f[-9:] != "Thumbs.db": #f windows # frame = cv2.imread(f) #Open image as grayscale gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) #Convert image to grayscale # #Detect face using 4 different classifiers face = faceDet.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=10, minSize=(5, 5), flags=cv2.CASCADE_SCALE_IMAGE) face2 = faceDet2.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=10, minSize=(5, 5), flags=cv2.CASCADE_SCALE_IMAGE) face3 = faceDet3.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=10, minSize=(5, 5), flags=cv2.CASCADE_SCALE_IMAGE) face4 = faceDet4.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=10, minSize=(5, 5), flags=cv2.CASCADE_SCALE_IMAGE) # #Go over detected faces, stop at first detected face, return empty if no face. if len(face) == 1: facefeatures = face elif len(face2) == 1: facefeatures = face2 elif len(face3) == 1: facefeatures = face3 elif len(face4) == 1: facefeatures = face4 else: facefeatures = None # if facefeatures is not None: #Cut and save face for (x, y, w, h) in facefeatures: #get coordinates and size of rectangle containing face #print "\tface found in file: %s" %f gray = gray[y:y+h, x:x+w] #Cut the frame to size # try: out = cv2.resize(gray, (350, 350)) #Resize face so all images have same size prediction_data.append(out) predictDataSrcImg.append(frame) predictFaceDims.append([x, y, w, h]) except: pass #If error, pass file # shutil.rmtree(framepath) return prediction_data, predictDataSrcImg, predictFaceDims
def detect_faces(emotion): # Get list of all images with emotion files = glob.glob("sorted_set\\%s\\*" % emotion) filenumber = 0 for f in files: frame = cv2.imread(f) # Open image # Convert image to grayscale gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Detect face using 4 different classifiers face1 = faceDet1.detectMultiScale( gray, scaleFactor=1.1, minNeighbors=10, minSize=( 5, 5), flags=cv2.CASCADE_SCALE_IMAGE) face2 = faceDet2.detectMultiScale( gray, scaleFactor=1.1, minNeighbors=10, minSize=( 5, 5), flags=cv2.CASCADE_SCALE_IMAGE) face3 = faceDet3.detectMultiScale( gray, scaleFactor=1.1, minNeighbors=10, minSize=( 5, 5), flags=cv2.CASCADE_SCALE_IMAGE) face4 = faceDet4.detectMultiScale( gray, scaleFactor=1.1, minNeighbors=10, minSize=( 5, 5), flags=cv2.CASCADE_SCALE_IMAGE) # Go over detected faces, stop at first detected face, return empty if # no face. if len(face1) == 1: facefeatures = face1 elif len(face2) == 1: facefeatures = face2 elif len(face3) == 1: facefeatures = face3 elif len(face4) == 1: facefeatures = face4 else: facefeatures = "" # Cut and save face for (x, y, w, h) in facefeatures: # Face coordinates. print "face found in file: %s" % f gray = gray[y:y + h, x:x + w] # Cut the frame to size try: # Resize face so all images have same size out = cv2.resize(gray, (350, 350)) cv2.imwrite("dataset\\%s\\%s.jpg" % (emotion, filenumber), out) # Write image except BaseException: pass # If error, pass file filenumber += 1 # Increment image number
def processframe(): retval, frame = cam.read() #frame = cv2.imread('img.png') #frame = camera.GrabNumPyImage(format='bgr') #frame = cv2.resize(frame,None,fx=0.5, fy=0.5, interpolation = cv2.INTER_AREA) detect = cv2.CascadeClassifier('haarcascade_frontalface_default.xml') upper = cv2.CascadeClassifier('haarcascade_frontalface_alt2.xml') #comments frontal = detect.detectMultiScale(frame,scaleFactor=1.3, minNeighbors=5, minSize=(30, 30), flags=cv2.CASCADE_SCALE_IMAGE) #Eventually will download and implement profile classifier profile = upper.detectMultiScale(frame,scaleFactor=1.3, minNeighbors=5, minSize=(30, 30), flags=cv2.CASCADE_SCALE_IMAGE) for (x,y,w,h) in frontal: center = ( (x+(w/2)), (y+(h/2))) cv2.rectangle(frame, (x, y), (x+w, y+h), (0,0,153), 5) cv2.circle(frame, (center), 3, (0, 200, 0), -1) center = ( (x+(w/2))) #print(center) if (center < 390 and center > 250 ): cv2.putText(frame, "Target Found", (20, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.5,(0, 0, 255), 2) stopTurning() startShooting() elif (center > 390): stopShooting() turnRight() elif (center < 250): stopShooting() turnLeft() else: stopShooting() stopTurning() cv2.imshow("w", frame) #context = pyfly2.Context() #if context.num_cameras: # camera = context.get_camera(0) # camera.Connect() # camera.StartCapture()
def CaptureFrames(self): while True: # Create a unique number for each frame frameNumber = '%08d' % (self.count) # Capture frame by frame ret, frame = self.videoSource.read() # Set screen color to gray, so the haar cascade can easily detect the edges an faces screenColor = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Cusomize how cascade detects your face faces = self.faceCascade.detectMultiScale( screenColor, scaleFactor=1.1, minNeighbors=5, minSize=(10,10), flags=cv2.CASCADE_SCALE_IMAGE) # Display the resulting frame cv2.imshow('Spying on you', screenColor) # If length of faces equal to zero, there have been no faces detected if len(faces) == 0: pass # If a face is detected, faces return 1 or more depending on the amount of faces detected if len(faces) > 0: print('Face detected') # Graph the face and draw the rectangle around it for (x,y,w,h) in faces: cv2.rectangle(frame, (x,y), (x+w, y+h), (0, 255, 0), 2) cv2.imwrite(DEFAULT_OUTPUT_PATH + frameNumber + '.png', frame) # Increement count so we get a unique name for each frame self.count += 1 # If press 'ESC' close the video if cv2.waitKey(1) == 27: break # When everything is done, release the capture and close window self.videoSource.release() cv2.waitKey(500) cv2.destroyAllWindows() cv2.waitKey(500)
def CaptureFrames(self): while True: # Create a unique number for each frame frameNumber = '%08d' % (self.count) # Capture frame by frame ret, frame = self.videoSource.read() # Set screen color to gray, so the haar cascade can easily detect the edges an eyes screenColor = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # Cusomize how cascade detects your eye eyes = self.eyeCascade.detectMultiScale( screenColor, flags=cv2.CASCADE_SCALE_IMAGE) # Display the resulting frame cv2.imshow('Spying on you', screenColor) # If length of eyes equal to zero, there have been no eyes detected if len(eyes) == 0: pass # If a eye is detected, eyes return 1 or more depending on the amount of eyes detected if len(eyes) > 0: print('Eyes detected') # Graph the eye and draw the rectangle around it for (x,y,w,h) in eyes: cv2.rectangle(frame, (x,y), (x+w, y+h), (255, 0, 255), 2) cv2.imwrite(DEFAULT_OUTPUT_PATH + frameNumber + '.png', frame) # Increement count so we get a unique name for each frame self.count += 1 # If press 'ESC' close the video if cv2.waitKey(1) == 27: break # When everything is done, release the capture and close window self.videoSource.release() cv2.waitKey(500) cv2.destroyAllWindows() cv2.waitKey(500)