示例#1
0
def add_mrz_overlay(img: np.ndarray,
                    text: str,
                    times: int,
                    width: float,
                    bottom: bool = False) -> np.ndarray:
    line_spacing = 1.5
    font = cv2.FONT_HERSHEY_SIMPLEX
    font_color = (0, 0, 0)
    line_type = 2
    text_width_s1, _ = cv2.getTextSize(text, font, 1, line_type)[0]
    font_scale = int(img.shape[1] * width) / text_width_s1
    text_width, text_height = cv2.getTextSize(text, font, font_scale,
                                              line_type)[0]
    if bottom:
        coords = (img.shape[1] - text_width) // 2, int(img.shape[0] -
                                                       text_height * times *
                                                       line_spacing)
    else:
        coords = (img.shape[1] - text_width) // 2, (img.shape[0] +
                                                    text_height) // 2

    for i in range(times):
        cv2.putText(
            img,
            text,
            (coords[0], coords[1] + int(line_spacing * i * text_height)),
            font,
            font_scale,
            font_color,
            line_type,
        )

    return img
示例#2
0
def setLabel(image, str, contour):
    (text_width, text_height), baseline = cv2.getTextSize(str, cv2.FONT_HERSHEY_SIMPLEX, 0.7, 1)
    x, y, width, height = cv2.boundingRect(contour)
    pt_x = x+int((width-text_width)/2)
    pt_y = y+int((height + text_height)/2)
    cv2.rectangle(image, (pt_x, pt_y+baseline), (pt_x+text_width, pt_y-text_height), (200,200,200), cv2.FILLED)
    cv2.putText(image, str, (pt_x, pt_y), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0,0,0), 1, 8)
示例#3
0
def plot_one_box(box, img, color=None, label=None, line_thickness=None):
    """Plots one bounding box on image img

    :param box: [x1, y1, x2, y2]
    :param img: image
    :param color: True or Float
    :param label: label
    :param line_thickness: line_thickness
    :return: image with bounding box
    """

    line_thick = line_thickness or round(
        0.002 * (img.shape[0] + img.shape[1]) / 2) + 1  # line/font thickness
    color = color or [random.randint(0, 255) for _ in range(3)]
    pt1, pt2 = (int(box[0]), int(box[1])), (int(box[2]), int(box[3]))
    cv2.rectangle(img,
                  pt1,
                  pt2,
                  color,
                  thickness=line_thick,
                  lineType=cv2.LINE_AA)
    if label:
        font_thick = max(line_thick - 1, 1)  # font thickness
        t_size = cv2.getTextSize(label,
                                 0,
                                 fontScale=line_thick / 3,
                                 thickness=font_thick)[0]
        pt2 = pt1[0] + t_size[0], pt1[1] - t_size[1] - 3
        cv2.rectangle(img, pt1, pt2, color, -1, cv2.LINE_AA)  # filled
        cv2.putText(img,
                    label, (pt1[0], pt1[1] - 2),
                    0,
                    line_thick / 3, [225, 255, 255],
                    hickness=font_thick,
                    lineType=cv2.LINE_AA)
示例#4
0
def draw_text(img,
              text,
              font=cv2.FONT_HERSHEY_COMPLEX_SMALL,
              position=(10, 10),
              font_scale=0.6,
              font_thickness=1,
              text_color=(0, 0, 0),
              text_color_bg=(255, 255, 255),
              alignment="center"):
    """
    draws text in a coloured rectangle
    """

    x, y = [int(x) for x in position]

    text_size, _ = cv2.getTextSize(text, font, font_scale, font_thickness)
    # space
    text_w, text_h = [int(x) for x in text_size]
    cv2.rectangle(img,
                  position, (x + text_w, y + text_h + 5),
                  text_color_bg,
                  -1,
                  lineType=cv2.LINE_AA)
    cv2.putText(img,
                text, (x, y + text_h),
                font,
                font_scale,
                text_color,
                font_thickness,
                lineType=cv2.LINE_AA)

    return img
