Python cv2.putText() Examples

The following are code examples for showing how to use cv2.putText(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the ones you don't like. You can also save this page to your account.

Example 1
Project: Gender   Author: rabeter   File: find.py    (license) View Source Project 23 votes vote down vote up
def draw_rects(img, rects):
    """
    ?????????????
    :param img: 
    :param rects: 
    :return: 
    """
    for x, y, w, h in rects:
        cv2.rectangle(img, (x, y), (x+w, y+h), (255, 255, 00), 2)
        face = img
        face = cv2.resize(face,(224,224))
        if Gender.predict(face)==1:
            text = "Male"
        else:
            text = "Female"
        cv2.putText(img, text, (x, h), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (255, 255, 255), lineType=cv2.LINE_AA) 
Example 2
Project: facial_emotion_recognition   Author: adamaulia   File: image_test.py    (license) View Source Project 11 votes vote down vote up
def test_image(addr):
    target = ['angry','disgust','fear','happy','sad','surprise','neutral']
    font = cv2.FONT_HERSHEY_SIMPLEX
    
    im = cv2.imread(addr)
    gray = cv2.cvtColor(im, cv2.COLOR_BGR2GRAY)
    faces = faceCascade.detectMultiScale(gray,scaleFactor=1.1)
    
    for (x, y, w, h) in faces:
            cv2.rectangle(im, (x, y), (x+w, y+h), (0, 255, 0), 2,5)
            face_crop = im[y:y+h,x:x+w]
            face_crop = cv2.resize(face_crop,(48,48))
            face_crop = cv2.cvtColor(face_crop, cv2.COLOR_BGR2GRAY)
            face_crop = face_crop.astype('float32')/255
            face_crop = np.asarray(face_crop)
            face_crop = face_crop.reshape(1, 1,face_crop.shape[0],face_crop.shape[1])
            result = target[np.argmax(model.predict(face_crop))]
            cv2.putText(im,result,(x,y), font, 1, (200,0,0), 3, cv2.LINE_AA)
            
    cv2.imshow('result', im)
    cv2.imwrite('result.jpg',im)
    cv2.waitKey(0) 
Example 3
Project: trackingtermites   Author: dmrib   File: simulation.py    (license) View Source Project 8 votes vote down vote up
def draw_termites(self):
        """Draw termites on simulation.

        Args:
            None.
        Returns:
            None.
        """
        for termite in self.termites:
            cv2.circle(self.background, termite.trail[self.current_step],
                       self.params['termite_radius'], termite.color, 2)
            cv2.circle(self.background, termite.trail[self.current_step],
                       2, termite.color, -1)
            cv2.putText(self.background, termite.number, (termite.trail[self.current_step][0] - 4,
                        termite.trail[self.current_step][1] - self.params['termite_radius'] - 5), 2,
                        color=termite.color, fontScale=0.4)
            cv2.circle(self.video_source.current_frame, termite.trail[self.current_step],
                       self.params['termite_radius'], termite.color, 2)
            cv2.circle(self.video_source.current_frame, termite.trail[self.current_step],
                       2, termite.color, -1)
            cv2.putText(self.video_source.current_frame, termite.number, (termite.trail[self.current_step][0] - 4,
                        termite.trail[self.current_step][1] - self.params['termite_radius'] - 5), 2,
                        color=termite.color, fontScale=0.4) 
Example 4
Project: human-rl   Author: gsastry   File: human_feedback.py    (MIT License) View Source Project 7 votes vote down vote up
def add_text(img, text, text_top, image_scale):
    """
    Args:
        img (numpy array of shape (width, height, 3): input image
        text (str): text to add to image
        text_top (int): location of top text to add
        image_scale (float): image resize scale

    Summary:
        Add display text to a frame.

    Returns:
        Next available location of top text (allows for chaining this function)
    """
    cv2.putText(
        img=img,
        text=text,
        org=(0, text_top),
        fontFace=cv2.FONT_HERSHEY_SIMPLEX,
        fontScale=0.15 * image_scale,
        color=(255, 255, 255))
    return text_top + int(5 * image_scale) 
Example 5
Project: pe   Author: anguelos   File: rrcvisualisation.py    (license) View Source Project 7 votes vote down vote up
def plotRectangles(rects,transcriptions,bgrImg,rgbCol):
    bgrCol=np.array(rgbCol)[[2,1,0]]
    res=bgrImg.copy()
    pts=np.empty([rects.shape[0],5,1,2])
    if rects.shape[1]==4:
        x=rects[:,[0,2,2,0,0]]
        y=rects[:,[1,1,3,3,1]]
    elif rects.shape[1]==8:
        x=rects[:,[0,2,4,6,0]]
        y=rects[:,[1,3,5,7,1]]
    else:
        raise Exception()
    pts[:,:,0,0]=x
    pts[:,:,0,1]=y
    pts=pts.astype('int32')
    ptList=[pts[k,:,:,:] for k in range(pts.shape[0])]
    if not (transcriptions is None):
        for rectNum in range(rects.shape[0]):
            res=cv2.putText(res,transcriptions[rectNum],(rects[rectNum,0],rects[rectNum,1]),1,cv2.FONT_HERSHEY_PLAIN,bgrCol)
    res=cv2.polylines(res,ptList,False,bgrCol)
    return res 
Example 6
Project: pedestrianSys   Author: PhilipChicco   File: detector.py    (license) View Source Project 6 votes vote down vote up
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 
Example 7
Project: MLPractices   Author: carefree0910   File: NNVis.py    (MIT License) View Source Project 6 votes vote down vote up
def put_text(img, i, layers, y):
    """
    Put text on canvas
    :param img    : Canvas 
    :param i      : i-th hidden layer, notice that layers[i].name is the name of i-th hidden layer
    :param layers : Layers
    :param y      : (?, y) is the center of the neuron graph of i-th hidden layer 
    """
    ############################################################
    #                  Write your code here!                   #
    ############################################################

    cv2.putText(img, layers[i].name, (12, y - 36), cv2.LINE_AA, 0.6, (0, 0, 0), 1)

    ############################################################
    #                           End                            #
    ############################################################ 
Example 8
Project: esys-pbi   Author: fsxfreak   File: fixation_detector.py    (license) View Source Project 6 votes vote down vote up
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)) 
Example 9
Project: esys-pbi   Author: fsxfreak   File: fixation_detector.py    (license) View Source Project 6 votes vote down vote up
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)) 
Example 10
Project: camera_calibration_frontend   Author: groundmelon   File: kalibr_camera_focus.py    (license) View Source Project 6 votes vote down vote up
def callback(self, msg):
        #convert image to opencv
        try:
            cv_image = self.bridge.imgmsg_to_cv2(msg)
            np_image= np.array(cv_image)
        except CvBridgeError, e:
            print "Could not convert ros message to opencv image: ", e
            return
    
        #calculate the fft magnitude
        img_float32 = np.float32(np_image)
        dft = cv2.dft(img_float32, flags = cv2.DFT_COMPLEX_OUTPUT)
        dft_shift = np.fft.fftshift(dft)
        magnitude_spectrum = cv2.magnitude(dft_shift[:,:,0],dft_shift[:,:,1])
        
        #normalize
        magnitude_spectrum_normalized = magnitude_spectrum / np.sum(magnitude_spectrum)
        
        #frequency domain entropy (-> Entropy Based Measure of Camera Focus. Matej Kristan, Franjo Pernu. University of Ljubljana. Slovenia)
        fde = np.sum( magnitude_spectrum_normalized * np.log(magnitude_spectrum_normalized) )
    
        y = 20; x = 20
        text = "fde: {0}   (minimize this for focus)".format(np.sum(fde))
        np_image = cv2.cvtColor(np_image, cv2.COLOR_GRAY2BGR)
        cv2.putText(np_image, text, (x,y), cv2.FONT_HERSHEY_SIMPLEX, fontScale=0.5, color=(0, 0, 255), thickness=2)
        cv2.imshow(self.windowNameOrig, np_image)
        cv2.waitKey(10) 
