Exemplo n.º 1
0
def run__crop():
    paper_size = 'A4'
    ref_dim = [1280, None]

    org_img = hp.hp_imread("test_videos/DB_1.jpg")
    ret, det_vertices, box_img = detect_four_corners_based_on_ref_squares(
        org_img, (0, 0),
        search_margin=0.1,
        square_width=50. / 2480,
        debug_=False)
    if paper_size == 'A4':
        ref_dim[1] = int(ref_dim[0] * np.sqrt(2.))

    tar_vertices = [[0, 0], [ref_dim[0], 0], [0, ref_dim[1]],
                    [ref_dim[0], ref_dim[1]]]
    mtx = cv2.getPerspectiveTransform(np.float32(det_vertices),
                                      np.float32(tar_vertices))
    warp_img = cv2.warpPerspective(org_img,
                                   mtx,
                                   dsize=tuple(ref_dim),
                                   flags=cv2.INTER_LINEAR)
    hp.hp_imshow(warp_img, "output")
    hp.hp_imwrite(warp_img, "output.png")
Exemplo n.º 2
0
def derotate_image(img,
                   max_angle=30,
                   max_angle_candidates=50,
                   angle_resolution=0.5,
                   inside_margin_ratio=0.1,
                   rot_img_fname=None,
                   check_time_=False,
                   pause_img_sec=-1):
    """
    Derotate image.

    :param img:
    :param max_angle: Maximum rotated angle. The angles above this should be ignored.
    :param max_angle_candidates:
    :param angle_resolution:
    :param inside_margin_ratio:
    :param rot_img_fname:
    :param check_time_:
    :param pause_img_sec:
    :return:
    """
    start_time = None
    if check_time_:
        start_time = time.time()
    if len(img.shape) == 3:
        img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
        # img_gray = np.amin(img, axis=2)
    else:
        img_gray = np.copy(img)

    inside_margin = [int(x * inside_margin_ratio) for x in img.shape[1::-1]]

    img_gray[:inside_margin[1], :] = 255
    img_gray[-inside_margin[1]:, :] = 255
    img_gray[:, :inside_margin[0]] = 255
    img_gray[:, -inside_margin[0]:] = 255

    if False:
        check_lines_in_img(img, algorithm='HoughLineTransform')
        check_lines_in_img(img, algorithm='ProbabilisticHoughTransform')

    ret, img_bw = cv2.threshold(img_gray, 128, 255,
                                cv2.THRESH_BINARY | cv2.THRESH_OTSU)
    """
    kernel = np.ones((5, 5), np.uint8)  # note this is a horizontal kernel
    bw = np.copy(img_bw)
    for i in range(9):
        bw = cv2.erode(bw, kernel, iterations=1)
        bw = cv2.dilate(bw, kernel, iterations=1)
    hp.hp_imshow(hp.hstack_images((img_bw, bw)))
    """
    img_edge = cv2.Canny(img_bw, 50, 150, apertureSize=3)
    if False:
        hp.hp_imshow(img_edge)
        # hp.plt_imshow(edges)

    lines = cv2.HoughLines(img_edge, 1, np.pi / 360,
                           int(min(img_edge.shape) / 8.))

    angles = []
    if lines is not None:
        for cnt, line in enumerate(lines):
            angle = int((90 - line[0][1] * 180 / np.pi) /
                        float(angle_resolution)) * angle_resolution
            draw_line_from_rho_and_theta(img,
                                         line[0][0],
                                         line[0][1],
                                         pause_sec=-1)

            if abs(angle) < max_angle:
                angles.append(angle)
            if max_angle_candidates < cnt:
                break

    # rot_angle = max(set(angles), key=angles.count)
    sorted_angles = sorted({x: angles.count(x)
                            for x in angles}.items(),
                           key=operator.itemgetter(1),
                           reverse=True)

    if len(sorted_angles) == 0:
        rot_angle = 0
    elif len(sorted_angles) == 1:
        rot_angle = sorted_angles[0][0]
    elif sorted_angles[0][0] == 0 and (sorted_angles[0][1] <
                                       2 * sorted_angles[1][1]):
        rot_angle = sorted_angles[1][0]
    elif (sorted_angles[0][1] / sorted_angles[1][1]
          ) < 3 and abs(sorted_angles[0][0] - sorted_angles[1][0]) <= 1.0:
        rot_angle = (sorted_angles[0][0] + sorted_angles[1][0]) / 2.
    else:
        rot_angle = sorted_angles[0][0]
    """
    if rot_angle != 0:
        rot_angle += 0.5
    """
    if pause_img_sec >= 0:
        print("# Rotated angle is {:5.1f} degree.".format(rot_angle))

    sz = img_bw.shape[1::-1]
    rot_img = ~imutils.rotate(~img,
                              angle=-rot_angle,
                              center=(int(sz[0] / 2), int(sz[1] / 2)),
                              scale=1)
    if check_time_:
        print(
            " # Time for rotation detection and de-rotation if any : {:.2f} sec"
            .format(float(time.time() - start_time)))

    if 0 <= pause_img_sec:
        hp.imshow(np.concatenate((img, rot_img), axis=1),
                  pause_sec=pause_img_sec,
                  desc="de-rotation")

    if rot_img_fname:
        hp.hp_imwrite(rot_img_fname, rot_img, 'RGB')

    return rot_img