Python cv2.TM_CCOEFF_NORMED Examples

The following are 30 code examples of cv2.TM_CCOEFF_NORMED(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module cv2 , or try the search function .
Example #1
Source File: split_img_generate_data.py    From 2019-CCF-BDCI-OCR-MCZJ-OCR-IdentificationIDElement with MIT License 9 votes vote down vote up
def match_img(image, template, value):
    """
    :param image: 图片
    :param template: 模板
    :param value: 阈值
    :return: 水印坐标
    描述:用于获得这幅图片模板对应的位置坐标,用途:校准元素位置信息
    """
    res = cv2.matchTemplate(image, template, cv2.TM_CCOEFF_NORMED)
    threshold = value
    min_v, max_v, min_pt, max_pt = cv2.minMaxLoc(res)
    if max_v < threshold:
        return False
    if not max_pt[0] in range(10, 40) or max_pt[1] > 20:
        return False
    return max_pt 
Example #2
Source File: TemplateMatchers.py    From lackey with MIT License 8 votes vote down vote up
def findAllMatches(self, needle, similarity):
        """ Find all matches for ``needle`` with confidence better than or equal to ``similarity``.

        Returns an array of tuples ``(position, confidence)`` if match(es) is/are found,
        or an empty array otherwise.
        """
        positions = []
        method = cv2.TM_CCOEFF_NORMED

        match = cv2.matchTemplate(self.haystack, self.needle, method)

        indices = (-match).argpartition(100, axis=None)[:100] # Review the 100 top matches
        unraveled_indices = numpy.array(numpy.unravel_index(indices, match.shape)).T
        for location in unraveled_indices:
            y, x = location
            confidence = match[y][x]
            if method == cv2.TM_SQDIFF_NORMED or method == cv2.TM_SQDIFF:
                if confidence <= 1-similarity:
                    positions.append(((x, y), confidence))
            else:
                if confidence >= similarity:
                    positions.append(((x, y), confidence))

        positions.sort(key=lambda x: (x[0][1], x[0][0]))
        return positions 
Example #3
Source File: image_detect_02.py    From image-detect with MIT License 7 votes vote down vote up
def matchAB(fileA, fileB):
    # 读取图像数据
    imgA = cv2.imread(fileA)
    imgB = cv2.imread(fileB)

    # 转换成灰色
    grayA = cv2.cvtColor(imgA, cv2.COLOR_BGR2GRAY)
    grayB = cv2.cvtColor(imgB, cv2.COLOR_BGR2GRAY)

    # 获取图片A的大小
    height, width = grayA.shape

    # 取局部图像,寻找匹配位置
    result_window = np.zeros((height, width), dtype=imgA.dtype)
    for start_y in range(0, height-100, 10):
        for start_x in range(0, width-100, 10):
            window = grayA[start_y:start_y+100, start_x:start_x+100]
            match = cv2.matchTemplate(grayB, window, cv2.TM_CCOEFF_NORMED)
            _, _, _, max_loc = cv2.minMaxLoc(match)
            matched_window = grayB[max_loc[1]:max_loc[1]+100, max_loc[0]:max_loc[0]+100]
            result = cv2.absdiff(window, matched_window)
            result_window[start_y:start_y+100, start_x:start_x+100] = result

    plt.imshow(result_window)
    plt.show() 
Example #4
Source File: scene_detector.py    From ATX with Apache License 2.0 7 votes vote down vote up
def get_match_confidence(img1, img2, mask=None):
    if img1.shape != img2.shape:
        return False
    ## first try, using absdiff
    # diff = cv2.absdiff(img1, img2)
    # h, w, d = diff.shape
    # total = h*w*d
    # num = (diff<20).sum()
    # print 'is_match', total, num
    # return num > total*0.90
    if mask is not None:
        img1 = img1.copy()
        img1[mask!=0] = 0
        img2 = img2.copy()
        img2[mask!=0] = 0
    ## using match
    match = cv2.matchTemplate(img1, img2, cv2.TM_CCOEFF_NORMED)
    _, confidence, _, _ = cv2.minMaxLoc(match)
    # print confidence
    return confidence 
Example #5
Source File: imagesearch.py    From python-imagesearch with MIT License 6 votes vote down vote up
def imagesearcharea(image, x1, y1, x2, y2, precision=0.8, im=None):
    if im is None:
        im = region_grabber(region=(x1, y1, x2, y2))
        if is_retina:
            im.thumbnail((round(im.size[0] * 0.5), round(im.size[1] * 0.5)))
        # im.save('testarea.png') usefull for debugging purposes, this will save the captured region as "testarea.png"

    img_rgb = np.array(im)
    img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
    template = cv2.imread(image, 0)

    res = cv2.matchTemplate(img_gray, template, cv2.TM_CCOEFF_NORMED)
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
    if max_val < precision:
        return [-1, -1]
    return max_loc 
Example #6
Source File: play.py    From Wechat_AutoJump with MIT License 6 votes vote down vote up
def multi_scale_search(pivot, screen, range=0.3, num=10):
    H, W = screen.shape[:2]
    h, w = pivot.shape[:2]

    found = None
    for scale in np.linspace(1-range, 1+range, num)[::-1]:
        resized = cv2.resize(screen, (int(W * scale), int(H * scale)))
        r = W / float(resized.shape[1])
        if resized.shape[0] < h or resized.shape[1] < w:
            break
        res = cv2.matchTemplate(resized, pivot, cv2.TM_CCOEFF_NORMED)

        loc = np.where(res >= res.max())
        pos_h, pos_w = list(zip(*loc))[0]

        if found is None or res.max() > found[-1]:
            found = (pos_h, pos_w, r, res.max())

    if found is None: return (0,0,0,0,0)
    pos_h, pos_w, r, score = found
    start_h, start_w = int(pos_h * r), int(pos_w * r)
    end_h, end_w = int((pos_h + h) * r), int((pos_w + w) * r)
    return [start_h, start_w, end_h, end_w, score] 
Example #7
Source File: idcardocr.py    From idcardocr with GNU General Public License v3.0 6 votes vote down vote up
def find_address(crop_gray, crop_org):
        template = cv2.UMat(cv2.imread('address_mask_%s.jpg'%pixel_x, 0))
        # showimg(template)
        #showimg(crop_gray)
        w, h = cv2.UMat.get(template).shape[::-1]
        #t1 = round(time.time()*1000)
        res = cv2.matchTemplate(crop_gray, template, cv2.TM_CCOEFF_NORMED)
        #t2 = round(time.time()*1000)
        #print 'time:%s'%(t2-t1)
        min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
        top_left = (max_loc[0] + w, max_loc[1] - int(20*x))
        bottom_right = (top_left[0] + int(1700*x), top_left[1] + int(550*x))
        result = cv2.UMat.get(crop_org)[top_left[1]-10:bottom_right[1], top_left[0]-10:bottom_right[0]]
        cv2.rectangle(crop_gray, top_left, bottom_right, 255, 2)
        #showimg(crop_gray)
        return cv2.UMat(result) 
Example #8
Source File: generate_test_csv_file.py    From 2019-CCF-BDCI-OCR-MCZJ-OCR-IdentificationIDElement with MIT License 6 votes vote down vote up
def match_img(image, template, value):
    """
    :param image: 图片
    :param template: 模板
    :param value: 阈值
    :return: 水印坐标
    描述:用于获得这幅图片模板对应的位置坐标,用途:校准元素位置信息
    """
    res = cv2.matchTemplate(image, template, cv2.TM_CCOEFF_NORMED)
    threshold = value
    min_v, max_v, min_pt, max_pt = cv2.minMaxLoc(res)
    if max_v < threshold:
        return False
    if not max_pt[0] in range(10, 40) or max_pt[1] > 20:
        return False
    return max_pt 
Example #9
Source File: cv_detection_right_hand.py    From AI-Robot-Challenge-Lab with MIT License 6 votes vote down vote up
def __apply_template_matching(angle, template, image):
    # Rotate the template
    template_rotated = __rotate_image_size_corrected(template, angle)

    # Apply template matching
    image_templated = cv2.matchTemplate(image, template_rotated, cv2.TM_CCOEFF_NORMED)

    # Correct template matching image size difference
    template_rotated_height, template_rotated_width = template_rotated.shape
    template_half_height = template_rotated_height // 2
    template_half_width = template_rotated_width // 2

    image_templated_inrange_size_corrected = cv2.copyMakeBorder(image_templated, template_half_height, template_half_height, template_half_width, template_half_width, cv2.BORDER_CONSTANT, value=0)

    # Calculate maximum match coefficient
    max_match = numpy.max(image_templated_inrange_size_corrected)

    return (max_match, angle, template_rotated, image_templated_inrange_size_corrected) 
Example #10
Source File: compare_photos.py    From OpenCV-Python-Tutorial with MIT License 6 votes vote down vote up
def get_image_difference(image_1, image_2):  # 这个函数不行
    first_image_hist = cv2.calcHist([image_1], [0], None, [256], [0, 256])
    second_image_hist = cv2.calcHist([image_2], [0], None, [256], [0, 256])

    img_hist_diff = cv2.compareHist(first_image_hist, second_image_hist, cv2.HISTCMP_BHATTACHARYYA)
    img_template_probability_match = cv2.matchTemplate(first_image_hist, second_image_hist, cv2.TM_CCOEFF_NORMED)[0][0]
    img_template_diff = 1 - img_template_probability_match

    # taking only 10% of histogram diff, since it's less accurate than template method
    commutative_image_diff = (img_hist_diff / 10) + img_template_diff
    return commutative_image_diff 
Example #11
Source File: compare_photos.py    From OpenCV-Python-Tutorial with MIT License 6 votes vote down vote up
def compare(i, j, img):
    for x in range(lenX):
        if x < i:
            continue
        for y in range(lenY):
            if x <= i and y < j:
                continue
            z = mat[x][y]
            # 图片相似度
            y1 = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
            z1 = cv2.cvtColor(z, cv2.COLOR_BGR2GRAY)
            # image_difference = get_image_difference(y1, z1)
            res = cv2.matchTemplate(z1, y1, cv2.TM_CCOEFF_NORMED)
            # print(i, j, x, y, image_difference)
            print(i, j, x, y, res)
            # if abs(image_difference-1)>0.5:
            # if image_difference < 0.1:
            #     pairs.append((i, j, x, y, image_difference))
            if res[0][0] >= 0.8 :#and (i != x and j != y): # 0.9较好
                if i ==x and j ==y:
                    continue
                pairs.append((i, j, x, y, res[0][0]))
        print('--------') 
Example #12
Source File: cal_confidence.py    From Airtest with Apache License 2.0 6 votes vote down vote up
def cal_rgb_confidence(img_src_rgb, img_sch_rgb):
    """同大小彩图计算相似度."""
    # BGR三通道心理学权重:
    weight = (0.114, 0.587, 0.299)
    src_bgr, sch_bgr = cv2.split(img_src_rgb), cv2.split(img_sch_rgb)

    # 计算BGR三通道的confidence,存入bgr_confidence:
    bgr_confidence = [0, 0, 0]
    for i in range(3):
        res_temp = cv2.matchTemplate(src_bgr[i], sch_bgr[i], cv2.TM_CCOEFF_NORMED)
        min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res_temp)
        bgr_confidence[i] = max_val

    # 加权可信度
    weighted_confidence = bgr_confidence[0] * weight[0] + bgr_confidence[1] * weight[1] + bgr_confidence[2] * weight[2]

    return weighted_confidence 