Example 11
Project: py-faster-rcnn-tk1   Author: joeking11829   File: demo_opencv.py    (license) View Source Project 6 votes vote down vote up
def vis_detections(im, class_name, dets, thresh=0.5):
    """Draw detected bounding boxes."""
    inds = np.where(dets[:, -1] >= thresh)[0]
    if len(inds) == 0:
        return
    
    for i in inds:
        bbox = dets[i, :4]
        score = dets[i, -1]

        #Create Rectangle and Text using OpenCV
        #print ('ClassName:', class_name, 'bbox:', bbox, 'score:' ,score)
        
        #Draw the Rectangle
        cv2.rectangle(im, (bbox[0], bbox[1]), (bbox[2], bbox[3]), (0, 255, 0), 3)
        #Draw the Text
        cv2.putText(im, class_name + ' ' + str(score), (bbox[0], bbox[1]), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 0, 255), 2, cv2.LINE_AA)

        #Show Image
        #cv2.imshow("Detect Result", im) 
Example 12
Project: piwall-cvtools   Author: infinnovation   File: video.py    (license) View Source Project 6 votes vote down vote up
def render(self, dst):
        t = self.t
        self.t += 1.0/30.0
        
        l = 120
        black = [245,245,245]
        white = [10,10,10]
        colors = [black,white]
        nsq = 0
        x = 0
        for xs in range(0,16):
            y = 0
            for ys in range(0,9):
                fg = colors[nsq%2]
                bg = colors[(nsq+1) % 2]
                dst[y:y+l,x:x+l] = bg
                cv2.putText(dst, "%s" % nsq, (x+l/4, y+2*l/3), cv2.FONT_HERSHEY_PLAIN, 3, [0,0,255], thickness = 2, lineType=cv2.LINE_AA)
                y+=l
                nsq+=1
            x+=l 
Example 13
Project: fcn   Author: wkentaro   File: utils.py    (license) View Source Project 6 votes vote down vote up
def get_label_colortable(n_labels, shape):
    if cv2 is None:
        raise RuntimeError('get_label_colortable requires OpenCV (cv2)')
    rows, cols = shape
    if rows * cols < n_labels:
        raise ValueError
    cmap = label_colormap(n_labels)
    table = np.zeros((rows * cols, 50, 50, 3), dtype=np.uint8)
    for lbl_id, color in enumerate(cmap):
        color_uint8 = (color * 255).astype(np.uint8)
        table[lbl_id, :, :] = color_uint8
        text = '{:<2}'.format(lbl_id)
        cv2.putText(table[lbl_id], text, (5, 35),
                    cv2.cv.CV_FONT_HERSHEY_SIMPLEX, 0.8, (255, 255, 255), 3)
    table = table.reshape(rows, cols, 50, 50, 3)
    table = table.transpose(0, 2, 1, 3, 4)
    table = table.reshape(rows * 50, cols * 50, 3)
    return table


# -----------------------------------------------------------------------------
# Evaluation
# ----------------------------------------------------------------------------- 
Example 14
Project: canshi   Author: hungsing92   File: tag_bb.py    (license) View Source Project 6 votes vote down vote up
def click_and_crop(event, x, y, flags, param):
    global bbs, x_upper, id

    if event == cv2.EVENT_LBUTTONDOWN:
        if x_upper:
            bbs.append([x,y,0,0, 0,0,0,0])
        else:
            bbs[-1][4] = x
            bbs[-1][5] = y
            
    elif event == cv2.EVENT_LBUTTONUP:
        if x_upper:
            bbs[-1][2] = abs(x - bbs[-1][0])            
            bbs[-1][3] = abs(y - bbs[-1][1])
            bbs[-1][0] = min(x, bbs[-1][0])
            bbs[-1][1] = min(y, bbs[-1][1])
            cv2.rectangle(image, (bbs[-1][0],bbs[-1][1]), (bbs[-1][0]+bbs[-1][2],bbs[-1][1]+bbs[-1][3]), (0,0,255), 2)
            #cv2.putText(image, 'Upper %d' % id, (bbs[-1][0],bbs[-1][1]), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0,0,255))
        else:
            bbs[-1][6] = abs(x - bbs[-1][4])
            bbs[-1][7] = abs(y - bbs[-1][5])
            bbs[-1][4] = min(x, bbs[-1][4])
            bbs[-1][5] = min(y, bbs[-1][5])
            cv2.rectangle(image, (bbs[-1][4],bbs[-1][5]), (bbs[-1][4]+bbs[-1][6],bbs[-1][5]+bbs[-1][7]), (0,255,0), 2)
            cv2.putText(image, 'Body %d' % id, (bbs[-1][4],bbs[-1][5]), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0,255,0))
            
            
        cv2.imshow("image", image)        
        x_upper = not x_upper 
