Python cv2 模块,getTextSize() 实例源码

我们从Python开源项目中,提取了以下18个代码示例,用于说明如何使用cv2.getTextSize()

项目:pynephoscope    作者:neXyon    | 项目源码 | 文件源码
def _stampText(image, text, line):
        font = cv2.FONT_HERSHEY_SIMPLEX
        font_scale = 0.55
        margin = 5
        thickness = 2
        color = (255, 255, 255)

        size = cv2.getTextSize(text, font, font_scale, thickness)

        text_width = size[0][0]
        text_height = size[0][1]
        line_height = text_height + size[1] + margin

        x = image.shape[1] - margin - text_width
        y = margin + size[0][1] + line * line_height

        cv2.putText(image, text, (x, y), font, font_scale, color, thickness)
项目:chainer-faster-rcnn    作者:mitmul    | 项目源码 | 文件源码
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
项目:live-age-gender-estimator    作者:taipalma    | 项目源码 | 文件源码
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)
项目:deel    作者:uei    | 项目源码 | 文件源码
def draw_result(out, im_scale, clss, bbox, nms_thresh, conf):
    CV_AA = 16
    print clss.shape
    print bbox.shape
    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
项目:camera_calibration_frontend    作者:groundmelon    | 项目源码 | 文件源码
def getTextSize(cls, text):
        return cv2.getTextSize(text, cls.FONT_FACE, cls.FONT_SCALE, cls.FONT_THICKNESS)[0]
项目:camera_calibration_frontend    作者:groundmelon    | 项目源码 | 文件源码
def button(self, dst, label, enable):
        dst.fill(255)
        size = (dst.shape[1], dst.shape[0])
        if enable:
            color = (155, 155, 80)
        else:
            color = (224, 224, 224)
        cv2.circle(dst, (size[0] / 2, size[1] / 2), min(size) / 2, color, -1)
        (w, h) = self.getTextSize(label)
        self.putText(dst, label, ((size[0] - w) / 2, (size[1] + h) / 2), (255,255,255))
项目:camera_calibration_frontend    作者:groundmelon    | 项目源码 | 文件源码
def redraw_monocular(self, drawable):
        height = drawable.scrib.shape[0]
        width = drawable.scrib.shape[1]

        display = numpy.zeros((max(480, height), width + 100, 3), dtype=numpy.uint8)
        display[0:height, 0:width,:] = drawable.scrib
        display[0:height, width:width+100,:].fill(255)


        self.buttons(display)
        if not self.c.calibrated:
            if drawable.params:
                 for i, (label, lo, hi, progress) in enumerate(drawable.params):
                    (w,_) = self.getTextSize(label)
                    self.putText(display, label, (width + (100 - w) / 2, self.y(i)))
                    color = (0,255,0)
                    if progress < 1.0:
                        color = (0, int(progress*255.), 255)
                    cv2.line(display,
                            (int(width + lo * 100), self.y(i) + 20),
                            (int(width + hi * 100), self.y(i) + 20),
                            color, 4)

        else:
            self.putText(display, "lin.", (width, self.y(0)))
            linerror = drawable.linear_error
            if linerror < 0:
                msg = "?"
            else:
                msg = "%.2f" % linerror
                #print "linear", linerror
            self.putText(display, msg, (width, self.y(1)))

        self.queue_display.append(display)

        if drawable.extra_image is not None:
            self.queue_extra_display.append(drawable.extra_image)
项目:camera_calibration_frontend    作者:groundmelon    | 项目源码 | 文件源码
def redraw_stereo(self, drawable):
        height = drawable.lscrib.shape[0]
        width = drawable.lscrib.shape[1]

        display = numpy.zeros((max(480, height), 2 * width + 100, 3), dtype=numpy.uint8)
        display[0:height, 0:width,:] = drawable.lscrib
        display[0:height, width:2*width,:] = drawable.rscrib
        display[0:height, 2*width:2*width+100,:].fill(255)

        self.buttons(display)

        if not self.c.calibrated:
            if drawable.params:
                for i, (label, lo, hi, progress) in enumerate(drawable.params):
                    (w,_) = self.getTextSize(label)
                    self.putText(display, label, (2 * width + (100 - w) / 2, self.y(i)))
                    color = (0,255,0)
                    if progress < 1.0:
                        color = (0, int(progress*255.), 255)
                    cv2.line(display,
                            (int(2 * width + lo * 100), self.y(i) + 20),
                            (int(2 * width + hi * 100), self.y(i) + 20),
                            color, 4)

        else:
            self.putText(display, "epi.", (2 * width, self.y(0)))
            if drawable.epierror == -1:
                msg = "?"
            else:
                msg = "%.2f" % drawable.epierror
            self.putText(display, msg, (2 * width, self.y(1)))
            # TODO dim is never set anywhere. Supposed to be observed chessboard size?
            if drawable.dim != -1:
                self.putText(display, "dim", (2 * width, self.y(2)))
                self.putText(display, "%.3f" % drawable.dim, (2 * width, self.y(3)))

        self.queue_display.append(display)

        if drawable.extra_image is not None:
            self.queue_extra_display.append(drawable.extra_image)