Example #13
Source File: general_extract.py    From SpaceXtract with MIT License 6 votes vote down vote up
def exists(frame, template, thresh):
        """
        Returns True if 'template' is in 'frame' with probability of at least 'thresh'
        :param frame: A frame
        :param template: An image to search in 'frame'.
        :param thresh: The minimum probability required to accept template.
        :return: If template is in frame
        """

        digit_res = cv2.matchTemplate(frame, template, cv2.TM_CCOEFF_NORMED)
        loc = np.where(digit_res >= thresh)

        if len(loc[-1]) == 0:
            return False

        for pt in zip(*loc[::-1]):
            if digit_res[pt[1]][pt[0]] == 1:
                return False

        return True 
Example #14
Source File: general_extract.py    From SpaceXtract with MIT License 6 votes vote down vote up
def most_probably_template(image, templates):
        """
        Get the index of the template(in the templates list) which is most likely to be in the image.


        :param image: Image that contain the template
        :param templates: A list of templates to search in image
        :return: the index (in templates) which has the highest probability of being in  image
        """
        probability_list = []

        for template in templates:
            res = cv2.matchTemplate(image, template, cv2.TM_CCOEFF_NORMED)
            probability_list.append(float(np.max(res)))

        return probability_list.index(max(probability_list)) 