Example 15
Project: chainer-faster-rcnn   Author: mitmul   File: forward.py    (license) View Source Project 6 votes vote down vote up
def draw_result(out, im_scale, clss, bbox, nms_thresh, conf):
    CV_AA = 16
    for cls_id in range(1, 21):
        _cls = clss[:, cls_id][:, np.newaxis]
        _bbx = bbox[:, cls_id * 4: (cls_id + 1) * 4]
        dets = np.hstack((_bbx, _cls))
        keep = nms(dets, nms_thresh)
        dets = dets[keep, :]

        inds = np.where(dets[:, -1] >= conf)[0]
        for i in inds:
            x1, y1, x2, y2 = map(int, dets[i, :4])
            cv.rectangle(out, (x1, y1), (x2, y2), (0, 0, 255), 2, CV_AA)
            ret, baseline = cv.getTextSize(
                CLASSES[cls_id], cv.FONT_HERSHEY_SIMPLEX, 0.8, 1)
            cv.rectangle(out, (x1, y2 - ret[1] - baseline),
                         (x1 + ret[0], y2), (0, 0, 255), -1)
            cv.putText(out, CLASSES[cls_id], (x1, y2 - baseline),
                       cv.FONT_HERSHEY_SIMPLEX, 0.8, (255, 255, 255), 1, CV_AA)

    return out 
Example 16
Project: Gender   Author: rabeter   File: videoFind.py    (license) View Source Project 6 votes vote down vote up
def draw_rects(img, rects, color):
    """
    ?????????????
    :param img: 
    :param rects: 
    :param color: 
    :return: 
    """
    for x, y, w, h in rects:
        face = img[x:x+w,y:y+h]
        face = cv2.resize(face,(224,224))
        if gender.predict(face)==1:
            text = "Male"
        else:
            text = "Female"
        cv2.rectangle(img, (x, y), (w, h), color, 2)
        cv2.putText(img, text, (x, h), cv2.FONT_HERSHEY_SIMPLEX, 2.0, (255, 255, 255), lineType=cv2.LINE_AA) 
Example 17
Project: yolo2-pytorch   Author: longcw   File: yolo.py    (license) View Source Project 6 votes vote down vote up
def draw_detection(im, bboxes, scores, cls_inds, cfg, thr=0.3):
    # draw image
    colors = cfg.colors
    labels = cfg.label_names

    imgcv = np.copy(im)
    h, w, _ = imgcv.shape
    for i, box in enumerate(bboxes):
        if scores[i] < thr:
            continue
        cls_indx = cls_inds[i]

        thick = int((h + w) / 300)
        cv2.rectangle(imgcv,
                      (box[0], box[1]), (box[2], box[3]),
                      colors[cls_indx], thick)
        mess = '%s: %.3f' % (labels[cls_indx], scores[i])
        cv2.putText(imgcv, mess, (box[0], box[1] - 12),
                    0, 1e-3 * h, colors[cls_indx], thick // 3)

    return imgcv 
Example 18
Project: apparent-age-gender-classification   Author: danielyou0230   File: Modules.py    (license) View Source Project 6 votes vote down vote up
def facial_landmark_detection(image, detector, predictor, file):
	gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
	img_size = gray.shape
	landmark_faces = detector(gray, 1)

	faces = list()
	area = 0
	face_idx = 0
	bItr = False
	for (idx, landmark_faces) in enumerate(landmark_faces):
		shape = predictor(gray, landmark_faces)
		shape = shape_to_np(shape)
		(x, y, w, h) = rect_to_bb(landmark_faces, img_size, file)
		
		if (w * h) > area:
			area = w * h
			faces = [x, y, w, h]
			bItr = True
		#cv2.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 2)
		#cv2.putText(image, "Face #{}".format(idx + 1), (x - 10, y - 10), \
		#           cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
		#for (x, y) in shape:
		#   cv2.circle(image, (x, y), 1, (0, 0, 255), -1)

	return bItr, faces 
Example 19
Project: apparent-age-gender-classification   Author: danielyou0230   File: Modules.py    (license) View Source Project 6 votes vote down vote up
def debug_face_landmark(file, output=False, output_name='output'):
	detector = dlib.get_frontal_face_detector()
	predictor = dlib.shape_predictor(dat_face_landmark)

	image = cv2.imread(file)
	image = imutils.resize(image, width=500)
	gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
	img_size = gray.shape

	faces = detector(gray, 1)
	for (i, itr_face) in enumerate(faces):
		shape = predictor(gray, itr_face)
		shape = shape_to_np(shape)
		# convert dlib's rectangle to a OpenCV-style bounding box
		# [i.e., (x, y, w, h)], then draw the face bounding box
		(x, y, w, h) = rect_to_bb(itr_face, img_size, file)
		#print "landmark: ({:d}, {:d}) ({:d}, {:d})".format(x, y, w, h)
		
		cv2.rectangle(image, (x, y), (x + w, y + h), (0, 255, 0), 2)
		# show the face number
		cv2.putText(image, "Face #{}".format(i + 1), (x - 10, y - 10),
			cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)
	 
		# loop over the (x, y)-coordinates for the facial landmarks
		# and draw them on the image
		for (x, y) in shape:
			cv2.circle(image, (x, y), 1, (0, 0, 255), -1)

	# show the output image with the face detections + facial landmarks
	cv2.imshow(file, image)
	cv2.waitKey(0)
	if output:
		cv2.imwrite("../" + str(output_name + 1) + '.jpg', image)
	cv2.destroyAllWindows() 
Example 20
Project: FPN   Author: xmyqsh   File: train.py    (license) View Source Project 6 votes vote down vote up
def _draw_boxes_to_image(im, res):
    colors = [(86, 0, 240), (173, 225, 61), (54, 137, 255),\
              (151, 0, 255), (243, 223, 48), (0, 117, 255),\
              (58, 184, 14), (86, 67, 140), (121, 82, 6),\
              (174, 29, 128), (115, 154, 81), (86, 255, 234)]
    font = cv2.FONT_HERSHEY_SIMPLEX
    image = np.copy(im)
    cnt = 0
    for ind, r in enumerate(res):
        if r['dets'] is None: continue
        dets = r['dets']
        for i in range(0, dets.shape[0]):
            (x1, y1, x2, y2, score) = dets[i, :]
            cv2.rectangle(image, (int(x1), int(y1)), (int(x2), int(y2)), colors[ind % len(colors)], 2)
            text = '{:s} {:.2f}'.format(r['class'], score)
            cv2.putText(image, text, (x1, y1), font, 0.6, colors[ind % len(colors)], 1)
            cnt = (cnt + 1)
    return image 
Example 21
Project: TFFRCNN   Author: InterVideo   File: kitti2pascalvoc.py    (license) View Source Project 6 votes vote down vote up
def _draw_on_image(img, objs, class_sets_dict):
    colors = [(86, 0, 240), (173, 225, 61), (54, 137, 255),\
              (151, 0, 255), (243, 223, 48), (0, 117, 255),\
              (58, 184, 14), (86, 67, 140), (121, 82, 6),\
              (174, 29, 128), (115, 154, 81), (86, 255, 234)]
    font = cv2.FONT_HERSHEY_SIMPLEX
    for ind, obj in enumerate(objs):
        if obj['box'] is None: continue
        x1, y1, x2, y2 = obj['box'].astype(int)
        cls_id = class_sets_dict[obj['class']]
        if obj['class'] == 'dontcare':
            cv2.rectangle(img, (int(x1), int(y1)), (int(x2), int(y2)), (255, 0, 0), 1)
            continue
        cv2.rectangle(img, (int(x1), int(y1)), (int(x2), int(y2)), colors[cls_id % len(colors)], 1)
        text = '{:s}*|'.format(obj['class'][:3]) if obj['difficult'] == 1 else '{:s}|'.format(obj['class'][:3])
        text += '{:.1f}|'.format(obj['truncation'])
        text += str(obj['occlusion'])
        cv2.putText(img, text, (x1-2, y2-2), font, 0.5, (255, 0, 255), 1)
    return img 
Example 22
Project: ck-tensorflow   Author: ctuning   File: continuous.py    (license) View Source Project 6 votes vote down vote up
def my_draw_box(im, box_list, label_list, color=(0,255,0), cdict=None, label_placement='bottom'):
    assert label_placement == 'bottom' or label_placement == 'top', \
        'label_placement format not accepted: {}.'.format(label_placement)

    for bbox, label in zip(box_list, label_list):

        xmin, ymin, xmax, ymax = [int(b) for b in bbox]

        l = label.split(':')[0] # text before "CLASS: (PROB)"
        if cdict and l in cdict:
            c = cdict[l]
        else:
            c = color

        # draw box
        cv2.rectangle(im, (xmin, ymin), (xmax, ymax), c, 1)
        # draw label
        font = cv2.FONT_HERSHEY_SIMPLEX
        if label_placement == 'bottom':
            cv2.putText(im, label, (xmin, ymax), font, 0.3, c, 1)
        else:
            cv2.putText(im, label, (xmin, ymin), font, 0.3, c, 1) 
Example 23
Project: tf-openpose   Author: ildoonet   File: common_test.py    (license) View Source Project 6 votes vote down vote up
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) 
Example 24
Project: imgProcessor   Author: radjkarl   File: patterns.py    (license) View Source Project 6 votes vote down vote up
def patText(s0):
    '''make text pattern'''
    arr = np.zeros((s0,s0), dtype=np.uint8)
    s = int(round(s0/100.))
    p1 = 0
    pp1 = int(round(s0/10.))
    for pos0 in np.linspace(0,s0,10):
        cv2.putText(arr, 'helloworld', (p1,int(round(pos0))), 
                    cv2.FONT_HERSHEY_COMPLEX_SMALL, fontScale=s,
                    color=255, thickness=s,
                    lineType=cv2.LINE_AA )
        if p1:
            p1 = 0
        else:
            p1 = pp1
    return arr.astype(float) 