项目:openface_ros    作者:schelian    | 项目源码 | 文件源码
def _set_label(img, label, origin):
    font = cv2.FONT_HERSHEY_SIMPLEX
    scale = 0.4
    thickness = 1

    text = cv2.getTextSize(label, font, scale, thickness)
    p2 = (origin[0] + text[0][0], origin[1] -text[0][1])
    cv2.rectangle(img, origin, p2, (0, 0, 0), -1)
    cv2.putText(img, label, origin, font, scale, (255, 255, 255), thickness, 8)
项目:imgProcessor    作者:radjkarl    | 项目源码 | 文件源码
def putTextAlpha(img, text, alpha, org, fontFace, fontScale, color,
                 thickness):  # , lineType=None
    '''
    Extends cv2.putText with [alpha] argument
    '''

    x, y = cv2.getTextSize(text, fontFace,
                           fontScale, thickness)[0]

    ox, oy = org

    imgcut = img[oy - y - 3:oy, ox:ox + x]

    if img.ndim == 3:
        txtarr = np.zeros(shape=(y + 3, x, 3), dtype=np.uint8)
    else:
        txtarr = np.zeros(shape=(y + 3, x), dtype=np.uint8)

    cv2.putText(txtarr, text, (0, y), fontFace,
                fontScale, color,
                thickness=thickness
                #, lineType=lineType
                )

    cv2.addWeighted(txtarr, alpha, imgcut, 1, 0, imgcut, -1)
    return img
项目:deep_sort    作者:nwojke    | 项目源码 | 文件源码
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)
项目:deel    作者:uei    | 项目源码 | 文件源码
def draw_rois(out,im_scale, rois,bbox,cls):
    CV_AA = 16
    print bbox.shape
    for i in range(len(rois)):
        n,x1,y1,x2,y2 = rois[i]
        canvas = out.copy()
        cv.rectangle(canvas, (x1, y1), (x2, y2), (255, 0, 0), 1, CV_AA)

        cls_id=np.argmax(cls[i])
        if cls[i][cls_id]>0.1 and cls_id != 0:
            x1 = int(x1)
            x2 = int(x2)
            y1 = int(x1)
            y2 = int(y2)
            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)
        for j in range(0,84,4):
            x1,y1,x2,y2 = bbox[i][j:j+4]
            cv.rectangle(canvas, (x1, y1), (x2, y2), (255, 255, 0), 1, CV_AA)
        cv.imshow("res",canvas)
        cv.waitKey(0)       

    return out
项目:RFCN-tensorflow    作者:xdever    | 项目源码 | 文件源码
def tile(cols, rows, imgs, titles=None):
    font = cv2.FONT_HERSHEY_COMPLEX_SMALL
    fontSize = 1
    fontThickness = 2
    pad=10
    titleColor = (255,192,0)

    hImg = imgs[0]
    i = 0
    z = None
    row = []
    for c in range(cols):
        col = []
        for r in range(rows):
            if i<len(imgs):
                img = imgs[i]
                if titles is not None and i<len(titles):
                    img = img.copy()
                    size = cv2.getTextSize(titles[i], font, fontSize, fontThickness)[0]
                    cv2.putText(img, titles[i], (pad, size[1]+pad), font, fontSize, titleColor, thickness=fontThickness)

                col.append(img)
            else:
                if z is None:
                    z = np.zeros_like(imgs[0])
                col.append(z)
            i+=1
        row.append(np.concatenate(col, axis=0))

    return np.concatenate(row, axis=1)