def write_solution(image, empty_boxes, solved):
    # Write grid on image
    side = image.shape[0] // 9
    for i in range(9):
        for j in range(9):
            if (empty_boxes[i][j] != 1):
                continue

            text = str(solved[i][j])
            offset = 0
            font = cv2.FONT_HERSHEY_SIMPLEX
            (text_height, text_width), baseLine = cv2.getTextSize(text,
                                                                  font,
                                                                  fontScale=1,
                                                                  thickness=3)

            font_scale = 0.4 * side / max(text_height, text_width)
            text_height *= font_scale
            text_width *= font_scale
            bottom_left_corner_x = side * j + math.floor(
                (side - text_width) / 2) + offset
            bottom_left_corner_y = side * (i + 1) - math.floor(
                (side - text_height) / 2) + offset
            image = cv2.putText(image,
                                text,
                                (bottom_left_corner_x, bottom_left_corner_y),
                                font,
                                font_scale, (0, 255, 0),
                                thickness=3,
                                lineType=cv2.LINE_AA)

    return image
示例#6
0
def generate_solution_grid_img(solved_grid_exc_predicted, grid_img):
    FONT = cv2.FONT_HERSHEY_DUPLEX
    CELL_WIDTH = grid_img.shape[1] // 9
    OFFSET = CELL_WIDTH // 15
    # FONT_SCALE = get_optimal_font_scale(CELL_WIDTH)
    FONT_SCALE = CELL_WIDTH / 10 / 4
    transparent_img = np.zeros((grid_img.shape[1], grid_img.shape[0]),
                               np.uint8)
    (text_height, text_width), _ = cv2.getTextSize("0",
                                                   FONT,
                                                   fontScale=FONT_SCALE,
                                                   thickness=1)
    for row in range(9):
        for column in range(9):
            if solved_grid_exc_predicted[row][column] == 0:
                continue
            cell_num_str = str(solved_grid_exc_predicted[row][column])
            bottom_left_x = CELL_WIDTH * column + (CELL_WIDTH -
                                                   text_width) // 2 + OFFSET
            bottom_left_y = CELL_WIDTH * (row + 1) - (
                CELL_WIDTH - text_height) // 2 + OFFSET
            transparent_img = cv2.putText(
                transparent_img,
                cell_num_str, (int(bottom_left_x), int(bottom_left_y)),
                FONT,
                FONT_SCALE,
                255,
                thickness=1,
                lineType=cv2.LINE_AA)
    return transparent_img
    def object_and_speed(self, filename, objects, frame, matrix, ratio_width):
        """
        Функция осуществляет отслеживание, идентификацию,
        подсчет скорости объектов и вывод инфо в заданный файл
        """
        # Добавление центроидов каждую секунду (или TIME) в упорядоченный словарь для нахождения скорости
        if self.frame_count % (self.skip_frames * TIME) < 1:
            self.centroids.save_centroids(objects)
        # цикл по отслеживанию объектов
        for (idx, (object_id, centroid)) in enumerate(objects.items()):
            # проверить, существует ли отслеживаемый объект для текущего идентификатора объекта
            add_object = self.centroids.track.get(object_id, None)
            # если не существует отслеживаемого объекта, создаем его
            if add_object is None:
                add_object = TrackableObject(object_id, centroid)
            else:
                add_object.centroids.append(centroid)
                if not add_object.counted:  # проверяем, был ли объект подсчитан
                    add_object.counted = True

            self.centroids.track[object_id] = add_object
            self.people_count = int(object_id + 1)
            cv2.putText(frame, str(object_id + 1),
                        (centroid[0] - 10, centroid[1] - 10),
                        cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2)
            cv2.circle(frame, (centroid[0], centroid[1]), 5, (0, 0, 255), -1)

            # TODO: лучше настроить отслеживание объектов
            if self.frame_count % (self.skip_frames * TIME) < 1 or \
                    object_id not in self.centroids.speed:
                self.centroids.search_delta_speed(object_id, matrix,
                                                  ratio_width)
                if self.frame_count % (self.skip_frames * TIME) < 1:
                    self.centroids.save_speed(
                        filename, round(self.frame_count / self.skip_frames),
                        object_id, self.centroids.speed[object_id])

            speed_label = str(
                "%d" % self.centroids.speed[object_id]) + " km/hr"
            speed_label_size, base_line = cv2.getTextSize(
                speed_label, cv2.FONT_HERSHEY_SIMPLEX, 0.5, 1)
            y_left_bottom = max(centroid[1], speed_label_size[1])
            cv2.rectangle(
                frame,
                (centroid[0] + 50, centroid[1] - speed_label_size[1] - 100),
                (centroid[0] - speed_label_size[1] - 35,
                 y_left_bottom + base_line - 100), (255, 255, 255), cv2.FILLED)
            cv2.putText(frame, speed_label,
                        (centroid[0] - 50, y_left_bottom - 100),
                        cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0))
            info = "time {}: ID {}: {}".format(
                round(self.frame_count / self.skip_frames), int(object_id + 1),
                speed_label)
            cv2.putText(frame, info, (int(frame.shape[1] / 2), frame.shape[0] -
                                      ((idx * 50) + 50)),
                        cv2.FONT_HERSHEY_SIMPLEX, 1.2, (0, 0, 0), 1,
                        cv2.LINE_AA)
