我们从Python开源项目中,提取了以下40个代码示例,用于说明如何使用cv2.FONT_HERSHEY_PLAIN。
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
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
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
def run(self, input_image, output_image, face): if not self.enabled: return if face is None: self.drone.hover() return face_x, face_y, face_w, face_h = face face_middle_x = face_x + face_w / 2 face_middle_y = face_y + face_h / 2 cv2.rectangle(output_image, (face_x, face_y), (face_x + face_w, face_y + face_h), (0, 255, 0), 2) u_face_x = self.x_pid.tick(face_middle_x, self.middle_x) / self.x_max u_face_y = self.y_pid.tick(face_middle_y, self.middle_y) / self.y_max u_face_z = self.z_pid.tick(face_h, self.z_opt) / self.z_max print u_face_x, u_face_y, u_face_z cv2.putText(output_image, '%f %f %f' % (u_face_x, u_face_y, u_face_z), (self.height - 30, self.width - 30), cv2.FONT_HERSHEY_PLAIN, 1, (255, 255, 255), 1) if math.fabs(face_middle_x - self.middle_x) > 80: self.drone.at(at_pcmd, True, 0, -u_face_z * 0.7, u_face_y * -0.8, u_face_x * 0.6) else: self.drone.at(at_pcmd, True, 0, -u_face_z * 2.5, u_face_y * -0.8, u_face_x * 0.2)
def _drawString(image, target, string): x, y = target cv2.putText( image, string, (x+1, y+1), cv2.FONT_HERSHEY_PLAIN, 1.0, (0, 0, 0), thickness=2, lineType=cv2.LINE_AA) cv2.putText( image, string, (x, y), cv2.FONT_HERSHEY_PLAIN, 1.0, (255, 255, 255), lineType=cv2.LINE_AA)
def annotateImg(img, color, size, position, text): cv2.putText(img, text, position, cv2.FONT_HERSHEY_PLAIN, size, color, thickness = 2) return img
def draw_str(dst, target, s, scale): x, y = target cv2.putText(dst, s, (x+1, y+1), cv2.FONT_HERSHEY_PLAIN, scale, (0, 0, 0), thickness = 2, lineType=cv2.LINE_AA) cv2.putText(dst, s, (x, y), cv2.FONT_HERSHEY_PLAIN, scale, (255, 255, 255), lineType=cv2.LINE_AA)
def vis_detections(im, class_name, dets, thresh=0.8): """Visual debugging of detections.""" for i in range(np.minimum(10, dets.shape[0])): bbox = tuple(int(np.round(x)) for x in dets[i, :4]) score = dets[i, -1] if score > thresh: cv2.rectangle(im, bbox[0:2], bbox[2:4], (0, 204, 0), 2) cv2.putText(im, '%s: %.3f' % (class_name, score), (bbox[0], bbox[1] + 15), cv2.FONT_HERSHEY_PLAIN, 1.0, (0, 0, 255), thickness=1) return im
def test(): import os im_file = 'demo/004545.jpg' # im_file = 'data/VOCdevkit2007/VOC2007/JPEGImages/009036.jpg' # im_file = '/media/longc/Data/data/2DMOT2015/test/ETH-Crossing/img1/000100.jpg' image = cv2.imread(im_file) model_file = '/media/longc/Data/models/VGGnet_fast_rcnn_iter_70000.h5' # model_file = '/media/longc/Data/models/faster_rcnn_pytorch3/faster_rcnn_100000.h5' # model_file = '/media/longc/Data/models/faster_rcnn_pytorch2/faster_rcnn_2000.h5' detector = FasterRCNN() network.load_net(model_file, detector) detector.cuda() detector.eval() print('load model successfully!') # network.save_net(r'/media/longc/Data/models/VGGnet_fast_rcnn_iter_70000.h5', detector) # print('save model succ') t = Timer() t.tic() # image = np.zeros(shape=[600, 800, 3], dtype=np.uint8) + 255 dets, scores, classes = detector.detect(image, 0.7) runtime = t.toc() print('total spend: {}s'.format(runtime)) im2show = np.copy(image) for i, det in enumerate(dets): det = tuple(int(x) for x in det) cv2.rectangle(im2show, det[0:2], det[2:4], (255, 205, 51), 2) cv2.putText(im2show, '%s: %.3f' % (classes[i], scores[i]), (det[0], det[1] + 15), cv2.FONT_HERSHEY_PLAIN, 1.0, (0, 0, 255), thickness=1) cv2.imwrite(os.path.join('demo', 'out.jpg'), im2show) cv2.imshow('demo', im2show) cv2.waitKey(0)
def draw_str(dst, pos, s): x,y = pos cv2.putText(dst, s, (x+1, y+1), cv2.FONT_HERSHEY_PLAIN, 1.0, (0, 0, 0), thickness = 2, lineType=cv2.LINE_AA) cv2.putText(dst, s, (x, y), cv2.FONT_HERSHEY_PLAIN, 1.0, (255, 255, 255), lineType=cv2.LINE_AA)
def drawOnImage(img, radius, AvgSentiment, key): img = cv2.circle(img,(x,y), radius, (0, 127.5+(AvgSentiment*127.5), 127.5+(AvgSentiment*-127.5)), -1) font = cv2.FONT_HERSHEY_PLAIN string = key #coordinates.append(str(x)+" "+str(y)+" "+key) cv2.putText(img,string,(x-8*len(string)-5,y), font, 2,(255,255,255),2,cv2.LINE_AA) string = str(value)+'+' cv2.putText(img,string,(x-8*len(string)-5,y+40), font, 2,(255,255,255),2,cv2.LINE_AA) return img
def addText(frame, text, size, x, y): font = cv2.FONT_HERSHEY_PLAIN cv2.putText(frame, "{0}".format(text), (x, y), font, size, (255, 255, 0), 1)
def process_image(self, inImg): 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) persons = [] for i in range(len(faces)): face_i = faces[i] 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.im_width, self.im_height)) confidence = self.model.predict(face_resize) # cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 3) if confidence[1]<500: person = self.names[confidence[0]] cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 3) cv2.putText(frame, '%s - %.0f' % (person, confidence[1]), (x-10, y-10), cv2.FONT_HERSHEY_PLAIN,2,(0, 255, 0),2) else: person = 'Unknown' cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 3) cv2.putText(frame, person, (x-10, y-10), cv2.FONT_HERSHEY_PLAIN,2,(0, 102, 255),2) persons.append(person) return (frame, persons)
def process_image(self, inImg): 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) persons = [] for i in range(len(faces)): face_i = faces[i] 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.im_width, self.im_height)) confidence = self.model.predict(face_resize) # cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 3) if confidence[1]<3100: person = self.names[confidence[0]] cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 3) cv2.putText(frame, '%s - %.0f' % (person, confidence[1]), (x-10, y-10), cv2.FONT_HERSHEY_PLAIN,2,(0, 255, 0),2) else: person = 'Unknown' cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 0, 255), 3) cv2.putText(frame, person, (x-10, y-10), cv2.FONT_HERSHEY_PLAIN,2,(0, 102, 255),2) persons.append(person) return (frame, persons)
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)
def circle(self, x, y, radius, label=None): """Draw a circle. Parameters ---------- x : float | int Center of the circle (x-axis). y : float | int Center of the circle (y-axis). radius : float | int Radius of the circle in pixels. label : Optional[str] A text label that is placed at the center of the circle. """ image_size = int(radius + self.thickness + 1.5) # actually half size roi = int(x - image_size), int(y - image_size), \ int(2 * image_size), int(2 * image_size) if not is_in_bounds(self.image, roi): return image = view_roi(self.image, roi) center = image.shape[1] // 2, image.shape[0] // 2 cv2.circle( image, center, int(radius + .5), self._color, self.thickness) if label is not None: cv2.putText( self.image, label, center, cv2.FONT_HERSHEY_PLAIN, 2, self.text_color, 2)
def gaussian(self, mean, covariance, label=None): """Draw 95% confidence ellipse of a 2-D Gaussian distribution. Parameters ---------- mean : array_like The mean vector of the Gaussian distribution (ndim=1). covariance : array_like The 2x2 covariance matrix of the Gaussian distribution. label : Optional[str] A text label that is placed at the center of the ellipse. """ # chi2inv(0.95, 2) = 5.9915 vals, vecs = np.linalg.eigh(5.9915 * covariance) indices = vals.argsort()[::-1] vals, vecs = np.sqrt(vals[indices]), vecs[:, indices] center = int(mean[0] + .5), int(mean[1] + .5) axes = int(vals[0] + .5), int(vals[1] + .5) angle = int(180. * np.arctan2(vecs[1, 0], vecs[0, 0]) / np.pi) cv2.ellipse( self.image, center, axes, angle, 0, 360, self._color, 2) if label is not None: cv2.putText(self.image, label, center, cv2.FONT_HERSHEY_PLAIN, 2, self.text_color, 2)
def annotate(self, x, y, text): """Draws a text string at a given location. Parameters ---------- x : int | float Bottom-left corner of the text in the image (x-axis). y : int | float Bottom-left corner of the text in the image (y-axis). text : str The text to be drawn. """ cv2.putText(self.image, text, (int(x), int(y)), cv2.FONT_HERSHEY_PLAIN, 2, self.text_color, 2)
def put_text(self, text, x, y): cv2.putText(self._img, text, (x, y), cv2.FONT_HERSHEY_PLAIN, 2, (0, 255, 0), 2)
def realtime(): #initialize preview cv2.namedWindow("preview") vc = cv2.VideoCapture(0) if vc.isOpened(): #get the first frame rval, frame = vc.read() else: rval = False classes=["peace","punch","stop","thumbs_up"] while rval: frame=cv2.flip(frame,1) cv2.rectangle(frame,(300,200),(500,400),(0,255,0),1) cv2.putText(frame,"Place your hand in the green box.", (50,50), cv2.FONT_HERSHEY_PLAIN , 1, 255) cv2.putText(frame,"Press esc to exit.", (50,100), cv2.FONT_HERSHEY_PLAIN , 1, 255) cv2.imshow("preview", frame) frame=frame[200:400,300:500] #frame = cv2.resize(frame, (200,200)) frame = cv2.cvtColor( frame, cv2.COLOR_RGB2GRAY) frame=frame.reshape((1,)+frame.shape) frame=frame.reshape(frame.shape+(1,)) test_datagen = ImageDataGenerator(rescale=1./255) m=test_datagen.flow(frame,batch_size=1) y_pred=model.predict_generator(m,1) histarray2={'PEACE': y_pred[0][0], 'PUNCH': y_pred[0][1], 'STOP': y_pred[0][2], 'Thumbs Up': y_pred[0][3]} update(histarray2) print(classes[list(y_pred[0]).index(y_pred[0].max())]) rval, frame = vc.read() key = cv2.waitKey(20) if key == 27: # exit on ESC break cv2.destroyWindow("preview") vc=None #loading the model
def draw_str(dst, target, s): x, y = target # cv2.putText(dst, s, (x+1, y+1), cv2.FONT_HERSHEY_PLAIN, 1.0, (0, 0, 0), thickness = 2, lineType=cv2.LINE_AA) cv2.putText(dst, s, (x+1, y+1), cv2.FONT_HERSHEY_PLAIN, 1.0, (0, 0, 0), thickness = 2) # cv2.putText(dst, s, (x, y), cv2.FONT_HERSHEY_PLAIN, 1.0, (255, 255, 255), lineType=cv2.LINE_AA) cv2.putText(dst, s, (x, y), cv2.FONT_HERSHEY_PLAIN, 1.0, (255, 255, 255))
def draw_str(dst, target, s): x, y = target cv2.putText(dst, s, (x+1, y+1), cv2.FONT_HERSHEY_PLAIN, 1.0, (0, 0, 0), thickness = 2, lineType=cv2.LINE_AA) cv2.putText(dst, s, (x, y), cv2.FONT_HERSHEY_PLAIN, 1.0, (255, 255, 255), lineType=cv2.LINE_AA)
def draw_groupRect(self, img_arr, ID): ID = int(ID) img = Image.fromarray(img_arr) draw = ImageDraw.Draw(img, mode='RGBA') bi_ID = bi_t = np.zeros(self.final_BI.shape, np.uint8) bi_ID[self.final_ID == ID] = 255 # Image.fromarray(bi_ID).show() ## get contour -- cnt of polygon if self.parent().line2_mode == "polygonOtsu": bi_ID = cv2.GaussianBlur(bi_ID, (11, 11), 0) bi_ID = cv2.dilate(bi_ID, None, iterations=4) im2, contours, hierarchy = cv2.findContours(bi_ID, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) cnt_union = contours[0] for i, cnt in enumerate(contours): if i > 0: cnt_union = np.concatenate((cnt_union, cnt), axis=0) ellipse = cv2.fitEllipse(cnt_union) cv2.ellipse(img_arr,ellipse,(0,255,0,175),2) extBottom = tuple(cnt_union[cnt_union[:, :, 1].argmax()][0]) font = cv2.FONT_HERSHEY_PLAIN cv2.putText(img_arr, "ID_"+str(ID), extBottom, font, 1.5, (255, 49, 12), 2) return img_arr
def test(visualize=False): import os im_file = 'data/cervix/train/Type_2/1381.jpg' im_name = im_file.split('/')[-1] image = cv2.imread(im_file) # model_file = 'models/VGGnet_fast_rcnn_iter_70000.h5' model_file = 'models/saved_model3/faster_rcnn_100000.h5' expm = model_file.split('/')[-1].split('.')[0] expm_dir = os.path.join('demo', expm) if not os.path.exists(expm_dir): os.makedirs(expm_dir) detector = FasterRCNN() network.load_net(model_file, detector) detector.cuda() detector.eval() # set model in evaluation mode, has effect on Dropout and Batchnorm. Use train() to set train mode. print('load model successfully!') # network.save_net(r'/media/longc/Data/models/VGGnet_fast_rcnn_iter_70000.h5', detector) # print('save model succ') t = Timer() t.tic() # image = np.zeros(shape=[600, 800, 3], dtype=np.uint8) + 255 dets, scores, classes = detector.detect(image, 0.7) runtime = t.toc() print('total spend: {}s'.format(runtime)) im2show = np.copy(image) for i, det in enumerate(dets): det = tuple(int(x) for x in det) cv2.rectangle(im2show, det[0:2], det[2:4], (255, 205, 51), 4) cv2.putText(im2show, '%s: %.3f' % (classes[i], scores[i]), (det[0], det[1] + 15), cv2.FONT_HERSHEY_PLAIN, 1.0, (0, 0, 255), thickness=1) cv2.imwrite(os.path.join('demo', expm, im_name), im2show) if visualize: im2show = cv2.resize(im2show, None, None, fx=0.15, fy=0.15, interpolation=cv2.INTER_LINEAR) cv2.imshow('demo', im2show) cv2.waitKey(0)
def annotate(img, comp_reports): ''' Draws boxes and label text around a detection region. Caution: Since img is overwritten, ensure caller passes a copy instead of original image. ''' for r in comp_reports: rect = r['rect'] cv2.rectangle(img, (rect[0], rect[1]), (rect[2], rect[3]), (255,255,255), 2) # Position the text annotation above rectangle by default, unless rectangle is at border. text_y = rect[1]-5 if rect[1] >= 5 else rect[1]+15 cv2.putText(img, r['labels'][0]['label'], (rect[0], text_y), cv2.FONT_HERSHEY_PLAIN, 2.0, (255,255,255), 2)
def draw_face_info(image, objects, labels, confidences): """ Draws the rectangle, label, and confidence around a face """ for i, (x, y, w, h) in enumerate(objects): cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 255), 2) cv2.putText(image, labels[i].title() + ' (' + str(confidences[i]) + ')', (x, y), cv2.FONT_HERSHEY_PLAIN, 1, (0, 0, 255)) cv2.putText(image, '{:d}x{:d}'.format(w, h), (x, y+h+13), cv2.FONT_HERSHEY_PLAIN, 1, (0, 0, 255))
def draw_label(self, text, xy, colour, offset=(0,0), size=1): try: pos = tuple([val - offset[i] for i, val in enumerate(self.convert(*xy))]) font = cv2.FONT_HERSHEY_PLAIN cv2.putText(self._surface, str(text), pos, font, size, colour, 1, cv2.LINE_AA) except: return
def draw(self): a, b = self.barsize() window = np.zeros((self.h, self.l, 3), np.uint8) cv2.rectangle(window, (0,0), (a,self.h), (0,255,20), -1) cv2.putText(window, "%.2f%%" % self.x, (self.l - 50, self.h / 2), cv2.FONT_HERSHEY_PLAIN, 1, (255,255,255), 1, cv2.LINE_AA) cv2.imshow('Converting...', window) return
def get_images(img, x, y, w, h): subimg = img[y:y+h,x:x+w] # Resize for easier viewing img = resize(img, 0.5) # Scaled x, y, w, h sx, sy, sw, sh = (int(v*0.5) for v in (x, y, w, h)) # Draw the rectangle so we know where the image is cv2.rectangle(img, (sx, sy), (sx + sw, sy + sh), (0, 0, 255), 1) cv2.putText(img, "x:{} y:{} w:{} h:{}".format(x, y, w, h), (sx, sy - 2), cv2.FONT_HERSHEY_PLAIN, 0.5, (0, 0, 255), 1) return subimg, img
def run(self, input_image, output_image, exec_result=None): battery = self.drone.navdata.get(0, dict()).get('battery', 0) cv2.putText(output_image, 'Battery %f' % battery, (15, 15), cv2.FONT_HERSHEY_PLAIN, 1, (255, 255, 255), 1)
def draw_watch(self, frame, track, proc): tx1 = self._tx1 tx2 = self._tx2 ty1 = self._ty1 ty2 = self._ty2 # draw a red frame around the tank, according to the ini file TL = (tx1, ty1) BR = (tx2, ty2) cv2.rectangle(frame, TL, BR, self.RED) # make an image for drawing tank-coord overlays tank_overlay = numpy.zeros((ty2-ty1, tx2-tx1, 4), frame.dtype) # draw contours for c_i in range(len(proc.contours)): cv2.drawContours(tank_overlay, proc.contours, c_i, self.GREEN, 1) # draw centroids for pt in proc.centroids: pt = [int(x) for x in pt] if pt == track.position_pixel: continue # will draw this one separately x = pt[0] y = pt[1] cv2.line(tank_overlay, (x-5,y), (x+5,y), self.YELLOW) cv2.line(tank_overlay, (x,y-5), (x,y+5), self.YELLOW) if track.status != 'init': # draw a larger cross at the known/estimated position color = self.STATUS_COLORS[track.status] x,y = track.position_pixel cv2.line(tank_overlay, (x-10,y), (x+10,y), color) cv2.line(tank_overlay, (x,y-10), (x,y+10), color) # draw a circle around the estimated position #position = track.position_pixel #cv2.circle(tank_overlay, position, 5, self.STATUS_COLORS[track.status]) # draw a trace of the past k positions recorded start = max(0, len(track.positions) - 50) prevpt = track.positions[start] for pt in track.positions[start:]: cv2.line(tank_overlay, prevpt, pt, self.YELLOW) prevpt = pt # draw the overlay into the frame at the tank's location alpha = tank_overlay[:,:,3] for c in 0,1,2: frame[ty1:ty2,tx1:tx2,c] = frame[ty1:ty2,tx1:tx2,c]*(1-alpha/255.0) + tank_overlay[:,:,c]*(alpha/255.0) # draw crosshair and frame coordinates at mouse if self._mouse_on: height, width = frame.shape[:2] cv2.line(frame, (0, self._mousey), (width, self._mousey), self.RED) cv2.line(frame, (self._mousex, 0), (self._mousex, height), self.RED) # NOTE: tank Y coordinate is inverted: 0=bottom, 1=top of frame. text = "%.3f %.3f" % (float(self._mousex) / width, 1.0 - (float(self._mousey) / height)) cv2.putText(frame, text, (5, height-5), cv2.FONT_HERSHEY_PLAIN, 1, self.RED) cv2.imshow("preview", frame)
def add_text_img(img, text, pos, box=None, color=None, thickness=1, scale=1, vertical=False): """ Adds the given text in the image. :param img: Input image :param text: String text :param pos: (x, y) in the image or relative to the given Box object :param box: Box object. If not None, the text is placed inside the box. :param color: Color of the text. :param thickness: Thickness of the font. :param scale: Font size scale. :param vertical: If true, the text is displayed vertically. (slow) :return: """ if color is None: color = COL_WHITE text = str(text) top_left = pos if box is not None: top_left = box.move(pos).to_int().top_left() if top_left[0] > img.shape[1]: return if vertical: if box is not None: h, w, d = box.height, box.width, 3 else: h, w, d = img.shape txt_img = np.zeros((w, h, d), dtype=np.uint8) # 90 deg rotation top_left = h - pos[1], pos[0] cv.putText(txt_img, text, top_left, cv.FONT_HERSHEY_PLAIN, scale, color, thickness) txt_img = ndimage.rotate(txt_img, 90) mask = txt_img > 0 if box is not None: im_box = img_box(img, box) im_box[mask] = txt_img[mask] else: img[mask] = txt_img[mask] else: cv.putText(img, text, top_left, cv.FONT_HERSHEY_PLAIN, scale, color, thickness)
def demo(modelPath, showBox=False): x = tf.placeholder(tf.float32, [None, 2304]) y_conv = deepnn(x) probs = tf.nn.softmax(y_conv) saver = tf.train.Saver() ckpt = tf.train.get_checkpoint_state(modelPath) sess = tf.Session() if ckpt and ckpt.model_checkpoint_path: saver.restore(sess, ckpt.model_checkpoint_path) print('Restore model sucsses!!') feelings_faces = [] for index, emotion in enumerate(EMOTIONS): feelings_faces.append(cv2.imread('./data/emojis/' + emotion + '.png', -1)) video_captor = cv2.VideoCapture(0) emoji_face = [] result = None while True: ret, frame = video_captor.read() detected_face, face_coor = format_image(frame) if showBox: if face_coor is not None: [x,y,w,h] = face_coor cv2.rectangle(frame, (x,y), (x+w,y+h), (255,0,0), 2) if cv2.waitKey(1) & 0xFF == ord(' '): if detected_face is not None: cv2.imwrite('a.jpg', detected_face) tensor = image_to_tensor(detected_face) result = sess.run(probs, feed_dict={x: tensor}) # print(result) if result is not None: for index, emotion in enumerate(EMOTIONS): cv2.putText(frame, emotion, (10, index * 20 + 20), cv2.FONT_HERSHEY_PLAIN, 0.5, (0, 255, 0), 1); cv2.rectangle(frame, (130, index * 20 + 10), (130 + int(result[0][index] * 100), (index + 1) * 20 + 4), (255, 0, 0), -1) emoji_face = feelings_faces[np.argmax(result[0])] for c in range(0, 3): frame[200:320, 10:130, c] = emoji_face[:, :, c] * (emoji_face[:, :, 3] / 255.0) + frame[200:320, 10:130, c] * (1.0 - emoji_face[:, :, 3] / 255.0) cv2.imshow('face', frame) if cv2.waitKey(1) & 0xFF == ord('q'): break
def update_count(self, matches, output_image = None): self.log.debug("Updating count using %d matches...", len(matches)) # First update all the existing vehicles for vehicle in self.vehicles: i = self.update_vehicle(vehicle, matches) if i is not None: del matches[i] # Add new vehicles based on the remaining matches for match in matches: contour, centroid = match new_vehicle = Vehicle(self.next_vehicle_id, centroid) self.next_vehicle_id += 1 self.vehicles.append(new_vehicle) self.log.debug("Created new vehicle #%d from match (%d, %d)." , new_vehicle.id, centroid[0], centroid[1]) # Count any uncounted vehicles that are past the divider for vehicle in self.vehicles: if not vehicle.counted and (((vehicle.last_position[1] > self.divider) and (vehicle.vehicle_dir == 1)) or ((vehicle.last_position[1] < self.divider) and (vehicle.vehicle_dir == -1))) and (vehicle.frames_seen > 6): vehicle.counted = True # update appropriate counter if ((vehicle.last_position[1] > self.divider) and (vehicle.vehicle_dir == 1) and (vehicle.last_position[0] >= (int(frame_w/2)-10))): self.vehicle_RHS += 1 self.vehicle_count += 1 elif ((vehicle.last_position[1] < self.divider) and (vehicle.vehicle_dir == -1) and (vehicle.last_position[0] <= (int(frame_w/2)+10))): self.vehicle_LHS += 1 self.vehicle_count += 1 self.log.debug("Counted vehicle #%d (total count=%d)." , vehicle.id, self.vehicle_count) # Optionally draw the vehicles on an image if output_image is not None: for vehicle in self.vehicles: vehicle.draw(output_image) # LHS cv2.putText(output_image, ("LH Lane: %02d" % self.vehicle_LHS), (12, 56) , cv2.FONT_HERSHEY_PLAIN, 1.2, (127,255, 255), 2) # RHS cv2.putText(output_image, ("RH Lane: %02d" % self.vehicle_RHS), (216, 56) , cv2.FONT_HERSHEY_PLAIN, 1.2, (127, 255, 255), 2) # Remove vehicles that have not been seen long enough removed = [ v.id for v in self.vehicles if v.frames_since_seen >= self.max_unseen_frames ] self.vehicles[:] = [ v for v in self.vehicles if not v.frames_since_seen >= self.max_unseen_frames ] for id in removed: self.log.debug("Removed vehicle #%d.", id) self.log.debug("Count updated, tracking %d vehicles.", len(self.vehicles)) # ============================================================================