项目:hazcam    作者:alex-sherman    | 项目源码 | 文件源码
def drawText(vis, text, position, scale, thickness, padding = 2, color = (255, 255, 0)):
    font = cv2.FONT_HERSHEY_SIMPLEX
    size = cv2.getTextSize(text, font, scale, thickness)[0]
    size = (size[0] + padding * 2, -size[1] - padding * 2)
    cv2.rectangle(vis, tuple(diff(position, (padding, -padding * 2))), tuple(add(position, size)), (0,0,0), thickness = -1)
    cv2.putText(vis, text, position, font, scale, color, thickness, bottomLeftOrigin = False)
项目:sherlock-hack    作者:StuartIanNaylor    | 项目源码 | 文件源码
def writeOSD(image, lines, size=0.0175):
    """Write text given in *lines* iterable, 
    the height of each line determined by *size* as
    proportion of image height."""

    # Compute row height at scale 1.0 first.
    (letter_width, letter_height), baseline = cv2.getTextSize(
        text='I', 
        fontFace=cv2.FONT_HERSHEY_SIMPLEX,
        fontScale=1.0,
        thickness=1)

    # Compute actual scale to match desired height. 
    image_height = np.shape(image)[0]
    line_height = int(image_height * size)
    scale = float(line_height) / letter_height

    # Deterimine base thickness, based on scale.
    thickness = int(scale * 4)

    # Increase line height, to account for thickness.
    line_height += thickness * 3

    # Iterate the lines of text, and draw them.
    xoffset = int(letter_width * scale)
    yoffset = line_height
    for line in lines:
        cv2.putText(  # Draw the drop shadow.
            image,
            text=line,
            org=(xoffset+max(1, thickness/2), yoffset+max(1, thickness/2)),
            fontFace=cv2.FONT_HERSHEY_SIMPLEX,
            fontScale=scale,
            color=(0, 0, 0),
            thickness=thickness,
            )
        cv2.putText(  # Draw the text body.
            image,
            text=line,
            org=(xoffset, yoffset),
            fontFace=cv2.FONT_HERSHEY_SIMPLEX,
            fontScale=scale,
            color=(215, 215, 70),
            thickness=thickness,
            )
        cv2.putText(  # Draw the highlight.
            image,
            text=line,
            org=(xoffset-max(1, thickness/3), yoffset-max(1, thickness/3)),
            fontFace=cv2.FONT_HERSHEY_SIMPLEX,
            fontScale=scale,
            color=(245, 255, 200),
            thickness=thickness/3,
            )
        yoffset += line_height

# The end.
项目:mcv-m5    作者:david-vazquez    | 项目源码 | 文件源码
def yolo_draw_detections(boxes, im, anchors, labels, threshold, nms_threshold):

        def get_color(c,x,max):
          colors = ( (1,0,1), (0,0,1),(0,1,1),(0,1,0),(1,1,0),(1,0,0) )
          ratio = (float(x)/max)*5
          i = np.floor(ratio)
          j = np.ceil(ratio)
          ratio -= i
          r = (1-ratio) * colors[int(i)][int(c)] + ratio*colors[int(j)][int(c)]
          return r*255

    if type(im) is not np.ndarray:
        imgcv = cv2.imread(im)
    else: imgcv = im
    h, w, _ = imgcv.shape
    for b in boxes:
        max_indx = np.argmax(b.probs)
        max_prob = b.probs[max_indx]
        label = 'object' * int(len(labels) < 2)
        label += labels[max_indx] * int(len(labels)>1)
        if max_prob > threshold:
            left  = int ((b.x - b.w/2.) * w)
            right = int ((b.x + b.w/2.) * w)
            top   = int ((b.y - b.h/2.) * h)
            bot   = int ((b.y + b.h/2.) * h)
            if left  < 0    :  left = 0
            if right > w - 1: right = w - 1
            if top   < 0    :   top = 0
            if bot   > h - 1:   bot = h - 1
            thick = int((h+w)/300)
            mess = '{}'.format(label)
                        offset = max_indx*123457 % len(labels)
                        color = (get_color(2,offset,len(labels)),
                                 get_color(1,offset,len(labels)),
                                 get_color(0,offset,len(labels)))
            cv2.rectangle(imgcv,
                (left, top), (right, bot),
                color, thick)
                        font = cv2.FONT_HERSHEY_SIMPLEX
                        scale = 0.65
                        thickness = 1
                        size=cv2.getTextSize(mess, font, scale, thickness)
                        cv2.rectangle(im, (left-2,top-size[0][1]-4), (left+size[0][0]+4,top), color, -1)
                        cv2.putText(im, mess, (left+2,top-2), font, scale, (0,0,0), thickness, cv2.LINE_AA)
    return imgcv