示例#8
0
def get_optimal_font_scale(width):
    for scale in reversed(range(0, 60, 1)):
        textSize = cv2.getTextSize("0",
                                   fontFace=cv2.FONT_HERSHEY_DUPLEX,
                                   fontScale=scale / 10,
                                   thickness=1)
        new_width = textSize[0][0]
        if (new_width <= width):
            return scale / 10 / 2
    return 1
示例#9
0
def _tagPhoto(opencvImage, tag):
    font = cv.FONT_HERSHEY_DUPLEX

    textsize = cv.getTextSize(tag, font, 1, 2)[0]

    cv.rectangle(opencvImage, (10 - 10, 40 + 10),
                 (10 + textsize[0] + 10, 40 + 10 - textsize[1] - 20),
                 (0, 0, 0), -1)
    cv.putText(opencvImage, tag, (10, 40), font, 1, (0, 255, 255), 2,
               cv.LINE_AA)
示例#10
0
def draw_predict(bss, strss, img, num):
    '''绘制预测框'''
    j = 0
    for bs in bss:
        width = 640
        height = 480
        x = [0 for i in range(9)]
        y = [0 for i in range(9)]
        a = np.arange(18)
        corners2D_gt = a.reshape(9, 2)

        for i in range(9):
            x[i] = int(bs[i][0] * width)
            y[i] = int(bs[i][1] * height)
            cv2.circle(img, (x[i], y[i]), 1, (255, 0, 255), -1)
            string = str(i)
            cv2.putText(
                img, string, (x[i], y[i]), cv2.FONT_HERSHEY_COMPLEX, 0.5, (255, 0, 255), 1)
            corners2D_gt[i, 0] = x[i]
            corners2D_gt[i, 1] = y[i]

        # 输出物品名称和识别率
        text = strss[j][0] + ' ' + strss[j][1]
        size = cv2.getTextSize(text, cv2.FONT_HERSHEY_COMPLEX_SMALL, 0.8, 1)
        if x[1] + size[0][0] <= width and y[1] - size[0][1] > 0:
            tx = x[1]
            ty = y[1]
        else:
            tx = x[8]
            ty = y[8]
        cv2.rectangle(img, (tx - 2, ty + 2), (tx + 2 +
                                             size[0][0], ty - 2 - size[0][1]), (255, 255, 0), cv2.FILLED)
        cv2.putText(img, text, (tx, ty),
                   cv2.FONT_HERSHEY_COMPLEX_SMALL, 0.8, (0, 0, 0))

        cv2.line(img, (x[1], y[1]), (x[2], y[2]), (255, 255, 0), 2)
        cv2.line(img, (x[2], y[2]), (x[4], y[4]), (255, 255, 0), 2)
        cv2.line(img, (x[3], y[3]), (x[4], y[4]), (255, 255, 0), 2)
        cv2.line(img, (x[1], y[1]), (x[3], y[3]), (255, 255, 0), 2)

        cv2.line(img, (x[1], y[1]), (x[5], y[5]), (255, 255, 0), 2)
        cv2.line(img, (x[2], y[2]), (x[6], y[6]), (255, 255, 0), 2)
        cv2.line(img, (x[3], y[3]), (x[7], y[7]), (255, 255, 0), 2)
        cv2.line(img, (x[4], y[4]), (x[8], y[8]), (255, 255, 0), 2)

        cv2.line(img, (x[5], y[5]), (x[6], y[6]), (255, 255, 0), 2)
        cv2.line(img, (x[5], y[5]), (x[7], y[7]), (255, 255, 0), 2)
        cv2.line(img, (x[6], y[6]), (x[8], y[8]), (255, 255, 0), 2)
        cv2.line(img, (x[7], y[7]), (x[8], y[8]), (255, 255, 0), 2)

        j += 1
        

    # 保存照片
    cv2.imwrite('JPEGImages/predict' + str(num) + '.jpg', img)