Example #15
Source File: template_matching.py    From dual-fisheye-video-stitching with MIT License 6 votes vote down vote up
def main():
    src = cv2.imread('src.jpg', cv2.IMREAD_GRAYSCALE)
    tpl = cv2.imread('tpl.jpg', cv2.IMREAD_GRAYSCALE)
    result = cv2.matchTemplate(src, tpl, cv2.TM_CCOEFF_NORMED)
    result = cv2.normalize(result, dst=None, alpha=0, beta=1,
                           norm_type=cv2.NORM_MINMAX, dtype=-1)
    minVal, maxVal, minLoc, maxLoc = cv2.minMaxLoc(result)
    matchLoc = maxLoc
    draw1 = cv2.rectangle(
        src, matchLoc, (matchLoc[0] + tpl.shape[1], matchLoc[1] + tpl.shape[0]), 0, 2, 8, 0)
    draw2 = cv2.rectangle(
        result, matchLoc, (matchLoc[0] + tpl.shape[1], matchLoc[1] + tpl.shape[0]), 0, 2, 8, 0)
    cv2.imshow('draw1', draw1)
    cv2.imshow('draw2', draw2)
    cv2.waitKey(0)
    print src.shape
    print tpl.shape
    print result.shape
    print matchLoc 
Example #16
Source File: dino_api.py    From go_dino with GNU General Public License v3.0 6 votes vote down vote up
def find_game_position(self, threshold) -> Dict:
        monitor = self.shooter.monitors[0]
        buffer = self.shooter.grab(monitor)
        image = Image.frombytes('RGB', buffer.size, buffer.rgb).convert('L')
        image = np.array(image)
        dino_template = cv2.imread(os.path.join('templates', 'dino.png'), 0)
        res = cv2.matchTemplate(image, dino_template, cv2.TM_CCOEFF_NORMED)
        loc = np.where(res >= threshold)
        if len(loc[0]) == 0:
            dino_template = cv2.imread(os.path.join('templates', 'dino2.png'), 0)
            res = cv2.matchTemplate(image, dino_template, cv2.TM_CCOEFF_NORMED)
            loc = np.where(res >= threshold)
        if len(loc[0]):
            pt = next(zip(*loc[::-1]))
            w, h = dino_template.shape[::-1]
            lw, lh = self.landscape_template.shape[::-1]
            return dict(monitor, height=lh, left=pt[0], top=pt[1] - lh + h, width=lw)
        return {} 
