From 85506b439f7d04b6e3aec347e373ea9f1a673282 Mon Sep 17 00:00:00 2001
From: Constantin Wenger <constantin.wenger@googlemail.com>
Date: Tue, 13 Aug 2019 20:38:51 +0000
Subject: [PATCH] make sure duplicate set abbreviations are removed

---
 opencv_dnn.py |  163 +++++++++++++++++++++++++++++++++++++++++++-----------
 1 files changed, 129 insertions(+), 34 deletions(-)

diff --git a/opencv_dnn.py b/opencv_dnn.py
index e9b8d5a..a2c9d3b 100644
--- a/opencv_dnn.py
+++ b/opencv_dnn.py
@@ -94,7 +94,9 @@
         hash_size = [hash_size]
 
     num_cores = 15
-    num_partitions = 60
+    num_partitions = round(card_pool.shape[0]/100)
+    if num_partitions < min(num_cores, card_pool.shape[0]):
+        num_partitions = min(num_cores, card_pool.shape[0])
     pool = Pool(num_cores)
     df_split = np.array_split(card_pool, num_partitions)
     new_pool = pd.concat(pool.map(do_calc, [(split, hash_size) for split in df_split]))
@@ -216,7 +218,7 @@
     return corrected
 
 
-def find_card(img, thresh_c=5, kernel_size=(3, 3), size_thresh=10000):
+def find_card(img, thresh_c=5, kernel_size=(3, 3), size_thresh=10000, debug=False):
     """
     Find contours of all cards in the image
     :param img: source image
@@ -229,24 +231,28 @@
     img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
     img_blur = cv2.medianBlur(img_gray, 5)
     img_thresh = cv2.adaptiveThreshold(img_blur, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, 11, thresh_c)
-    cv2.imshow('Thres', img_thresh)
+    if debug:
+        cv2.imshow('Thres', img_thresh)
     # Dilute the image, then erode them to remove minor noises
     kernel = np.ones(kernel_size, np.uint8)
     img_dilate = cv2.dilate(img_thresh, kernel, iterations=1)
     img_erode = cv2.erode(img_dilate, kernel, iterations=1)
-    cv2.imshow('Eroded', img_erode)
+    if debug:
+        cv2.imshow('Eroded', img_erode)
     # Find the contour
     cnts, hier = cv2.findContours(img_erode, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
     if len(cnts) == 0:
         #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]))
-    cv2.drawContours(img_cont, cnts2, -1, (0, 255, 0), 3)
-    cv2.imshow('Contours', img_cont)
+    if debug:
+        cv2.drawContours(img_cont, cnts2, -1, (0, 255, 0), 3)
+        cv2.imshow('Contours', img_cont)
     # The hierarchy from cv2.findContours() is similar to a tree: each node has an access to the parent, the first child
     # their previous and next node
     # Using recursive search, find the uppermost contour in the hierarchy that satisfies the condition
@@ -262,9 +268,45 @@
         size = cv2.contourArea(cnt)
         peri = cv2.arcLength(cnt, True)
         approx = cv2.approxPolyDP(cnt, 0.04 * peri, True)
-        if size >= size_thresh and len(approx) < 6:
-            print('Size:', size)
-            cnts_rect.append(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:
+                img_ccont = img_cont_base.copy()
+                # lets collect all children
+                c_list = [cnts[i_child]]
+                h_info = hier[0][i_child]
+                while h_info[0] != -1:
+                    cld = cnts[h_info[0]]
+                    c_list.append(cld)
+                    h_info = hier[0][h_info[0]]
+                # child with biggest area
+                c_list.sort(key=cv2.contourArea, reverse=True)
+                c_cnt = c_list[0]  # the biggest child
+                if debug:
+                    cv2.drawContours(img_ccont, c_list[:1], -1, (0, 255, 0), 1)
+                    cv2.imshow('CCont %d' % i_cnt, img_ccont)
+                c_size = cv2.contourArea(c_cnt)
+                c_approx = cv2.approxPolyDP(c_cnt, 0.04 * peri, True)
+                if len(c_approx) == 4 and (c_size/size) > 0.85:
+                    rect = cv2.minAreaRect(c_cnt)
+                    box = cv2.boxPoints(rect)
+                    box = np.intp(box)
+                    print(c_cnt)
+                    print(box)
+
+                    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)
+                    cnts_rect.append(approx)
+            else:
+                #print('CF:', (c_size/size))
+                print('Size:', size)
+                cnts_rect.append(approx)
         else:
             if i_child != -1:
                 stack.append((i_child, hier[0][i_child]))
@@ -349,7 +391,7 @@
     img_result = img.copy()  # For displaying and saving
     det_cards = []
     # Detect contours of all cards in the image
-    cnts = find_card(img_result, size_thresh=size_thresh)
+    cnts = find_card(img_result, size_thresh=size_thresh, debug=debug)
     for i in range(len(cnts)):
         cnt = cnts[i]
         # For the region of the image covered by the contour, transform them into a rectangular image
@@ -375,7 +417,8 @@
         img_set_part = img_warp[cut[0]:cut[1], cut[2]:cut[3]]
         print(img_set_part.shape)
         img_set = Image.fromarray(img_set_part.astype('uint8'), 'RGB')
-        cv2.imshow("Set Img#%d" % i, img_set_part)
+        if debug:
+            cv2.imshow("Set Img#%d" % i, img_set_part)
 
         # the stored values of hashes in the dataframe is pre-emptively flattened already to minimize computation time
         card_hash = ih.phash(img_card, hash_size=hash_size).hash.flatten()
@@ -385,24 +428,28 @@
         hash_diff = min_card['hash_diff']
 
         top_matches = sorted(card_pool['hash_diff'])
-        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))
-        candidates = []
-        for ix in range(0, 2):
-            cdr = 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] = cdr
-            cd = cdr
-            print('Idx:', ix, 'Name:', cd['name'], 'Set:', cd['set'], 'Diff:', top_matches[ix])
+        card_one = card_pool[card_pool['hash_diff'] == top_matches[0]].iloc[0]
+        card_two = card_pool[card_pool['hash_diff'] == top_matches[1]].iloc[0]
 
-        cd_data['set_hash_diff'] = cd_data['set_hash_%d' % hash_size]
-        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)
-        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'])
+        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))
+            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])
 
-        min_card = best_match
+
+            cd_data['set_hash_diff'] = cd_data['set_hash_%d' % hash_size]
+            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)
+            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'])
+
+            min_card = best_match
         card_name = min_card['name']
         card_set = min_card['set']
         det_cards.append((card_name, card_set))
@@ -426,7 +473,7 @@
 
 
 def detect_video(capture, card_pool, hash_size=32, size_thresh=10000,
-                 out_path=None, display=True, show_graph=True, debug=False):
+                 out_path=None, display=True, show_graph=True, debug=False, crop_x=0, crop_y=0):
     """
     Identify all cards in the continuous video stream, display or save the result if needed
     :param capture: input video stream