Example 25
Project: Course-Projects   Author: manujagobind   File: paint.py    (license) View Source Project 6 votes vote down vote up
def display_shape():
	global shape
	if shape == 0:
		cv2.putText(obj, 'Off', (50, 250), cv2.FONT_HERSHEY_SIMPLEX, 3, (255, 255, 255), 2)
	elif shape == 1:
		cv2.putText(obj, 'Pencil', (50, 250), cv2.FONT_HERSHEY_SIMPLEX, 3, (255, 255, 255), 2)
	elif shape == 2:
		cv2.putText(obj, 'Brush', (50, 250), cv2.FONT_HERSHEY_SIMPLEX, 3, (255, 255, 255), 2)
	elif shape == 3:
		cv2.putText(obj, 'Eraser', (50, 250), cv2.FONT_HERSHEY_SIMPLEX, 3, (255, 255, 255), 2)
	elif shape == 4:
		cv2.putText(obj, 'Line', (50, 250), cv2.FONT_HERSHEY_SIMPLEX, 3, (255, 255, 255), 2)
	elif shape == 5:
		cv2.putText(obj, 'Rectangle', (50, 250), cv2.FONT_HERSHEY_SIMPLEX, 3, (255, 255, 255), 2)
	elif shape == 6:
		cv2.putText(obj, 'Circle', (50, 250), cv2.FONT_HERSHEY_SIMPLEX, 3, (255, 255, 255), 2) 
Example 26
Project: SSD_tensorflow_VOC   Author: LevinJ   File: visualization.py    (license) View Source Project 6 votes vote down vote up
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...
# =========================================================================== # 
Example 27
Project: BAR4Py   Author: bxtkezhan   File: debugtools.py    (license) View Source Project 6 votes vote down vote up
def drawAxis(camera_parameters, markers, frame):
    axis = np.float32([[1,0,0], [0,1,0], [0,0,1]]).reshape(-1,3)
    mtx, dist = camera_parameters.camera_matrix, camera_parameters.dist_coeff

    for marker in markers:
        rvec, tvec = marker.rvec, marker.tvec
        imgpts, jac = cv2.projectPoints(axis, rvec, tvec, mtx, dist)
        corners = marker.corners
        corner = tuple(corners[0].ravel())
        cv2.line(frame, corner, tuple(imgpts[0].ravel()), (0,0,255), 2)
        cv2.line(frame, corner, tuple(imgpts[1].ravel()), (0,255,0), 2)
        cv2.line(frame, corner, tuple(imgpts[2].ravel()), (255,0,0), 2)
        font = cv2.FONT_HERSHEY_SIMPLEX
        cv2.putText(frame, 'X', tuple(imgpts[0].ravel()), font, 0.5, (0,0,255), 2, cv2.LINE_AA)
        cv2.putText(frame, 'Y', tuple(imgpts[1].ravel()), font, 0.5, (0,255,0), 2, cv2.LINE_AA)
        cv2.putText(frame, 'Z', tuple(imgpts[2].ravel()), font, 0.5, (255,0,0), 2, cv2.LINE_AA) 