Example #17
Source File: nn_play.py    From Wechat_AutoJump with MIT License 6 votes vote down vote up
def multi_scale_search(pivot, screen, range=0.3, num=10):
    H, W = screen.shape[:2]
    h, w = pivot.shape[:2]

    found = None
    for scale in np.linspace(1-range, 1+range, num)[::-1]:
        resized = cv2.resize(screen, (int(W * scale), int(H * scale)))
        r = W / float(resized.shape[1])
        if resized.shape[0] < h or resized.shape[1] < w:
            break
        res = cv2.matchTemplate(resized, pivot, cv2.TM_CCOEFF_NORMED)

        loc = np.where(res >= res.max())
        pos_h, pos_w = list(zip(*loc))[0]

        if found is None or res.max() > found[-1]:
            found = (pos_h, pos_w, r, res.max())

    if found is None: return (0,0,0,0,0)
    pos_h, pos_w, r, score = found
    start_h, start_w = int(pos_h * r), int(pos_w * r)
    end_h, end_w = int((pos_h + h) * r), int((pos_w + w) * r)
    return [start_h, start_w, end_h, end_w, score] 
Example #18
Source File: imagesearch.py    From python-imagesearch with MIT License 6 votes vote down vote up
def imagesearch_count(image, precision=0.9):
    img_rgb = pyautogui.screenshot()
    if is_retina:
        img_rgb.thumbnail((round(img_rgb.size[0] * 0.5), round(img_rgb.size[1] * 0.5)))
    img_rgb = np.array(img_rgb)
    img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
    template = cv2.imread(image, 0)
    w, h = template.shape[::-1]
    res = cv2.matchTemplate(img_gray, template, cv2.TM_CCOEFF_NORMED)
    loc = np.where(res >= precision)
    count = 0
    for pt in zip(*loc[::-1]):  # Swap columns and rows
        # cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (0, 0, 255), 2) // Uncomment to draw boxes around found occurrences
        count = count + 1
    # cv2.imwrite('result.png', img_rgb) // Uncomment to write output image with boxes drawn around occurrences
    return count 
