import glob
import os
import math
from .util import *
import ctypes
import time
import sys
import numpy as np
try:
    temp = ctypes.windll.LoadLibrary('opencv_ffmpeg410_64.dll')
except:
    pass


def rotate_by_anchor(image, method='connected', debug=0):
    #   寻找试卷大定位点并据此旋转纠偏

    shift_threshold = 80   # 50    # 最上方两个定位点纵坐标相差阈值
    pie = 3.14159
    # height, width = image.shape[:2]
    height, width = image.shape[:2]
    # h_ratio = (0.1, 0.9)
    area_threshold = 0.28   # 0.25
    anchors_len_threshold = 2
    # shape_para = {'height': (80, 10), 'w2h': (3, 1.1), 'area': (6000, 500), 'area_ratio': 0.5}

    binary = pre_process_for_anchors(image, debug=0)
    # h0 = int(binary.shape[0] * h_ratio[0])
    # h1 = int(binary.shape[0] * h_ratio[1])
    # binary[h0:h1, :] = 0
    binary = extract_feature(binary, method=4, debug=0)
    boxes = find_boxes(binary, method=method, debug=0)
    markers = find_marker_by_shape(boxes, debug=0)
    # 按面积从大到小排列
    markers.sort(reverse=True, key=lambda x: x[-1])
    anchors = []
    for i in range(len(markers)):
        anchors = []
        anchors.append(markers[i])
        for j in range(i+1, len(markers)):
            if (anchors[0][-1] - markers[j][-1]) / anchors[0][-1] <= area_threshold:
                anchors.append(markers[j])
        if len(anchors) >= anchors_len_threshold:
            break

    anchors.sort(key=lambda x: x[4][1])
    top_anchors = []
    bottom_anchors = []
    for a in anchors:
        if a[4][1] - anchors[0][4][1] < shift_threshold:
            top_anchors.append(a)
        else:
            bottom_anchors.append(a)

    # draw_box(image, top_anchors, (0, 255, 255))
    # draw_box(image, bottom_anchors, (255, 0, 255))
    # plt.figure(figsize=(15, 10))
    # plt.title(method)
    # plt.imshow(image)
    # plt.show()

    #   旋转纠偏
    if len(top_anchors) >= 2:
        mean_y = sum([x[4][1] for x in top_anchors]) / len(top_anchors)
        top_anchors.sort(key=lambda x: abs(x[4][1] - mean_y))
        angle = 180 / pie * math.atan((top_anchors[1][4][1] - top_anchors[0][4][1]) / (top_anchors[1][4][0] -
                                                                                       top_anchors[0][4][0]))
    elif len(bottom_anchors) >= 2:
        mean_y = sum([x[4][1] for x in bottom_anchors]) / len(bottom_anchors)
        bottom_anchors.sort(key=lambda x: abs(x[4][1] - mean_y))
        angle = 180 / pie * math.atan((bottom_anchors[1][4][1] - bottom_anchors[0][4][1]) / (bottom_anchors[1][4][0] -
                                                                                             bottom_anchors[0][4][0]))
    else:
        return image, False
    # try:
    #     angle = 180 / pie * math.atan((top_anchors[1][4][1] - top_anchors[0][4][1]) / (top_anchors[1][4][0] -
    #                                                                                    top_anchors[0][4][0]))
    # except IndexError:
    #     print('Not Enough top_anchors! Proceed any way!')
    #     return image, 0
    (cx, cy) = (width // 2, height // 2)
    mat = cv2.getRotationMatrix2D((cx, cy), angle, 1.0)
    # compute the new bounding dimensions of the image
    cos = np.abs(mat[0, 0])
    sin = np.abs(mat[0, 1])
    new_width = int((height * sin) + (width * cos))
    new_height = int((height * cos) + (width * sin))
    # adjust the rotation matrix to take into account translation
    mat[0, 2] += (new_width / 2) - cx
    mat[1, 2] += (new_height / 2) - cy

    rot_image = cv2.warpAffine(image, mat, (new_width, new_height), borderValue=(255, 255, 255))

    if debug == 1:
        draw_box(image, top_anchors, (0, 255, 255))
        draw_box(image, bottom_anchors, (255, 0, 255))
        plt.figure(figsize=(15, 10))
        plt.title(method)
        plt.imshow(image)
        plt.show()

    return rot_image, True


def detect_anchor_by_position(anchors, markers, image, method, debug=0):
    #   按默认位置寻找第一个及最后一个定位点
    position_threshold = 300
    h_ratio = (0.1, 0.9)
    shift_shreshold = 50

    height, width = image.shape[:2]
    first_anchor, last_anchor = [], []
    if method == 't':
        top_left_flag, top_right_flag = height*h_ratio[0] + position_threshold, height*h_ratio[0] - position_threshold

        if len(anchors) == 0:
            for m in markers:
                if m[4][0] < position_threshold and m[4][1] + m[4][0] < top_left_flag:
                    top_left_flag = m[4][1] + m[4][0]
                    first_anchor = m
                elif width - m[4][0] < position_threshold and m[4][1] - m[4][0] < top_right_flag:
                    top_right_flag = m[4][1] - m[4][0]
                    last_anchor = m
            if len(first_anchor) > 0:
                anchors.append(first_anchor)
            if len(last_anchor) > 0:
                anchors.append(last_anchor)
        else:
            if anchors[0][4][0] > position_threshold:
                for m in markers:
                    if m[4][0] < position_threshold and m[4][1] + m[4][0] < top_left_flag:
                        top_left_flag = m[4][1] + m[4][0]
                        first_anchor = m
                if len(first_anchor) > 0:
                    anchors.insert(0, first_anchor)
            if width - anchors[-1][4][0] > position_threshold:
                for m in markers:
                    if width - m[4][0] < position_threshold and m[4][1] - m[4][0] < top_right_flag:
                        top_right_flag = m[4][1] - m[4][0]
                        last_anchor = m
                if len(last_anchor) > 0:
                    anchors.append(last_anchor)
    if method == 'b':
        bottom_left_flag, bottom_right_flag = height*h_ratio[1]-position_threshold, height*h_ratio[1]+position_threshold

        if len(anchors) == 0:
            for m in markers:
                if m[4][0] < position_threshold and m[4][1] - m[4][0] > bottom_left_flag:
                    bottom_left_flag = m[4][1] - m[4][0]
                    first_anchor = m
                elif width - m[4][0] < position_threshold and m[4][1] + m[4][0] > bottom_right_flag:
                    bottom_right_flag = m[4][1] + m[4][0]
                    last_anchor = m
            if len(first_anchor) > 0:
                anchors.append(first_anchor)
            if len(last_anchor) > 0:
                anchors.append(last_anchor)
        else:
            if anchors[0][4][0] > position_threshold:
                for m in markers:
                    if m[4][0] < position_threshold and m[4][1] - m[4][0] > bottom_left_flag:
                        bottom_left_flag = m[4][1] - m[4][0]
                        first_anchor = m
                if len(first_anchor) > 0:
                    anchors.insert(0, first_anchor)
            if width - anchors[-1][4][0] > position_threshold:
                for m in markers:
                    if width - m[4][0] < position_threshold and m[4][1] + m[4][0] > bottom_right_flag:
                        bottom_right_flag = m[4][1] + m[4][0]
                        last_anchor = m
                if len(last_anchor) > 0:
                    anchors.append(last_anchor)

    if debug == 1:
        draw_box(image, [first_anchor, last_anchor], debug=1)
        plt.figure(figsize=(15, 10))
        plt.title('anchor by position')
        plt.imshow(image)
        plt.show()


def detect_anchor_public(image, method='connected', debug=0):
    #   寻找第三方试卷最上方及最下方的定位点
    shift_threshold = 50  # 80
    height, width = image.shape[:2]
    h0, h1 = 0.1, 0.9
    pos = (0.1, 0.3, 0.5, 0.6, 0.8, 0.9)
    pos_threshold = 0.1
    area_threshold = 0.28  # 0.25   # 大定位点面积差阈值
    anchors_len_threshold = 2
    shape_para = {'height': (80, 10), 'w2h': (3, 0.6), 'area': (6000, 500), 'area_ratio': 0.9}
    blur_size = 3
    sigma = 5
    shift_edge = 2  # 对定位点位置做微调偏移

    binary = pre_process_for_anchors(image, debug=0, blur_size=blur_size, sigma=sigma)
    binary = extract_feature(binary, method=4, debug=0)
    boxes = find_boxes(binary, method=method, debug=0)
    markers = find_marker_by_shape(boxes, shape_para=shape_para, debug=0)
    marker_list = collect_markers_by_position(markers, method='h', shift_threshold=shift_threshold)

    if len(marker_list) == 0:
        anchors = []
    elif len(marker_list) == 1:
        anchors = marker_list[0]
    else:
        anchors = marker_list[0]
        anchors.extend(marker_list[-1])
    anchors = [[a[0]-shift_edge, a[1]-shift_edge, a[2]-shift_edge-1, a[3]-shift_edge-1] for a in anchors]

    if debug == 1:
        # print(anchors)
        draw_box(image, anchors, (0, 255, 255), debug=1)
        plt.figure(figsize=(15, 10))
        plt.title(method)
        plt.imshow(image, cmap='gray')
        plt.show()
    elif debug == 2:
        markers.sort(reverse=True, key=lambda x: x[4][1])
        draw_box(image, markers, debug=1)
        plt.figure(figsize=(15, 10))
        plt.title('by shape')
        plt.imshow(image, cmap='gray')
        plt.show()

    return anchors


def detect_anchor(image, method='connected', debug=0):
    #   寻找试卷最上方及最下方的定位点

    shift_threshold = 50    # 80
    height, width = image.shape[:2]
    h0, h1 = 0.1, 0.9
    pos = (0.1, 0.3, 0.5, 0.6, 0.8, 0.9)
    pos_threshold = 0.1
    area_threshold = 0.28   # 0.25   # 大定位点面积差阈值
    anchors_len_threshold = 2

    binary = pre_process_for_anchors(image, debug=0)
    binary = extract_feature(binary, method=4, debug=0)
    boxes = find_boxes(binary, method=method, debug=0)
    markers = find_marker_by_shape(boxes, debug=0)
    marker_list = collect_markers_by_position(markers, method='h', shift_threshold=shift_threshold)
    # print(len(marker_list[0]))
    # print(len(marker_list[-1]))
    if len(marker_list) == 0:
        return []

    #   如果上方定位点不多于下方定位点，上下左右翻转答题卡
    if len(marker_list[0]) < len(marker_list[-1]) and len(marker_list[-1]) >= 6:
        image = cv2.flip(image, -1)
        binary = cv2.flip(binary, -1)
        boxes = find_boxes(binary, method=method, debug=0)
        markers = find_marker_by_shape(boxes, debug=0)
        marker_list = collect_markers_by_position(markers, method='h', shift_threshold=shift_threshold)

    # for m in marker_list:
    #     m.sort(key=lambda x: x[4][0])
    top_anchors = []
    bottom_anchors = []
    version_points = []
    top_y = np.mean(np.array([m[4][1] for m in marker_list[0]]))
    bottom_y = np.mean(np.array([m[4][1] for m in marker_list[-1]]))
    top_index, bottom_index = 0, -1

    try:
        bottom_anchors.append(min([m for m in marker_list[bottom_index] if m[4][0] / width < pos[0]],
                                  key=lambda x: abs(x[4][1] - bottom_y)))
    except ValueError:
        pass
    try:
        bottom_anchors.append(min([m for m in marker_list[bottom_index] if m[4][0] / width > pos[-1]],
                                  key=lambda x: abs(x[4][1] - bottom_y)))
    except ValueError:
        pass

    top_list = [m for m in marker_list[top_index] if m[4][0] / width < pos[0]]
    if len(top_list) > 0:
        top_anchors.append(min(top_list, key=lambda x: abs(x[4][1] - top_y)))
    top_list = [m for m in marker_list[top_index] if abs(m[4][0] / width - pos[1]) < pos_threshold]
    if len(top_list) > 0:
        top_anchors.append(min(top_list, key=lambda x: abs(x[4][1] - top_y)))
        top_list = [m for m in marker_list[top_index] if abs(m[4][0] / width - pos[3]) < pos_threshold]
        if len(top_list) > 0:
            top_anchors.append(min(top_list, key=lambda x: abs(x[4][1] - top_y)))
    else:
        top_list = [m for m in marker_list[top_index] if abs(m[4][0] / width - pos[2]) < pos_threshold]
        if len(top_list) > 0:
            top_anchors.append(min(top_list, key=lambda x: abs(x[4][1] - top_y)))
        else:
            top_list = [m for m in marker_list[top_index] if abs(m[4][0] / width - pos[3]) < pos_threshold]
            if len(top_list) > 0:
                top_anchors.append(min(top_list, key=lambda x: abs(x[4][1] - top_y)))

    try:
        top_anchors.append(min([m for m in marker_list[top_index] if m[4][0] / width > pos[-1]],
                               key=lambda x: abs(x[4][1] - top_y) - x[4][0]))
    except ValueError:
        pass
    # for m in marker_list[-1]:
    #     if m[4][0] / width < pos[0]:
    #         bottom_anchors[0] = m
    #     elif m[4][0] / width > pos[-1]:
    #         bottom_anchors[1] = m
    # for m in marker_list[0]:
    #     if m[4][0] / width > pos[-1]:
    #         top_anchors[-1] = m
    #     elif abs(m[4][0] / width - pos[2]) < pos_threshold:
    #         top_anchors[1] = m
    #         top_anchors.pop(2)
    #     elif abs(m[4][0] / width - pos[1]) < pos_threshold:
    #         top_anchors[1] = m
    #     elif abs(m[4][0] / width - pos[3]) < pos_threshold:
    #         top_anchors[2] = m

    # for i in range(1, len(marker_list[0])+1):
    #     if marker_list[0][len(marker_list[0])-i][4][0] / width < pos[0]:
    #         top_anchors[0] = marker_list[0][-i]
    #         break


    # # 按面积从大到小排列
    # markers.sort(reverse=True, key=lambda x: x[-1])
    # flag = 0
    # anchors = []
    # for i in range(len(markers)):
    #     anchors = []
    #     anchors.append(markers[i])
    #     for j in range(i+1, len(markers)):
    #         if (anchors[0][-1] - markers[j][-1]) / anchors[0][-1] <= area_threshold:
    #             anchors.append(markers[j])
    #             flag = j
    #     if len(anchors) >= anchors_len_threshold:
    #         break
    # if len(anchors) == 0:
    #     return [[], [], []]
    # anchors.sort(key=lambda x: x[4][1])
    # # print('anchors\n')
    # # print(anchors)
    # top_anchors = []
    # bottom_anchors = []
    # for a in anchors:
    #     if a[4][1] - anchors[0][4][1] < shift_threshold:
    #         top_anchors.append(a)
    #     elif anchors[-1][4][1] - a[4][1] < shift_threshold:
    #         bottom_anchors.append(a)
    # top_anchors.sort(key=lambda x: x[4][0])
    # bottom_anchors.sort(key=lambda x: x[4][0])
    # detect_anchor_by_position(top_anchors, markers, image, method='t', debug=0)
    # detect_anchor_by_position(bottom_anchors, markers, image, method='b', debug=0)
    #
    # version_points = []
    # for i in range(flag + 1, len(markers)):
    #     if abs(markers[i][4][1] - anchors[0][4][1]) <= shift_threshold and markers[i][4][0] > width / 2:
    #         version_points.append(markers[i])

    if debug == 1:
        draw_box(image, top_anchors, (0, 255, 255), debug=1)
        draw_box(image, bottom_anchors, (255, 0, 255), debug=1)
        draw_box(image, version_points, (255, 255, 0), debug=1)
        plt.figure(figsize=(15, 10))
        plt.title(method)
        plt.imshow(image)
        plt.show()
    elif debug == 2:
        markers.sort(reverse=True, key=lambda x: x[4][1])
        draw_box(image, markers, debug=1)
        plt.figure(figsize=(15, 10))
        plt.title('by shape')
        plt.imshow(image)
        plt.show()
    elif debug == 3:
        colors = ((0, 255, 255), (255, 0, 255), (255, 255, 0))
        if len(marker_list) > 0:
            c = 0
            for p in marker_list:
                draw_box(image, p, color=colors[c])
                c = (c + 1) % 3
            plt.figure(figsize=(15, 10))
            plt.title('marker list')
            plt.imshow(image)
            plt.show()

    return [[top_anchors, bottom_anchors, version_points], image]


def detect_problem_marker(image, anchors, method='connected', column_num=2, debug=0):
    #   寻找题目定位点
    double_page_width_ratio = 0.42      # 默认双栏宽度比例
    three_page_width_ratio = 0.29       # 默认三栏宽度比例
    double_page_separation = 250        # 默认双栏栏间间距
    three_page_separation = 100         # 默认三栏栏间间距
    horizontal_threshold = 100           # 单栏宽度比例阈值
    shift_threshold = 80    # 50
    col_threshold = 100
    blank1 = 20
    blank2 = 100
    # shape_para = {'height': (80, 10), 'w2h': (3, 0.5), 'area': (6000, 500), 'area_ratio': 0.5}
    colors = ((0, 255, 255), (255, 0, 255), (255, 255, 0))
    height, width = image.shape[:2]
    remove_iteration = 1                # 去除异常值循环次数

    #   确定单栏宽度及每栏定位
    page_width, column_num, column_pos = find_column(anchors, width, column_num, debug=0)

    #   清除答题卡上下方定位点
    top_anchors, bottom_anchors = anchors[:2]
    if len(top_anchors) > 0:
        blank_top = max(top_anchors, key=lambda x: x[3])[3] + blank1
    else:
        blank_top = blank2
    if len(bottom_anchors) > 0:
        blank_bottom = min(bottom_anchors, key=lambda x: x[1])[1] - blank1
    else:
        blank_bottom = height - blank2
    binary = pre_process(image, blank_top, blank_bottom, debug=0)

    #   寻找所有可能的题目定位点
    binary = extract_feature(binary, method=3, debug=0)
    boxes = find_boxes(binary, method=method, debug=0)
    marker_candidates = find_marker_by_shape(boxes, debug=0)
    marker_candidates.sort(key=lambda x: x[4][0])

    # #   寻找配对点
    # pair_list = []
    # pair_list_indexes = []
    # for i in range(len(marker_candidates)):
    #     if i not in pair_list_indexes:
    #         p, p_index = find_pair(marker_candidates[i], marker_candidates, page_width, horizontal_threshold)
    #         if p_index >= 0:
    #             pair_list.append([marker_candidates[i], p])
    #             pair_list_indexes.append(p_index)
    # if len(pair_list) > 0:
    #     pair_list.sort(key=lambda x: x[0][4][0])
    #
    # #   按栏寻找题目定位点
    # if column_num == 2:
    #     problem_markers = [[], []]      # 题目定位点分两栏排列
    #     for p in pair_list:
    #         if abs(p[0][4][0] - column_pos[0]) < shift_threshold:
    #             problem_markers[0].extend(p)
    #         elif abs(p[0][4][0] - column_pos[1]) < shift_threshold:
    #             problem_markers[1].extend(p)
    #
    # elif column_num == 3:
    #     problem_markers = [[], [], []]  # 题目定位点分三栏排列
    #     for p in pair_list:
    #         if abs(p[0][4][0] - column_pos[0]) < shift_threshold:
    #             problem_markers[0].extend(p)
    #         elif abs(p[0][4][0] - column_pos[1]) < shift_threshold:
    #             problem_markers[2].extend(p)
    #         elif abs(p[0][4][0] - column_pos[0] - page_width - three_page_separation) < shift_threshold:
    #             problem_markers[1].extend(p)
    #
    # #   剔除异常mark
    # for i in range(len(problem_markers)):
    #     problem_markers[i] = remove_abnormal_marker(problem_markers[i], debug=0)

    #   将定位点按垂直位置排列
    marker_list = collect_markers_by_position(marker_candidates, method='v', debug=0)
    if column_num == 2:
        problem_markers = [[], []]
    elif column_num == 3:
        problem_markers = [[], [], []]
    if len(marker_list) == 0:
        return problem_markers

    #   将题目定位点配对
    # for col in marker_list:
    #     col.sort(key=lambda x: x[4][1])
    mid_left_col_pos, mid_right_col_pos = column_pos[0] + page_width, column_pos[1] - page_width
    mid_left_col_indexes, mid_right_col_indexes = [], []
    for col_index, col in enumerate(marker_list):
        if abs(col[0][4][0] - column_pos[0]) < col_threshold:
            pair_list_index = find_pair_list(col, marker_list, page_width, col_threshold)[1]
            if pair_list_index >= 0:
                for c in col:
                    pair, pair_index, distance = find_pair(c, marker_list[pair_list_index], page_width, col_threshold)
                    if pair_index >= 0:
                        problem_markers[0].extend([c, pair])
                        mid_left_col_indexes.append(pair_list_index)
                        # print('distance', col_index, distance)
                        if pair[4][0] < mid_left_col_pos:
                            mid_left_col_pos = pair[4][0]
        elif abs(col[0][4][0] - column_pos[1]) < col_threshold:
            pair_list_index = find_pair_list(col, marker_list, page_width, col_threshold)[1]
            if pair_list_index >= 0:
                for c in col:
                    pair, pair_index, distance = find_pair(c, marker_list[pair_list_index], page_width, col_threshold)
                    if pair_index >= 0:
                        problem_markers[-1].extend([c, pair])
                        mid_right_col_indexes.append(col_index)
                        # print('distance', col_index, distance)
                        if c[4][0] - page_width > mid_right_col_pos:
                            mid_right_col_pos = c[4][0] - page_width
    mid_left_col_indexes = set(mid_left_col_indexes)
    mid_right_col_indexes = set(mid_right_col_indexes)
    # print(mid_left_col_indexes, mid_left_col_pos)
    # print(mid_right_col_indexes, mid_right_col_pos)
    if column_num == 3:
        for col_index, col in enumerate(marker_list):
            if mid_left_col_pos < col[0][4][0] < mid_right_col_pos and (col_index not in mid_left_col_indexes):
                pair_list_index = find_pair_list(col, marker_list, page_width, col_threshold)[1]
                if pair_list_index not in mid_right_col_indexes:
                    for c in col:
                        pair, pair_index, distance = find_pair(c, marker_list[pair_list_index], page_width,
                                                               col_threshold)
                        if pair_index >= 0:
                            problem_markers[1].extend([c, pair])
                            # print('distance', col_index, distance)

    for index, p in enumerate(problem_markers):
        temp = [[p[2*i], p[2*i+1]] for i in range(len(p)//2)]
        temp.sort(key=lambda x: x[0][4][1])
        problem_markers[index] = []
        for t in temp:
            problem_markers[index].extend(t)
    #   剔除异常mark
    for i in range(len(problem_markers)):
        for j in range(remove_iteration):
            problem_markers[i], page_width = remove_abnormal_marker(problem_markers[i], page_width, debug=0)
    problem_markers = check_with_anchor(problem_markers, top_anchors, page_width, column_num)

    # pair_list = find_pair_list(marker_list[0], marker_list, page_width)
    # if pair_list:
    #     page_width = abs(marker_list[0][0][4][0] - pair_list[0][4][0])
    # abscissa_flag = 0
    # for prob in marker_list:
    #     if prob[0][4][0] >= abscissa_flag:
    #         pair_list = find_pair_list(prob, marker_list, page_width)
    #         if pair_list:
    #             for p in prob:
    #                 pair = find_pair(p, pair_list, page_width)
    #                 if pair:
    #                     problem_markers.extend(pair)
    #                     abscissa_flag = pair[1][4][0] + shift_threshold

    if debug == 1:
        print(page_width, column_num, column_pos)
        c = 0
        for p in problem_markers:
            print('column:', c)
            draw_box(image, p, color=colors[c], debug=1)
            c = (c + 1) % 3
            t = [(p[2*i+2][4][0]-p[2*i][4][0])/(p[2*i+2][4][1]-p[2*i][4][1]) for i in range(len(p)//2-1)]
            print('slope', t)
        # draw_box(image, problem_markers)
        plt.figure(figsize=(12, 8))
        plt.title('problem markers')
        plt.imshow(image)
        plt.show()
    elif debug == 2:
        print(page_width, column_num, column_pos)
        if len(marker_list) > 0:
            c = 0
            for p in marker_list:
                draw_box(image, p, color=colors[c], debug=1)
                c = (c + 1) % 3
            plt.figure(figsize=(15, 10))
            plt.title('marker list')
            plt.imshow(image)
            plt.show()

        # c = 0
        # for p in pair_list:
        #     draw_box(image, p, color=colors[c])
        #     c = (c + 1) % 3
        # plt.figure(figsize=(15, 10))
        # plt.title('pair list')
        # plt.imshow(image)
        # plt.show()
    elif debug == 3:
        draw_box(image, marker_candidates)
        plt.figure(figsize=(15, 10))
        plt.title('marker candidates')
        plt.imshow(image)
        plt.show()
    elif debug == 4:
        draw_box(image, boxes, debug=1)
        plt.figure(figsize=(15, 10))
        plt.title('boxes')
        plt.imshow(image)
        plt.show()

    return problem_markers


def main(img_file, method='connected', debug=0):
    #   寻找所有定位点
    colors = ((0, 255, 255), (255, 0, 255), (255, 255, 0))
    # image = cv2.imread(img_file)
    image = read_single_img(img_file)
    # image = Image.open(img_file)

    rot_image, flag = rotate_by_anchor(image, method=method, debug=0)
    # if not flag:
    #     return []
    anchors, rot_image = detect_anchor(rot_image, method=method, debug=0)

    # #   如果上方定位点不多于下方定位点，上下左右翻转答题卡
    # if len(anchors) > 0:
    #     if len(anchors[0]) + len(anchors[2]) <= len(anchors[1]):
    #         rot_image = cv2.flip(rot_image, -1)
    #         anchors = detect_anchor(rot_image, method=method, debug=0)

    #   寻找题目定位点
    problem_markers = detect_problem_marker(rot_image, anchors, method=method, debug=0)

    if debug == 1:
        c = 0
        for i in range(3):
            draw_box(rot_image, anchors[i], color=colors[c])
            c = (c + 1) % 3
        for p in problem_markers:
            draw_box(rot_image, p)
        plt.figure(figsize=(12, 8))
        plt.title('markers')
        plt.imshow(rot_image)
        plt.show()
    # elif debug == 2:
    #     path, image_name = os.path.split(img_file)
    #     out_dir = path + '_output'
    #     out_img_file = os.path.join(out_dir, image_name)
    #     if not os.path.exists(out_dir):
    #         os.makedirs(out_dir)
    #     cv2.imwrite(out_img_file, rot_image)
    #     rot_image.save(out_img_file)
    #     xml_file = out_img_file.replace('.jpg', '.xml')
    #     create_xml(xml_file, markers)

    return anchors, problem_markers


def find_anchor(image, method='connected'):
    # rot_image, flag = rotate_by_anchor(image, method=method, debug=0)
    anchors_raw = detect_anchor_public(image, method=method, debug=0)
    anchors_list = []
    for anchor in anchors_raw:
        bbox = {'xmin': int(str(anchor[0])), 'ymin': int(str(anchor[1])),
                'xmax': int(str(anchor[2])), 'ymax': int(str(anchor[3]))}
        anchor_dict = {'class_name': 'anchor_point', 'bounding_box': bbox}
        anchors_list.append(anchor_dict)
    return anchors_list