Example 28
Project: BAR4Py   Author: bxtkezhan   File: debugtools.py    (license) View Source Project 6 votes vote down vote up
def drawAxis(camera_parameters, markers, frame):
    axis = np.float32([[1,0,0], [0,1,0], [0,0,1]]).reshape(-1,3)
    mtx, dist = camera_parameters.camera_matrix, camera_parameters.dist_coeff

    for marker in markers:
        rvec, tvec = marker.rvec, marker.tvec
        imgpts, jac = cv2.projectPoints(axis, rvec, tvec, mtx, dist)
        corners = marker.corners
        corner = tuple(corners[0].ravel())
        cv2.line(frame, corner, tuple(imgpts[0].ravel()), (0,0,255), 2)
        cv2.line(frame, corner, tuple(imgpts[1].ravel()), (0,255,0), 2)
        cv2.line(frame, corner, tuple(imgpts[2].ravel()), (255,0,0), 2)
        font = cv2.FONT_HERSHEY_SIMPLEX
        cv2.putText(frame, 'X', tuple(imgpts[0].ravel()), font, 0.5, (0,0,255), 2, cv2.LINE_AA)
        cv2.putText(frame, 'Y', tuple(imgpts[1].ravel()), font, 0.5, (0,255,0), 2, cv2.LINE_AA)
        cv2.putText(frame, 'Z', tuple(imgpts[2].ravel()), font, 0.5, (255,0,0), 2, cv2.LINE_AA) 
Example 29
Project: BAR4Py   Author: bxtkezhan   File: debugtools.py    (license) View Source Project 6 votes vote down vote up
def drawAxis(camera_parameters, markers, frame):
    axis = np.float32([[1,0,0], [0,1,0], [0,0,1]]).reshape(-1,3)
    mtx, dist = camera_parameters.camera_matrix, camera_parameters.dist_coeff

    for marker in markers:
        rvec, tvec = marker.rvec, marker.tvec
        imgpts, jac = cv2.projectPoints(axis, rvec, tvec, mtx, dist)
        corners = marker.corners
        corner = tuple(corners[0].ravel())
        cv2.line(frame, corner, tuple(imgpts[0].ravel()), (0,0,255), 2)
        cv2.line(frame, corner, tuple(imgpts[1].ravel()), (0,255,0), 2)
        cv2.line(frame, corner, tuple(imgpts[2].ravel()), (255,0,0), 2)
        font = cv2.FONT_HERSHEY_SIMPLEX
        cv2.putText(frame, 'X', tuple(imgpts[0].ravel()), font, 0.5, (0,0,255), 2, cv2.LINE_AA)
        cv2.putText(frame, 'Y', tuple(imgpts[1].ravel()), font, 0.5, (0,255,0), 2, cv2.LINE_AA)
        cv2.putText(frame, 'Z', tuple(imgpts[2].ravel()), font, 0.5, (255,0,0), 2, cv2.LINE_AA) 
Example 30
Project: tbotnav   Author: patilnabhi   File: train_faces2.py    (license) View Source Project 6 votes vote down vote up
def process_image(self, inImg):
        (self.frame_width, self.frame_height) = (112, 92)        
        frame = cv2.flip(inImg,1,0)
        grayImg = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) 
        cropped = cv2.resize(grayImg, (grayImg.shape[1] / self.size, grayImg.shape[0] / self.size))        
        faces = self.haar_cascade.detectMultiScale(cropped)
        faces = sorted(faces, key=lambda x: x[3])  
        if faces:
            face_i = faces[0] 
            x = face_i[0] * self.size
            y = face_i[1] * self.size
            w = face_i[2] * self.size
            h = face_i[3] * self.size
            face = grayImg[y:y + h, x:x + w]
            face_resize = cv2.resize(face, (self.frame_width, self.frame_height))
            img_no = sorted([int(fn[:fn.find('.')]) for fn in os.listdir(self.path) if fn[0]!='.' ]+[0])[-1] + 1
            if self.count % self.cp_rate == 0:
                cv2.imwrite('%s/%s.png' % (self.path, img_no), face_resize)
                print "Captured Img: ", self.count/self.cp_rate + 1
            cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 3)
            cv2.putText(frame, self.face_name, (x - 10, y - 10), cv2.FONT_HERSHEY_PLAIN, 1,(0, 255, 0))            
            self.count += 1 
        return frame 
Example 31
Project: tbotnav   Author: patilnabhi   File: train_faces.py    (license) View Source Project 6 votes vote down vote up
def process_image(self, inImg):
        (self.frame_width, self.frame_height) = (112, 92)        
        frame = cv2.flip(inImg,1,0)
        grayImg = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) 
        cropped = cv2.resize(grayImg, (grayImg.shape[1] / self.size, grayImg.shape[0] / self.size))        
        faces = self.haar_cascade.detectMultiScale(cropped)
        faces = sorted(faces, key=lambda x: x[3])  
        if faces:
            face_i = faces[0] 
            x = face_i[0] * self.size
            y = face_i[1] * self.size
            w = face_i[2] * self.size
            h = face_i[3] * self.size
            face = grayImg[y:y + h, x:x + w]
            face_resize = cv2.resize(face, (self.frame_width, self.frame_height))
            img_no = sorted([int(fn[:fn.find('.')]) for fn in os.listdir(self.path) if fn[0]!='.' ]+[0])[-1] + 1
            if self.count % self.cp_rate == 0:
                cv2.imwrite('%s/%s.png' % (self.path, img_no), face_resize)
                print "Captured Img: ", self.count/self.cp_rate + 1
            cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 3)
            cv2.putText(frame, self.face_name, (x - 10, y - 10), cv2.FONT_HERSHEY_PLAIN, 1,(0, 255, 0))            
            self.count += 1 
        return frame 
Example 32
Project: projectoxford   Author: zooba   File: emotion.py    (license) View Source Project 6 votes vote down vote up
def _renderResultOnImage(self, result, arr):
        """
            Draws boxes and text representing each face's emotion.
        """

        import operator, cv2

        img = cv2.cvtColor(cv2.imdecode(arr, -1), cv2.COLOR_BGR2RGB)

        for currFace in result:
            faceRectangle = currFace['faceRectangle']
            cv2.rectangle(img,(faceRectangle['left'],faceRectangle['top']),
                               (faceRectangle['left']+faceRectangle['width'], faceRectangle['top'] + faceRectangle['height']),
                               color = (255,0,0), thickness = 5)

        for currFace in result:
            faceRectangle = currFace['faceRectangle']
            currEmotion = max(iter(currFace['scores'].items()), key=operator.itemgetter(1))[0]

            textToWrite = '{0}'.format(currEmotion)
            cv2.putText(img, textToWrite, (faceRectangle['left'],faceRectangle['top']-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,0,0), 1)

        return img 