Example #19
Source File: hearthstone_auto.py    From hearthstone_script- with MIT License 5 votes vote down vote up
def detect_my_attend():
    img = ImageGrab.grab(bbox=(450, 490, 1470, 690))
    img_np = np.array(img)
    img_in_range = in_range(img_np)
    template = cv.imread("images/range.png", 0)

    res = cv.matchTemplate(img_in_range, template, cv.TM_CCOEFF_NORMED)
    loc = np.where(res >= 0.5)
    return np.unique(loc[1]) 
Example #20
Source File: util.py    From FGO-Automata with MIT License 5 votes vote down vote up
def standby(sh: str, tmp: str, threshold: float = 0.85) -> bool:
    img = cv2.imread(sh, 0)
    template = cv2.imread(tmp, 0)
    res = cv2.matchTemplate(img, template, cv2.TM_CCOEFF_NORMED)
    if (res >= threshold).any():
        return True
    return False 
Example #21
Source File: breakgeetest.py    From roc with MIT License 5 votes vote down vote up
def calculate_max_matching(target,icon,d):
    largest_val = 0
    for degree in range(0,360,d):
        tmp = ndimage.rotate(target, degree, reshape=False)
        res = cv2.matchTemplate(icon,tmp,cv2.TM_CCOEFF_NORMED)
        min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
        if max_val > largest_val:
            largest_val = max_val
    return largest_val

    # Calculate similarity matrix for each target, icon pair 
Example #22
Source File: search.py    From zmMagik with GNU General Public License v2.0 5 votes vote down vote up
def find_in_frame(frame, template):
    # simple template matching. This is scale invariant. For more complex
    # scale/rotation capable searching use SIFT/ORB/FLANN
    # https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_feature2d/py_matcher/py_matcher.html
    result = cv2.matchTemplate(frame,template,cv2.TM_CCOEFF_NORMED)
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(result)
    top_left = max_loc
    h,w = template.shape
    bottom_right = (top_left[0] + w, top_left[1] + h)
    return top_left, bottom_right, min_val, max_val 
