【OpenCV】模板匹配、图像二值化

一、模板匹配

1.1 概念

在这里插入图片描述
  **模板匹配:**就是在整个图像区域发现与给与子图像匹配的小块区域。所以模板匹配首先需要一个模板图像T(给与的子图像),另外还需要一个待检测图像-原图像s。
  工作方法: 在待检测图像上,从左到右,从上向下计算模板图像与重叠子图像的匹配度,匹配程度越大,两者相同的可能性越大。

1.2 实战cv.matchTemplate

  cv.matchTemplate(图片,模板,匹配方法)

import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt

def template_demo():
   
    target=cv.imread(r'D:\Project\Opencv\Learning01\angelababy.jpg')
    tpl=cv.imread(r'D:\Project\Opencv\Learning01\muban.png')
    cv.imshow('template',tpl)
    cv.imshow('target',target)
    '''三种匹配时的度量方法'''
    method=[cv.TM_SQDIFF_NORMED,cv.TM_CCORR_NORMED,cv.TM_CCOEFF_NORMED]
    th,tw=tpl.shape[0:2]
    for md in method:
        print(md)
        '''模板匹配'''
        result=cv.matchTemplate(target,tpl,md)#原图像、模板、匹配方法
        min_val,max_val,min_loc,max_loc=cv.minMaxLoc(result)
        if md==cv.TM_SQDIFF_NORMED:
            tl=min_loc
        else:
            tl=max_loc
        br=(tl[0]+tw,tl[1]+th)
        cv.rectangle(target,tl,br,(0,0,255),2)
        cv.imshow('result'+str(md),target)

template_demo()
cv.waitKey(10000)

在这里插入图片描述

二、图像二值化