Example 33
Project: OpenCV2   Author: SarathM1   File: dip.py    (license) View Source Project 6 votes vote down vote up
def lipSegment(self, img):
        # self.t1 = cv2.getTickCount()
        lipHull = self.dlib_obj.get_landmarks(img)
        cv2.drawContours(img, lipHull, -1, (255, 0, 0), 2)
        (x, y), (MA, ma), angle = cv2.fitEllipse(lipHull)
        a = ma/2
        b = MA/2

        eccentricity = sqrt(pow(a, 2)-pow(b, 2))
        eccentricity = round(eccentricity/a, 2)

        cv2.putText(img, 'E = '+str(round(eccentricity, 3)), (10, 350),
                    self.font, 1, (255, 0, 0), 1)

        if(eccentricity < 0.9):
            self.flags.cmd = 'b'
        else:
            self.flags.cmd = 'f'

        if angle < 80:
            self.flags.cmd = 'l'
        elif angle > 100:
            self.flags.cmd = 'r'

        cv2.putText(img, 'Cmd = ' + self.flags.cmd, (10, 300),  self.font,  1,
                    (0, 0, 255), 1, 16)
        # self.t2 = cv2.getTickCount()
        # print "Time = ", (self.t2-self.t1)/cv2.getTickFrequency()
        return img 
Example 34
Project: Face-recognition-test   Author: jiangwei1995910   File: Read.py    (license) View Source Project 6 votes vote down vote up
def photoRead(filename):
    frame = cv2.imread(filename)

    FaceArray = getFaceArray(frame)

    for r in FaceArray:
        img2 = cv2.rectangle(frame, (r[0], r[1]), (r[2], r[3]), (0, 255, 0), 3)
        img3 = frame[r[1]:r[3], r[0]:r[2]]  # ?????????????
        feature = Tools.get_feature(img3)
        name = readFace(feature)
        font = cv2.FONT_HERSHEY_SIMPLEX
        img2 = cv2.putText(img2, name, (r[1], r[3]), font, 1, (255, 255, 255), 2)


    cv2.imshow('frame', frame)
    cv2.waitKey(0) 
Example 35
Project: Face-recognition-test   Author: jiangwei1995910   File: Read.py    (license) View Source Project 6 votes vote down vote up
def start():
    cap = cv2.VideoCapture(0)
    while(True):
        # Capture frame-by-frame
        ret, frame = cap.read()

        FaceArray=getFaceArray(frame)
        img2=frame
        for r in FaceArray :
            img2=cv2.rectangle(frame, (r[0], r[1]), (r[2], r[3]), (0, 255, 0), 3)
            img3 = frame[r[1]:r[3], r[0]:r[2]]  # ?????????????
            feature=Tools.get_feature(img3)
            name=readFace(feature)
            font=cv2.FONT_HERSHEY_SIMPLEX
            img2= cv2.putText(img2,name,(r[1],r[3]), font, 1,(255,255,255),2)

        cv2.imshow('frame',img2)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break 
Example 36
Project: deep_sort   Author: nwojke   File: image_viewer.py    (license) View Source Project 6 votes vote down vote up
def rectangle(self, x, y, w, h, label=None):
        """Draw a rectangle.

        Parameters
        ----------
        x : float | int
            Top left corner of the rectangle (x-axis).
        y : float | int
            Top let corner of the rectangle (y-axis).
        w : float | int
            Width of the rectangle.
        h : float | int
            Height of the rectangle.
        label : Optional[str]
            A text label that is placed at the top left corner of the
            rectangle.

        """
        pt1 = int(x), int(y)
        pt2 = int(x + w), int(y + h)
        cv2.rectangle(self.image, pt1, pt2, self._color, self.thickness)
        if label is not None:
            text_size = cv2.getTextSize(
                label, cv2.FONT_HERSHEY_PLAIN, 1, self.thickness)

            center = pt1[0] + 5, pt1[1] + 5 + text_size[0][1]
            pt2 = pt1[0] + 10 + text_size[0][0], pt1[1] + 10 + \
                text_size[0][1]
            cv2.rectangle(self.image, pt1, pt2, self._color, -1)
            cv2.putText(self.image, label, center, cv2.FONT_HERSHEY_PLAIN,
                        1, (255, 255, 255), self.thickness) 
Example 37
Project: DubHacks2016   Author: joseph-zhong   File: cognitiveService.py    (license) View Source Project 6 votes vote down vote up
def renderResultOnImage( result, img ):

  """Display the obtained results onto the input image"""

  for currFace in result:
    faceRectangle = currFace['faceRectangle']
    cv2.rectangle( img,(faceRectangle['left'],faceRectangle['top']),
                       (faceRectangle['left']+faceRectangle['width'], faceRectangle['top'] + faceRectangle['height']),
                   color = (255,0,0), thickness = 5 )


  for currFace in result:
    faceRectangle = currFace['faceRectangle']
    currEmotion = max(currFace['scores'].items(), key=operator.itemgetter(1))[0]


    textToWrite = "%s" % ( currEmotion )
    cv2.putText( img, textToWrite, (faceRectangle['left'],faceRectangle['top']-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,0,0), 1 )

# img = os.path.expanduser('~/Development/sentiEdu/learning/confusedImgs/4.jpg') 
Example 38
Project: DubHacks2016   Author: joseph-zhong   File: notConfusedCognitiveService.py    (license) View Source Project 6 votes vote down vote up
def renderResultOnImage( result, img ):

  """Display the obtained results onto the input image"""

  for currFace in result:
    faceRectangle = currFace['faceRectangle']
    cv2.rectangle( img,(faceRectangle['left'],faceRectangle['top']),
                       (faceRectangle['left']+faceRectangle['width'], faceRectangle['top'] + faceRectangle['height']),
                   color = (255,0,0), thickness = 5 )


  for currFace in result:
    faceRectangle = currFace['faceRectangle']
    currEmotion = max(currFace['scores'].items(), key=operator.itemgetter(1))[0]


    textToWrite = "%s" % ( currEmotion )
    cv2.putText( img, textToWrite, (faceRectangle['left'],faceRectangle['top']-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,0,0), 1 )

# img = os.path.expanduser('~/Development/sentiEdu/learning/confusedImgs/4.jpg') 
Example 39
Project: DubHacks2016   Author: joseph-zhong   File: test.py    (license) View Source Project 6 votes vote down vote up
def renderResultOnImage( result, img ):

  """Display the obtained results onto the input image"""

  for currFace in result:
    faceRectangle = currFace['faceRectangle']
    cv2.rectangle( img,(faceRectangle['left'],faceRectangle['top']),
                       (faceRectangle['left']+faceRectangle['width'], faceRectangle['top'] + faceRectangle['height']),
                   color = (255,0,0), thickness = 5 )


  for currFace in result:
    faceRectangle = currFace['faceRectangle']
    currEmotion = max(currFace['scores'].items(), key=operator.itemgetter(1))[0]


    textToWrite = "%s" % ( currEmotion )
    cv2.putText( img, textToWrite, (faceRectangle['left'],faceRectangle['top']-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255,0,0), 1 )