示例#11
0
def draw_boxes(x, img, classes):
    c1 = tuple(x[1:3].int())
    c2 = tuple(x[3:5].int())
    cls = int(x[-1])
    label = "{0}".format(classes[cls])
    color = (0, 0, 255)
    cv2.rectangle(img, c1, c2, color, 2)
    t_size = cv2.getTextSize(label, cv2.FONT_HERSHEY_PLAIN, 1, 1)[0]
    c2 = c1[0] + t_size[0] + 3, c1[1] + t_size[1] + 4
    cv2.rectangle(img, c1, c2, color, -1)
    cv2.putText(img, label, (c1[0], c1[1] + t_size[1] + 4),
                cv2.FONT_HERSHEY_PLAIN, 1, [225, 255, 255], 1)
    return img
示例#12
0
def find_font_params(top_text, bot_text):
    FONT = cv2.FONT_HERSHEY_COMPLEX
    FONT_SCALE = 1.5
    FONT_THICKNESS = 2

    (top_label_width, top_label_height), _ = cv2.getTextSize(top_text,
                                                             FONT,
                                                             FONT_SCALE,
                                                             FONT_THICKNESS)
    (bot_label_width, bot_label_height), _ = cv2.getTextSize(bot_text,
                                                             FONT,
                                                             FONT_SCALE,
                                                             FONT_THICKNESS)

    max_width = max([top_label_width, bot_label_width])

    font = {
        'font': FONT,
        'scale': FONT_SCALE,
        'thickness': FONT_THICKNESS
    }
    return font
示例#13
0
def create_and_write_meme(partitioned_text):
    my_path = os.path.abspath(os.path.dirname(__file__))
    pic_path = os.path.join(my_path, 'spongebob.jpg')

    # height, width, channels
    img = cv2.imread(pic_path)
    img_height, img_width, _ = img.shape

    print('[!] Use num characters to determine font')
    # def find_font_size()

    top_text, bot_text = partitioned_text.split("|SPONGEPIC|")

    # TODO: swap font type -> IMPACT, use Dank Learnings meme writer maybe?
    font = find_font_params(top_text, bot_text)
    label_color = (255, 255, 255) #255 #(0, 0, 0)
    # TODO: add black outline to text

    (top_label_width, top_label_height), _ = cv2.getTextSize(top_text,
                                                             font['font'],
                                                             font['scale'],
                                                             font['thickness'])
    top_center = top_label_width / 2
    top_left = int((img_width/2) - top_center)
    top_top = int((img_height * .05) + top_label_height)  # 5% down

    (bot_label_width, bot_label_height), _ = cv2.getTextSize(bot_text,
                                                             font['font'],
                                                             font['scale'],
                                                             font['thickness'])
    bot_center = bot_label_width / 2
    bot_left = int((img_width/2) - bot_center)
    bot_bot = int((img_height * .95) - bot_label_height)  # 5% down

    label_color = (255, 255, 255) #255 #(0, 0, 0)
    cv2.putText(img, top_text, (top_left, top_top), font['font'], font['scale'], label_color, thickness=font['thickness']S)
    cv2.putText(img, bot_text, (bot_left, bot_bot), font['font'], font['scale'], label_color, thickness=font['thickness'])

    cv2.imwrite(os.path.join(os.getcwd(), 'meme.jpg'), img)
示例#14
0
def crea_video(inizio_dt, fine_dt, percorso, fps, grayscale, gif):
    if percorso[-1] != "/":
        percorso = percorso + "/"
    frame_width = 1280
    frame_height = 720

    out = cv2.VideoWriter('video_out.mp4', cv2.VideoWriter_fourcc(*'mp4v'),
                          fps, (frame_width, frame_height))

    vettore_file_data = {}
    for filename in os.listdir(percorso):
        exif_dict = piexif.load(percorso + filename)
        data = exif_dict["Exif"][36867].decode()
        data_dt = datetime.datetime.strptime(data, "%Y:%m:%d %H:%M:%S")
        if data_dt >= inizio_dt and data_dt <= fine_dt:
            vettore_file_data[data_dt] = filename

    for key in sorted(vettore_file_data):

        if (grayscale == 1):
            img = cv2.imread(percorso + vettore_file_data[key],
                             cv2.IMREAD_GRAYSCALE)
            img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
        else:
            img = cv2.imread(percorso + vettore_file_data[key],
                             cv2.IMREAD_ANYCOLOR)
        # shape restituisce (altezza,larghezza,num_canali)
        #calcolo nuove dimensioni
        if img.shape[0] != frame_height or img.shape[1] != frame_width:
            frame = ridimensiona(img, frame_height, frame_width)
        else:
            frame = img

        dimtesto = cv2.getTextSize(str(key), cv2.FONT_HERSHEY_SIMPLEX, 1,
                                   1)[0]  # (larghezza,altezza)
        altezza_rect = dimtesto[1] + 10
        cv2.rectangle(frame, (0, frame_height),
                      (frame_width, frame_height - altezza_rect), (0, 0, 0),
                      -1)
        cv2.putText(frame, str(key),
                    (int((frame_width - dimtesto[0]) / 2),
                     int(frame_height - (altezza_rect - dimtesto[1]) / 2)),
                    cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 1,
                    cv2.LINE_AA)

        out.write(frame)

    out.release()
    if (gif == 1):
        clip = VideoFileClip("video_out.mp4")
        clip.write_gif("video_out.gif")