项目:keras_zoo    作者:david-vazquez    | 项目源码 | 文件源码
def yolo_draw_detections(boxes, im, anchors, labels, threshold, nms_threshold):

        def get_color(c,x,max):
          colors = ( (1,0,1), (0,0,1),(0,1,1),(0,1,0),(1,1,0),(1,0,0) )
          ratio = (float(x)/max)*5
          i = np.floor(ratio)
          j = np.ceil(ratio)
          ratio -= i
          r = (1-ratio) * colors[int(i)][int(c)] + ratio*colors[int(j)][int(c)]
          return r*255

    if type(im) is not np.ndarray:
        imgcv = cv2.imread(im)
    else: imgcv = im
    h, w, _ = imgcv.shape
    for b in boxes:
        max_indx = np.argmax(b.probs)
        max_prob = b.probs[max_indx]
        label = 'object' * int(len(labels) < 2)
        label += labels[max_indx] * int(len(labels)>1)
        if max_prob > threshold:
            left  = int ((b.x - b.w/2.) * w)
            right = int ((b.x + b.w/2.) * w)
            top   = int ((b.y - b.h/2.) * h)
            bot   = int ((b.y + b.h/2.) * h)
            if left  < 0    :  left = 0
            if right > w - 1: right = w - 1
            if top   < 0    :   top = 0
            if bot   > h - 1:   bot = h - 1
            thick = int((h+w)/300)
            mess = '{}'.format(label)
                        offset = max_indx*123457 % len(labels)
                        color = (get_color(2,offset,len(labels)),
                                 get_color(1,offset,len(labels)),
                                 get_color(0,offset,len(labels)))
            cv2.rectangle(imgcv,
                (left, top), (right, bot),
                color, thick)
                        font = cv2.FONT_HERSHEY_SIMPLEX
                        scale = 0.65
                        thickness = 1
                        size=cv2.getTextSize(mess, font, scale, thickness)
                        cv2.rectangle(im, (left-2,top-size[0][1]-4), (left+size[0][0]+4,top), color, -1)
                        cv2.putText(im, mess, (left+2,top-2), font, scale, (0,0,0), thickness, cv2.LINE_AA)
    return imgcv
项目:RFCN-tensorflow    作者:xdever    | 项目源码 | 文件源码
def drawBoxes(img, boxes, categories, names, palette, scores=None, fade=False):
    def clipCoord(xy):
        return np.minimum(np.maximum(np.array(xy,dtype=np.int32),0),[img.shape[1]-1, img.shape[0]-1]).tolist()

    cmap = palette.getMap(list=True)
    font = cv2.FONT_HERSHEY_COMPLEX_SMALL 
    fontSize = 0.8
    fontThickness = 1
    pad=5


    img=np.copy(img)

    for box in range(boxes.shape[0]):
        if fade and scores is not None:
            iOrig = img
            img=np.copy(img)

        topleft = tuple(clipCoord(boxes[box][0:2]))
        if categories is not None:
            color = tuple(cmap[categories[box]])
        else:
            color = (0,0,255)
        cv2.rectangle(img, topleft, tuple(clipCoord(boxes[box][2:5])), color, thickness=4)
        if names:
            title=names[box]
            if scores is not None:
                title+=": %.2f" % scores[box]
            textpos=[topleft[0], topleft[1]-pad]
            size = cv2.getTextSize(title, font, fontSize, fontThickness)[0]

            boxTL = textpos[:]
            boxTL[1] = boxTL[1] - size[1]
            boxBR = list(topleft)
            boxBR[0] = boxBR[0] + size[0]

            cv2.rectangle(img, tuple(boxTL), tuple(boxBR), color, thickness=-1)
            cv2.rectangle(img, tuple(boxTL), tuple(boxBR), color, thickness=4)
            cv2.putText(img, title, tuple(textpos), font, fontSize, (255,255,255), thickness=fontThickness)

        if fade and scores is not None:
            img = scores[box] * img + (1.0-scores[box]) * iOrig
    return img