# img = os.path.expanduser('~/Development/sentiEdu/learning/confusedImgs/4.jpg') 
Example 40
Project: faster_rcnn_logo   Author: romyny   File: demo.py    (license) View Source Project 6 votes vote down vote up
def vis_detections(im, class_name, dets, thresh=0.5):
    """Draw detected bounding boxes."""
    inds = np.where(dets[:, -1] >= thresh)[0]
    if len(inds) == 0:
        return
        
    l_bboxes = []    
    for i in inds:
        bbox = dets[i, :4]
        score = dets[i, -1]

        print ('Det: (x_min,y_min,W,H) = ({},{},{},{}), class_name = {:s}, score = {:.3f}').format(
                int(bbox[0]),int(bbox[1]),int(bbox[2]-bbox[0]),int(bbox[3]-bbox[1]),class_name,score)
        cv2.rectangle(im, (bbox[0], bbox[3]),(bbox[2],bbox[1]), (0,255,0),2)      
        cv2.putText(im,'{:s}:{:.3f}'.format(class_name, score),
                (int(bbox[0]), int(bbox[1]) - 3), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,255,0),2)
        
        l_bboxes.append({'x_min':int(bbox[0]),'y_min':int(bbox[1]),'x_max':bbox[2],'y_max':bbox[3],'cls':class_name,'score':score})
    
    return l_bboxes 
Example 41
Project: TF_Deformable_Net   Author: Zardinality   File: train.py    (license) View Source Project 6 votes vote down vote up
def _draw_boxes_to_image(im, res):
    colors = [(86, 0, 240), (173, 225, 61), (54, 137, 255),\
              (151, 0, 255), (243, 223, 48), (0, 117, 255),\
              (58, 184, 14), (86, 67, 140), (121, 82, 6),\
              (174, 29, 128), (115, 154, 81), (86, 255, 234)]
    font = cv2.FONT_HERSHEY_SIMPLEX
    image = np.copy(im)
    cnt = 0
    for ind, r in enumerate(res):
        if r['dets'] is None: continue
        dets = r['dets']
        for i in range(0, dets.shape[0]):
            (x1, y1, x2, y2, score) = dets[i, :]
            cv2.rectangle(image, (int(x1), int(y1)), (int(x2), int(y2)), colors[ind % len(colors)], 2)
            text = '{:s} {:.2f}'.format(r['class'], score)
            cv2.putText(image, text, (x1, y1), font, 0.6, colors[ind % len(colors)], 1)
            cnt = (cnt + 1)
    return image 
Example 42
Project: TF_Deformable_Net   Author: Zardinality   File: kitti2pascalvoc.py    (license) View Source Project 6 votes vote down vote up
def _draw_on_image(img, objs, class_sets_dict):
    colors = [(86, 0, 240), (173, 225, 61), (54, 137, 255),\
              (151, 0, 255), (243, 223, 48), (0, 117, 255),\
              (58, 184, 14), (86, 67, 140), (121, 82, 6),\
              (174, 29, 128), (115, 154, 81), (86, 255, 234)]
    font = cv2.FONT_HERSHEY_SIMPLEX
    for ind, obj in enumerate(objs):
        if obj['box'] is None: continue
        x1, y1, x2, y2 = obj['box'].astype(int)
        cls_id = class_sets_dict[obj['class']]
        if obj['class'] == 'dontcare':
            cv2.rectangle(img, (int(x1), int(y1)), (int(x2), int(y2)), (255, 0, 0), 1)
            continue
        cv2.rectangle(img, (int(x1), int(y1)), (int(x2), int(y2)), colors[cls_id % len(colors)], 1)
        text = '{:s}*|'.format(obj['class'][:3]) if obj['difficult'] == 1 else '{:s}|'.format(obj['class'][:3])
        text += '{:.1f}|'.format(obj['truncation'])
        text += str(obj['occlusion'])
        cv2.putText(img, text, (x1-2, y2-2), font, 0.5, (255, 0, 255), 1)
    return img 
Example 43
Project: IoT-Client   Author: suquark   File: simple_motion_detection.py    (license) View Source Project 6 votes vote down vote up
def draw_on_detected(frame, rects, timestamp):
    # Draw the bounding box on the frame
    for (x, y, w, h) in rects:
        cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)

    # draw the text and timestamp on the frame
    ts = timestamp.strftime("%A %d %B %Y %I:%M:%S%p")
    cv2.putText(frame, "Status: Open", (10, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255),
                2)
    cv2.putText(frame, ts, (10, frame.shape[0] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.35, (0, 0, 255), 1)

    # write the image to temporary file

    # t = TempImage()
    # print('File saved at' + str(t.path))
    # cv2.imwrite(t.path, frame)

    # analyze
    # pi_surveillance_analyze.analyze(t.path) 
Example 44
Project: GLMF203   Author: GLMF   File: ocv_detection.py    (license) View Source Project 6 votes vote down vote up
def archive_with_items(self):
        """ Ecrit dans le dossier d'archive la frame complète avec des carrés dessinés autour
            des visages détectés
        """
        logging.info("Archive l'image avec les items trouvés...")
        # Dessine un carré autour de chaque item
        for f in self.items: 
            x, y, w, h = f #[ v for v in f ] 
            cv2.rectangle(self.frame, (x,y), (x+w,y+h), (0,255,0), 3) 

        # Ajoute la date et l'heure à l'image
        cv2.putText(self.frame, datetime.datetime.now().strftime("%c"), (5, 25), 
                    cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0,0,0), 3) 
            
        # On affiche l'image qui va être archivée dans une fenêtre
        if self.debug:
            cv2.imshow("preview", self.frame) 
            cv2.waitKey() 

        # Ecriture du fichier
        archive_full_name = "{0}_full.jpg".format(self.images_prefix)
        logging.info("Archive file is : '{0}'".format(archive_full_name))
        cv2.imwrite(os.path.join(self.archive_folder,  archive_full_name), self.frame) 
Example 45
Project: live-age-gender-estimator   Author: taipalma   File: VideoThread.py    (license) View Source Project 6 votes vote down vote up
def annotate(self, frame):
         text = "Frame rate: %.1f" % self.frameRate
         textColor = (0,255,0)
         font = cv2.FONT_HERSHEY_SIMPLEX
         size = 0.5
         thickness = 2
         textSize = cv2.getTextSize(text, font, size, thickness)
         height = textSize[1]         
         location = (0,frame.shape[0] - 4*height)
         cv2.putText(frame, text, location, font, size, textColor,
            thickness=thickness)
                     
         text = "Detection rate: %.1f" % self.detectionRate
         location = (0,frame.shape[0] - height)
         cv2.putText(frame, text, location, font, size, textColor,
            thickness=thickness) 