示例#15
0
    def drawAllResult(self, image):
        """Draw the detection result on image"""
        for facebox, conf in self.detectionResult:
            cv2.rectangle(image, (facebox[0], facebox[1]),
                          (facebox[2], facebox[3]), (0, 255, 0))
            label = "face: %.4f" % conf
            labelSize, baseLine = cv2.getTextSize(label,
                                                  cv2.FONT_HERSHEY_SIMPLEX,
                                                  0.5, 1)

            cv2.rectangle(image, (facebox[0], facebox[1] - labelSize[1]),
                          (facebox[0] + labelSize[0], facebox[1] + baseLine),
                          (0, 255, 0), cv2.FILLED)
            cv2.putText(image, label, (facebox[0], facebox[1]),
                        cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 0))
示例#16
0
def put_text_right(img, text):
    if text is None:
        return None
    text_size = cv2.getTextSize(text,
                                FONT,
                                fontScale=FONT_SCALE,
                                thickness=FONT_THICKNESS)[0]
    text_x = int(ICON_RIGHT_X1 + ((ICON_WIDTH - text_size[0]) / 2))
    text_y = int(ICON_RIGHT_Y1 + ICON_HEIGHT + text_size[1] + 20)
    cv2.putText(img,
                text, (text_x, text_y),
                fontFace=FONT,
                fontScale=FONT_SCALE,
                color=(147, 58, 31),
                thickness=FONT_THICKNESS,
                lineType=cv2.LINE_AA)
示例#17
0
def show_confidence(result, img, color):
    for box in result:
        text = box.object_class
        (text_width, text_height) = cv2.getTextSize(text,
                                                    font,
                                                    fontScale=fontScale,
                                                    thickness=1)[0]
        text_offset_x = box.topleft_x
        text_offset_y = box.topleft_y
        # make the coords of the box with a small padding of two pixels
        box_coords = ((text_offset_x, text_offset_y),
                      (text_offset_x + text_width - 2,
                       text_offset_y - text_height - 2))
        cv2.rectangle(img, box_coords[0], box_coords[1], color, cv2.FILLED)
        cv2.putText(img, text, (box.topleft_x, box.topleft_y), font, fontScale,
                    fontColor, lineType)
示例#18
0
 def draw_prediction(self, image, class_id, confidence, x1, y1, x2, y2):
     image_height, image_width, _ = image.shape
     fontSize = round(image_height / 1024)
     label = (str(self.classes[class_id]) + " " + str(round(confidence * 100)) + "%").upper()
     color = self.colors[class_id]
     x1 = max(x1, 0)
     y1 = max(y1, 0)
     cv2.rectangle(image, (x1, y1), (x2, y2), color, fontSize)
     (textWidth, textHeight), baseline = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, fontSize, fontSize)
     if y1 - textHeight <= 0:
         y1 = y1 + textHeight
         cv2.rectangle(image, (x1, y1), (x1 + textWidth, y1 - textHeight), color, -1)
         cv2.putText(image, label, (x1, y1), cv2.FONT_HERSHEY_SIMPLEX, fontSize, (0, 0, 0), fontSize)
     else:
         cv2.rectangle(image, (x1, y1), (x1 + textWidth, y1 - textHeight), color, -1)
         cv2.putText(image, label, (x1, y1), cv2.FONT_HERSHEY_SIMPLEX, fontSize, (0, 0, 0), fontSize)
示例#19
0
def put_end_text(img, text):
    if text is None:
        return None
    text_size = cv2.getTextSize(text,
                                FONT,
                                fontScale=FONT_SCALE,
                                thickness=FONT_THICKNESS)[0]
    text_x = int((WINDOW_WIDTH / 2) - (text_size[0] / 2))
    text_y = ICON_CENTER_Y1 + ICON_HEIGHT + text_size[1] + 90
    cv2.putText(img,
                text, (text_x, text_y),
                fontFace=FONT,
                fontScale=FONT_SCALE,
                color=(147, 58, 31),
                thickness=FONT_THICKNESS,
                lineType=cv2.LINE_AA)