2.1 概念

  二值图像:
  图像中只有两种颜色[0,1]。灰度图像是[0,255]彩色图像是[[0,255],[0,255][0,255]。
                在这里插入图片描述
         在这里插入图片描述

2.2 实战

  二值化之前要先把图片变为灰度图

2.2.1 全局阈值cv.threshold

  ret,binary=cv.threshold()

import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
''''''
def threshold_demo():
    ''''''
    target=cv.imread(r'D:\Project\Opencv\Learning01\angelababy.jpg')
    """变为灰度图像"""
    gray=cv.cvtColor(target,cv.COLOR_BGR2GRAY)
    """变为二值图像"""
    #########方法1:此时cv.THRESH_OTSU计算阈值,0,255作废
    ret,binary=cv.threshold(gray,0,255,cv.THRESH_BINARY|cv.THRESH_OTSU)#参数:原图像,0,255,二值化方法
    cv.imshow('origin', target)
    print('yuzhi:',ret)#自动计算的分割阈值
    cv.imshow('binary',binary)
    # #########方法2,自动全局阈值,此时cv.THRESH_TRIANGLE计算阈值,0,255作废
    # ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY | cv.THRESH_TRIANGLE)
    # cv.imshow('origin', target)
    # print('yuzhi:', ret)  # 自动计算的分割阈值
    # cv.imshow('binary', binary)
    # #########方法3,自动指定阈值,小于127是黑色,大于127是白色
    # ret, binary = cv.threshold(gray, 127, 255, cv.THRESH_BINARY )
    # cv.imshow('origin', target)
    # print('yuzhi:', ret)  # 自动计算的分割阈值
    # cv.imshow('binary', binary)
    # #########方法4.取反.大于127是黑色,小于127是白色
    # ret, binary = cv.threshold(gray, 127, 255, cv.THRESH_BINARY_INV)
    # cv.imshow('origin', target)
    # print('yuzhi:', ret)  # 自动计算的分割阈值
    # cv.imshow('binary', binary)
    # #########方法5.截断阈值,大于127变成127,
    # ret, binary = cv.threshold(gray, 127, 255, cv.THRESH_TRUNC)
    # cv.imshow('origin', target)
    # print('yuzhi:', ret)  # 自动计算的分割阈值
    # cv.imshow('binary', binary)
    # #########方法6.小于127变为0
    # ret, binary = cv.threshold(gray, 127, 255, cv.THRESH_TOZERO)
    # cv.imshow('origin', target)
    # print('yuzhi:', ret)  # 自动计算的分割阈值
    # cv.imshow('binary', binary)

threshold_demo()
cv.waitKey(10000)

在这里插入图片描述

2.2.2 局部(自适应)阈值cv.adaptiveThreshold

  binary=cv.adaptiveThreshold()

import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
''''''
def local_threshold():
    ''''''
    target=cv.imread(r'D:\Project\Opencv\Learning01\angelababy.jpg')
    """变为灰度图像"""
    gray=cv.cvtColor(target,cv.COLOR_BGR2GRAY)
    """变为二值图像"""
    #########自适应阈值
    ###方法1:cv.ADAPTIVE_THRESH_MEAN_C
    dst=cv.adaptiveThreshold(gray,255,cv.ADAPTIVE_THRESH_MEAN_C,cv.THRESH_BINARY,25,10)
    cv.imshow('target', target)
    cv.imshow('binary',dst)
    ###方法2:cv.ADAPTIVE_THRESH_GAUSSIAN_C
    # dst=cv.adaptiveThreshold(gray,255,cv.ADAPTIVE_THRESH_GAUSSIAN_C,cv.THRESH_BINARY,25,10)
    # cv.imshow('target', target)
    # cv.imshow('binary',dst)

local_threshold()
cv.waitKey(10000)

在这里插入图片描述

2.2.3 自定义阈值cv.threshold

  ret,binary=cv.threshold()
  例使用均值阈值

import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
''''''
def custom_threshold():
    ''''''
    target=cv.imread(r'D:\Project\Opencv\Learning01\angelababy.jpg')
    """变为灰度图像"""
    gray=cv.cvtColor(target,cv.COLOR_BGR2GRAY)
    """变为二值图像"""
    h,w=gray.shape[0:2]
    m=np.reshape(gray,[1,w*h])
    mean=m.sum()/(w*h)
    print('mean',mean)
    ret,binary=cv.threshold(gray,mean,255,cv.THRESH_BINARY)
    cv.imshow('target',target)
    cv.imshow('binary',binary)


custom_threshold()
cv.waitKey(10000)

在这里插入图片描述

三、超大图像二值化

  二值化:全局阈值、局部阈值、自定义阈值。对于超大图像,通常先图像分块,再局部二值化(常用)

import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
''''''
def big_image_binary():
    ''''''
    big_img=cv.imread(r'D:\Project\Opencv\Learning01\bigimage.png')
    print(big_img.shape)
    #设置分成的小块的大小
    cw=125
    ch=125
    h,w=big_img.shape[0:2]
    gray=cv.cvtColor(big_img,cv.COLOR_BGR2GRAY)#转灰度图
    for row in range(0,h,ch):
        for col in range(0,w,cw):
            roi=gray[row:row+ch,col:col+col+cw]#得到一小块图片
            """计算小块图像的二值化的结果"""
            dst=cv.adaptiveThreshold(roi,255,cv.ADAPTIVE_THRESH_GAUSSIAN_C,cv.THRESH_BINARY,127,20)
            """图像块二值化的结果赋值到原图"""
            gray[row:row+ch,col:col+col+cw]=dst
            print(np.std(dst),np.mean(dst))
    cv.imshow('big binary',gray)


big_image_binary()
cv.waitKey(10000)

在这里插入图片描述

在这里插入图片描述

  
  

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
OpenCV 模板匹配是一种基于模板像和待匹配像进行匹配的技术。该技术主要用于在待匹配像中查找与模板像相似的区域位置。OpenCV 提供了多种模板匹配算法,包括平方差匹配、归一化平方差匹配、相关性匹配和归一化相关性匹配等。 模板匹配的基本流程如下: 1. 加载待匹配像和模板像 2. 对模板像进行预处理,如灰度化、二值化等操作 3. 使用模板像在待匹配像中进行滑动窗口搜索,计算匹配度 4. 根据匹配度确定匹配位置 5. 绘制匹配结果或输出匹配位置信息 以下是一个基于归一化平方差匹配的模板匹配示例代码: ```python import cv2 import numpy as np # 加载待匹配像和模板像 img = cv2.imread('test.jpg') template = cv2.imread('template.jpg') # 对模板像进行灰度化和二值化处理 template_gray = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY) _, template_thresh = cv2.threshold(template_gray, 0, 255, cv2.THRESH_BINARY) # 获取模板像大小 h, w = template_thresh.shape[:2] # 使用归一化平方差匹配算法进行模板匹配 res = cv2.matchTemplate(img, template_thresh, cv2.TM_SQDIFF_NORMED) # 获取匹配位置 min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res) top_left = min_loc bottom_right = (top_left[0] + w, top_left[1] + h) # 绘制匹配结果 cv2.rectangle(img, top_left, bottom_right, (0, 0, 255), 2) # 显示匹配结果 cv2.imshow('Match result', img) cv2.waitKey(0) cv2.destroyAllWindows() ``` 在上述代码中,我们首先加载了待匹配像和模板像,并对模板像进行了灰度化和二值化处理。然后使用 `cv2.matchTemplate()` 函数进行模板匹配,并获取匹配位置。最后使用 `cv2.rectangle()` 函数绘制匹配结果,并展示出来。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值