Constantin Wenger
2019-06-21 b7dd760578dbbde908c6779782a91cfcbc916d38
extra set detection code
2 files modified
67 ■■■■ changed files
opencv_dnn.py 62 ●●●● patch | view | raw | blame | history
requirements.txt 5 ●●●●● patch | view | raw | blame | history
opencv_dnn.py
@@ -28,6 +28,7 @@
    new_pool = pd.DataFrame(columns=list(card_pool.columns.values))
    for hs in hash_size:
        new_pool['card_hash_%d' % hs] = np.NaN
        new_pool['set_hash_%d' % hs] = np.NaN
        #new_pool['art_hash_%d' % hs] = np.NaN
    for ind, card_info in card_pool.iterrows():
        if ind % 100 == 0:
@@ -60,13 +61,20 @@
                card_img = cv2.imread(img_name)
            if card_img is None:
                print('WARNING: card %s is not found!' % img_name)
                continue
            set_img = card_img[575:638, 567:700]
            #cv2.imshow(card_info['name'], set_img)
            # Compute value of the card's perceptual hash, then store it to the database
            #img_art = Image.fromarray(card_img[121:580, 63:685])  # For 745*1040 size card image
            img_card = Image.fromarray(card_img)
            img_set = Image.fromarray(set_img)
            for hs in hash_size:
                card_hash = ih.phash(img_card, hash_size=hs)
                set_hash = ih.whash(img_set, hash_size=hs)
                card_info['card_hash_%d' % hs] = card_hash
                card_info['set_hash_%d' % hs] = set_hash
                #print('Setting set_hash_%d' % hs)
                #art_hash = ih.phash(img_art, hash_size=hs)
                #card_info['art_hash_%d' % hs] = art_hash
            new_pool.loc[0 if new_pool.empty else new_pool.index.max() + 1] = card_info
@@ -220,19 +228,25 @@
    # Typical pre-processing - grayscale, blurring, thresholding
    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, 5, thresh_c)
    img_thresh = cv2.adaptiveThreshold(img_blur, 255, cv2.ADAPTIVE_THRESH_MEAN_C, cv2.THRESH_BINARY_INV, 11, thresh_c)
    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)
    # 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)
    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)
    # 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
@@ -248,7 +262,8 @@
        size = cv2.contourArea(cnt)
        peri = cv2.arcLength(cnt, True)
        approx = cv2.approxPolyDP(cnt, 0.04 * peri, True)
        if size >= size_thresh and len(approx) == 4:
        if size >= size_thresh and len(approx) < 6:
            print('Size:', size)
            cnts_rect.append(approx)
        else:
            if i_child != -1:
@@ -317,7 +332,7 @@
    return img_graph
def detect_frame(img, card_pool, hash_size=32, size_thresh=10000,
def detect_frame(img, card_pool, hash_size=32, size_thresh=100000,
                 out_path=None, display=True, debug=False):
    """
    Identify all cards in the input frame, display or save the frame if needed
@@ -353,15 +368,44 @@
        card_pool['hash_diff'] = card_pool['art_hash'].apply(lambda x: np.count_nonzero(x != art_hash))
        '''
        img_card = Image.fromarray(img_warp.astype('uint8'), 'RGB')
        img_card_size = img_warp.shape
        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)
        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)
        # 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()
        card_pool['hash_diff'] = card_pool['card_hash_%d' % hash_size]
        card_pool['hash_diff'] = card_pool['hash_diff'].apply(lambda x: np.count_nonzero(x != card_hash))
        min_card = card_pool[card_pool['hash_diff'] == min(card_pool['hash_diff'])].iloc[0]
        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])
        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))
        hash_diff = min_card['hash_diff']
        # Render the result, and display them if needed
        cv2.drawContours(img_result, [cnt], -1, (0, 255, 0), 2)
@@ -496,12 +540,13 @@
        card_pool.drop('Unnamed: 0', axis=1, inplace=True, errors='ignore')
        card_pool = calc_image_hashes(card_pool, save_to=pck_path, hash_size=hash_sizes)
    ch_key = 'card_hash_%d' % args.hash_size
    set_key = 'set_hash_%d' % args.hash_size
    if ch_key not in card_pool.columns:
        # we did not generate this hash_size yet
        print('We need to add hash_size=%d' % (args.hash_size,))
        card_pool = calc_image_hashes(card_pool, save_to=pck_path, hash_size=[args.hash_size])
    card_pool = card_pool[['name', 'set', 'collector_number', ch_key]]
    card_pool = card_pool[['name', 'set', 'collector_number', ch_key, set_key]]
    # 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
@@ -510,6 +555,7 @@
    # 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())
    # If the test file isn't given, use webcam to capture video
    if args.in_path is None:
requirements.txt
@@ -1,8 +1,7 @@
ast
cv2==3.4.2
opencv-python==3.4.2.17
pandas
imgaug==0.2.6
imutils==0.5.1
json==2.0.9
matplotlib==2.2.2
numpy==1.15.2
pandas==0.23.0