Example 46
Project: YOLO_tensorflow   Author: gliese581gg   File: YOLO_tiny_tf.py    (license) View Source Project 6 votes vote down vote up
def show_results(self,img,results):
		img_cp = img.copy()
		if self.filewrite_txt :
			ftxt = open(self.tofile_txt,'w')
		for i in range(len(results)):
			x = int(results[i][1])
			y = int(results[i][2])
			w = int(results[i][3])//2
			h = int(results[i][4])//2
			if self.disp_console : print '    class : ' + results[i][0] + ' , [x,y,w,h]=[' + str(x) + ',' + str(y) + ',' + str(int(results[i][3])) + ',' + str(int(results[i][4]))+'], Confidence = ' + str(results[i][5])
			if self.filewrite_img or self.imshow:
				cv2.rectangle(img_cp,(x-w,y-h),(x+w,y+h),(0,255,0),2)
				cv2.rectangle(img_cp,(x-w,y-h-20),(x+w,y-h),(125,125,125),-1)
				cv2.putText(img_cp,results[i][0] + ' : %.2f' % results[i][5],(x-w+5,y-h-7),cv2.FONT_HERSHEY_SIMPLEX,0.5,(0,0,0),1)
			if self.filewrite_txt :				
				ftxt.write(results[i][0] + ',' + str(x) + ',' + str(y) + ',' + str(w) + ',' + str(h)+',' + str(results[i][5]) + '\n')
		if self.filewrite_img : 
			if self.disp_console : print '    image file writed : ' + self.tofile_img
			cv2.imwrite(self.tofile_img,img_cp)			
		if self.imshow :
			cv2.imshow('YOLO_tiny detection',img_cp)
			cv2.waitKey(1)
		if self.filewrite_txt : 
			if self.disp_console : print '    txt file writed : ' + self.tofile_txt
			ftxt.close() 
Example 47
Project: YOLO_tensorflow   Author: gliese581gg   File: YOLO_face_tf.py    (license) View Source Project 6 votes vote down vote up
def show_results(self,img,results):
		img_cp = img.copy()
		if self.filewrite_txt :
			ftxt = open(self.tofile_txt,'w')
		for i in range(len(results)):
			x = int(results[i][1])
			y = int(results[i][2])
			w = int(results[i][3])//2
			h = int(results[i][4])//2
			if self.disp_console : print '    class : ' + results[i][0] + ' , [x,y,w,h]=[' + str(x) + ',' + str(y) + ',' + str(int(results[i][3])) + ',' + str(int(results[i][4]))+'], Confidence = ' + str(results[i][5])
			if self.filewrite_img or self.imshow:
				cv2.rectangle(img_cp,(x-w,y-h),(x+w,y+h),(0,255,0),2)
				cv2.rectangle(img_cp,(x-w,y-h-20),(x+w,y-h),(125,125,125),-1)
				cv2.putText(img_cp,results[i][0] + ' : %.2f' % results[i][5],(x-w+5,y-h-7),cv2.FONT_HERSHEY_SIMPLEX,0.5,(0,0,0),1)
			if self.filewrite_txt :				
				ftxt.write(results[i][0] + ',' + str(x) + ',' + str(y) + ',' + str(w) + ',' + str(h)+',' + str(results[i][5]) + '\n')
		if self.filewrite_img : 
			if self.disp_console : print '    image file writed : ' + self.tofile_img
			cv2.imwrite(self.tofile_img,img_cp)			
		if self.imshow :
			cv2.imshow('YOLO_face detection',img_cp)
			cv2.waitKey(1)
		if self.filewrite_txt : 
			if self.disp_console : print '    txt file writed : ' + self.tofile_txt
			ftxt.close() 
Example 48
Project: recognizeFitExercise   Author: tyiannak   File: visualMovieAnalysis2.py    (license) View Source Project 6 votes vote down vote up
def drawArrow(image, p, q, color, arrowMagnitude = 5, thickness=1, line_type=8, shift=0):
    # Draw the principle line
    cv2.line(image, tuple(p), tuple(q), color, thickness, line_type, shift);
    # compute the angle alpha
    angle = numpy.arctan2( p[1]-q[1], p[0]-q[0]);
    # compute the coordinates of the first segment
    p[0] =  int(q[0] +  arrowMagnitude * numpy.cos(angle + numpy.pi/4.0));
    p[1] =  int(q[1] +  arrowMagnitude * numpy.sin(angle + numpy.pi/4.0));
    # /Draw the first segment
    cv2.line(image, tuple(p), tuple(q), color, thickness, line_type, shift);
    # compute the coordinates of the second segment
    p[0] =  int(q[0] +  arrowMagnitude * numpy.cos(angle - numpy.pi/4.0));
    p[1] =  int(q[1] +  arrowMagnitude * numpy.sin(angle - numpy.pi/4.0));

    # Draw the second segment
    cv2.line(image, tuple(p), tuple(q), color, thickness, line_type, shift);
#    cv2.putText(image, str(int(180.0*angle/numpy.pi)), tuple(p), cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, 255 )
    return image 
Example 49
Project: prepare-faces-zyf   Author: walkoncross   File: mtcnn_aligner.py    (license) View Source Project 6 votes vote down vote up
def cv2_put_text_to_image(img, text, x, y, font_pix_h=10, color=(255, 0, 0)):
    if font_pix_h < 10:
        font_pix_h = 10

    # print img.shape

    h = img.shape[0]

    if x < 0:
        x = 0

    if y > h - 1:
        y = h - font_pix_h

    if y < 0:
        y = font_pix_h

    font_size = font_pix_h / 30.0
    # print font_size
    cv2.putText(img, text, (x, y), cv2.FONT_HERSHEY_SIMPLEX,
                font_size, color, 1) 
Example 50
Project: prepare-faces-zyf   Author: walkoncross   File: mtcnn_aligner.py    (license) View Source Project 6 votes vote down vote up
def cv2_put_text_to_image(img, text, x, y, font_pix_h=10, color=(255, 0, 0)):
    if font_pix_h < 10:
        font_pix_h = 10

    # print img.shape

    h = img.shape[0]

    if x < 0:
        x = 0

    if y > h - 1:
        y = h - font_pix_h

    if y < 0:
        y = font_pix_h

    font_size = font_pix_h / 30.0
    # print font_size
    cv2.putText(img, text, (x, y), cv2.FONT_HERSHEY_SIMPLEX,
                font_size, color, 1)