示例#20
0
    def text_height(self, text, **kwargs):

        overlay_font = \
            getattr( cv2, 'FONT_{}'.format( kwargs['overlayfont'] ) ) \
            if 'overlayfont' in kwargs else cv2.FONT_HERSHEY_SIMPLEX
        overlay_scale = float( kwargs['overlayscale'] ) \
            if 'overlayscale' in kwargs else 0.5
        overlay_thickness = int( kwargs['overlaythickness'] ) \
            if 'overlaythickness' in kwargs else 1

        size = cv2.getTextSize(text,
                               fontFace=overlay_font,
                               fontScale=overlay_scale,
                               thickness=overlay_thickness * 4)

        return size[0][1]
示例#21
0
def draw_bboxes(img, bbox, identities=None, offset=(0, 0)):
    for i, box in enumerate(bbox):
        x1, y1, x2, y2 = [int(i) for i in box]
        x1 += offset[0]
        x2 += offset[0]
        y1 += offset[1]
        y2 += offset[1]
        # box text and bar
        id = int(identities[i]) if identities is not None else 0
        color = COLORS_10[id % len(COLORS_10)]
        label = '{}{:d}'.format("", id)
        t_size = cv2.getTextSize(label, cv2.FONT_HERSHEY_PLAIN, 2, 2)[0]
        cv2.rectangle(img, (x1, y1), (x2, y2), color, 3)
        cv2.rectangle(img, (x1, y1), (x1 + t_size[0] + 3, y1 + t_size[1] + 4),
                      color, -1)
        cv2.putText(img, label, (x1, y1 + t_size[1] + 4),
                    cv2.FONT_HERSHEY_PLAIN, 2, [255, 255, 255], 2)
示例#22
0
def plot_one_box(x, img, color=None, label=None, line_thickness=None):
    # Plots one bounding box on image img
    tl = line_thickness or round(
        0.002 * (img.shape[0] + img.shape[1]) / 2) + 1  # line/font thickness
    color = color or [random.randint(0, 255) for _ in range(3)]
    c1, c2 = (int(x[0]), int(x[1])), (int(x[2]), int(x[3]))
    cv2.rectangle(img, c1, c2, color, thickness=tl, lineType=cv2.LINE_AA)
    if label:
        tf = max(tl - 1, 1)  # font thickness
        t_size = cv2.getTextSize(label, 0, fontScale=tl / 3, thickness=tf)[0]
        c2 = c1[0] + t_size[0], c1[1] - t_size[1] - 3
        cv2.rectangle(img, c1, c2, color, -1, cv2.LINE_AA)  # filled
        cv2.putText(img,
                    label, (c1[0], c1[1] - 2),
                    0,
                    tl / 3, [225, 255, 255],
                    thickness=tf,
                    lineType=cv2.LINE_AA)
示例#23
0
def drawPred(class_id, confidence, left, top, right, bottom, car_num):
    """
    根据预测结果在图片上画出矩形框
    :param class_id:
    :param confidence:
    :param left:
    :param top:
    :param right:
    :param bottom:
    :return:
    """
    cv2.rectangle(frame, (left, top), (right, bottom), (0, 255, 0), 3)
    #label = "{0}: {1:.4f},count={2}".format(class_names[class_id], confidence,count_car)
    label = "{0}".format(car_num)
    labelSize, _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 1, 2)
    top = max(top, labelSize[1])
    cv2.putText(frame, label, (left, top), cv2.FONT_HERSHEY_SIMPLEX, 1,
                (0, 0, 0), 2)