Example #23
Source File: YZ.py    From musically-tiktok-api-python with MIT License 5 votes vote down vote up
def checkimage(self,buyuk,kucuk,id):
        urllib.request.urlretrieve(buyuk, "resimler/cop/buyuk/"+str(id)+".jpg")
        urllib.request.urlretrieve(kucuk, "resimler/cop/kucuk/"+str(id)+".jpg")
        boyutlar = {}
        img_rgb = cv2.imread("resimler/cop/buyuk/"+str(id)+".jpg")
        img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
        template = cv2.imread("resimler/cop/kucuk/"+str(id)+".jpg",0)
        w, h = template.shape[::-1]

        res = cv2.matchTemplate(img_gray,template,cv2.TM_CCOEFF_NORMED)
        threshold = 0.7
        loc = np.where( res >= threshold)
        for pt in zip(*loc[::-1]):
            cv2.rectangle(img_rgb, pt, (pt[0] + w, pt[1] + h), (5,5,255), 2)
            boyutlar['sol_x'] = pt[0]
            boyutlar['sol_y'] = pt[1]
            boyutlar['sag_x'] = pt[0] + w
            boyutlar['sag_y'] = pt[1] + h
        os.remove("resimler/cop/kucuk/"+str(id)+".jpg")
        os.remove("resimler/cop/buyuk/"+str(id)+".jpg")
        '''for i in range(1):
            plt.subplot(1,1,1),plt.imshow(img_rgb,'gray')
            plt.title("test")
            plt.xticks([]),plt.yticks([])
            plt.show()
        '''
        return boyutlar 
Example #24
Source File: player.py    From OverwatchDataAnalysis with GNU General Public License v3.0 5 votes vote down vote up
def _identify_ult_charge_digit(self, digit, digit_refs):
        """Retrieves ultimate charge for current player.

        Author:
            Appcell
            
        Args:
            None

        Returns:
            None
        """
        score = 0
        res = -1
        digit = ImageUtils.float_to_uint8(digit)
        for i in range(10):
            match_result = []

            match_result = cv2.matchTemplate(
                digit, digit_refs[i], cv2.TM_CCOEFF_NORMED)

            _, max_val, _, max_loc = cv2.minMaxLoc(match_result)
            temp_digit = ImageUtils.crop(
                digit, 
                [max_loc[1], digit_refs[i].shape[0], max_loc[0], digit_refs[i].shape[1]])

            score_ssim = measure.compare_ssim(temp_digit, digit_refs[i], multichannel=True)
            if score_ssim + max_val > score:
                score = score_ssim + max_val
                res = i
        return [res, score] 
Example #25
Source File: util.py    From FGO-Automata with MIT License 5 votes vote down vote up
def get_crd(sh: str, tmp: str, threshold: float = 0.85) -> [(int, int)]:
    img = cv2.imread(sh, 0)
    template = cv2.imread(tmp, 0)
    res = cv2.matchTemplate(img, template, cv2.TM_CCOEFF_NORMED)
    pos = []
    loc = np.where(res >= threshold)
    for pt in zip(*loc[::-1]):
        pos.append(pt)
    return pos 
Example #26
Source File: hearthstone_auto.py    From hearthstone_script- with MIT License 5 votes vote down vote up
def detect_sneer():
    img = ImageGrab.grab(bbox=(450, 300, 1470, 500))
    img_np = np.array(img)
    img_canny = cv.Canny(img_np, 600, 900)
    template = cv.imread("images/canny.png", 0)

    res = cv.matchTemplate(img_canny, template, cv.TM_CCOEFF_NORMED)
    loc = np.where(res >= 0.3)
    return np.unique(loc[1])


