Constantin Wenger
2022-02-01 6943e6eea0eee1ccf3ee9034699b6a94f334b003
added option to load from streams
added option to set crop x and crop y
added option to set percentage a card must take up
added ability to scroll detected cards list with o and p
added ability to remove topmost shown detected card with u
1 files modified
128 ■■■■■ changed files
opencv_dnn.py 128 ●●●●● patch | view | raw | blame | history
opencv_dnn.py
@@ -92,7 +92,7 @@
            #cv2.imshow('Set' + card_names[0], set_img)
            for hs in hash_size:
                card_hash = ih.phash(img_card, hash_size=hs)
                set_hash = ih.whash(img_set, hash_size=64)
                set_hash = ih.phash(img_set, hash_size=64)
                card_info['card_hash_%d' % hs] = card_hash
                card_info['set_hash_%d' % 64] = set_hash
                #print('Setting set_hash_%d' % hs)
@@ -263,14 +263,14 @@
    # Find the contour
    cnts, hier = cv2.findContours(img_erode, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
    if len(cnts) == 0:
        print('no contours')
#        print('no contours')
        return []
    img_cont = cv2.cvtColor(img_erode, cv2.COLOR_GRAY2BGR)
    img_cont_base = img_cont.copy()
    cnts2 = sorted(cnts, key=cv2.contourArea, reverse=True)
    cnts2 = cnts2[:10]
    for i in range(0, len(cnts2)):
        print(i, len(cnts2[i]))
#    for i in range(0, len(cnts2)):
#        print(i, len(cnts2[i]))
    if debug:
        cv2.drawContours(img_cont, cnts2, -1, (0, 255, 0), 3)
        cv2.imshow('Contours', img_cont)
@@ -289,8 +289,8 @@
        size = cv2.contourArea(cnt)
        peri = cv2.arcLength(cnt, True)
        approx = cv2.approxPolyDP(cnt, 0.04 * peri, True)
        print('Base Size:', size)
        print('Len Approx:', len(approx))
        #print('Base Size:', size)
        #print('Len Approx:', len(approx))
        if size >= size_thresh and len(approx) == 4:
            # lets see if we got a contour very close in size as child
            if i_child != -1:
@@ -314,21 +314,21 @@
                    rect = cv2.minAreaRect(c_cnt)
                    box = cv2.boxPoints(rect)
                    box = np.intp(box)
                    print(c_cnt)
                    print(box)
                    #print(c_cnt)
                    #print(box)
                    print('CSize:', c_size, '%:', c_size/size)
                    #print('CSize:', c_size, '%:', c_size/size)
                    b2 = []
                    for x in box:
                        b2.append([x])
                    cnts_rect.append(np.array(b2))
                else:
                    print('CF:', (c_size/size))
                    print('Size:', size)
                    #print('CF:', (c_size/size))
                    #print('Size:', size)
                    cnts_rect.append(approx)
            else:
                #print('CF:', (c_size/size))
                print('Size:', size)
                #print('Size:', size)
                cnts_rect.append(approx)
        else:
            if i_child != -1:
@@ -415,9 +415,9 @@
    det_cards = []
    # Detect contours of all cards in the image
    cnts = find_card(img_result, size_thresh=size_thresh, debug=debug)
    print('Countours:', len(cnts))
    #print('Contours:', len(cnts))
    for i in range(len(cnts)):
        print('Contour', i)
        #print('Contour', i)
        cnt = cnts[i]
        # For the region of the image covered by the contour, transform them into a rectangular image
        pts = np.float32([p[0] for p in cnt])
@@ -436,13 +436,13 @@
        '''
        img_card = Image.fromarray(img_warp.astype('uint8'), 'RGB')
        img_card_size = img_warp.shape
        print(img_card_size)
        #print(img_card_size)
        cut = [round(img_card_size[0]*0.57),round(img_card_size[0]*0.615),round(img_card_size[1]*0.81),round(img_card_size[1]*0.940)]
        print(cut)
        #print(cut)
        img_set_part = img_warp[cut[0]:cut[1], cut[2]:cut[3]]
        print(img_set_part.shape)
        #print(img_set_part.shape)
        img_set = Image.fromarray(img_set_part.astype('uint8'), 'RGB')
        print('img set')
        #print('img set')
        if debug:
            cv2.imshow("Set Img#%d" % i, img_set_part)
@@ -460,20 +460,20 @@
        if card_one['name'] == card_two['name'] and card_one['set'] != card_two['set']:
            set_img_hash = ih.whash(img_set, hash_size=hash_size).hash.flatten()
            cd_data = pd.DataFrame(columns=list(card_pool.columns.values))
            print(list(card_pool.columns.values))
#            print(list(card_pool.columns.values))
            candidates = []
            for ix in range(0, 2):
                cd = card_pool[card_pool['hash_diff'] == top_matches[ix]].iloc[0]
                cd_data.loc[0 if cd_data.empty else cd_data.index.max()+1] = cd
                print('Idx:', ix, 'Name:', cd['name'], 'Set:', cd['set'], 'Diff:', top_matches[ix])
#                print('Idx:', ix, 'Name:', cd['name'], 'Set:', cd['set'], 'Diff:', top_matches[ix])
            cd_data['set_hash_diff'] = cd_data['set_hash_%d' % 64]
            cd_data['set_hash_diff'] = cd_data['set_hash_diff'].apply(lambda x: np.count_nonzero(x != set_img_hash))
            conf = sorted(cd_data['set_hash_diff'])
            print('Confs:', conf)
            #print('Confs:', conf)
            best_match = cd_data[cd_data['set_hash_diff'] == min(cd_data['set_hash_diff'])].iloc[0]
            print('Best Match', 'Name:', best_match['name'], 'Set:', best_match['set'])
            #print('Best Match', 'Name:', best_match['name'], 'Set:', best_match['set'])
            min_card = best_match
        card_name = min_card['name']
@@ -482,7 +482,7 @@
        # Render the result, and display them if needed
        cv2.drawContours(img_result, [cnt], -1, (0, 255, 0), 2)
        cv2.putText(img_result, card_name, (min(pts[0][0], pts[1][0]), min(pts[0][1], pts[1][1])),
        cv2.putText(img_result, card_name, (int(min(pts[0][0], pts[1][0])), int(min(pts[0][1], pts[1][1]))),
                    cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 255, 255), 2)
        if debug:
            # cv2.rectangle(img_warp, (22, 47), (294, 249), (0, 255, 0), 2)
@@ -514,6 +514,7 @@
    :return: list of detected card's name/set and resulting image
    :return:
    """
    list_names_from = 0
    # Get the dimension of the output video, and set it up
    if show_graph:
        img_graph = draw_card_graph({}, pd.DataFrame(), -1)  # Black image of the graph just to get the dimension
@@ -535,7 +536,16 @@
    try:
        while True:
            ret, frame = capture.read()
            croped_img = frame[crop_y:-crop_y, crop_x:-crop_x]
            if not ret:
                continue
            y_max_index = -crop_y
            if crop_y == 0:
                y_max_index = frame.shape[0]
            x_max_index = -crop_x
            if crop_x == 0:
               x_max_index = frame.shape[1]
            croped_img = frame[crop_y:y_max_index, crop_x:x_max_index]
            fimg = cv2.flip(croped_img, -1)
            start_time = time.time()
            if not ret:
@@ -543,6 +553,9 @@
                print("End of video. Press any key to exit")
                cv2.waitKey(0)
                break
            if fimg is None:
                print("flipped image is none")
                break
            # Detect all cards from the current frame
            det_cards, img_result = detect_frame(fimg, card_pool, hash_size=hash_size, size_thresh=size_thresh,
                                                 out_path=None, display=False, debug=debug)
@@ -588,6 +601,7 @@
                        if key not in written_out_cards and key in det_card_map:
                            written_out_cards.add(key)
                            found_cards.append(det_card_map[key])
                            list_names_from += 1
                for key in det_card_map:
                    if key not in exist_card_single.keys():
@@ -608,7 +622,9 @@
                img_save = np.zeros((height, width, 3), dtype=np.uint8)
                img_save[0:img_result.shape[0], 0:img_result.shape[1]] = img_result
                img_save[0:img_graph.shape[0], img_result.shape[1]:img_result.shape[1] + img_graph.shape[1]] = img_graph
                for c, card in enumerate(reversed(found_cards[-10:]), 1):
                start_at = max(0,list_names_from-10)
                end_at = min(len(found_cards), list_names_from)
                for c, card in enumerate(reversed(found_cards[start_at:end_at]), 1):
                    cv2.putText(img_save, f'{card[0]} ({card[1].upper()})',(0, height-200+18*c), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0))
            else:
                img_save = img_result
@@ -625,19 +641,37 @@
            print('Elapsed time: %.2f ms' % elapsed_ms)
            if out_path is not None:
                vid_writer.write(img_save.astype(np.uint8))
            inp = cv2.waitKey(0)
            if 'q' == chr(inp & 255):
            if debug:
                print("Waiting for keypress to continue")
                inp = cv2.waitKey(0)
            else:
                inp = cv2.waitKey(1)
            if 'u' == chr(inp & 255):
                if len(found_cards) > 0:
                    del found_cards[list_names_from-1]
                    list_names_from = min(len(found_cards), max(0, list_names_from))
                #os.sleep(1000)
            elif 'p' == chr(inp & 255):
                list_names_from = max(1, list_names_from - 1)
            elif 'o' == chr(inp & 255):
                list_names_from = min(len(found_cards),list_names_from + 1)
            elif 'q' == chr(inp & 255):
                break
    except KeyboardInterrupt:
        print("KeyboardInterrupt happened")
    finally:
        write_found_cards(found_cards)
        capture.release()
        if out_path is not None:
            vid_writer.release()
        cv2.destroyAllWindows()
        with open('detect.txt', 'w') as of:
            counter = collections.Counter(found_cards)
            for key in counter:
                of.write(f'{counter[key]} [{key[1].upper()}] {key[0]}\n')
def write_found_cards(found_cards):
    with open('detect.txt', 'w') as of:
        counter = collections.Counter(found_cards)
        for key in counter:
            of.write(f'{counter[key]} [{key[1].upper()}] {key[0]}\n')
@@ -673,26 +707,36 @@
    # Processing time is almost linear to the size of the database
    # Program can be much faster if the search scope for the card can be reduced
    card_pool = card_pool[card_pool['set'].isin(Config.set_2003_list)]
    #card_pool = card_pool[card_pool['set'].isin(Config.set_2003_list)]
    # ImageHash is basically just one numpy.ndarray with (hash_size)^2 number of bits. pre-emptively flattening it
    # significantly increases speed for subtracting hashes in the future.
    card_pool[ch_key] = card_pool[ch_key].apply(lambda x: x.hash.flatten())
    card_pool[set_key] = card_pool[set_key].apply(lambda x: x.hash.flatten())
    print("Hash-Database setup done")
    # If the test file isn't given, use webcam to capture video
    if args.in_path is None:
        capture = cv2.VideoCapture(0, cv2.CAP_V4L)
        capture.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc(*"MJPG"))
        capture.set(cv2.CAP_PROP_FRAME_WIDTH, 1920)
        capture.set(cv2.CAP_PROP_FRAME_HEIGHT, 1080)
        if args.stream_url is None:
            print("Using webcam")
            capture = cv2.VideoCapture(0)
            capture.set(cv2.CAP_PROP_FOURCC, cv2.VideoWriter_fourcc(*"MJPG"))
            capture.set(cv2.CAP_PROP_FRAME_WIDTH, 1920)
            capture.set(cv2.CAP_PROP_FRAME_HEIGHT, 1080)
        else:
            print(f"Using streami {args.stream_url}")
            capture = cv2.VideoCapture(args.stream_url)
        thres = int(((1920-2*500)*(1080-2*200)*0.3))
        thres = int((1920-2*args.crop_x)*(1080-2*args.crop_y)*(float(args.threshold_percent)/100))
        print('Threshold:', thres)
        detect_video(capture, card_pool, hash_size=args.hash_size, out_path='%s/result.avi' % args.out_path,
                     display=args.display, show_graph=args.show_graph, debug=args.debug, crop_x=500, crop_y=200, size_thresh=thres)
        if args.out_path is None:
            out_path = None
        else:
            out_path = '%s/result.avi' % args.out_path
        detect_video(capture, card_pool, hash_size=args.hash_size, out_path=out_path,
                     display=args.display, show_graph=args.show_graph, debug=args.debug, crop_x=args.crop_x, crop_y=args.crop_y, size_thresh=thres)
        capture.release()
    else:
        print(f"Using image or video {args.in_path}")
        # Save the detection result if args.out_path is provided
        if args.out_path is None:
            out_path = None
@@ -734,6 +778,10 @@
    parser.add_argument('-dbg', '--debug', dest='debug', help='Enable debug mode', action='store_true', default=False)
    parser.add_argument('-gph', '--show_graph', dest='show_graph', help='Display the graph for video output', 
                        action='store_true', default=False)
    parser.add_argument('-s', '--stream', dest='stream_url', type=str)
    parser.add_argument('-cx', '--crop-x', dest='crop_x', help='crop x amount of pixel on each side in x-axis', type=int, default=0)
    parser.add_argument('-cy', '--crop-y', dest='crop_y', help='crop x amount of pixel on each side in y-axis', type=int, default=0)
    parser.add_argument('-tp', '--threshold-percent', dest='threshold_percent', help='percentage amount that the card image needs to take up to be detected',type=int, default=5)
    args = parser.parse_args()
    if not args.display and args.out_path is None:
        # Then why the heck are you running this thing in the first place?