我们从Python开源项目中,提取了以下21个代码示例,用于说明如何使用cv2.FONT_HERSHEY_DUPLEX。
def display_detected(self, frame, face_locs, people, confidence): """ - Display ROI's of detected faces with labels :param frame: :param face_locs: :param people : people in image classified :param confidence : recognition confidence :return: """ if not len(face_locs) == 0: # nothing detected for (top, right, bottom, left), name, conf in zip(face_locs, people, confidence): # Scale back up face locations since the frame we detected in was scaled to 1/4 size top right bottom left # string conf_4f = "%.3f" % conf peop_conf = "{} {}%".format(name, float(conf_4f) * 100) # Draw a box around the face cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2) # Draw a label with a name below the face # cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED) cv2.rectangle(frame, (left, top + 20), (right, top), (0, 0, 255), cv2.FILLED) font = cv2.FONT_HERSHEY_DUPLEX # color # cv2.putText(frame, peop_conf , (left + 6, bottom - 6), font, 0.5, (255, 255, 255), 1) cv2.putText(frame, peop_conf, (left, top + 15), font, 0.5, (255, 255, 255), 1) pass
def update(self,frame,events): self.last_frame_ts = frame.timestamp from player_methods import transparent_circle events['fixations'] = self.g_pool.fixations_by_frame[frame.index] if self.show_fixations: for f in self.g_pool.fixations_by_frame[frame.index]: x = int(f['norm_pos'][0]*self.img_size[0]) y = int((1-f['norm_pos'][1])*self.img_size[1]) transparent_circle(frame.img, (x,y), radius=f['pix_dispersion']/2, color=(.5, .2, .6, .7), thickness=-1) cv2.putText( frame.img, '{:d}'.format(f['id']), (x+20,y), cv2.FONT_HERSHEY_DUPLEX, 0.8,(255,150,100)) # cv2.putText(frame.img,'%i - %i'%(f['start_frame_index'],f['end_frame_index']),(x,y), cv2.FONT_HERSHEY_DUPLEX,0.8,(255,150,100))
def update(self,frame,events): self.last_frame_ts = frame.timestamp from player_methods import transparent_circle events['fixations'] = self.g_pool.fixations_by_frame[frame.index] if self.show_fixations: for f in self.g_pool.fixations_by_frame[frame.index]: eye_id = f['eye_id'] x = int(f['norm_pos'][0]*self.img_size[0]) y = int((1-f['norm_pos'][1])*self.img_size[1]) transparent_circle(frame.img, (x,y), radius=f['pix_dispersion']/2, color=(.5, .2, .6, .7), thickness=-1) cv2.putText( frame.img, '{:d} - eye {:d}'.format(f['id'], eye_id), (x+20,y-5+30*eye_id), cv2.FONT_HERSHEY_DUPLEX, 0.8,(255,150,100)) # cv2.putText(frame.img,'%i - %i'%(f['start_frame_index'],f['end_frame_index']),(x,y), cv2.FONT_HERSHEY_DUPLEX,0.8,(255,150,100))
def DispID(x, y, w, h, NAME, Image): # --------------------------------- THE POSITION OF THE ID BOX --------------------------------------------- Name_y_pos = y - 10 Name_X_pos = x + w/2 - (len(NAME)*7/2) if Name_X_pos < 0: Name_X_pos = 0 elif (Name_X_pos +10 + (len(NAME) * 7) > Image.shape[1]): Name_X_pos= Name_X_pos - (Name_X_pos +10 + (len(NAME) * 7) - (Image.shape[1])) if Name_y_pos < 0: Name_y_pos = Name_y_pos = y + h + 10 # ------------------------------------ THE DRAWING OF THE BOX AND ID -------------------------------------- draw_box(Image, x, y, w, h) cv2.rectangle(Image, (Name_X_pos-10, Name_y_pos-25), (Name_X_pos +10 + (len(NAME) * 7), Name_y_pos-1), (0,0,0), -2) # Draw a Black Rectangle over the face frame cv2.rectangle(Image, (Name_X_pos-10, Name_y_pos-25), (Name_X_pos +10 + (len(NAME) * 7), Name_y_pos-1), WHITE, 1) cv2.putText(Image, NAME, (Name_X_pos, Name_y_pos - 10), cv2.FONT_HERSHEY_DUPLEX, .4, WHITE) # Print the name of the ID
def DispID2(x, y, w, h, NAME, Image): # --------------------------------- THE POSITION OF THE ID BOX ------------------------------------------------- Name_y_pos = y - 40 Name_X_pos = x + w/2 - (len(NAME)*7/2) if Name_X_pos < 0: Name_X_pos = 0 elif (Name_X_pos +10 + (len(NAME) * 7) > Image.shape[1]): Name_X_pos= Name_X_pos - (Name_X_pos +10 + (len(NAME) * 7) - (Image.shape[1])) if Name_y_pos < 0: Name_y_pos = Name_y_pos = y + h + 10 # ------------------------------------ THE DRAWING OF THE BOX AND ID -------------------------------------- cv2.rectangle(Image, (Name_X_pos-10, Name_y_pos-25), (Name_X_pos +10 + (len(NAME) * 7), Name_y_pos-1), (0,0,0), -2) # Draw a Black Rectangle over the face frame cv2.rectangle(Image, (Name_X_pos-10, Name_y_pos-25), (Name_X_pos +10 + (len(NAME) * 7), Name_y_pos-1), WHITE, 1) cv2.putText(Image, NAME, (Name_X_pos, Name_y_pos - 10), cv2.FONT_HERSHEY_DUPLEX, .4, WHITE) # Print the name of the ID # --------------- THIRD ID BOX ----------------------
def DispID3(x, y, w, h, NAME, Image): # --------------------------------- THE POSITION OF THE ID BOX ------------------------------------------------- Name_y_pos = y - 70 Name_X_pos = x + w/2 - (len(NAME)*7/2) if Name_X_pos < 0: Name_X_pos = 0 elif (Name_X_pos +10 + (len(NAME) * 7) > Image.shape[1]): Name_X_pos= Name_X_pos - (Name_X_pos +10 + (len(NAME) * 7) - (Image.shape[1])) if Name_y_pos < 0: Name_y_pos = Name_y_pos = y + h + 10 # ------------------------------------ THE DRAWING OF THE BOX AND ID -------------------------------------- cv2.rectangle(Image, (Name_X_pos-10, Name_y_pos-25), (Name_X_pos +10 + (len(NAME) * 7), Name_y_pos-1), (0,0,0), -2) # Draw a Black Rectangle over the face frame cv2.rectangle(Image, (Name_X_pos-10, Name_y_pos-25), (Name_X_pos +10 + (len(NAME) * 7), Name_y_pos-1), WHITE, 1) cv2.putText(Image, NAME, (Name_X_pos, Name_y_pos - 10), cv2.FONT_HERSHEY_DUPLEX, .4, WHITE) # Print the name of the ID
def _show(self, path, inpmat, heatmat, pafmat, humans): image = cv2.imread(path) # CocoPoseLMDB.display_image(inpmat, heatmat, pafmat) image_h, image_w = image.shape[:2] heat_h, heat_w = heatmat.shape[:2] for _, human in humans.items(): for part in human: if part['partIdx'] not in common.CocoPairsRender: continue center1 = (int((part['c1'][0] + 0.5) * image_w / heat_w), int((part['c1'][1] + 0.5) * image_h / heat_h)) center2 = (int((part['c2'][0] + 0.5) * image_w / heat_w), int((part['c2'][1] + 0.5) * image_h / heat_h)) cv2.circle(image, center1, 2, (255, 0, 0), thickness=3, lineType=8, shift=0) cv2.circle(image, center2, 2, (255, 0, 0), thickness=3, lineType=8, shift=0) cv2.putText(image, str(part['partIdx'][1]), center2, cv2.FONT_HERSHEY_DUPLEX, 0.5, (255, 0, 0), 1) image = cv2.line(image, center1, center2, (255, 0, 0), 1) cv2.imshow('result', image) cv2.waitKey(0)
def bboxes_draw_on_img(img, classes, scores, bboxes, colors, thickness=2): shape = img.shape for i in range(bboxes.shape[0]): bbox = bboxes[i] color = colors[classes[i]] # Draw bounding box... p1 = (int(bbox[0] * shape[0]), int(bbox[1] * shape[1])) p2 = (int(bbox[2] * shape[0]), int(bbox[3] * shape[1])) cv2.rectangle(img, p1[::-1], p2[::-1], color, thickness) # Draw text... s = '%s/%.3f' % (classes[i], scores[i]) p1 = (p1[0]-5, p1[1]) cv2.putText(img, s, p1[::-1], cv2.FONT_HERSHEY_DUPLEX, 0.4, color, 1) # =========================================================================== # # Matplotlib show... # =========================================================================== #
def __init__(self, matric_num): WHITE = [255, 255, 255] face_cascade = cv2.CascadeClassifier('Haar/haarcascade_frontalcatface.xml') eye_cascade = cv2.CascadeClassifier('Haar/haarcascade_eye.xml') ID = NameFind.AddName(matric_num) Count = 0 cap = cv2.VideoCapture(0) # Camera object self.__trainer__ = None if not os.path.exists('dataSet'): os.makedirs('dataSet') while True: ret, img = cap.read() gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Convert the Camera to grayScale faces = face_cascade.detectMultiScale(gray, 1.3, 5) # Detect the faces and store the positions for (x, y, w, h) in faces: # Frames LOCATION X, Y WIDTH, HEIGHT FaceImage = gray[y - int(h / 2): y + int(h * 1.5), x - int(x / 2): x + int(w * 1.5)] # The Face is isolated and cropped Img = (NameFind.DetectEyes(FaceImage)) cv2.putText(gray, "FACE DETECTED", (x + (w / 2), y - 5), cv2.FONT_HERSHEY_DUPLEX, .4, WHITE) if Img is not None: frame = Img # Show the detected faces else: frame = gray[y: y + h, x: x + w] cv2.imwrite("dataSet/" + matric_num.replace('/', '') + "." + str(ID) + "." + str(Count) + ".jpg", frame) Count = Count + 1 # cv2.waitKey(300) cv2.imshow("CAPTURED PHOTO", frame) # show the captured image cv2.imshow('Face Recognition System Capture Faces', gray) # Show the video if Count == 150: Trainer() break if cv2.waitKey(1) & 0xFF == ord('q'): break print 'FACE CAPTURE FOR THE SUBJECT IS COMPLETE' cap.release() cv2.destroyAllWindows()
def draw_id(self, img): # tag_width_px = self.p[0][0] - self.p[1][0] text = str(self.id) center = (int(self.c[0] - 15), int(self.c[1])) font = cv2.FONT_HERSHEY_DUPLEX color = (0, 255, 0) thickness = 2 cv2.putText(img, text, center, font, 0.7, color, thickness)
def draw_text(img, text, box, color='bw'): """ FONT_HERSHEY_COMPLEX FONT_HERSHEY_COMPLEX_SMALL FONT_HERSHEY_DUPLEX FONT_HERSHEY_PLAIN FONT_HERSHEY_SCRIPT_COMPLEX FONT_HERSHEY_SCRIPT_SIMPLEX FONT_HERSHEY_SIMPLEX FONT_HERSHEY_TRIPLEX FONT_ITALIC """ x, y, w, h = box font = cv2.FONT_HERSHEY_DUPLEX region = crop(img, box) if color == 'bw': brightness = np.mean(cv2.cvtColor(region, cv2.COLOR_BGR2GRAY)) if brightness > 127: font_color = (0,0,0) else: font_color = (255,255,255) elif color == 'color': mean_bg = np.round(np.mean(region, axis=(0, 1))) font_color = tuple(map(int, np.array((255,255,255)) - mean_bg)) else: font_color = (255, 0, 0) # blue cv2.putText(img, text, (x, y+h), font, 1, font_color, 2)
def draw_bbox(img, bbox, shape, label, color=[255, 0, 0], thickness=2): p1 = (int(bbox[0] * shape[0]), int(bbox[1] * shape[1])) p2 = (int(bbox[2] * shape[0]), int(bbox[3] * shape[1])) cv2.rectangle(img, p1[::-1], p2[::-1], color, thickness) p1 = (p1[0]+15, p1[1]) cv2.putText(img, str(label), p1[::-1], cv2.FONT_HERSHEY_DUPLEX, 0.5, color, 1)
def find_gesture(frame_in,finger,palm): frame_gesture.set_palm(palm[0],palm[1]) frame_gesture.set_finger_pos(finger) frame_gesture.calc_angles() gesture_found=DecideGesture(frame_gesture,GestureDictionary) gesture_text="GESTURE:"+str(gesture_found) cv2.putText(frame_in,gesture_text,(int(0.56*frame_in.shape[1]),int(0.97*frame_in.shape[0])),cv2.FONT_HERSHEY_DUPLEX,1,(0,255,255),1,8) return frame_in,gesture_found # 7. Remove bg from image
def score_emotions(im, eyebrowheight, mouthdist): gray = (129, 129, 129) red = (0, 0, 255) if eyebrowheight > 0.75: surscore = eyebrowheight * 10 surscore = str(int(surscore)) color = red else: color = gray surscore = '' cv2.putText(im, "SURPRISE = " + surscore, (3 * screenwidth / 5, screenheight / 3), fontFace=cv2.FONT_HERSHEY_DUPLEX, fontScale=0.7, color=color, thickness=1) if mouthdist > 0.9: hapscore = mouthdist * 100 hapscore = str(int(hapscore)) color = red else: color = gray hapscore = '' cv2.putText(im, "HAPPINESS = " + hapscore, (3 * screenwidth / 5, screenheight / 3 + 20), fontFace=cv2.FONT_HERSHEY_DUPLEX, fontScale=0.7, color=color, thickness=1) return im # Initialize camera
def draw_XYcoord(arg_frame, arg_pt, arg_dirList): arg_x_axis_reverse= arg_dirList[0] arg_y_axis_reverse= arg_dirList[1] arg_xy_axis_swap= arg_dirList[2] frame= arg_frame.copy() hor_word = "X" ver_word = "Y" hor_color = (0, 255, 0) ver_color = (0, 0, 255) #hor_start, hor_stop = (60, 50), (150, 50) #ver_start, ver_stop = (50, 60), (50, 150) hor_start, hor_stop = (arg_pt[0]+10, arg_pt[1]), (arg_pt[0]+ 90, arg_pt[1]+ 0) ver_start, ver_stop = (arg_pt[0], arg_pt[1]+10), (arg_pt[0]+ 0, arg_pt[1]+ 90) #print arg_xy_axis_swap if arg_x_axis_reverse: hor_start, hor_stop = hor_stop, hor_start if arg_y_axis_reverse: ver_start, ver_stop = ver_stop, ver_start if arg_xy_axis_swap: #(hor_word, hor_color, hor_start, hor_stop, ver_word, ver_color, ver_start, ver_stop) =\ #(ver_word, ver_color, ver_start, ver_stop, hor_word, hor_color, hor_start, hor_stop) hor_word, hor_color, ver_word, ver_color =\ ver_word, ver_color, hor_word, hor_color #print hor_word, hor_color, ver_word, ver_color cv2.arrowedLine(frame, hor_start, hor_stop, hor_color, 5, 8, 0, 0.2) cv2.arrowedLine(frame, ver_start, ver_stop, ver_color, 5, 8, 0, 0.2) cv2.putText(frame, hor_word, (arg_pt[0]+ 30, arg_pt[1]- 10) , cv2.FONT_HERSHEY_DUPLEX, 0.7, hor_color, 2) cv2.putText(frame, ver_word, (arg_pt[0]- 20, arg_pt[1]+ 50) , cv2.FONT_HERSHEY_DUPLEX, 0.7, ver_color, 2) return frame
def vis_detections(im, class_name, dets, thresh=0.5): global video_writer """Draw detected bounding boxes.""" inds = np.where(dets[:, -1] >= thresh)[0] if len(inds) == 0: return show_im = im.copy() for i in inds: bbox = dets[i, :4] score = dets[i, -1] # Rectangle color is brighter if its probability is higher if score>0.2: cv2.rectangle(show_im,(int(bbox[0]), int(bbox[1])), (int(bbox[2]), int(bbox[3])), (0,0,255*score), 3) # Draw classic certainty percentage # cv2.putText(show_im, '{:.0f}%'.format(score*100), # (int(bbox[0]), int(bbox[1])-10), cv2.FONT_HERSHEY_DUPLEX, # 0.6, (0,0,255)) cv2.imshow("result", show_im) key = cv2.waitKey(3) if args.record>0: if video_writer is None: video_writer = cv2.VideoWriter("output.avi", fourcc, 30, (im.shape[1], im.shape[0])) print 'VideoWriter is ready' video_writer.write(show_im) if key==27: # Esc key to stop sys.exit(0)
def mark_fingers(frame_in,hull,pt,radius): global first_iteration global finger_ct_history finger=[(hull[0][0][0],hull[0][0][1])] j=0 cx = pt[0] cy = pt[1] for i in range(len(hull)): dist = np.sqrt((hull[-i][0][0] - hull[-i+1][0][0])**2 + (hull[-i][0][1] - hull[-i+1][0][1])**2) if (dist>18): if(j==0): finger=[(hull[-i][0][0],hull[-i][0][1])] else: finger.append((hull[-i][0][0],hull[-i][0][1])) j=j+1 temp_len=len(finger) i=0 while(i<temp_len): dist = np.sqrt( (finger[i][0]- cx)**2 + (finger[i][1] - cy)**2) if(dist<finger_thresh_l*radius or dist>finger_thresh_u*radius or finger[i][1]>cy+radius): finger.remove((finger[i][0],finger[i][1])) temp_len=temp_len-1 else: i=i+1 temp_len=len(finger) if(temp_len>5): for i in range(1,temp_len+1-5): finger.remove((finger[temp_len-i][0],finger[temp_len-i][1])) palm=[(cx,cy),radius] if(first_iteration): finger_ct_history[0]=finger_ct_history[1]=len(finger) first_iteration=False else: finger_ct_history[0]=0.34*(finger_ct_history[0]+finger_ct_history[1]+len(finger)) if((finger_ct_history[0]-int(finger_ct_history[0]))>0.8): finger_count=int(finger_ct_history[0])+1 else: finger_count=int(finger_ct_history[0]) finger_ct_history[1]=len(finger) count_text="FINGERS:"+str(finger_count) cv2.putText(frame_in,count_text,(int(0.62*frame_in.shape[1]),int(0.88*frame_in.shape[0])),cv2.FONT_HERSHEY_DUPLEX,1,(0,255,255),1,8) for k in range(len(finger)): cv2.circle(frame_in,finger[k],10,255,2) cv2.line(frame_in,finger[k],(cx,cy),255,2) return frame_in,finger,palm # 5. Mark hand center circle
def main_func(): img_path='snap.jpg' # THE PATH OF THE IMAGE TO BE ANALYZED font=cv2.FONT_HERSHEY_DUPLEX emotions = ["anger", "happy", "sadness"] #Emotion list clahe=cv2.createCLAHE(clipLimit=2.0,tileGridSize=(8,8)) # Histogram equalization object face_det=dlib.get_frontal_face_detector() land_pred=dlib.shape_predictor("data/DlibPredictor/shape_predictor_68_face_landmarks.dat") SUPPORT_VECTOR_MACHINE_clf2 = joblib.load('data/Trained_ML_Models/SVM_emo_model_7.pkl') # Loading the SVM model trained earlier in the path mentioned above. pred_data=[] pred_labels=[] a=crop_face(img_path) img=cv2.imread(a) gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) clahe_gray=clahe.apply(gray) landmarks_vec = get_landmarks(clahe_gray,face_det,land_pred) #print(len(landmarks_vec)) #print(landmarks_vec) if landmarks_vec == "error": pass else: pred_data.append(landmarks_vec) np_test_data = np.array(pred_data) a=SUPPORT_VECTOR_MACHINE_clf2.predict(pred_data) #cv2.putText(img,'DETECTED FACIAL EXPRESSION : ',(8,30),font,0.7,(0,0,255),2,cv2.LINE_AA) #l=len('Facial Expression Detected : ') #cv2.putText(img,emotions[a[0]].upper(),(150,60),font,1,(255,0,0),2,cv2.LINE_AA) #cv2.imshow('test_image',img) #print(emotions[a[0]]) cv2.waitKey(0) cv2.destroyAllWindows() return emotions[a[0]]
def checkSurfaceMask(context,cellSize,gridResolution,tileSize,maskResolution): def calculateOverlap(cellSize,gridResolution,tileSize,maskResolution): def roundToInt( x ): return floor(x + 0.5) def nearlyInt( x, i ): return (abs( x - i ) < 0.000001) def check( x ): return nearlyInt(x, roundToInt( x )) terrainSize = cellSize * gridResolution multiplier = 1 bestDist = 1000000 bestMult = -1 for i in range(0,8): landGrid = multiplier * cellSize dist = abs(40.0 - landGrid) if dist < bestDist: bestDist = dist bestMult = multiplier multiplier *= 2 subDiv = bestMult m_landGrid = subDiv * cellSize #land grid cell size or _landGrid totalLandGrids = floor( terrainSize / m_landGrid ) #land grid size or _landRange m_gridSize = subDiv * totalLandGrids #terrain grid size or _terrainRange m_width = m_height = m_gridSize * cellSize #final terrain size defaultOverlap = 16 # minimum overlap tileUsable = int(tileSize) - defaultOverlap tileUsableMeters = maskResolution * tileUsable segmentLGCs = floor( tileUsableMeters / m_landGrid ) segmentLGCs -= segmentLGCs % 4 segmentMeters = segmentLGCs * m_landGrid segmentPixels = segmentMeters / maskResolution actualOverlap = int(tileSize) - segmentPixels tilesInRow = ceil( m_width / segmentMeters ) return actualOverlap, tilesInRow from cv2 import imread as cv2imread, imwrite as cv2imwrite surfaceMask = cv2imread(context.scene.checkSurfaceMaskPath,1) maskWidth = maskHeight = int((cellSize * gridResolution) / maskResolution) rgb = zeros((maskWidth,maskHeight,3), uint8) alpha = zeros((maskWidth,maskHeight,1), uint8) actualOverlap, tilesInRow = calculateOverlap(cellSize,gridResolution,tileSize,maskResolution) font = cv2.FONT_HERSHEY_DUPLEX print(actualOverlap, tilesInRow)