# 我放随从 
Example #27
Source File: image_detect_03.py    From image-detect with MIT License 5 votes vote down vote up
def matchAB(fileA, fileB):
    # 读取图像数据
    imgA = cv2.imread(fileA)
    imgB = cv2.imread(fileB)

    # 转换成灰色
    grayA = cv2.cvtColor(imgA, cv2.COLOR_BGR2GRAY)
    grayB = cv2.cvtColor(imgB, cv2.COLOR_BGR2GRAY)

    # 获取图片A的大小
    height, width = grayA.shape

    # 取局部图像,寻找匹配位置
    result_window = np.zeros((height, width), dtype=imgA.dtype)
    for start_y in range(0, height-100, 10):
        for start_x in range(0, width-100, 10):
            window = grayA[start_y:start_y+100, start_x:start_x+100]
            match = cv2.matchTemplate(grayB, window, cv2.TM_CCOEFF_NORMED)
            _, _, _, max_loc = cv2.minMaxLoc(match)
            matched_window = grayB[max_loc[1]:max_loc[1]+100, max_loc[0]:max_loc[0]+100]
            result = cv2.absdiff(window, matched_window)
            result_window[start_y:start_y+100, start_x:start_x+100] = result

    # 用四边形圈出不同部分
    _, result_window_bin = cv2.threshold(result_window, 30, 255, cv2.THRESH_BINARY)
    _, contours, _ = cv2.findContours(result_window_bin, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    imgC = imgA.copy()
    for contour in contours:
        min = np.nanmin(contour, 0)
        max = np.nanmax(contour, 0)
        loc1 = (min[0][0], min[0][1])
        loc2 = (max[0][0], max[0][1])
        cv2.rectangle(imgC, loc1, loc2, 255, 2)

    plt.subplot(1, 3, 1), plt.imshow(cv2.cvtColor(imgA, cv2.COLOR_BGR2RGB)), plt.title('A'), plt.xticks([]), plt.yticks([])
    plt.subplot(1, 3, 2), plt.imshow(cv2.cvtColor(imgB, cv2.COLOR_BGR2RGB)), plt.title('B'), plt.xticks([]), plt.yticks([])
    plt.subplot(1, 3, 3), plt.imshow(cv2.cvtColor(imgC, cv2.COLOR_BGR2RGB)), plt.title('Answer'), plt.xticks([]), plt.yticks([])
    plt.show() 
Example #28
Source File: Fic.py    From RENAT with Apache License 2.0 5 votes vote down vote up
def match_template(self,img,template,threshold=u"0.8"):
        """  Matches a template in an image using TM_CCOEFF_NORMED method

        Both `img` and `tempalte` are BGR ndarray object.
        The result is in the the center and boundary of the match.
        """
        _method = cv2.TM_CCOEFF_NORMED
        gray_img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
        gray_template = cv2.cvtColor(template,cv2.COLOR_BGR2GRAY)
        w,h = gray_template.shape[::-1]

        res = cv2.matchTemplate(gray_img,gray_template,_method)
        loc = np.where(res >= float(threshold))
        if len(loc[0]) != 0 and len(loc[1]) != 0:
            min_val,max_val,min_loc,max_loc = cv2.minMaxLoc(res)
            if _method in [cv2.TM_SQDIFF, cv2.TM_SQDIFF_NORMED]:
                top_left = min_loc
            else:
                top_left = max_loc
            bottom_right = (top_left[0] + w, top_left[1] + h)
            mx = int((top_left[0] + bottom_right[0])/2)
            my = int((top_left[1] + bottom_right[1])/2)
            result = ((mx,my),(top_left[0],top_left[1],bottom_right[0],bottom_right[1]))
            BuiltIn().log("Found image at %s" % str(result))
        else:
            result = (None,None)
            BuiltIn().log("WRN: Could not found the template")
        return result 
Example #29
Source File: imagesearch.py    From python-imagesearch with MIT License 5 votes vote down vote up
def imagesearch(image, precision=0.8):
    im = pyautogui.screenshot()
    if is_retina:
        im.thumbnail((round(im.size[0] * 0.5), round(im.size[1] * 0.5)))
    # im.save('testarea.png') useful for debugging purposes, this will save the captured region as "testarea.png"
    img_rgb = np.array(im)
    img_gray = cv2.cvtColor(img_rgb, cv2.COLOR_BGR2GRAY)
    template = cv2.imread(image, 0)
    template.shape[::-1]

    res = cv2.matchTemplate(img_gray, template, cv2.TM_CCOEFF_NORMED)
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
    if max_val < precision:
        return [-1, -1]
    return max_loc 
Example #30
Source File: util.py    From FGO-Automata with MIT License 5 votes vote down vote up
def check_color(sh: str, tmp: str, threshold: float = 0.8) -> bool:
    img = cv2.imread(sh, cv2.IMREAD_COLOR)
    template = cv2.imread(tmp, cv2.IMREAD_COLOR)
    res = cv2.matchTemplate(img, template, cv2.TM_CCOEFF_NORMED)
    if (res >= threshold).any():
        return True
    return False