示例#24
0
def addCV2Text(text):
    from cv2 import cv2

    font = cv2.FONT_HERSHEY_SIMPLEX

    # Work out how big we will need to make an array to display the text, line by line.
    lineCount = 0
    maxHeight = 0
    maxWidth = 0
    for line in enumerate(text.split('\n')):
        lineCount += 1
        s = line[1]
        (width, height), baseline = cv2.getTextSize(s,
                                                    font,
                                                    fontScale=1,
                                                    thickness=2)
        print(height, width, baseline, s)
        maxHeight = max(maxHeight, height)
        maxWidth = max(maxWidth, width)

    textImgArray = newImageArray((maxHeight + 20) * lineCount, maxWidth + 20)

    print('Lines = ', lineCount)
    print('Maxh, Maxw =', maxHeight, maxWidth)
    print('Shape is', textImgArray.shape)

    # Line-by-line add the text to the array
    for line in enumerate(
            text.split('\n')):  # line is compound: (line-number, text)
        i = line[0]
        text_offset_x = 10
        text_offset_y = i * (maxHeight + 20)
        cv2.putText(textImgArray,
                    line[1], (text_offset_x, text_offset_y),
                    font,
                    fontScale=1,
                    thickness=1,
                    color=(0, 0, 0))

    showImage('CV2Text', textImgArray)

    return textImgArray
 def draw_box(self):
     boxes = self.get_boxes(self.frame_no)
     for box in boxes:
         x1, y1, x2, y2 = box[0], box[1], box[2], box[3]
         id = box[4]
         label = f"{id}"
         if id in self.window.mark_map:
             color = (0, 255, 0)
             t = self.window.mark_map[id]
             if t[0] != -1:
                 label += f" {self.window.names[t[0]]}({self.window.names[t[1]]})"
         elif self.window.identity == id:
             color = (255, 0, 0)
         else:
             color = (0, 0, 255)
         # print(color)
         t_size = cv2.getTextSize(label, cv2.FONT_HERSHEY_PLAIN, 2, 2)[0]
         cv2.rectangle(self.frame, (x1, y1), (x2, y2), color, 3)
         cv2.rectangle(self.frame, (x1, y1), (x1 + t_size[0] + 3, y1 + t_size[1] + 4), color, -1)
         cv2.putText(self.frame, label, (x1, y1 + t_size[1] + 4), cv2.FONT_HERSHEY_PLAIN, 2, [255, 255, 255], 2)
示例#26
0
def put_countdown_text(img, eye_position, count):
    countdown = str(
        round((SELECTED_CYCLE_THRESHOLD * CYCLE_TIME) - (count * CYCLE_TIME),
              1))
    text_size = cv2.getTextSize(countdown,
                                FONT,
                                fontScale=FONT_SCALE,
                                thickness=FONT_THICKNESS)[0]
    text_x = 20  # left
    if eye_position == EYE_POSITION_RIGHT:
        text_x = WINDOW_WIDTH - text_size[0] - 20
    elif eye_position == EYE_POSITION_CENTER:
        text_x = int((WINDOW_WIDTH / 2) - (text_size[0] / 2))
    text_y = text_size[1] + 100
    cv2.putText(img,
                countdown, (text_x, text_y),
                fontFace=FONT,
                fontScale=FONT_SCALE,
                color=(147, 58, 31),
                thickness=FONT_THICKNESS,
                lineType=cv2.LINE_AA)
示例#27
0
def make_video(begin, end, path, fps, grayscale, frame_width, frame_height,
               name_video, client, bucket):
    path_list = retrieve_photos(begin, end, path, client, bucket)
    out = cv2.VideoWriter('/tmp/{}.avi'.format(name_video),
                          cv2.VideoWriter_fourcc(*'MJPG'), fps,
                          (frame_width, frame_height))

    for photo_file in path_list:
        if grayscale == 1:
            img = cv2.imread(photo_file, cv2.IMREAD_GRAYSCALE)
            img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
        elif grayscale == 0:
            img = cv2.imread(photo_file, cv2.IMREAD_ANYCOLOR)
        # shape restituisce (altezza,larghezza,num_canali)
        #calcolo nuove dimensioni
        if img.shape[0] != frame_height or img.shape[1] != frame_width:
            frame = resize_frame(img, frame_height, frame_width)
        else:
            frame = img
        # Aggiunta della data
        #la data deve essere trasformata in un formato leggibile
        date = photo_file.split('/')[-1].split('.')[0]
        date = '{}-{}-{} {}:{}'.format(date[0:4], date[4:6], date[6:8],
                                       date[8:10], date[10:])
        dimtesto = cv2.getTextSize(date, cv2.FONT_HERSHEY_SIMPLEX, 1,
                                   1)[0]  # (larghezza,altezza)
        altezza_rect = dimtesto[1] + 10
        cv2.rectangle(frame, (0, frame_height),
                      (frame_width, frame_height - altezza_rect), (0, 0, 0),
                      -1)
        cv2.putText(frame, date,
                    (int((frame_width - dimtesto[0]) / 2),
                     int(frame_height - (altezza_rect - dimtesto[1]) / 2)),
                    cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 1,
                    cv2.LINE_AA)
        out.write(frame)

    out.release()
    return path_list[-1]