@@ -443,8 +490,9 @@
     # 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
-        width = round(capture.get(cv2.CAP_PROP_FRAME_WIDTH)) + img_graph.shape[1]
-        height = max(round(capture.get(cv2.CAP_PROP_FRAME_HEIGHT)), img_graph.shape[0])
+        width = round(capture.get(cv2.CAP_PROP_FRAME_WIDTH)) - 2*crop_x  + img_graph.shape[1]
+        height = max(round(capture.get(cv2.CAP_PROP_FRAME_HEIGHT)) - 2*crop_y, img_graph.shape[0])
+        height += 200  # some space to display last detected cards
     else:
         width = round(capture.get(cv2.CAP_PROP_FRAME_WIDTH))
         height = round(capture.get(cv2.CAP_PROP_FRAME_HEIGHT))
@@ -453,9 +501,15 @@
     max_num_obj = 0
     f_len = 10  # number of frames to consider to check for existing cards
     exist_cards = {}
+
+    exist_card_single = {}
+    written_out_cards = set()
+    found_cards = []
     try:
         while True:
             ret, frame = capture.read()
+            croped_img = frame[crop_y:-crop_y, crop_x:-crop_x]
+            fimg = cv2.flip(croped_img, -1)
             start_time = time.time()
             if not ret:
                 # End of video
@@ -463,7 +517,7 @@
                 cv2.waitKey(0)
                 break
             # Detect all cards from the current frame
-            det_cards, img_result = detect_frame(frame, card_pool, hash_size=hash_size, size_thresh=size_thresh,
+            det_cards, img_result = detect_frame(fimg, card_pool, hash_size=hash_size, size_thresh=size_thresh,
                                                  out_path=None, display=False, debug=debug)
             if show_graph:
                 # If the card was already detected in the previous frame, append 1 to the list
@@ -485,18 +539,50 @@
                     else:
                         exist_cards[key] = exist_cards[key][1 - f_len:] + [0]
                     if len(val) == f_len and sum(val) == 0:
-                        gone.append(key)
+                        gone.append(key)  # not there anymore
+
+                det_card_map = {}
+                gone_single =  []
+                for card_name, card_set in det_cards:
+                    skey = '%s (%s)' % (card_name, card_set)
+                    det_card_map[skey] = (card_name, card_set)
+
+                for key, val in exist_card_single.items():
+                    if key in det_card_map:
+                        exist_card_single[key] = exist_card_single[key][1 - f_len:] + [1]
+                    else:
+                        exist_card_single[key] = exist_card_single[key][1 - f_len:] + [0]
+
+                    if len(val) == f_len and sum(val) == 0:
+                        gone_single.append(key)
+                        if key in written_out_cards:
+                            written_out_cards.remove(key)
+                    if len(val) == f_len and sum(val) == f_len:
+                        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])
+
+                for key in det_card_map:
+                    if key not in exist_card_single.keys():
+                        exist_card_single[key] = [1]
+                for key in gone_single:
+                    exist_card_single.pop(key)
+
+
                 for key in det_cards_list:
                     if key not in exist_cards.keys():
                         exist_cards[key] = [1]
                 for key in gone:
                     exist_cards.pop(key)
 
+
                 # Draw the graph based on the history of detected cards, then concatenate it with the result image
                 img_graph = draw_card_graph(exist_cards, card_pool, f_len)
                 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):
+                    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
 
@@ -519,6 +605,12 @@
             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 main(args):
     # Specify paths for all necessary files
@@ -559,9 +651,12 @@
 
     # If the test file isn't given, use webcam to capture video
     if args.in_path is None:
-        capture = cv2.VideoCapture(0)
+        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)
         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)
+                     display=args.display, show_graph=args.show_graph, debug=args.debug, crop_x=500, crop_y=200)
         capture.release()
     else:
         # Save the detection result if args.out_path is provided

--
Gitblit v1.10.0