示例#28
0
def drawPredCar(car):
    """
    根据预测结果在图片上画出矩形框
    """
    if car.lane_num == 1:
        rectcolor = (0, 255, 0)  #绿
    elif car.lane_num == 2:
        rectcolor = (255, 0, 0)  #蓝
    elif car.lane_num == 3:
        rectcolor = (0, 255, 255)  #黄
    elif car.lane_num == 4:
        rectcolor = (255, 0, 255)
    else:  #car.lane_num==-1: #错误
        rectcolor = (0, 0, 255)

    cv2.rectangle(frame, (car.left, car.top),
                  (car.left + car.width, car.top + car.height), rectcolor, 3)
    #label = "{0}: {1:.4f},count={2}".format(class_names[class_id], confidence,count_car)
    label = "{0},y={1:.1f},x={2:.1f}".format(car.car_num, car.dy, car.dx)
    labelSize, _ = cv2.getTextSize(label, cv2.FONT_HERSHEY_SIMPLEX, 1, 2)
    #top = max(car.top, labelSize[1])
    cv2.putText(frame, label, (int(car.x_center), car.top + car.height),
                cv2.FONT_HERSHEY_SIMPLEX, 1, (255, 255, 255), 2)
示例#29
0
def write_soln_on_image(image, grid, user_grid):
    # Write grid on the image
    SIZE = 9
    width = image.shape[1] // 9
    height = image.shape[0] // 9
    for i in range(SIZE):
        for j in range(SIZE):
            if (user_grid[i][j] != 0):  # If already filled
                continue
            # Convert to string
            text = str(grid[i][j])
            off_set_x = width // 15
            off_set_y = height // 15
            font = cv2.FONT_HERSHEY_SIMPLEX
            (text_height, text_width), baseline = cv2.getTextSize(text,
                                                                  font,
                                                                  fontScale=1,
                                                                  thickness=3)

            font_scale = 0.6 * min(width, height) / max(
                text_height, text_width)
            text_height *= font_scale
            text_width *= font_scale
            bottom_left_corner_x = width * j + math.floor(
                (width - text_width) / 2) + off_set_x
            bottom_left_corner_y = height * (i + 1) - math.floor(
                (height - text_height) / 2) + off_set_y
            # Line_AA minimizes distortion in the text drawn
            image = cv2.putText(image,
                                text,
                                (bottom_left_corner_x, bottom_left_corner_y),
                                font,
                                font_scale, (0, 255, 0),
                                thickness=3,
                                lineType=cv2.LINE_AA)
    return image
def writeLicensePlateCharsOnImage(imgOriginalScene, licPlate):
    ptCenterOfTextAreaX = 0
    ptCenterOfTextAreaY = 0

    ptLowerLeftTextOriginX = 0
    ptLowerLeftTextOriginY = 0

    sceneHeight, sceneWidth, sceneNumChannels = imgOriginalScene.shape
    plateHeight, plateWidth, plateNumChannels = licPlate.imgPlate.shape

    intFontFace = cv2.FONT_HERSHEY_SIMPLEX
    fltFontScale = float(plateHeight) / 30.0
    intFontThickness = int(round(fltFontScale * 1.5))
    textSize, baseline = cv2.getTextSize(licPlate.strChars, intFontFace,
                                         fltFontScale, intFontThickness)
    ((intPlateCenterX, intPlateCenterY), (intPlateWidth, intPlateHeight),
     fltCorrectionAngleInDeg) = licPlate.rrLocationOfPlateInScene

    intPlateCenterX = int(intPlateCenterX)
    intPlateCenterY = int(intPlateCenterY)
    ptCenterOfTextAreaX = int(intPlateCenterX)

    if intPlateCenterY < (sceneHeight * 0.75):
        ptCenterOfTextAreaY = int(round(intPlateCenterY)) + int(
            round(plateHeight * 1.6))

    else:
        ptCenterOfTextAreaY = int(round(intPlateCenterY)) - int(
            round(plateHeight * 1.6))

    textSizeWidth, textSizeHeight = textSize
    ptLowerLeftTextOriginX = int(ptCenterOfTextAreaX - (textSizeWidth / 2))
    ptLowerLeftTextOriginY = int(ptCenterOfTextAreaY + (textSizeHeight / 2))
    cv2.putText(imgOriginalScene, licPlate.strChars,
                (ptLowerLeftTextOriginX, ptLowerLeftTextOriginY), intFontFace,
                fltFontScale, SCALAR_YELLOW, intFontThickness)